file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
configuration.ts
/** * Copyright 2016 Google Inc. 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. */ import * as assert from 'assert'; import * as is from 'is'; import merge = require('lodash.merge'); import {FakeConfiguration as Configuration} from '../fixtures/configuration'; import {ConfigurationOptions, Logger} from '../../src/configuration'; import {Fuzzer} from '../../utils/fuzzer'; import {deepStrictEqual} from '../util'; const level = process.env.GCLOUD_ERRORS_LOGLEVEL; import {createLogger} from '../../src/logger'; const logger = createLogger({ logLevel: is.number(level) ? level : 4, }); import * as nock from 'nock'; const METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/project'; const configEnv = { NODE_ENV: process.env.NODE_ENV, GCLOUD_PROJECT: process.env.GCLOUD_PROJECT, GAE_MODULE_NAME: process.env.GAE_MODULE_NAME, GAE_MODULE_VERSION: process.env.GAE_MODULE_VERSION, }; function sterilizeConfigEnv() { delete process.env.NODE_ENV; delete process.env.GCLOUD_PROJECT; delete process.env.GAE_MODULE_NAME; delete process.env.GAE_MODULE_VERSION; } function restoreConfigEnv() { process.env.NODE_ENV = configEnv.NODE_ENV; process.env.GCLOUD_PROJECT = configEnv.GCLOUD_PROJECT; process.env.GAE_MODULE_NAME = configEnv.GAE_MODULE_NAME; process.env.GAE_MODULE_VERSION = configEnv.GAE_MODULE_VERSION; } function createDeadMetadataService() { return nock(METADATA_URL) .get('/project-id') .times(1) .reply(500); } describe('Configuration class', () => { before(() => { sterilizeConfigEnv(); }); after(() => { restoreConfigEnv(); }); describe('Initialization', () => { const f = new Fuzzer(); describe('fuzzing the constructor', () => { it('Should return default values', () => { let c; f.fuzzFunctionForTypes( (givenConfigFuzz: ConfigurationOptions) => { c = new Configuration(givenConfigFuzz, logger); deepStrictEqual(c._givenConfiguration, {}); }, ['object'] ); }); }); describe('valid config and default values', () => { let c: Configuration; const validConfig = {reportMode: 'always'} as {reportMode: 'always'}; before(() => { process.env.NODE_ENV = 'development'; }); after(() => { sterilizeConfigEnv(); }); it('Should not throw with a valid configuration', () => { assert.doesNotThrow(() => { c = new Configuration(validConfig, logger); }); }); it('Should have a property reflecting the config argument', () => { deepStrictEqual(c._givenConfiguration, validConfig); }); it('Should not have a project id', () => { assert.strictEqual(c._projectId, null); }); it('Should not have a key', () => { assert.strictEqual(c.getKey(), null); }); it('Should have a default service context', () => { deepStrictEqual(c.getServiceContext(), { service: 'node', version: undefined, }); }); it('Should specify to not report unhandledRejections', () => { assert.strictEqual(c.getReportUnhandledRejections(), false); }); }); describe('reportMode', () => { let nodeEnv: string | undefined; beforeEach(() => { nodeEnv = process.env.NODE_ENV; }); afterEach(() => { if (nodeEnv === undefined) { delete process.env.NODE_ENV; } else { process.env.NODE_ENV = nodeEnv; } }); it('Should print a deprecation warning if "ignoreEvnironmentCheck" is used', () => { let warnText = ''; const logger = { warn: text => { warnText += text + '\n'; }, } as Logger; // tslint:disable-next-line:no-unused-expression new Configuration({ignoreEnvironmentCheck: true}, logger); assert.strictEqual( warnText, 'The "ignoreEnvironmentCheck" config option is deprecated. ' + 'Use the "reportMode" config option instead.\n' ); }); it('Should print a warning if both "ignoreEnvironmentCheck" and "reportMode" are specified', () => { let warnText = ''; const logger = { warn: text => { warnText += text + '\n'; }, } as Logger; // tslint:disable-next-line:no-unused-expression new Configuration( {ignoreEnvironmentCheck: true, reportMode: 'never'}, logger ); assert.strictEqual( warnText, 'The "ignoreEnvironmentCheck" config option is deprecated. ' + 'Use the "reportMode" config option instead.\nBoth the "ignoreEnvironmentCheck" ' + 'and "reportMode" configuration options have been specified. The "reportMode" ' + 'option will take precedence.\n' ); }); it('Should set "reportMode" to "always" if "ignoreEnvironmentCheck" is true', () => { const conf = new Configuration({ignoreEnvironmentCheck: true}, logger); assert.strictEqual(conf._reportMode, 'always'); }); it('Should set "reportMode" to "production" if "ignoreEnvironmentCheck" is false', () => { const conf = new Configuration({ignoreEnvironmentCheck: false}, logger); assert.strictEqual(conf._reportMode, 'production'); }); it('Should prefer "reportMode" config if "ignoreEnvironmentCheck" is also set', () => { const conf = new Configuration( {ignoreEnvironmentCheck: true, reportMode: 'never'}, logger ); assert.strictEqual(conf._reportMode, 'never'); }); it('Should be set to "production" by default', () => { const conf = new Configuration({}, logger); assert.strictEqual(conf._reportMode, 'production'); }); it('Should state reporting is enabled with mode "production"', () => { const conf = new Configuration({reportMode: 'production'}, logger); assert.strictEqual(conf.isReportingEnabled(), true); }); it('Should state reporting is enabled with mode "always"', () => { const conf = new Configuration({reportMode: 'always'}, logger); assert.strictEqual(conf.isReportingEnabled(), true); }); it('Should state reporting is not enabled with mode "never"', () => { const conf = new Configuration({reportMode: 'never'}, logger); assert.strictEqual(conf.isReportingEnabled(), false); }); it('Should state reporting should proceed with mode "production" and env "production"', () => { process.env.NODE_ENV = 'production'; const conf = new Configuration({reportMode: 'production'}, logger); assert.strictEqual(conf.getShouldReportErrorsToAPI(), true); }); it('Should state reporting should not proceed with mode "production" and env not "production"', () => { process.env.NODE_ENV = 'dev'; const conf = new Configuration({reportMode: 'production'}, logger); assert.strictEqual(conf.getShouldReportErrorsToAPI(), false); }); it('Should state reporting should proceed with mode "always" and env "production"', () => { process.env.NODE_ENV = 'production'; const conf = new Configuration({reportMode: 'always'}, logger); assert.strictEqual(conf.getShouldReportErrorsToAPI(), true); }); it('Should state reporting should proceed with mode "always" and env not "production"', () => { process.env.NODE_ENV = 'dev'; const conf = new Configuration({reportMode: 'always'}, logger); assert.strictEqual(conf.getShouldReportErrorsToAPI(), true); }); it('Should state reporting should not proceed with mode "never" and env "production"', () => { process.env.NODE_ENV = 'production'; const conf = new Configuration({reportMode: 'never'}, logger); assert.strictEqual(conf.getShouldReportErrorsToAPI(), false); }); it('Should state reporting should not proceed with mode "never" and env not "production"', () => { process.env.NODE_ENV = 'dev'; const conf = new Configuration({reportMode: 'never'}, logger); assert.strictEqual(conf.getShouldReportErrorsToAPI(), false); }); }); describe('with ignoreEnvironmentCheck', () => { const conf = merge( {}, {projectId: 'some-id'}, {ignoreEnvironmentCheck: true} ); const c = new Configuration(conf, logger); it('Should reportErrorsToAPI', () => { assert.strictEqual(c.getShouldReportErrorsToAPI(), true); }); }); describe('without ignoreEnvironmentCheck', () => { describe('report behaviour with production env', () => { let c: Configuration; before(() => { sterilizeConfigEnv(); process.env.NODE_ENV = 'production'; c = new Configuration(undefined, logger); }); after(() => { sterilizeConfigEnv(); }); it('Should reportErrorsToAPI', () => { assert.strictEqual(c.getShouldReportErrorsToAPI(), true); }); }); }); describe('exception behaviour', () => { it('Should throw if invalid type for reportMode', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-expression new Configuration( ({reportMode: new Date()} as {}) as ConfigurationOptions, logger ); }); }); it('Should throw if invalid value for reportMode', () => { assert.throws(() => { // tslint:disable-next-line:no-unused-expression new Configuration( ({reportMode: 'invalid-mode'} as {}) as ConfigurationOptions, logger ); }); }); it('Should throw if invalid type for key', () => { assert.throws(() => { // we are intentionally providing an invalid configuration // thus an explicit cast is needed // tslint:disable-next-line:no-unused-expression new Configuration( ({key: null} as {}) as ConfigurationOptions, logger ); }); }); it('Should throw if invalid for ignoreEnvironmentCheck', () => { assert.throws(() => { // we are intentionally providing an invalid configuration // thus an explicit cast is needed // tslint:disable-next-line:no-unused-expression new Configuration( ({ignoreEnvironmentCheck: null} as {}) as ConfigurationOptions, logger ); }); }); it('Should throw if invalid for serviceContext.service', () => { assert.throws(() => { // we are intentionally providing an invalid configuration // thus an explicit cast is needed // tslint:disable-next-line:no-unused-expression new Configuration( ({serviceContext: {service: false}} as {}) as ConfigurationOptions, logger ); }); }); it('Should throw if invalid for serviceContext.version', () => { assert.throws(() => { // we are intentionally providing an invalid configuration // thus an explicit cast is needed // tslint:disable-next-line:no-unused-expression new Configuration( ({serviceContext: {version: true}} as {}) as ConfigurationOptions, logger );
assert.throws(() => { // we are intentionally providing an invalid configuration // thus an explicit cast is needed // tslint:disable-next-line:no-unused-expression new Configuration( ({ reportUnhandledRejections: 'INVALID', } as {}) as ConfigurationOptions, logger ); }); }); it('Should not throw given an empty object for serviceContext', () => { assert.doesNotThrow(() => { // tslint:disable-next-line:no-unused-expression new Configuration({serviceContext: {}}, logger); }); }); }); describe('Configuration resource aquisition', () => { before(() => { sterilizeConfigEnv(); }); describe('project id from configuration instance', () => { const pi = 'test'; let c: Configuration; before(() => { c = new Configuration({projectId: pi}, logger); }); after(() => { nock.cleanAll(); }); it('Should return the project id', () => { assert.strictEqual(c.getProjectId(), pi); }); }); describe('project number from configuration instance', () => { const pn = 1234; let c: Configuration; before(() => { sterilizeConfigEnv(); c = new Configuration( ({projectId: pn} as {}) as ConfigurationOptions, logger ); }); after(() => { nock.cleanAll(); sterilizeConfigEnv(); }); it('Should return the project number', () => { assert.strictEqual(c.getProjectId(), pn.toString()); }); }); }); describe('Exception behaviour', () => { describe('While lacking a project id', () => { let c: Configuration; before(() => { sterilizeConfigEnv(); createDeadMetadataService(); c = new Configuration(undefined, logger); }); after(() => { nock.cleanAll(); sterilizeConfigEnv(); }); it('Should return null', () => { assert.strictEqual(c.getProjectId(), null); }); }); describe('Invalid type for projectId in runtime config', () => { let c: Configuration; before(() => { sterilizeConfigEnv(); createDeadMetadataService(); // we are intentionally providing an invalid configuration // thus an explicit cast is needed c = new Configuration( ({projectId: null} as {}) as ConfigurationOptions, logger ); }); after(() => { nock.cleanAll(); sterilizeConfigEnv(); }); it('Should return null', () => { assert.strictEqual(c.getProjectId(), null); }); }); }); describe('Resource aquisition', () => { after(() => { /* * !! IMPORTANT !! * THE restoreConfigEnv FUNCTION SHOULD BE CALLED LAST AS THIS TEST FILE * EXITS AND SHOULD THEREFORE BE THE LAST THING TO EXECUTE FROM THIS * FILE. * !! IMPORTANT !! */ restoreConfigEnv(); }); describe('via env', () => { before(() => { sterilizeConfigEnv(); }); afterEach(() => { sterilizeConfigEnv(); }); describe('no longer tests env itself', () => { let c: Configuration; const projectId = 'test-xyz'; before(() => { process.env.GCLOUD_PROJECT = projectId; c = new Configuration(undefined, logger); }); it('Should assign', () => { assert.strictEqual(c.getProjectId(), null); }); }); describe('serviceContext', () => { let c: Configuration; const projectId = 'test-abc'; const serviceContext = { service: 'test', version: '1.x', }; before(() => { process.env.GCLOUD_PROJECT = projectId; process.env.GAE_MODULE_NAME = serviceContext.service; process.env.GAE_MODULE_VERSION = serviceContext.version; c = new Configuration(undefined, logger); }); it('Should assign', () => { deepStrictEqual(c.getServiceContext(), serviceContext); }); }); }); describe('via runtime configuration', () => { before(() => { sterilizeConfigEnv(); }); describe('serviceContext', () => { let c: Configuration; const projectId = 'xyz123'; const serviceContext = { service: 'evaluation', version: '2.x', }; before(() => { c = new Configuration({ projectId, serviceContext, }); }); it('Should assign', () => { deepStrictEqual(c.getServiceContext(), serviceContext); }); }); describe('api key', () => { let c: Configuration; const projectId = '987abc'; const key = '1337-api-key'; before(() => { c = new Configuration( { key, projectId, }, logger ); }); it('Should assign', () => { assert.strictEqual(c.getKey(), key); }); }); describe('reportUnhandledRejections', () => { let c: Configuration; const reportRejections = false; before(() => { c = new Configuration({ reportUnhandledRejections: reportRejections, }); }); it('Should assign', () => { assert.strictEqual( c.getReportUnhandledRejections(), reportRejections ); }); }); }); }); }); });
}); }); it('Should throw if invalid for reportUnhandledRejections', () => {
context.rs
// 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. //! SessionContext contains methods for registering data sources and executing queries use crate::{ catalog::{ catalog::{CatalogList, MemoryCatalogList}, information_schema::CatalogWithInformationSchema, }, datasource::listing::{ListingOptions, ListingTable}, datasource::{ file_format::{ avro::{AvroFormat, DEFAULT_AVRO_EXTENSION}, csv::{CsvFormat, DEFAULT_CSV_EXTENSION}, json::{JsonFormat, DEFAULT_JSON_EXTENSION}, parquet::{ParquetFormat, DEFAULT_PARQUET_EXTENSION}, FileFormat, }, MemTable, }, logical_plan::{PlanType, ToStringifiedPlan}, optimizer::eliminate_filter::EliminateFilter, optimizer::eliminate_limit::EliminateLimit, physical_optimizer::{ aggregate_statistics::AggregateStatistics, hash_build_probe_order::HashBuildProbeOrder, optimizer::PhysicalOptimizerRule, }, }; use log::{debug, trace}; use parking_lot::RwLock; use std::string::String; use std::sync::Arc; use std::{ collections::{HashMap, HashSet}, fmt::Debug, }; use arrow::datatypes::{DataType, SchemaRef}; use crate::catalog::{ catalog::{CatalogProvider, MemoryCatalogProvider}, schema::{MemorySchemaProvider, SchemaProvider}, ResolvedTableReference, TableReference, }; use crate::dataframe::DataFrame; use crate::datasource::listing::ListingTableConfig; use crate::datasource::TableProvider; use crate::error::{DataFusionError, Result}; use crate::logical_plan::{ CreateCatalog, CreateCatalogSchema, CreateExternalTable, CreateMemoryTable, DropTable, FunctionRegistry, LogicalPlan, LogicalPlanBuilder, UNNAMED_TABLE, }; use crate::optimizer::common_subexpr_eliminate::CommonSubexprEliminate; use crate::optimizer::filter_push_down::FilterPushDown; use crate::optimizer::limit_push_down::LimitPushDown; use crate::optimizer::optimizer::OptimizerRule; use crate::optimizer::projection_push_down::ProjectionPushDown; use crate::optimizer::simplify_expressions::SimplifyExpressions; use crate::optimizer::single_distinct_to_groupby::SingleDistinctToGroupBy; use crate::optimizer::to_approx_perc::ToApproxPerc; use crate::physical_optimizer::coalesce_batches::CoalesceBatches; use crate::physical_optimizer::merge_exec::AddCoalescePartitionsExec; use crate::physical_optimizer::repartition::Repartition; use crate::execution::runtime_env::{RuntimeConfig, RuntimeEnv}; use crate::logical_plan::plan::Explain; use crate::physical_plan::file_format::{plan_to_csv, plan_to_json, plan_to_parquet}; use crate::physical_plan::planner::DefaultPhysicalPlanner; use crate::physical_plan::udaf::AggregateUDF; use crate::physical_plan::udf::ScalarUDF; use crate::physical_plan::ExecutionPlan; use crate::physical_plan::PhysicalPlanner; use crate::sql::{ parser::{DFParser, FileType}, planner::{ContextProvider, SqlToRel}, }; use crate::variable::{VarProvider, VarType}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use parquet::file::properties::WriterProperties; use uuid::Uuid; use super::options::{ AvroReadOptions, CsvReadOptions, NdJsonReadOptions, ParquetReadOptions, }; /// The default catalog name - this impacts what SQL queries use if not specified const DEFAULT_CATALOG: &str = "datafusion"; /// The default schema name - this impacts what SQL queries use if not specified const DEFAULT_SCHEMA: &str = "public"; /// SessionContext is the main interface for executing queries with DataFusion. It stands for /// the connection between user and DataFusion/Ballista cluster. /// The context provides the following functionality /// /// * Create DataFrame from a CSV or Parquet data source. /// * Register a CSV or Parquet data source as a table that can be referenced from a SQL query. /// * Register a custom data source that can be referenced from a SQL query. /// * Execution a SQL query /// /// The following example demonstrates how to use the context to execute a query against a CSV /// data source using the DataFrame API: /// /// ``` /// use datafusion::prelude::*; /// # use datafusion::error::Result; /// # #[tokio::main] /// # async fn main() -> Result<()> { /// let ctx = SessionContext::new(); /// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new()).await?; /// let df = df.filter(col("a").lt_eq(col("b")))? /// .aggregate(vec![col("a")], vec![min(col("b"))])? /// .limit(100)?; /// let results = df.collect(); /// # Ok(()) /// # } /// ``` /// /// The following example demonstrates how to execute the same query using SQL: /// /// ``` /// use datafusion::prelude::*; /// /// # use datafusion::error::Result; /// # #[tokio::main] /// # async fn main() -> Result<()> { /// let mut ctx = SessionContext::new(); /// ctx.register_csv("example", "tests/example.csv", CsvReadOptions::new()).await?; /// let results = ctx.sql("SELECT a, MIN(b) FROM example GROUP BY a LIMIT 100").await?; /// # Ok(()) /// # } /// ``` #[derive(Clone)] pub struct SessionContext { /// Uuid for the session session_id: String, /// Session start time pub session_start_time: DateTime<Utc>, /// Shared session state for the session pub state: Arc<RwLock<SessionState>>, } impl Default for SessionContext { fn default() -> Self { Self::new() } } impl SessionContext { /// Creates a new execution context using a default session configuration. pub fn new() -> Self { Self::with_config(SessionConfig::new()) } /// Creates a new session context using the provided session configuration. pub fn with_config(config: SessionConfig) -> Self { let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap()); Self::with_config_rt(config, runtime) } /// Creates a new session context using the provided configuration and RuntimeEnv. pub fn with_config_rt(config: SessionConfig, runtime: Arc<RuntimeEnv>) -> Self { let state = SessionState::with_config_rt(config, runtime); Self { session_id: state.session_id.clone(), session_start_time: chrono::Utc::now(), state: Arc::new(RwLock::new(state)), } } /// Creates a new session context using the provided session state. pub fn with_state(state: SessionState) -> Self { Self { session_id: state.session_id.clone(), session_start_time: chrono::Utc::now(), state: Arc::new(RwLock::new(state)), } } /// Return the [RuntimeEnv] used to run queries with this [SessionContext] pub fn runtime_env(&self) -> Arc<RuntimeEnv> { self.state.read().runtime_env.clone() } /// Return the session_id of this Session pub fn session_id(&self) -> String { self.session_id.clone() } /// Return a copied version of config for this Session pub fn copied_config(&self) -> SessionConfig { self.state.read().config.clone() } /// Creates a dataframe that will execute a SQL query. /// /// This method is `async` because queries of type `CREATE EXTERNAL TABLE` /// might require the schema to be inferred. pub async fn sql(&self, sql: &str) -> Result<Arc<DataFrame>> { let plan = self.create_logical_plan(sql)?; match plan { LogicalPlan::CreateExternalTable(CreateExternalTable { ref schema, ref name, ref location, ref file_type, ref has_header, ref delimiter, ref table_partition_cols, ref if_not_exists, }) => { let (file_format, file_extension) = match file_type { FileType::CSV => ( Arc::new( CsvFormat::default() .with_has_header(*has_header) .with_delimiter(*delimiter as u8), ) as Arc<dyn FileFormat>, DEFAULT_CSV_EXTENSION, ), FileType::Parquet => ( Arc::new(ParquetFormat::default()) as Arc<dyn FileFormat>, DEFAULT_PARQUET_EXTENSION, ), FileType::Avro => ( Arc::new(AvroFormat::default()) as Arc<dyn FileFormat>, DEFAULT_AVRO_EXTENSION, ), FileType::NdJson => ( Arc::new(JsonFormat::default()) as Arc<dyn FileFormat>, DEFAULT_JSON_EXTENSION, ), }; let table = self.table(name.as_str()); match (if_not_exists, table) { (true, Ok(_)) => { let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (_, Err(_)) => { // TODO make schema in CreateExternalTable optional instead of empty let provided_schema = if schema.fields().is_empty() { None } else { Some(Arc::new(schema.as_ref().to_owned().into())) }; let options = ListingOptions { format: file_format, collect_stat: false, file_extension: file_extension.to_owned(), target_partitions: self.copied_config().target_partitions, table_partition_cols: table_partition_cols.clone(), }; self.register_listing_table( name, location, options, provided_schema, ) .await?; let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (false, Ok(_)) => Err(DataFusionError::Execution(format!( "Table '{:?}' already exists", name ))), } } LogicalPlan::CreateMemoryTable(CreateMemoryTable { name, input, if_not_exists, }) => { let table = self.table(name.as_str()); match (if_not_exists, table) { (true, Ok(_)) => { let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (_, Err(_)) => { let plan = self.optimize(&input)?; let physical = Arc::new(DataFrame::new(self.state.clone(), &plan)); let batches: Vec<_> = physical.collect_partitioned().await?; let table = Arc::new(MemTable::try_new( Arc::new(plan.schema().as_ref().into()), batches, )?); self.register_table(name.as_str(), table)?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (false, Ok(_)) => Err(DataFusionError::Execution(format!( "Table '{:?}' already exists", name ))), } } LogicalPlan::DropTable(DropTable { name, if_exists, .. }) => { let returned = self.deregister_table(name.as_str())?; if !if_exists && returned.is_none() { Err(DataFusionError::Execution(format!( "Memory table {:?} doesn't exist.", name ))) } else { let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } } LogicalPlan::CreateCatalogSchema(CreateCatalogSchema { schema_name, if_not_exists, .. }) => { // sqlparser doesnt accept database / catalog as parameter to CREATE SCHEMA // so for now, we default to default catalog let tokens: Vec<&str> = schema_name.split('.').collect(); let (catalog, schema_name) = match tokens.len() { 1 => Ok((DEFAULT_CATALOG, schema_name.as_str())), 2 => Ok((tokens[0], tokens[1])), _ => Err(DataFusionError::Execution(format!( "Unable to parse catalog from {}", schema_name ))), }?; let catalog = self.catalog(catalog).ok_or_else(|| { DataFusionError::Execution(format!( "Missing '{}' catalog", DEFAULT_CATALOG )) })?; let schema = catalog.schema(schema_name); match (if_not_exists, schema) { (true, Some(_)) => { let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (true, None) | (false, None) => { let schema = Arc::new(MemorySchemaProvider::new()); catalog.register_schema(schema_name, schema)?; let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (false, Some(_)) => Err(DataFusionError::Execution(format!( "Schema '{:?}' already exists", schema_name ))), } } LogicalPlan::CreateCatalog(CreateCatalog { catalog_name, if_not_exists, .. }) => { let catalog = self.catalog(catalog_name.as_str()); match (if_not_exists, catalog) { (true, Some(_)) => { let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (true, None) | (false, None) => { let new_catalog = Arc::new(MemoryCatalogProvider::new()); self.state .write() .catalog_list .register_catalog(catalog_name, new_catalog); let plan = LogicalPlanBuilder::empty(false).build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } (false, Some(_)) => Err(DataFusionError::Execution(format!( "Catalog '{:?}' already exists", catalog_name ))), } } plan => Ok(Arc::new(DataFrame::new( self.state.clone(), &self.optimize(&plan)?, ))), } } /// Creates a logical plan. /// /// This function is intended for internal use and should not be called directly. pub fn create_logical_plan(&self, sql: &str) -> Result<LogicalPlan> { let mut statements = DFParser::parse_sql(sql)?; if statements.len() != 1 { return Err(DataFusionError::NotImplemented( "The context currently only supports a single SQL statement".to_string(), )); } // create a query planner let state = self.state.read().clone(); let query_planner = SqlToRel::new(&state); query_planner.statement_to_plan(statements.pop_front().unwrap()) } /// Registers a variable provider within this context. pub fn register_variable( &mut self, variable_type: VarType, provider: Arc<dyn VarProvider + Send + Sync>, ) { self.state .write() .execution_props .add_var_provider(variable_type, provider); } /// Registers a scalar UDF within this context. /// /// Note in SQL queries, function names are looked up using /// lowercase unless the query uses quotes. For example, /// /// `SELECT MY_FUNC(x)...` will look for a function named `"my_func"` /// `SELECT "my_FUNC"(x)` will look for a function named `"my_FUNC"` pub fn register_udf(&mut self, f: ScalarUDF) { self.state .write() .scalar_functions .insert(f.name.clone(), Arc::new(f)); } /// Registers an aggregate UDF within this context. /// /// Note in SQL queries, aggregate names are looked up using /// lowercase unless the query uses quotes. For example, /// /// `SELECT MY_UDAF(x)...` will look for an aggregate named `"my_udaf"` /// `SELECT "my_UDAF"(x)` will look for an aggregate named `"my_UDAF"` pub fn register_udaf(&mut self, f: AggregateUDF) { self.state .write() .aggregate_functions .insert(f.name.clone(), Arc::new(f)); } /// Creates a DataFrame for reading an Avro data source. pub async fn read_avro( &self, uri: impl Into<String>, options: AvroReadOptions<'_>, ) -> Result<Arc<DataFrame>> { let uri: String = uri.into(); let (object_store, path) = self.runtime_env().object_store(&uri)?; let target_partitions = self.copied_config().target_partitions; Ok(Arc::new(DataFrame::new( self.state.clone(), &LogicalPlanBuilder::scan_avro( object_store, path, options, None, target_partitions, ) .await? .build()?, ))) } /// Creates a DataFrame for reading an Json data source. pub async fn read_json( &mut self, uri: impl Into<String>, options: NdJsonReadOptions<'_>, ) -> Result<Arc<DataFrame>> { let uri: String = uri.into(); let (object_store, path) = self.runtime_env().object_store(&uri)?; let target_partitions = self.copied_config().target_partitions; Ok(Arc::new(DataFrame::new( self.state.clone(), &LogicalPlanBuilder::scan_json( object_store, path, options, None, target_partitions, ) .await? .build()?, ))) } /// Creates an empty DataFrame. pub fn read_empty(&self) -> Result<Arc<DataFrame>> { Ok(Arc::new(DataFrame::new( self.state.clone(), &LogicalPlanBuilder::empty(true).build()?, ))) } /// Creates a DataFrame for reading a CSV data source. pub async fn read_csv( &self, uri: impl Into<String>, options: CsvReadOptions<'_>, ) -> Result<Arc<DataFrame>> { let uri: String = uri.into(); let (object_store, path) = self.runtime_env().object_store(&uri)?; let target_partitions = self.copied_config().target_partitions; Ok(Arc::new(DataFrame::new( self.state.clone(), &LogicalPlanBuilder::scan_csv( object_store, path, options, None, target_partitions, ) .await? .build()?, ))) } /// Creates a DataFrame for reading a Parquet data source. pub async fn read_parquet( &self, uri: impl Into<String>, options: ParquetReadOptions<'_>, ) -> Result<Arc<DataFrame>> { let uri: String = uri.into(); let (object_store, path) = self.runtime_env().object_store(&uri)?; let target_partitions = self.copied_config().target_partitions; let logical_plan = LogicalPlanBuilder::scan_parquet( object_store, path, options, None, target_partitions, ) .await? .build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &logical_plan))) } /// Creates a DataFrame for reading a custom TableProvider. pub fn read_table(&self, provider: Arc<dyn TableProvider>) -> Result<Arc<DataFrame>> { Ok(Arc::new(DataFrame::new( self.state.clone(), &LogicalPlanBuilder::scan(UNNAMED_TABLE, provider, None)?.build()?, ))) } /// Registers a table that uses the listing feature of the object store to /// find the files to be processed /// This is async because it might need to resolve the schema. pub async fn register_listing_table<'a>( &'a self, name: &'a str, uri: &'a str, options: ListingOptions, provided_schema: Option<SchemaRef>, ) -> Result<()> { let (object_store, path) = self.runtime_env().object_store(uri)?; let resolved_schema = match provided_schema { None => { options .infer_schema(Arc::clone(&object_store), path) .await? } Some(s) => s, }; let config = ListingTableConfig::new(object_store, path) .with_listing_options(options) .with_schema(resolved_schema); let table = ListingTable::try_new(config)?; self.register_table(name, Arc::new(table))?; Ok(()) } /// Registers a CSV data source so that it can be referenced from SQL statements /// executed against this context. pub async fn register_csv( &self, name: &str, uri: &str, options: CsvReadOptions<'_>, ) -> Result<()> { let listing_options = options.to_listing_options(self.copied_config().target_partitions); self.register_listing_table( name, uri, listing_options, options.schema.map(|s| Arc::new(s.to_owned())), ) .await?; Ok(()) } // Registers a Json data source so that it can be referenced from SQL statements /// executed against this context. pub async fn register_json( &self, name: &str, uri: &str, options: NdJsonReadOptions<'_>, ) -> Result<()> { let listing_options = options.to_listing_options(self.copied_config().target_partitions); self.register_listing_table(name, uri, listing_options, options.schema) .await?; Ok(()) } /// Registers a Parquet data source so that it can be referenced from SQL statements /// executed against this context. pub async fn register_parquet( &self, name: &str, uri: &str, options: ParquetReadOptions<'_>, ) -> Result<()> { let (target_partitions, parquet_pruning) = { let conf = self.copied_config(); (conf.target_partitions, conf.parquet_pruning) }; let listing_options = options .parquet_pruning(parquet_pruning) .to_listing_options(target_partitions); self.register_listing_table(name, uri, listing_options, None) .await?; Ok(()) } /// Registers an Avro data source so that it can be referenced from SQL statements /// executed against this context. pub async fn register_avro( &self, name: &str, uri: &str, options: AvroReadOptions<'_>, ) -> Result<()> { let listing_options = options.to_listing_options(self.copied_config().target_partitions); self.register_listing_table(name, uri, listing_options, options.schema) .await?; Ok(()) } /// Registers a named catalog using a custom `CatalogProvider` so that /// it can be referenced from SQL statements executed against this /// context. /// /// Returns the `CatalogProvider` previously registered for this /// name, if any pub fn register_catalog( &self, name: impl Into<String>, catalog: Arc<dyn CatalogProvider>, ) -> Option<Arc<dyn CatalogProvider>> { let name = name.into(); let information_schema = self.copied_config().information_schema; let state = self.state.read(); let catalog = if information_schema { Arc::new(CatalogWithInformationSchema::new( Arc::downgrade(&state.catalog_list), catalog, )) } else { catalog }; state.catalog_list.register_catalog(name, catalog) } /// Retrieves a `CatalogProvider` instance by name pub fn catalog(&self, name: &str) -> Option<Arc<dyn CatalogProvider>> { self.state.read().catalog_list.catalog(name) } /// Registers a table using a custom `TableProvider` so that /// it can be referenced from SQL statements executed against this /// context. /// /// Returns the `TableProvider` previously registered for this /// reference, if any pub fn register_table<'a>( &'a self, table_ref: impl Into<TableReference<'a>>, provider: Arc<dyn TableProvider>, ) -> Result<Option<Arc<dyn TableProvider>>> { let table_ref = table_ref.into(); self.state .read() .schema_for_ref(table_ref)? .register_table(table_ref.table().to_owned(), provider) } /// Deregisters the given table. /// /// Returns the registered provider, if any pub fn deregister_table<'a>( &'a self, table_ref: impl Into<TableReference<'a>>, ) -> Result<Option<Arc<dyn TableProvider>>> { let table_ref = table_ref.into(); self.state .read() .schema_for_ref(table_ref)? .deregister_table(table_ref.table()) } /// Check whether the given table exists in the schema provider or not /// Returns true if the table exists. pub fn table_exist<'a>( &'a self, table_ref: impl Into<TableReference<'a>>, ) -> Result<bool> { let table_ref = table_ref.into(); Ok(self .state .read() .schema_for_ref(table_ref)? .table_exist(table_ref.table())) } /// Retrieves a DataFrame representing a table previously registered by calling the /// register_table function. /// /// Returns an error if no table has been registered with the provided reference. pub fn table<'a>( &self, table_ref: impl Into<TableReference<'a>>, ) -> Result<Arc<DataFrame>> { let table_ref = table_ref.into(); let schema = self.state.read().schema_for_ref(table_ref)?; match schema.table(table_ref.table()) { Some(ref provider) => { let plan = LogicalPlanBuilder::scan( table_ref.table(), Arc::clone(provider), None, )? .build()?; Ok(Arc::new(DataFrame::new(self.state.clone(), &plan))) } _ => Err(DataFusionError::Plan(format!( "No table named '{}'", table_ref.table() ))), } } /// Returns the set of available tables in the default catalog and schema. /// /// Use [`table`] to get a specific table. /// /// [`table`]: SessionContext::table #[deprecated( note = "Please use the catalog provider interface (`SessionContext::catalog`) to examine available catalogs, schemas, and tables" )] pub fn tables(&self) -> Result<HashSet<String>> { Ok(self .state .read() // a bare reference will always resolve to the default catalog and schema .schema_for_ref(TableReference::Bare { table: "" })? .table_names() .iter() .cloned() .collect()) } /// Optimizes the logical plan by applying optimizer rules. pub fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> { self.state.read().optimize(plan) } /// Creates a physical plan from a logical plan. pub async fn create_physical_plan( &self, logical_plan: &LogicalPlan, ) -> Result<Arc<dyn ExecutionPlan>> { let state_cloned = { let mut state = self.state.write(); state.execution_props.start_execution(); // We need to clone `state` to release the lock that is not `Send`. We could // make the lock `Send` by using `tokio::sync::Mutex`, but that would require to // propagate async even to the `LogicalPlan` building methods. // Cloning `state` here is fine as we then pass it as immutable `&state`, which // means that we avoid write consistency issues as the cloned version will not // be written to. As for eventual modifications that would be applied to the // original state after it has been cloned, they will not be picked up by the // clone but that is okay, as it is equivalent to postponing the state update // by keeping the lock until the end of the function scope. state.clone() }; state_cloned.create_physical_plan(logical_plan).await } /// Executes a query and writes the results to a partitioned CSV file. pub async fn write_csv( &self, plan: Arc<dyn ExecutionPlan>, path: impl AsRef<str>, ) -> Result<()> { let state = self.state.read().clone(); plan_to_csv(&state, plan, path).await } /// Executes a query and writes the results to a partitioned JSON file. pub async fn write_json( &self, plan: Arc<dyn ExecutionPlan>, path: impl AsRef<str>, ) -> Result<()> { let state = self.state.read().clone(); plan_to_json(&state, plan, path).await } /// Executes a query and writes the results to a partitioned Parquet file. pub async fn write_parquet( &self, plan: Arc<dyn ExecutionPlan>, path: impl AsRef<str>, writer_properties: Option<WriterProperties>, ) -> Result<()> { let state = self.state.read().clone(); plan_to_parquet(&state, plan, path, writer_properties).await } /// Get a new TaskContext to run in this session pub fn task_ctx(&self) -> Arc<TaskContext>
} impl FunctionRegistry for SessionContext { fn udfs(&self) -> HashSet<String> { self.state.read().udfs() } fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> { self.state.read().udf(name) } fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> { self.state.read().udaf(name) } } /// A planner used to add extensions to DataFusion logical and physical plans. #[async_trait] pub trait QueryPlanner { /// Given a `LogicalPlan`, create an `ExecutionPlan` suitable for execution async fn create_physical_plan( &self, logical_plan: &LogicalPlan, session_state: &SessionState, ) -> Result<Arc<dyn ExecutionPlan>>; } /// The query planner used if no user defined planner is provided struct DefaultQueryPlanner {} #[async_trait] impl QueryPlanner for DefaultQueryPlanner { /// Given a `LogicalPlan`, create an `ExecutionPlan` suitable for execution async fn create_physical_plan( &self, logical_plan: &LogicalPlan, session_state: &SessionState, ) -> Result<Arc<dyn ExecutionPlan>> { let planner = DefaultPhysicalPlanner::default(); planner .create_physical_plan(logical_plan, session_state) .await } } /// Session Configuration entry name for 'BATCH_SIZE' pub const BATCH_SIZE: &str = "batch_size"; /// Session Configuration entry name for 'TARGET_PARTITIONS' pub const TARGET_PARTITIONS: &str = "target_partitions"; /// Session Configuration entry name for 'REPARTITION_JOINS' pub const REPARTITION_JOINS: &str = "repartition_joins"; /// Session Configuration entry name for 'REPARTITION_AGGREGATIONS' pub const REPARTITION_AGGREGATIONS: &str = "repartition_aggregations"; /// Session Configuration entry name for 'REPARTITION_WINDOWS' pub const REPARTITION_WINDOWS: &str = "repartition_windows"; /// Session Configuration entry name for 'PARQUET_PRUNING' pub const PARQUET_PRUNING: &str = "parquet_pruning"; /// Configuration options for session context #[derive(Clone)] pub struct SessionConfig { /// Default batch size while creating new batches, it's especially useful /// for buffer-in-memory batches since creating tiny batches would results /// in too much metadata memory consumption. pub batch_size: usize, /// Number of partitions for query execution. Increasing partitions can increase concurrency. pub target_partitions: usize, /// Default catalog name for table resolution default_catalog: String, /// Default schema name for table resolution default_schema: String, /// Whether the default catalog and schema should be created automatically create_default_catalog_and_schema: bool, /// Should DataFusion provide access to `information_schema` /// virtual tables for displaying schema information information_schema: bool, /// Should DataFusion repartition data using the join keys to execute joins in parallel /// using the provided `target_partitions` level pub repartition_joins: bool, /// Should DataFusion repartition data using the aggregate keys to execute aggregates in parallel /// using the provided `target_partitions` level pub repartition_aggregations: bool, /// Should DataFusion repartition data using the partition keys to execute window functions in /// parallel using the provided `target_partitions` level pub repartition_windows: bool, /// Should DataFusion parquet reader using the predicate to prune data pub parquet_pruning: bool, } impl Default for SessionConfig { fn default() -> Self { Self { batch_size: 8192, target_partitions: num_cpus::get(), default_catalog: DEFAULT_CATALOG.to_owned(), default_schema: DEFAULT_SCHEMA.to_owned(), create_default_catalog_and_schema: true, information_schema: false, repartition_joins: true, repartition_aggregations: true, repartition_windows: true, parquet_pruning: true, } } } impl SessionConfig { /// Create an execution config with default setting pub fn new() -> Self { Default::default() } /// Customize batch size pub fn with_batch_size(mut self, n: usize) -> Self { // batch size must be greater than zero assert!(n > 0); self.batch_size = n; self } /// Customize target_partitions pub fn with_target_partitions(mut self, n: usize) -> Self { // partition count must be greater than zero assert!(n > 0); self.target_partitions = n; self } /// Selects a name for the default catalog and schema pub fn with_default_catalog_and_schema( mut self, catalog: impl Into<String>, schema: impl Into<String>, ) -> Self { self.default_catalog = catalog.into(); self.default_schema = schema.into(); self } /// Controls whether the default catalog and schema will be automatically created pub fn create_default_catalog_and_schema(mut self, create: bool) -> Self { self.create_default_catalog_and_schema = create; self } /// Enables or disables the inclusion of `information_schema` virtual tables pub fn with_information_schema(mut self, enabled: bool) -> Self { self.information_schema = enabled; self } /// Enables or disables the use of repartitioning for joins to improve parallelism pub fn with_repartition_joins(mut self, enabled: bool) -> Self { self.repartition_joins = enabled; self } /// Enables or disables the use of repartitioning for aggregations to improve parallelism pub fn with_repartition_aggregations(mut self, enabled: bool) -> Self { self.repartition_aggregations = enabled; self } /// Enables or disables the use of repartitioning for window functions to improve parallelism pub fn with_repartition_windows(mut self, enabled: bool) -> Self { self.repartition_windows = enabled; self } /// Enables or disables the use of pruning predicate for parquet readers to skip row groups pub fn with_parquet_pruning(mut self, enabled: bool) -> Self { self.parquet_pruning = enabled; self } /// Convert configuration to name-value pairs pub fn to_props(&self) -> HashMap<String, String> { let mut map = HashMap::new(); map.insert(BATCH_SIZE.to_owned(), format!("{}", self.batch_size)); map.insert( TARGET_PARTITIONS.to_owned(), format!("{}", self.target_partitions), ); map.insert( REPARTITION_JOINS.to_owned(), format!("{}", self.repartition_joins), ); map.insert( REPARTITION_AGGREGATIONS.to_owned(), format!("{}", self.repartition_aggregations), ); map.insert( REPARTITION_WINDOWS.to_owned(), format!("{}", self.repartition_windows), ); map.insert( PARQUET_PRUNING.to_owned(), format!("{}", self.parquet_pruning), ); map } } /// Holds per-execution properties and data (such as starting timestamps, etc). /// An instance of this struct is created each time a [`LogicalPlan`] is prepared for /// execution (optimized). If the same plan is optimized multiple times, a new /// `ExecutionProps` is created each time. /// /// It is important that this structure be cheap to create as it is /// done so during predicate pruning and expression simplification #[derive(Clone)] pub struct ExecutionProps { pub(crate) query_execution_start_time: DateTime<Utc>, /// providers for scalar variables pub var_providers: Option<HashMap<VarType, Arc<dyn VarProvider + Send + Sync>>>, } impl Default for ExecutionProps { fn default() -> Self { Self::new() } } impl ExecutionProps { /// Creates a new execution props pub fn new() -> Self { ExecutionProps { query_execution_start_time: chrono::Utc::now(), var_providers: None, } } /// Marks the execution of query started timestamp pub fn start_execution(&mut self) -> &Self { self.query_execution_start_time = chrono::Utc::now(); &*self } /// Registers a variable provider, returning the existing /// provider, if any pub fn add_var_provider( &mut self, var_type: VarType, provider: Arc<dyn VarProvider + Send + Sync>, ) -> Option<Arc<dyn VarProvider + Send + Sync>> { let mut var_providers = self.var_providers.take().unwrap_or_default(); let old_provider = var_providers.insert(var_type, provider); self.var_providers = Some(var_providers); old_provider } /// Returns the provider for the var_type, if any pub fn get_var_provider( &self, var_type: VarType, ) -> Option<Arc<dyn VarProvider + Send + Sync>> { self.var_providers .as_ref() .and_then(|var_providers| var_providers.get(&var_type).map(Arc::clone)) } } /// Execution context for registering data sources and executing queries #[derive(Clone)] pub struct SessionState { /// Uuid for the session pub session_id: String, /// Responsible for optimizing a logical plan pub optimizers: Vec<Arc<dyn OptimizerRule + Send + Sync>>, /// Responsible for optimizing a physical execution plan pub physical_optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>, /// Responsible for planning `LogicalPlan`s, and `ExecutionPlan` pub query_planner: Arc<dyn QueryPlanner + Send + Sync>, /// Collection of catalogs containing schemas and ultimately TableProviders pub catalog_list: Arc<dyn CatalogList>, /// Scalar functions that are registered with the context pub scalar_functions: HashMap<String, Arc<ScalarUDF>>, /// Aggregate functions registered in the context pub aggregate_functions: HashMap<String, Arc<AggregateUDF>>, /// Session configuration pub config: SessionConfig, /// Execution properties pub execution_props: ExecutionProps, /// Runtime environment pub runtime_env: Arc<RuntimeEnv>, } impl Debug for SessionState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SessionState") .field("session_id", &self.session_id) // TODO should we print out more? .finish() } } /// Default session builder using the provided configuration pub fn default_session_builder(config: SessionConfig) -> SessionState { SessionState::with_config_rt( config, Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap()), ) } impl SessionState { /// Returns new SessionState using the provided configuration and runtime pub fn with_config_rt(config: SessionConfig, runtime: Arc<RuntimeEnv>) -> Self { let session_id = Uuid::new_v4().to_string(); let catalog_list = Arc::new(MemoryCatalogList::new()) as Arc<dyn CatalogList>; if config.create_default_catalog_and_schema { let default_catalog = MemoryCatalogProvider::new(); default_catalog .register_schema( &config.default_schema, Arc::new(MemorySchemaProvider::new()), ) .expect("memory catalog provider can register schema"); let default_catalog: Arc<dyn CatalogProvider> = if config.information_schema { Arc::new(CatalogWithInformationSchema::new( Arc::downgrade(&catalog_list), Arc::new(default_catalog), )) } else { Arc::new(default_catalog) }; catalog_list .register_catalog(config.default_catalog.clone(), default_catalog); } SessionState { session_id, optimizers: vec![ // Simplify expressions first to maximize the chance // of applying other optimizations Arc::new(SimplifyExpressions::new()), Arc::new(EliminateFilter::new()), Arc::new(CommonSubexprEliminate::new()), Arc::new(EliminateLimit::new()), Arc::new(ProjectionPushDown::new()), Arc::new(FilterPushDown::new()), Arc::new(LimitPushDown::new()), Arc::new(SingleDistinctToGroupBy::new()), // ToApproxPerc must be applied last because // it rewrites only the function and may interfere with // other rules Arc::new(ToApproxPerc::new()), ], physical_optimizers: vec![ Arc::new(AggregateStatistics::new()), Arc::new(HashBuildProbeOrder::new()), Arc::new(CoalesceBatches::new()), Arc::new(Repartition::new()), Arc::new(AddCoalescePartitionsExec::new()), ], query_planner: Arc::new(DefaultQueryPlanner {}), catalog_list, scalar_functions: HashMap::new(), aggregate_functions: HashMap::new(), config, execution_props: ExecutionProps::new(), runtime_env: runtime, } } fn resolve_table_ref<'a>( &'a self, table_ref: impl Into<TableReference<'a>>, ) -> ResolvedTableReference<'a> { table_ref .into() .resolve(&self.config.default_catalog, &self.config.default_schema) } fn schema_for_ref<'a>( &'a self, table_ref: impl Into<TableReference<'a>>, ) -> Result<Arc<dyn SchemaProvider>> { let resolved_ref = self.resolve_table_ref(table_ref); self.catalog_list .catalog(resolved_ref.catalog) .ok_or_else(|| { DataFusionError::Plan(format!( "failed to resolve catalog: {}", resolved_ref.catalog )) })? .schema(resolved_ref.schema) .ok_or_else(|| { DataFusionError::Plan(format!( "failed to resolve schema: {}", resolved_ref.schema )) }) } /// Replace the default query planner pub fn with_query_planner( mut self, query_planner: Arc<dyn QueryPlanner + Send + Sync>, ) -> Self { self.query_planner = query_planner; self } /// Replace the optimizer rules pub fn with_optimizer_rules( mut self, optimizers: Vec<Arc<dyn OptimizerRule + Send + Sync>>, ) -> Self { self.optimizers = optimizers; self } /// Replace the physical optimizer rules pub fn with_physical_optimizer_rules( mut self, physical_optimizers: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>, ) -> Self { self.physical_optimizers = physical_optimizers; self } /// Adds a new [`OptimizerRule`] pub fn add_optimizer_rule( mut self, optimizer_rule: Arc<dyn OptimizerRule + Send + Sync>, ) -> Self { self.optimizers.push(optimizer_rule); self } /// Adds a new [`PhysicalOptimizerRule`] pub fn add_physical_optimizer_rule( mut self, optimizer_rule: Arc<dyn PhysicalOptimizerRule + Send + Sync>, ) -> Self { self.physical_optimizers.push(optimizer_rule); self } /// Optimizes the logical plan by applying optimizer rules. pub fn optimize(&self, plan: &LogicalPlan) -> Result<LogicalPlan> { if let LogicalPlan::Explain(e) = plan { let mut stringified_plans = e.stringified_plans.clone(); // optimize the child plan, capturing the output of each optimizer let plan = self.optimize_internal(e.plan.as_ref(), |optimized_plan, optimizer| { let optimizer_name = optimizer.name().to_string(); let plan_type = PlanType::OptimizedLogicalPlan { optimizer_name }; stringified_plans.push(optimized_plan.to_stringified(plan_type)); })?; Ok(LogicalPlan::Explain(Explain { verbose: e.verbose, plan: Arc::new(plan), stringified_plans, schema: e.schema.clone(), })) } else { self.optimize_internal(plan, |_, _| {}) } } /// Optimizes the logical plan by applying optimizer rules, and /// invoking observer function after each call fn optimize_internal<F>( &self, plan: &LogicalPlan, mut observer: F, ) -> Result<LogicalPlan> where F: FnMut(&LogicalPlan, &dyn OptimizerRule), { let execution_props = &mut self.execution_props.clone(); let optimizers = &self.optimizers; let execution_props = execution_props.start_execution(); let mut new_plan = plan.clone(); debug!("Input logical plan:\n{}\n", plan.display_indent()); trace!("Full input logical plan:\n{:?}", plan); for optimizer in optimizers { new_plan = optimizer.optimize(&new_plan, execution_props)?; observer(&new_plan, optimizer.as_ref()); } debug!("Optimized logical plan:\n{}\n", new_plan.display_indent()); trace!("Full Optimized logical plan:\n {:?}", plan); Ok(new_plan) } /// Creates a physical plan from a logical plan. pub async fn create_physical_plan( &self, logical_plan: &LogicalPlan, ) -> Result<Arc<dyn ExecutionPlan>> { let planner = self.query_planner.clone(); planner.create_physical_plan(logical_plan, self).await } } impl ContextProvider for SessionState { fn get_table_provider(&self, name: TableReference) -> Option<Arc<dyn TableProvider>> { let resolved_ref = self.resolve_table_ref(name); let schema = self.schema_for_ref(resolved_ref).ok()?; schema.table(resolved_ref.table) } fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> { self.scalar_functions.get(name).cloned() } fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>> { self.aggregate_functions.get(name).cloned() } fn get_variable_type(&self, variable_names: &[String]) -> Option<DataType> { if variable_names.is_empty() { return None; } let provider_type = if &variable_names[0][0..2] == "@@" { VarType::System } else { VarType::UserDefined }; self.execution_props .var_providers .as_ref() .and_then(|provider| provider.get(&provider_type)?.get_type(variable_names)) } } impl FunctionRegistry for SessionState { fn udfs(&self) -> HashSet<String> { self.scalar_functions.keys().cloned().collect() } fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> { let result = self.scalar_functions.get(name); result.cloned().ok_or_else(|| { DataFusionError::Plan(format!( "There is no UDF named \"{}\" in the registry", name )) }) } fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> { let result = self.aggregate_functions.get(name); result.cloned().ok_or_else(|| { DataFusionError::Plan(format!( "There is no UDAF named \"{}\" in the registry", name )) }) } } /// Task Context Properties pub enum TaskProperties { ///SessionConfig SessionConfig(SessionConfig), /// Name-value pairs of task properties KVPairs(HashMap<String, String>), } /// Task Execution Context pub struct TaskContext { /// Session Id session_id: String, /// Optional Task Identify task_id: Option<String>, /// Task properties properties: TaskProperties, /// Scalar functions associated with this task context scalar_functions: HashMap<String, Arc<ScalarUDF>>, /// Aggregate functions associated with this task context aggregate_functions: HashMap<String, Arc<AggregateUDF>>, /// Runtime environment associated with this task context runtime: Arc<RuntimeEnv>, } impl TaskContext { /// Create a new task context instance pub fn new( task_id: String, session_id: String, task_props: HashMap<String, String>, scalar_functions: HashMap<String, Arc<ScalarUDF>>, aggregate_functions: HashMap<String, Arc<AggregateUDF>>, runtime: Arc<RuntimeEnv>, ) -> Self { Self { task_id: Some(task_id), session_id, properties: TaskProperties::KVPairs(task_props), scalar_functions, aggregate_functions, runtime, } } /// Return the SessionConfig associated with the Task pub fn session_config(&self) -> SessionConfig { let task_props = &self.properties; match task_props { TaskProperties::KVPairs(props) => { let session_config = SessionConfig::new(); if props.is_empty() { session_config } else { session_config .with_batch_size(props.get(BATCH_SIZE).unwrap().parse().unwrap()) .with_target_partitions( props.get(TARGET_PARTITIONS).unwrap().parse().unwrap(), ) .with_repartition_joins( props.get(REPARTITION_JOINS).unwrap().parse().unwrap(), ) .with_repartition_aggregations( props .get(REPARTITION_AGGREGATIONS) .unwrap() .parse() .unwrap(), ) .with_repartition_windows( props.get(REPARTITION_WINDOWS).unwrap().parse().unwrap(), ) .with_parquet_pruning( props.get(PARQUET_PRUNING).unwrap().parse().unwrap(), ) } } TaskProperties::SessionConfig(session_config) => session_config.clone(), } } /// Return the session_id of this [TaskContext] pub fn session_id(&self) -> String { self.session_id.clone() } /// Return the task_id of this [TaskContext] pub fn task_id(&self) -> Option<String> { self.task_id.clone() } /// Return the [RuntimeEnv] associated with this [TaskContext] pub fn runtime_env(&self) -> Arc<RuntimeEnv> { self.runtime.clone() } } /// Create a new task context instance from SessionContext impl From<&SessionContext> for TaskContext { fn from(session: &SessionContext) -> Self { let session_id = session.session_id.clone(); let (config, scalar_functions, aggregate_functions) = { let session_state = session.state.read(); ( session_state.config.clone(), session_state.scalar_functions.clone(), session_state.aggregate_functions.clone(), ) }; let runtime = session.runtime_env(); Self { task_id: None, session_id, properties: TaskProperties::SessionConfig(config), scalar_functions, aggregate_functions, runtime, } } } /// Create a new task context instance from SessionState impl From<&SessionState> for TaskContext { fn from(state: &SessionState) -> Self { let session_id = state.session_id.clone(); let config = state.config.clone(); let scalar_functions = state.scalar_functions.clone(); let aggregate_functions = state.aggregate_functions.clone(); let runtime = state.runtime_env.clone(); Self { task_id: None, session_id, properties: TaskProperties::SessionConfig(config), scalar_functions, aggregate_functions, runtime, } } } impl FunctionRegistry for TaskContext { fn udfs(&self) -> HashSet<String> { self.scalar_functions.keys().cloned().collect() } fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> { let result = self.scalar_functions.get(name); result.cloned().ok_or_else(|| { DataFusionError::Internal(format!( "There is no UDF named \"{}\" in the TaskContext", name )) }) } fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> { let result = self.aggregate_functions.get(name); result.cloned().ok_or_else(|| { DataFusionError::Internal(format!( "There is no UDAF named \"{}\" in the TaskContext", name )) }) } } #[cfg(test)] mod tests { use super::*; use crate::execution::context::QueryPlanner; use crate::from_slice::FromSlice; use crate::logical_plan::{binary_expr, lit, Operator}; use crate::physical_plan::functions::make_scalar_function; use crate::test; use crate::variable::VarType; use crate::{ assert_batches_eq, assert_batches_sorted_eq, logical_plan::{col, create_udf, sum, Expr}, }; use crate::{ datasource::MemTable, logical_plan::create_udaf, physical_plan::expressions::AvgAccumulator, }; use arrow::array::{ Array, ArrayRef, DictionaryArray, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, LargeStringArray, UInt16Array, UInt32Array, UInt64Array, UInt8Array, }; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use async_trait::async_trait; use datafusion_expr::Volatility; use std::fs::File; use std::sync::Weak; use std::thread::{self, JoinHandle}; use std::{io::prelude::*, sync::Mutex}; use tempfile::TempDir; #[tokio::test] async fn shared_memory_and_disk_manager() { // Demonstrate the ability to share DiskManager and // MemoryManager between two different executions. let ctx1 = SessionContext::new(); // configure with same memory / disk manager let memory_manager = ctx1.runtime_env().memory_manager.clone(); let disk_manager = ctx1.runtime_env().disk_manager.clone(); let ctx2 = SessionContext::with_config_rt(SessionConfig::new(), ctx1.runtime_env()); assert!(std::ptr::eq( Arc::as_ptr(&memory_manager), Arc::as_ptr(&ctx1.runtime_env().memory_manager) )); assert!(std::ptr::eq( Arc::as_ptr(&memory_manager), Arc::as_ptr(&ctx2.runtime_env().memory_manager) )); assert!(std::ptr::eq( Arc::as_ptr(&disk_manager), Arc::as_ptr(&ctx1.runtime_env().disk_manager) )); assert!(std::ptr::eq( Arc::as_ptr(&disk_manager), Arc::as_ptr(&ctx2.runtime_env().disk_manager) )); } #[tokio::test] async fn create_variable_expr() -> Result<()> { let tmp_dir = TempDir::new()?; let partition_count = 4; let mut ctx = create_ctx(&tmp_dir, partition_count).await?; let variable_provider = test::variable::SystemVar::new(); ctx.register_variable(VarType::System, Arc::new(variable_provider)); let variable_provider = test::variable::UserDefinedVar::new(); ctx.register_variable(VarType::UserDefined, Arc::new(variable_provider)); let provider = test::create_table_dual(); ctx.register_table("dual", provider)?; let results = plan_and_collect(&ctx, "SELECT @@version, @name, @integer + 1 FROM dual") .await?; let expected = vec![ "+----------------------+------------------------+------------------------+", "| @@version | @name | @integer Plus Int64(1) |", "+----------------------+------------------------+------------------------+", "| system-var-@@version | user-defined-var-@name | 42 |", "+----------------------+------------------------+------------------------+", ]; assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn register_deregister() -> Result<()> { let tmp_dir = TempDir::new()?; let partition_count = 4; let ctx = create_ctx(&tmp_dir, partition_count).await?; let provider = test::create_table_dual(); ctx.register_table("dual", provider)?; assert!(ctx.deregister_table("dual")?.is_some()); assert!(ctx.deregister_table("dual")?.is_none()); Ok(()) } #[tokio::test] async fn left_join_using() -> Result<()> { let results = execute( "SELECT t1.c1, t2.c2 FROM test t1 JOIN test t2 USING (c2) ORDER BY t2.c2", 1, ) .await?; assert_eq!(results.len(), 1); let expected = vec![ "+----+----+", "| c1 | c2 |", "+----+----+", "| 0 | 1 |", "| 0 | 2 |", "| 0 | 3 |", "| 0 | 4 |", "| 0 | 5 |", "| 0 | 6 |", "| 0 | 7 |", "| 0 | 8 |", "| 0 | 9 |", "| 0 | 10 |", "+----+----+", ]; assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn left_join_using_join_key_projection() -> Result<()> { let results = execute( "SELECT t1.c1, t1.c2, t2.c2 FROM test t1 JOIN test t2 USING (c2) ORDER BY t2.c2", 1, ) .await?; assert_eq!(results.len(), 1); let expected = vec![ "+----+----+----+", "| c1 | c2 | c2 |", "+----+----+----+", "| 0 | 1 | 1 |", "| 0 | 2 | 2 |", "| 0 | 3 | 3 |", "| 0 | 4 | 4 |", "| 0 | 5 | 5 |", "| 0 | 6 | 6 |", "| 0 | 7 | 7 |", "| 0 | 8 | 8 |", "| 0 | 9 | 9 |", "| 0 | 10 | 10 |", "+----+----+----+", ]; assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn left_join() -> Result<()> { let results = execute( "SELECT t1.c1, t1.c2, t2.c2 FROM test t1 JOIN test t2 ON t1.c2 = t2.c2 ORDER BY t1.c2", 1, ) .await?; assert_eq!(results.len(), 1); let expected = vec![ "+----+----+----+", "| c1 | c2 | c2 |", "+----+----+----+", "| 0 | 1 | 1 |", "| 0 | 2 | 2 |", "| 0 | 3 | 3 |", "| 0 | 4 | 4 |", "| 0 | 5 | 5 |", "| 0 | 6 | 6 |", "| 0 | 7 | 7 |", "| 0 | 8 | 8 |", "| 0 | 9 | 9 |", "| 0 | 10 | 10 |", "+----+----+----+", ]; assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn window() -> Result<()> { let results = execute( "SELECT \ c1, \ c2, \ SUM(c2) OVER (), \ COUNT(c2) OVER (), \ MAX(c2) OVER (), \ MIN(c2) OVER (), \ AVG(c2) OVER () \ FROM test \ ORDER BY c1, c2 \ LIMIT 5", 4, ) .await?; // result in one batch, although e.g. having 2 batches do not change // result semantics, having a len=1 assertion upfront keeps surprises // at bay assert_eq!(results.len(), 1); let expected = vec![ "+----+----+--------------+----------------+--------------+--------------+--------------+", "| c1 | c2 | SUM(test.c2) | COUNT(test.c2) | MAX(test.c2) | MIN(test.c2) | AVG(test.c2) |", "+----+----+--------------+----------------+--------------+--------------+--------------+", "| 0 | 1 | 220 | 40 | 10 | 1 | 5.5 |", "| 0 | 2 | 220 | 40 | 10 | 1 | 5.5 |", "| 0 | 3 | 220 | 40 | 10 | 1 | 5.5 |", "| 0 | 4 | 220 | 40 | 10 | 1 | 5.5 |", "| 0 | 5 | 220 | 40 | 10 | 1 | 5.5 |", "+----+----+--------------+----------------+--------------+--------------+--------------+", ]; // window function shall respect ordering assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn window_order_by() -> Result<()> { let results = execute( "SELECT \ c1, \ c2, \ ROW_NUMBER() OVER (ORDER BY c1, c2), \ FIRST_VALUE(c2) OVER (ORDER BY c1, c2), \ LAST_VALUE(c2) OVER (ORDER BY c1, c2), \ NTH_VALUE(c2, 2) OVER (ORDER BY c1, c2), \ SUM(c2) OVER (ORDER BY c1, c2), \ COUNT(c2) OVER (ORDER BY c1, c2), \ MAX(c2) OVER (ORDER BY c1, c2), \ MIN(c2) OVER (ORDER BY c1, c2), \ AVG(c2) OVER (ORDER BY c1, c2) \ FROM test \ ORDER BY c1, c2 \ LIMIT 5", 4, ) .await?; // result in one batch, although e.g. having 2 batches do not change // result semantics, having a len=1 assertion upfront keeps surprises // at bay assert_eq!(results.len(), 1); let expected = vec![ "+----+----+--------------+----------------------+---------------------+-----------------------------+--------------+----------------+--------------+--------------+--------------+", "| c1 | c2 | ROW_NUMBER() | FIRST_VALUE(test.c2) | LAST_VALUE(test.c2) | NTH_VALUE(test.c2,Int64(2)) | SUM(test.c2) | COUNT(test.c2) | MAX(test.c2) | MIN(test.c2) | AVG(test.c2) |", "+----+----+--------------+----------------------+---------------------+-----------------------------+--------------+----------------+--------------+--------------+--------------+", "| 0 | 1 | 1 | 1 | 1 | | 1 | 1 | 1 | 1 | 1 |", "| 0 | 2 | 2 | 1 | 2 | 2 | 3 | 2 | 2 | 1 | 1.5 |", "| 0 | 3 | 3 | 1 | 3 | 2 | 6 | 3 | 3 | 1 | 2 |", "| 0 | 4 | 4 | 1 | 4 | 2 | 10 | 4 | 4 | 1 | 2.5 |", "| 0 | 5 | 5 | 1 | 5 | 2 | 15 | 5 | 5 | 1 | 3 |", "+----+----+--------------+----------------------+---------------------+-----------------------------+--------------+----------------+--------------+--------------+--------------+", ]; // window function shall respect ordering assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn window_partition_by() -> Result<()> { let results = execute( "SELECT \ c1, \ c2, \ SUM(c2) OVER (PARTITION BY c2), \ COUNT(c2) OVER (PARTITION BY c2), \ MAX(c2) OVER (PARTITION BY c2), \ MIN(c2) OVER (PARTITION BY c2), \ AVG(c2) OVER (PARTITION BY c2) \ FROM test \ ORDER BY c1, c2 \ LIMIT 5", 4, ) .await?; let expected = vec![ "+----+----+--------------+----------------+--------------+--------------+--------------+", "| c1 | c2 | SUM(test.c2) | COUNT(test.c2) | MAX(test.c2) | MIN(test.c2) | AVG(test.c2) |", "+----+----+--------------+----------------+--------------+--------------+--------------+", "| 0 | 1 | 4 | 4 | 1 | 1 | 1 |", "| 0 | 2 | 8 | 4 | 2 | 2 | 2 |", "| 0 | 3 | 12 | 4 | 3 | 3 | 3 |", "| 0 | 4 | 16 | 4 | 4 | 4 | 4 |", "| 0 | 5 | 20 | 4 | 5 | 5 | 5 |", "+----+----+--------------+----------------+--------------+--------------+--------------+", ]; // window function shall respect ordering assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn window_partition_by_order_by() -> Result<()> { let results = execute( "SELECT \ c1, \ c2, \ ROW_NUMBER() OVER (PARTITION BY c2 ORDER BY c1), \ FIRST_VALUE(c2 + c1) OVER (PARTITION BY c2 ORDER BY c1), \ LAST_VALUE(c2 + c1) OVER (PARTITION BY c2 ORDER BY c1), \ NTH_VALUE(c2 + c1, 1) OVER (PARTITION BY c2 ORDER BY c1), \ SUM(c2) OVER (PARTITION BY c2 ORDER BY c1), \ COUNT(c2) OVER (PARTITION BY c2 ORDER BY c1), \ MAX(c2) OVER (PARTITION BY c2 ORDER BY c1), \ MIN(c2) OVER (PARTITION BY c2 ORDER BY c1), \ AVG(c2) OVER (PARTITION BY c2 ORDER BY c1) \ FROM test \ ORDER BY c1, c2 \ LIMIT 5", 4, ) .await?; let expected = vec![ "+----+----+--------------+--------------------------------+-------------------------------+---------------------------------------+--------------+----------------+--------------+--------------+--------------+", "| c1 | c2 | ROW_NUMBER() | FIRST_VALUE(test.c2 + test.c1) | LAST_VALUE(test.c2 + test.c1) | NTH_VALUE(test.c2 + test.c1,Int64(1)) | SUM(test.c2) | COUNT(test.c2) | MAX(test.c2) | MIN(test.c2) | AVG(test.c2) |", "+----+----+--------------+--------------------------------+-------------------------------+---------------------------------------+--------------+----------------+--------------+--------------+--------------+", "| 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |", "| 0 | 2 | 1 | 2 | 2 | 2 | 2 | 1 | 2 | 2 | 2 |", "| 0 | 3 | 1 | 3 | 3 | 3 | 3 | 1 | 3 | 3 | 3 |", "| 0 | 4 | 1 | 4 | 4 | 4 | 4 | 1 | 4 | 4 | 4 |", "| 0 | 5 | 1 | 5 | 5 | 5 | 5 | 1 | 5 | 5 | 5 |", "+----+----+--------------+--------------------------------+-------------------------------+---------------------------------------+--------------+----------------+--------------+--------------+--------------+", ]; // window function shall respect ordering assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_decimal_min() -> Result<()> { let ctx = SessionContext::new(); // the data type of c1 is decimal(10,3) ctx.register_table("d_table", test::table_with_decimal()) .unwrap(); let result = plan_and_collect(&ctx, "select min(c1) from d_table") .await .unwrap(); let expected = vec![ "+-----------------+", "| MIN(d_table.c1) |", "+-----------------+", "| -100.009 |", "+-----------------+", ]; assert_eq!( &DataType::Decimal(10, 3), result[0].schema().field(0).data_type() ); assert_batches_sorted_eq!(expected, &result); Ok(()) } #[tokio::test] async fn aggregate_decimal_max() -> Result<()> { let ctx = SessionContext::new(); // the data type of c1 is decimal(10,3) ctx.register_table("d_table", test::table_with_decimal()) .unwrap(); let result = plan_and_collect(&ctx, "select max(c1) from d_table") .await .unwrap(); let expected = vec![ "+-----------------+", "| MAX(d_table.c1) |", "+-----------------+", "| 110.009 |", "+-----------------+", ]; assert_eq!( &DataType::Decimal(10, 3), result[0].schema().field(0).data_type() ); assert_batches_sorted_eq!(expected, &result); Ok(()) } #[tokio::test] async fn aggregate_decimal_sum() -> Result<()> { let ctx = SessionContext::new(); // the data type of c1 is decimal(10,3) ctx.register_table("d_table", test::table_with_decimal()) .unwrap(); let result = plan_and_collect(&ctx, "select sum(c1) from d_table") .await .unwrap(); let expected = vec![ "+-----------------+", "| SUM(d_table.c1) |", "+-----------------+", "| 100.000 |", "+-----------------+", ]; assert_eq!( &DataType::Decimal(20, 3), result[0].schema().field(0).data_type() ); assert_batches_sorted_eq!(expected, &result); Ok(()) } #[tokio::test] async fn aggregate_decimal_avg() -> Result<()> { let ctx = SessionContext::new(); // the data type of c1 is decimal(10,3) ctx.register_table("d_table", test::table_with_decimal()) .unwrap(); let result = plan_and_collect(&ctx, "select avg(c1) from d_table") .await .unwrap(); let expected = vec![ "+-----------------+", "| AVG(d_table.c1) |", "+-----------------+", "| 5.0000000 |", "+-----------------+", ]; assert_eq!( &DataType::Decimal(14, 7), result[0].schema().field(0).data_type() ); assert_batches_sorted_eq!(expected, &result); Ok(()) } #[tokio::test] async fn aggregate() -> Result<()> { let results = execute("SELECT SUM(c1), SUM(c2) FROM test", 4).await?; assert_eq!(results.len(), 1); let expected = vec![ "+--------------+--------------+", "| SUM(test.c1) | SUM(test.c2) |", "+--------------+--------------+", "| 60 | 220 |", "+--------------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_empty() -> Result<()> { // The predicate on this query purposely generates no results let results = execute("SELECT SUM(c1), SUM(c2) FROM test where c1 > 100000", 4) .await .unwrap(); assert_eq!(results.len(), 1); let expected = vec![ "+--------------+--------------+", "| SUM(test.c1) | SUM(test.c2) |", "+--------------+--------------+", "| | |", "+--------------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_avg() -> Result<()> { let results = execute("SELECT AVG(c1), AVG(c2) FROM test", 4).await?; assert_eq!(results.len(), 1); let expected = vec![ "+--------------+--------------+", "| AVG(test.c1) | AVG(test.c2) |", "+--------------+--------------+", "| 1.5 | 5.5 |", "+--------------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_max() -> Result<()> { let results = execute("SELECT MAX(c1), MAX(c2) FROM test", 4).await?; assert_eq!(results.len(), 1); let expected = vec![ "+--------------+--------------+", "| MAX(test.c1) | MAX(test.c2) |", "+--------------+--------------+", "| 3 | 10 |", "+--------------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_min() -> Result<()> { let results = execute("SELECT MIN(c1), MIN(c2) FROM test", 4).await?; assert_eq!(results.len(), 1); let expected = vec![ "+--------------+--------------+", "| MIN(test.c1) | MIN(test.c2) |", "+--------------+--------------+", "| 0 | 1 |", "+--------------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_grouped() -> Result<()> { let results = execute("SELECT c1, SUM(c2) FROM test GROUP BY c1", 4).await?; let expected = vec![ "+----+--------------+", "| c1 | SUM(test.c2) |", "+----+--------------+", "| 0 | 55 |", "| 1 | 55 |", "| 2 | 55 |", "| 3 | 55 |", "+----+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_grouped_avg() -> Result<()> { let results = execute("SELECT c1, AVG(c2) FROM test GROUP BY c1", 4).await?; let expected = vec![ "+----+--------------+", "| c1 | AVG(test.c2) |", "+----+--------------+", "| 0 | 5.5 |", "| 1 | 5.5 |", "| 2 | 5.5 |", "| 3 | 5.5 |", "+----+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn boolean_literal() -> Result<()> { let results = execute("SELECT c1, c3 FROM test WHERE c1 > 2 AND c3 = true", 4).await?; let expected = vec![ "+----+------+", "| c1 | c3 |", "+----+------+", "| 3 | true |", "| 3 | true |", "| 3 | true |", "| 3 | true |", "| 3 | true |", "+----+------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_grouped_empty() -> Result<()> { let results = execute("SELECT c1, AVG(c2) FROM test WHERE c1 = 123 GROUP BY c1", 4).await?; let expected = vec![ "+----+--------------+", "| c1 | AVG(test.c2) |", "+----+--------------+", "+----+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_grouped_max() -> Result<()> { let results = execute("SELECT c1, MAX(c2) FROM test GROUP BY c1", 4).await?; let expected = vec![ "+----+--------------+", "| c1 | MAX(test.c2) |", "+----+--------------+", "| 0 | 10 |", "| 1 | 10 |", "| 2 | 10 |", "| 3 | 10 |", "+----+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_grouped_min() -> Result<()> { let results = execute("SELECT c1, MIN(c2) FROM test GROUP BY c1", 4).await?; let expected = vec![ "+----+--------------+", "| c1 | MIN(test.c2) |", "+----+--------------+", "| 0 | 1 |", "| 1 | 1 |", "| 2 | 1 |", "| 3 | 1 |", "+----+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_avg_add() -> Result<()> { let results = execute( "SELECT AVG(c1), AVG(c1) + 1, AVG(c1) + 2, 1 + AVG(c1) FROM test", 4, ) .await?; assert_eq!(results.len(), 1); let expected = vec![ "+--------------+----------------------------+----------------------------+----------------------------+", "| AVG(test.c1) | AVG(test.c1) Plus Int64(1) | AVG(test.c1) Plus Int64(2) | Int64(1) Plus AVG(test.c1) |", "+--------------+----------------------------+----------------------------+----------------------------+", "| 1.5 | 2.5 | 3.5 | 2.5 |", "+--------------+----------------------------+----------------------------+----------------------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn join_partitioned() -> Result<()> { // self join on partition id (workaround for duplicate column name) let results = execute( "SELECT 1 FROM test JOIN (SELECT c1 AS id1 FROM test) AS a ON c1=id1", 4, ) .await?; assert_eq!( results.iter().map(|b| b.num_rows()).sum::<usize>(), 4 * 10 * 10 ); Ok(()) } #[tokio::test] async fn count_basic() -> Result<()> { let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 1).await?; assert_eq!(results.len(), 1); let expected = vec![ "+----------------+----------------+", "| COUNT(test.c1) | COUNT(test.c2) |", "+----------------+----------------+", "| 10 | 10 |", "+----------------+----------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn count_partitioned() -> Result<()> { let results = execute("SELECT COUNT(c1), COUNT(c2) FROM test", 4).await?; assert_eq!(results.len(), 1); let expected = vec![ "+----------------+----------------+", "| COUNT(test.c1) | COUNT(test.c2) |", "+----------------+----------------+", "| 40 | 40 |", "+----------------+----------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn count_aggregated() -> Result<()> { let results = execute("SELECT c1, COUNT(c2) FROM test GROUP BY c1", 4).await?; let expected = vec![ "+----+----------------+", "| c1 | COUNT(test.c2) |", "+----+----------------+", "| 0 | 10 |", "| 1 | 10 |", "| 2 | 10 |", "| 3 | 10 |", "+----+----------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn group_by_date_trunc() -> Result<()> { let tmp_dir = TempDir::new()?; let ctx = SessionContext::new(); let schema = Arc::new(Schema::new(vec![ Field::new("c2", DataType::UInt64, false), Field::new( "t1", DataType::Timestamp(TimeUnit::Microsecond, None), false, ), ])); // generate a partitioned file for partition in 0..4 { let filename = format!("partition-{}.{}", partition, "csv"); let file_path = tmp_dir.path().join(&filename); let mut file = File::create(file_path)?; // generate some data for i in 0..10 { let data = format!("{},2020-12-{}T00:00:00.000Z\n", i, i + 10); file.write_all(data.as_bytes())?; } } ctx.register_csv( "test", tmp_dir.path().to_str().unwrap(), CsvReadOptions::new().schema(&schema).has_header(false), ) .await?; let results = plan_and_collect( &ctx, "SELECT date_trunc('week', t1) as week, SUM(c2) FROM test GROUP BY date_trunc('week', t1)", ).await?; let expected = vec![ "+---------------------+--------------+", "| week | SUM(test.c2) |", "+---------------------+--------------+", "| 2020-12-07 00:00:00 | 24 |", "| 2020-12-14 00:00:00 | 156 |", "+---------------------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn group_by_largeutf8() { { let ctx = SessionContext::new(); // input data looks like: // A, 1 // B, 2 // A, 2 // A, 4 // C, 1 // A, 1 let str_array: LargeStringArray = vec!["A", "B", "A", "A", "C", "A"] .into_iter() .map(Some) .collect(); let str_array = Arc::new(str_array); let val_array: Int64Array = vec![1, 2, 2, 4, 1, 1].into(); let val_array = Arc::new(val_array); let schema = Arc::new(Schema::new(vec![ Field::new("str", str_array.data_type().clone(), false), Field::new("val", val_array.data_type().clone(), false), ])); let batch = RecordBatch::try_new(schema.clone(), vec![str_array, val_array]).unwrap(); let provider = MemTable::try_new(schema.clone(), vec![vec![batch]]).unwrap(); ctx.register_table("t", Arc::new(provider)).unwrap(); let results = plan_and_collect(&ctx, "SELECT str, count(val) FROM t GROUP BY str") .await .expect("ran plan correctly"); let expected = vec![ "+-----+--------------+", "| str | COUNT(t.val) |", "+-----+--------------+", "| A | 4 |", "| B | 1 |", "| C | 1 |", "+-----+--------------+", ]; assert_batches_sorted_eq!(expected, &results); } } #[tokio::test] async fn unprojected_filter() { let ctx = SessionContext::new(); let df = ctx .read_table(test::table_with_sequence(1, 3).unwrap()) .unwrap(); let df = df .select(vec![binary_expr(col("i"), Operator::Plus, col("i"))]) .unwrap() .filter(col("i").gt(lit(2))) .unwrap(); let results = df.collect().await.unwrap(); let expected = vec![ "+--------------------------+", "| ?table?.i Plus ?table?.i |", "+--------------------------+", "| 6 |", "+--------------------------+", ]; assert_batches_sorted_eq!(expected, &results); } #[tokio::test] async fn group_by_dictionary() { async fn run_test_case<K: ArrowDictionaryKeyType>() { let ctx = SessionContext::new(); // input data looks like: // A, 1 // B, 2 // A, 2 // A, 4 // C, 1 // A, 1 let dict_array: DictionaryArray<K> = vec!["A", "B", "A", "A", "C", "A"].into_iter().collect(); let dict_array = Arc::new(dict_array); let val_array: Int64Array = vec![1, 2, 2, 4, 1, 1].into(); let val_array = Arc::new(val_array); let schema = Arc::new(Schema::new(vec![ Field::new("dict", dict_array.data_type().clone(), false), Field::new("val", val_array.data_type().clone(), false), ])); let batch = RecordBatch::try_new(schema.clone(), vec![dict_array, val_array]) .unwrap(); let provider = MemTable::try_new(schema.clone(), vec![vec![batch]]).unwrap(); ctx.register_table("t", Arc::new(provider)).unwrap(); let results = plan_and_collect(&ctx, "SELECT dict, count(val) FROM t GROUP BY dict") .await .expect("ran plan correctly"); let expected = vec![ "+------+--------------+", "| dict | COUNT(t.val) |", "+------+--------------+", "| A | 4 |", "| B | 1 |", "| C | 1 |", "+------+--------------+", ]; assert_batches_sorted_eq!(expected, &results); // Now, use dict as an aggregate let results = plan_and_collect(&ctx, "SELECT val, count(dict) FROM t GROUP BY val") .await .expect("ran plan correctly"); let expected = vec![ "+-----+---------------+", "| val | COUNT(t.dict) |", "+-----+---------------+", "| 1 | 3 |", "| 2 | 2 |", "| 4 | 1 |", "+-----+---------------+", ]; assert_batches_sorted_eq!(expected, &results); // Now, use dict as an aggregate let results = plan_and_collect( &ctx, "SELECT val, count(distinct dict) FROM t GROUP BY val", ) .await .expect("ran plan correctly"); let expected = vec![ "+-----+------------------------+", "| val | COUNT(DISTINCT t.dict) |", "+-----+------------------------+", "| 1 | 2 |", "| 2 | 2 |", "| 4 | 1 |", "+-----+------------------------+", ]; assert_batches_sorted_eq!(expected, &results); } run_test_case::<Int8Type>().await; run_test_case::<Int16Type>().await; run_test_case::<Int32Type>().await; run_test_case::<Int64Type>().await; run_test_case::<UInt8Type>().await; run_test_case::<UInt16Type>().await; run_test_case::<UInt32Type>().await; run_test_case::<UInt64Type>().await; } async fn run_count_distinct_integers_aggregated_scenario( partitions: Vec<Vec<(&str, u64)>>, ) -> Result<Vec<RecordBatch>> { let tmp_dir = TempDir::new()?; let ctx = SessionContext::new(); let schema = Arc::new(Schema::new(vec![ Field::new("c_group", DataType::Utf8, false), Field::new("c_int8", DataType::Int8, false), Field::new("c_int16", DataType::Int16, false), Field::new("c_int32", DataType::Int32, false), Field::new("c_int64", DataType::Int64, false), Field::new("c_uint8", DataType::UInt8, false), Field::new("c_uint16", DataType::UInt16, false), Field::new("c_uint32", DataType::UInt32, false), Field::new("c_uint64", DataType::UInt64, false), ])); for (i, partition) in partitions.iter().enumerate() { let filename = format!("partition-{}.csv", i); let file_path = tmp_dir.path().join(&filename); let mut file = File::create(file_path)?; for row in partition { let row_str = format!( "{},{}\n", row.0, // Populate values for each of the integer fields in the // schema. (0..8) .map(|_| { row.1.to_string() }) .collect::<Vec<_>>() .join(","), ); file.write_all(row_str.as_bytes())?; } } ctx.register_csv( "test", tmp_dir.path().to_str().unwrap(), CsvReadOptions::new().schema(&schema).has_header(false), ) .await?; let results = plan_and_collect( &ctx, " SELECT c_group, COUNT(c_uint64), COUNT(DISTINCT c_int8), COUNT(DISTINCT c_int16), COUNT(DISTINCT c_int32), COUNT(DISTINCT c_int64), COUNT(DISTINCT c_uint8), COUNT(DISTINCT c_uint16), COUNT(DISTINCT c_uint32), COUNT(DISTINCT c_uint64) FROM test GROUP BY c_group ", ) .await?; Ok(results) } #[tokio::test] async fn count_distinct_integers_aggregated_single_partition() -> Result<()> { let partitions = vec![ // The first member of each tuple will be the value for the // `c_group` column, and the second member will be the value for // each of the int/uint fields. vec![ ("a", 1), ("a", 1), ("a", 2), ("b", 9), ("c", 9), ("c", 10), ("c", 9), ], ]; let results = run_count_distinct_integers_aggregated_scenario(partitions).await?; let expected = vec![ "+---------+----------------------+-----------------------------+------------------------------+------------------------------+------------------------------+------------------------------+-------------------------------+-------------------------------+-------------------------------+", "| c_group | COUNT(test.c_uint64) | COUNT(DISTINCT test.c_int8) | COUNT(DISTINCT test.c_int16) | COUNT(DISTINCT test.c_int32) | COUNT(DISTINCT test.c_int64) | COUNT(DISTINCT test.c_uint8) | COUNT(DISTINCT test.c_uint16) | COUNT(DISTINCT test.c_uint32) | COUNT(DISTINCT test.c_uint64) |", "+---------+----------------------+-----------------------------+------------------------------+------------------------------+------------------------------+------------------------------+-------------------------------+-------------------------------+-------------------------------+", "| a | 3 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |", "| b | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |", "| c | 3 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |", "+---------+----------------------+-----------------------------+------------------------------+------------------------------+------------------------------+------------------------------+-------------------------------+-------------------------------+-------------------------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn count_distinct_integers_aggregated_multiple_partitions() -> Result<()> { let partitions = vec![ // The first member of each tuple will be the value for the // `c_group` column, and the second member will be the value for // each of the int/uint fields. vec![("a", 1), ("a", 1), ("a", 2), ("b", 9), ("c", 9)], vec![("a", 1), ("a", 3), ("b", 8), ("b", 9), ("b", 10), ("b", 11)], ]; let results = run_count_distinct_integers_aggregated_scenario(partitions).await?; let expected = vec![ "+---------+----------------------+-----------------------------+------------------------------+------------------------------+------------------------------+------------------------------+-------------------------------+-------------------------------+-------------------------------+", "| c_group | COUNT(test.c_uint64) | COUNT(DISTINCT test.c_int8) | COUNT(DISTINCT test.c_int16) | COUNT(DISTINCT test.c_int32) | COUNT(DISTINCT test.c_int64) | COUNT(DISTINCT test.c_uint8) | COUNT(DISTINCT test.c_uint16) | COUNT(DISTINCT test.c_uint32) | COUNT(DISTINCT test.c_uint64) |", "+---------+----------------------+-----------------------------+------------------------------+------------------------------+------------------------------+------------------------------+-------------------------------+-------------------------------+-------------------------------+", "| a | 5 | 3 | 3 | 3 | 3 | 3 | 3 | 3 | 3 |", "| b | 5 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |", "| c | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |", "+---------+----------------------+-----------------------------+------------------------------+------------------------------+------------------------------+------------------------------+-------------------------------+-------------------------------+-------------------------------+", ]; assert_batches_sorted_eq!(expected, &results); Ok(()) } #[tokio::test] async fn aggregate_with_alias() -> Result<()> { let tmp_dir = TempDir::new()?; let ctx = create_ctx(&tmp_dir, 1).await?; let schema = Arc::new(Schema::new(vec![ Field::new("c1", DataType::Utf8, false), Field::new("c2", DataType::UInt32, false), ])); let plan = LogicalPlanBuilder::scan_empty(None, schema.as_ref(), None)? .aggregate(vec![col("c1")], vec![sum(col("c2"))])? .project(vec![col("c1"), sum(col("c2")).alias("total_salary")])? .build()?; let plan = ctx.optimize(&plan)?; let physical_plan = ctx.create_physical_plan(&Arc::new(plan)).await?; assert_eq!("c1", physical_plan.schema().field(0).name().as_str()); assert_eq!( "total_salary", physical_plan.schema().field(1).name().as_str() ); Ok(()) } #[tokio::test] async fn limit() -> Result<()> { let tmp_dir = TempDir::new()?; let ctx = create_ctx(&tmp_dir, 1).await?; ctx.register_table("t", test::table_with_sequence(1, 1000).unwrap()) .unwrap(); let results = plan_and_collect(&ctx, "SELECT i FROM t ORDER BY i DESC limit 3") .await .unwrap(); let expected = vec![ "+------+", "| i |", "+------+", "| 1000 |", "| 999 |", "| 998 |", "+------+", ]; assert_batches_eq!(expected, &results); let results = plan_and_collect(&ctx, "SELECT i FROM t ORDER BY i limit 3") .await .unwrap(); let expected = vec![ "+---+", "| i |", "+---+", "| 1 |", "| 2 |", "| 3 |", "+---+", ]; assert_batches_eq!(expected, &results); let results = plan_and_collect(&ctx, "SELECT i FROM t limit 3") .await .unwrap(); // the actual rows are not guaranteed, so only check the count (should be 3) let num_rows: usize = results.into_iter().map(|b| b.num_rows()).sum(); assert_eq!(num_rows, 3); Ok(()) } #[tokio::test] async fn limit_multi_partitions() -> Result<()> { let tmp_dir = TempDir::new()?; let ctx = create_ctx(&tmp_dir, 1).await?; let partitions = vec![ vec![test::make_partition(0)], vec![test::make_partition(1)], vec![test::make_partition(2)], vec![test::make_partition(3)], vec![test::make_partition(4)], vec![test::make_partition(5)], ]; let schema = partitions[0][0].schema(); let provider = Arc::new(MemTable::try_new(schema, partitions).unwrap()); ctx.register_table("t", provider).unwrap(); // select all rows let results = plan_and_collect(&ctx, "SELECT i FROM t").await.unwrap(); let num_rows: usize = results.into_iter().map(|b| b.num_rows()).sum(); assert_eq!(num_rows, 15); for limit in 1..10 { let query = format!("SELECT i FROM t limit {}", limit); let results = plan_and_collect(&ctx, &query).await.unwrap(); let num_rows: usize = results.into_iter().map(|b| b.num_rows()).sum(); assert_eq!(num_rows, limit, "mismatch with query {}", query); } Ok(()) } #[tokio::test] async fn case_sensitive_identifiers_functions() { let ctx = SessionContext::new(); ctx.register_table("t", test::table_with_sequence(1, 1).unwrap()) .unwrap(); let expected = vec![ "+-----------+", "| sqrt(t.i) |", "+-----------+", "| 1 |", "+-----------+", ]; let results = plan_and_collect(&ctx, "SELECT sqrt(i) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); let results = plan_and_collect(&ctx, "SELECT SQRT(i) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); // Using double quotes allows specifying the function name with capitalization let err = plan_and_collect(&ctx, "SELECT \"SQRT\"(i) FROM t") .await .unwrap_err(); assert_eq!( err.to_string(), "Error during planning: Invalid function 'SQRT'" ); let results = plan_and_collect(&ctx, "SELECT \"sqrt\"(i) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); } #[tokio::test] async fn case_builtin_math_expression() { let ctx = SessionContext::new(); let type_values = vec![ ( DataType::Int8, Arc::new(Int8Array::from_slice(&[1])) as ArrayRef, ), ( DataType::Int16, Arc::new(Int16Array::from_slice(&[1])) as ArrayRef, ), ( DataType::Int32, Arc::new(Int32Array::from_slice(&[1])) as ArrayRef, ), ( DataType::Int64, Arc::new(Int64Array::from_slice(&[1])) as ArrayRef, ), ( DataType::UInt8, Arc::new(UInt8Array::from_slice(&[1])) as ArrayRef, ), ( DataType::UInt16, Arc::new(UInt16Array::from_slice(&[1])) as ArrayRef, ), ( DataType::UInt32, Arc::new(UInt32Array::from_slice(&[1])) as ArrayRef, ), ( DataType::UInt64, Arc::new(UInt64Array::from_slice(&[1])) as ArrayRef, ), ( DataType::Float32, Arc::new(Float32Array::from_slice(&[1.0_f32])) as ArrayRef, ), ( DataType::Float64, Arc::new(Float64Array::from_slice(&[1.0_f64])) as ArrayRef, ), ]; for (data_type, array) in type_values.iter() { let schema = Arc::new(Schema::new(vec![Field::new("v", data_type.clone(), false)])); let batch = RecordBatch::try_new(schema.clone(), vec![array.clone()]).unwrap(); let provider = MemTable::try_new(schema, vec![vec![batch]]).unwrap(); ctx.deregister_table("t").unwrap(); ctx.register_table("t", Arc::new(provider)).unwrap(); let expected = vec![ "+-----------+", "| sqrt(t.v) |", "+-----------+", "| 1 |", "+-----------+", ]; let results = plan_and_collect(&ctx, "SELECT sqrt(v) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); } } #[tokio::test] async fn case_sensitive_identifiers_user_defined_functions() -> Result<()> { let mut ctx = SessionContext::new(); ctx.register_table("t", test::table_with_sequence(1, 1).unwrap()) .unwrap(); let myfunc = |args: &[ArrayRef]| Ok(Arc::clone(&args[0])); let myfunc = make_scalar_function(myfunc); ctx.register_udf(create_udf( "MY_FUNC", vec![DataType::Int32], Arc::new(DataType::Int32), Volatility::Immutable, myfunc, )); // doesn't work as it was registered with non lowercase let err = plan_and_collect(&ctx, "SELECT MY_FUNC(i) FROM t") .await .unwrap_err(); assert_eq!( err.to_string(), "Error during planning: Invalid function \'my_func\'" ); // Can call it if you put quotes let result = plan_and_collect(&ctx, "SELECT \"MY_FUNC\"(i) FROM t").await?; let expected = vec![ "+--------------+", "| MY_FUNC(t.i) |", "+--------------+", "| 1 |", "+--------------+", ]; assert_batches_eq!(expected, &result); Ok(()) } #[tokio::test] async fn case_sensitive_identifiers_aggregates() { let ctx = SessionContext::new(); ctx.register_table("t", test::table_with_sequence(1, 1).unwrap()) .unwrap(); let expected = vec![ "+----------+", "| MAX(t.i) |", "+----------+", "| 1 |", "+----------+", ]; let results = plan_and_collect(&ctx, "SELECT max(i) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); let results = plan_and_collect(&ctx, "SELECT MAX(i) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); // Using double quotes allows specifying the function name with capitalization let err = plan_and_collect(&ctx, "SELECT \"MAX\"(i) FROM t") .await .unwrap_err(); assert_eq!( err.to_string(), "Error during planning: Invalid function 'MAX'" ); let results = plan_and_collect(&ctx, "SELECT \"max\"(i) FROM t") .await .unwrap(); assert_batches_sorted_eq!(expected, &results); } #[tokio::test] async fn case_sensitive_identifiers_user_defined_aggregates() -> Result<()> { let mut ctx = SessionContext::new(); ctx.register_table("t", test::table_with_sequence(1, 1).unwrap()) .unwrap(); // Note capitalization let my_avg = create_udaf( "MY_AVG", DataType::Float64, Arc::new(DataType::Float64), Volatility::Immutable, Arc::new(|| Ok(Box::new(AvgAccumulator::try_new(&DataType::Float64)?))), Arc::new(vec![DataType::UInt64, DataType::Float64]), ); ctx.register_udaf(my_avg); // doesn't work as it was registered as non lowercase let err = plan_and_collect(&ctx, "SELECT MY_AVG(i) FROM t") .await .unwrap_err(); assert_eq!( err.to_string(), "Error during planning: Invalid function \'my_avg\'" ); // Can call it if you put quotes let result = plan_and_collect(&ctx, "SELECT \"MY_AVG\"(i) FROM t").await?; let expected = vec![ "+-------------+", "| MY_AVG(t.i) |", "+-------------+", "| 1 |", "+-------------+", ]; assert_batches_eq!(expected, &result); Ok(()) } #[tokio::test] async fn query_csv_with_custom_partition_extension() -> Result<()> { let tmp_dir = TempDir::new()?; // The main stipulation of this test: use a file extension that isn't .csv. let file_extension = ".tst"; let ctx = SessionContext::new(); let schema = populate_csv_partitions(&tmp_dir, 2, file_extension)?; ctx.register_csv( "test", tmp_dir.path().to_str().unwrap(), CsvReadOptions::new() .schema(&schema) .file_extension(file_extension), ) .await?; let results = plan_and_collect(&ctx, "SELECT SUM(c1), SUM(c2), COUNT(*) FROM test").await?; assert_eq!(results.len(), 1); let expected = vec![ "+--------------+--------------+-----------------+", "| SUM(test.c1) | SUM(test.c2) | COUNT(UInt8(1)) |", "+--------------+--------------+-----------------+", "| 10 | 110 | 20 |", "+--------------+--------------+-----------------+", ]; assert_batches_eq!(expected, &results); Ok(()) } #[tokio::test] async fn send_context_to_threads() -> Result<()> { // ensure SessionContexts can be used in a multi-threaded // environment. Usecase is for concurrent planing. let tmp_dir = TempDir::new()?; let partition_count = 4; let ctx = Arc::new(Mutex::new(create_ctx(&tmp_dir, partition_count).await?)); let threads: Vec<JoinHandle<Result<_>>> = (0..2) .map(|_| ctx.clone()) .map(|ctx_clone| { thread::spawn(move || { let ctx = ctx_clone.lock().expect("Locked context"); // Ensure we can create logical plan code on a separate thread. ctx.create_logical_plan( "SELECT c1, c2 FROM test WHERE c1 > 0 AND c1 < 3", ) }) }) .collect(); for thread in threads { thread.join().expect("Failed to join thread")?; } Ok(()) } #[tokio::test] async fn ctx_sql_should_optimize_plan() -> Result<()> { let ctx = SessionContext::new(); let plan1 = ctx .create_logical_plan("SELECT * FROM (SELECT 1) AS one WHERE TRUE AND TRUE")?; let opt_plan1 = ctx.optimize(&plan1)?; let plan2 = ctx .sql("SELECT * FROM (SELECT 1) AS one WHERE TRUE AND TRUE") .await?; assert_eq!( format!("{:?}", opt_plan1), format!("{:?}", plan2.to_logical_plan()) ); Ok(()) } #[tokio::test] async fn simple_avg() -> Result<()> { let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); let batch1 = RecordBatch::try_new( Arc::new(schema.clone()), vec![Arc::new(Int32Array::from_slice(&[1, 2, 3]))], )?; let batch2 = RecordBatch::try_new( Arc::new(schema.clone()), vec![Arc::new(Int32Array::from_slice(&[4, 5]))], )?; let ctx = SessionContext::new(); let provider = MemTable::try_new(Arc::new(schema), vec![vec![batch1], vec![batch2]])?; ctx.register_table("t", Arc::new(provider))?; let result = plan_and_collect(&ctx, "SELECT AVG(a) FROM t").await?; let batch = &result[0]; assert_eq!(1, batch.num_columns()); assert_eq!(1, batch.num_rows()); let values = batch .column(0) .as_any() .downcast_ref::<Float64Array>() .expect("failed to cast version"); assert_eq!(values.len(), 1); // avg(1,2,3,4,5) = 3.0 assert_eq!(values.value(0), 3.0_f64); Ok(()) } #[tokio::test] async fn custom_query_planner() -> Result<()> { let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap()); let session_state = SessionState::with_config_rt(SessionConfig::new(), runtime) .with_query_planner(Arc::new(MyQueryPlanner {})); let ctx = SessionContext::with_state(session_state); let df = ctx.sql("SELECT 1").await?; df.collect().await.expect_err("query not supported"); Ok(()) } #[tokio::test] async fn disabled_default_catalog_and_schema() -> Result<()> { let ctx = SessionContext::with_config( SessionConfig::new().create_default_catalog_and_schema(false), ); assert!(matches!( ctx.register_table("test", test::table_with_sequence(1, 1)?), Err(DataFusionError::Plan(_)) )); assert!(matches!( ctx.sql("select * from datafusion.public.test").await, Err(DataFusionError::Plan(_)) )); Ok(()) } #[tokio::test] async fn custom_catalog_and_schema() { let config = SessionConfig::new() .create_default_catalog_and_schema(true) .with_default_catalog_and_schema("my_catalog", "my_schema"); catalog_and_schema_test(config).await; } #[tokio::test] async fn custom_catalog_and_schema_no_default() { let config = SessionConfig::new() .create_default_catalog_and_schema(false) .with_default_catalog_and_schema("my_catalog", "my_schema"); catalog_and_schema_test(config).await; } #[tokio::test] async fn custom_catalog_and_schema_and_information_schema() { let config = SessionConfig::new() .create_default_catalog_and_schema(true) .with_information_schema(true) .with_default_catalog_and_schema("my_catalog", "my_schema"); catalog_and_schema_test(config).await; } async fn catalog_and_schema_test(config: SessionConfig) { let ctx = SessionContext::with_config(config); let catalog = MemoryCatalogProvider::new(); let schema = MemorySchemaProvider::new(); schema .register_table("test".to_owned(), test::table_with_sequence(1, 1).unwrap()) .unwrap(); catalog .register_schema("my_schema", Arc::new(schema)) .unwrap(); ctx.register_catalog("my_catalog", Arc::new(catalog)); for table_ref in &["my_catalog.my_schema.test", "my_schema.test", "test"] { let result = plan_and_collect( &ctx, &format!("SELECT COUNT(*) AS count FROM {}", table_ref), ) .await .unwrap(); let expected = vec![ "+-------+", "| count |", "+-------+", "| 1 |", "+-------+", ]; assert_batches_eq!(expected, &result); } } #[tokio::test] async fn cross_catalog_access() -> Result<()> { let ctx = SessionContext::new(); let catalog_a = MemoryCatalogProvider::new(); let schema_a = MemorySchemaProvider::new(); schema_a .register_table("table_a".to_owned(), test::table_with_sequence(1, 1)?)?; catalog_a.register_schema("schema_a", Arc::new(schema_a))?; ctx.register_catalog("catalog_a", Arc::new(catalog_a)); let catalog_b = MemoryCatalogProvider::new(); let schema_b = MemorySchemaProvider::new(); schema_b .register_table("table_b".to_owned(), test::table_with_sequence(1, 2)?)?; catalog_b.register_schema("schema_b", Arc::new(schema_b))?; ctx.register_catalog("catalog_b", Arc::new(catalog_b)); let result = plan_and_collect( &ctx, "SELECT cat, SUM(i) AS total FROM ( SELECT i, 'a' AS cat FROM catalog_a.schema_a.table_a UNION ALL SELECT i, 'b' AS cat FROM catalog_b.schema_b.table_b ) AS all GROUP BY cat ORDER BY cat ", ) .await?; let expected = vec![ "+-----+-------+", "| cat | total |", "+-----+-------+", "| a | 1 |", "| b | 3 |", "+-----+-------+", ]; assert_batches_eq!(expected, &result); Ok(()) } #[tokio::test] async fn catalogs_not_leaked() { // the information schema used to introduce cyclic Arcs let ctx = SessionContext::with_config( SessionConfig::new().with_information_schema(true), ); // register a single catalog let catalog = Arc::new(MemoryCatalogProvider::new()); let catalog_weak = Arc::downgrade(&catalog); ctx.register_catalog("my_catalog", catalog); let catalog_list_weak = { let state = ctx.state.read(); Arc::downgrade(&state.catalog_list) }; drop(ctx); assert_eq!(Weak::strong_count(&catalog_list_weak), 0); assert_eq!(Weak::strong_count(&catalog_weak), 0); } #[tokio::test] async fn sql_create_schema() -> Result<()> { // the information schema used to introduce cyclic Arcs let ctx = SessionContext::with_config( SessionConfig::new().with_information_schema(true), ); // Create schema ctx.sql("CREATE SCHEMA abc").await?.collect().await?; // Add table to schema ctx.sql("CREATE TABLE abc.y AS VALUES (1,2,3)") .await? .collect() .await?; // Check table exists in schema let results = ctx.sql("SELECT * FROM information_schema.tables WHERE table_schema='abc' AND table_name = 'y'").await.unwrap().collect().await.unwrap(); assert_eq!(results[0].num_rows(), 1); Ok(()) } #[tokio::test] async fn sql_create_catalog() -> Result<()> { // the information schema used to introduce cyclic Arcs let ctx = SessionContext::with_config( SessionConfig::new().with_information_schema(true), ); // Create catalog ctx.sql("CREATE DATABASE test").await?.collect().await?; // Create schema ctx.sql("CREATE SCHEMA test.abc").await?.collect().await?; // Add table to schema ctx.sql("CREATE TABLE test.abc.y AS VALUES (1,2,3)") .await? .collect() .await?; // Check table exists in schema let results = ctx.sql("SELECT * FROM information_schema.tables WHERE table_catalog='test' AND table_schema='abc' AND table_name = 'y'").await.unwrap().collect().await.unwrap(); assert_eq!(results[0].num_rows(), 1); Ok(()) } struct MyPhysicalPlanner {} #[async_trait] impl PhysicalPlanner for MyPhysicalPlanner { async fn create_physical_plan( &self, _logical_plan: &LogicalPlan, _session_state: &SessionState, ) -> Result<Arc<dyn ExecutionPlan>> { Err(DataFusionError::NotImplemented( "query not supported".to_string(), )) } fn create_physical_expr( &self, _expr: &Expr, _input_dfschema: &crate::logical_plan::DFSchema, _input_schema: &Schema, _session_state: &SessionState, ) -> Result<Arc<dyn crate::physical_plan::PhysicalExpr>> { unimplemented!() } } struct MyQueryPlanner {} #[async_trait] impl QueryPlanner for MyQueryPlanner { async fn create_physical_plan( &self, logical_plan: &LogicalPlan, session_state: &SessionState, ) -> Result<Arc<dyn ExecutionPlan>> { let physical_planner = MyPhysicalPlanner {}; physical_planner .create_physical_plan(logical_plan, session_state) .await } } /// Execute SQL and return results async fn plan_and_collect( ctx: &SessionContext, sql: &str, ) -> Result<Vec<RecordBatch>> { ctx.sql(sql).await?.collect().await } /// Execute SQL and return results async fn execute(sql: &str, partition_count: usize) -> Result<Vec<RecordBatch>> { let tmp_dir = TempDir::new()?; let ctx = create_ctx(&tmp_dir, partition_count).await?; plan_and_collect(&ctx, sql).await } /// Generate CSV partitions within the supplied directory fn populate_csv_partitions( tmp_dir: &TempDir, partition_count: usize, file_extension: &str, ) -> Result<SchemaRef> { // define schema for data source (csv file) let schema = Arc::new(Schema::new(vec![ Field::new("c1", DataType::UInt32, false), Field::new("c2", DataType::UInt64, false), Field::new("c3", DataType::Boolean, false), ])); // generate a partitioned file for partition in 0..partition_count { let filename = format!("partition-{}.{}", partition, file_extension); let file_path = tmp_dir.path().join(&filename); let mut file = File::create(file_path)?; // generate some data for i in 0..=10 { let data = format!("{},{},{}\n", partition, i, i % 2 == 0); file.write_all(data.as_bytes())?; } } Ok(schema) } /// Generate a partitioned CSV file and register it with an execution context async fn create_ctx( tmp_dir: &TempDir, partition_count: usize, ) -> Result<SessionContext> { let ctx = SessionContext::with_config(SessionConfig::new().with_target_partitions(8)); let schema = populate_csv_partitions(tmp_dir, partition_count, ".csv")?; // register csv file with the execution context ctx.register_csv( "test", tmp_dir.path().to_str().unwrap(), CsvReadOptions::new().schema(&schema), ) .await?; Ok(ctx) } // Test for compilation error when calling read_* functions from an #[async_trait] function. // See https://github.com/apache/arrow-datafusion/issues/1154 #[async_trait] trait CallReadTrait { async fn call_read_csv(&self) -> Arc<DataFrame>; async fn call_read_avro(&self) -> Arc<DataFrame>; async fn call_read_parquet(&self) -> Arc<DataFrame>; } struct CallRead {} #[async_trait] impl CallReadTrait for CallRead { async fn call_read_csv(&self) -> Arc<DataFrame> { let ctx = SessionContext::new(); ctx.read_csv("dummy", CsvReadOptions::new()).await.unwrap() } async fn call_read_avro(&self) -> Arc<DataFrame> { let ctx = SessionContext::new(); ctx.read_avro("dummy", AvroReadOptions::default()) .await .unwrap() } async fn call_read_parquet(&self) -> Arc<DataFrame> { let ctx = SessionContext::new(); ctx.read_parquet("dummy", ParquetReadOptions::default()) .await .unwrap() } } }
{ Arc::new(TaskContext::from(self)) }
stats.ts
import Component from '@glimmer/component'; import { inject as service } from '@ember/service'; import type GameHistory from 'doctor-who-ai/services/history'; import type Game from 'doctor-who-ai/services/game'; export default class Stats extends Component { @service history!: GameHistory; @service game!: Game;
get data() { return this.history.latest; } get topDoctor() { return this.game.topDoctor; } }
lookupError.ts
import HttpStatus from '../../types/httpStatus'
MissingPayId = 'MissingPayId', MissingAddress = 'MissingAddress', // TODO: Remove Unknown after MissingPayId/MissingAddress are implemented Unknown = 'Unknown', } /** * A custom error class to organize logic around errors related to a 404 - Not Found. */ export default class LookupError extends PayIDError { public readonly kind: LookupErrorType /** * The constructor for new LookupErrors. * * @param message - An error message. * @param kind - The kind of LookupError for this instance. */ public constructor(message: string, kind: LookupErrorType) { // All lookup errors should return a 404 - Not Found super(message, HttpStatus.NotFound) this.kind = kind } }
import PayIDError from './payIdError' export enum LookupErrorType {
options_menu.js
//非保存フラグ let save_flag = true; //ロード時 window.onload = function() { newload(); Options_onload(); SoftVersionWrite(); //10ミリ秒ごとの処理 const intervalId = setInterval(() => { if (save_flag == true) { Options_view_select("video_downloading"); Options_view_input("video_pattern"); Options_view_select("video_autosave"); Options_view_select("debug"); } save_flag = false; }, 10); } function Options_view_select(name) { let name_func = name; chrome.storage.local.get(name_func, function(value) { //chrome.storage.localから読み出し document.getElementById(name_func).value = setOption(name_func); localStorage.setItem(name_func, setOption(name_func)); //表示書き換え let nowtext = "現在の設定:" + document.getElementById(name_func).options[setOption(name_func)].innerText; let rewrite = name_func + "_now_setting"; document.getElementById(rewrite).innerText = nowtext; }) } function Options_view_input(name) { name_func = name; chrome.storage.local.get(name_func, function(value) { //chrome.storage.localから読み出し document.getElementById(name_func).value = setOption(name_func); localStorage.setItem(name_func, setOption(name_func)); //表示書き換え let nowtext = "現在の設定:" + setOption(name_func); document.getElementById(name_func + "_now_setting").innerText = nowtext; }) } function Options_Save() { //オプション設定保存時 //オプションの値を書き込み Option_setWritingByID("video_downloading"); Op
ingByID("video_pattern"); Option_setWritingByID("debug"); Option_setWritingByID("video_autosave"); //保存日時 let now = new Date(); document.getElementById("saved").innerText = "保存日時:" + now.toLocaleString(); //非保存フラグ save_flag = true; } function Option_setWritingByID(ID) { Option_setWriting(ID, document.getElementById(ID).value); } function Default_click() { //デフォルト設定を入力 document.getElementById("form").value = document.getElementById("form").reset(); } function SoftVersion() { let manifest = chrome.runtime.getManifest(); return manifest['version']; } function SoftVersionWrite() { let ver = SoftVersion(); document.getElementById("version").innerText = `バージョン:` + ver; } //保存ボタンクリック時 document.getElementById("save_button").onclick = Options_Save; document.getElementById("default_val").onclick = Default_click;
tion_setWrit
MetadataService_pb2.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: modeldb/metadata/MetadataService.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='modeldb/metadata/MetadataService.proto', package='ai.verta.modeldb.metadata', syntax='proto3', serialized_options=b'P\001ZGgithub.com/VertaAI/modeldb/protos/gen/go/protos/public/modeldb/metadata', serialized_pb=b'\n&modeldb/metadata/MetadataService.proto\x12\x19\x61i.verta.modeldb.metadata\x1a\x1cgoogle/api/annotations.proto\"U\n\nIDTypeEnum\"G\n\x06IDType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x19\n\x15VERSIONING_REPOSITORY\x10\x01\x12\x15\n\x11VERSIONING_COMMIT\x10\x02\"\x80\x01\n\x12IdentificationType\x12=\n\x07id_type\x18\x01 \x01(\x0e\x32,.ai.verta.modeldb.metadata.IDTypeEnum.IDType\x12\x10\n\x06int_id\x18\x02 \x01(\x04H\x00\x12\x13\n\tstring_id\x18\x03 \x01(\tH\x00\x42\x04\n\x02id\"i\n\x10GetLabelsRequest\x12\x39\n\x02id\x18\x01 \x01(\x0b\x32-.ai.verta.modeldb.metadata.IdentificationType\x1a\x1a\n\x08Response\x12\x0e\n\x06labels\x18\x01 \x03(\t\"y\n\x10\x41\x64\x64LabelsRequest\x12\x39\n\x02id\x18\x01 \x01(\x0b\x32-.ai.verta.modeldb.metadata.IdentificationType\x12\x0e\n\x06labels\x18\x02 \x03(\t\x1a\x1a\n\x08Response\x12\x0e\n\x06status\x18\x01 \x01(\x08\"|\n\x13\x44\x65leteLabelsRequest\x12\x39\n\x02id\x18\x01 \x01(\x0b\x32-.ai.verta.modeldb.metadata.IdentificationType\x12\x0e\n\x06labels\x18\x02 \x03(\t\x1a\x1a\n\x08Response\x12\x0e\n\x06status\x18\x01 \x01(\x08\x32\xca\x03\n\x0fMetadataService\x12\x8b\x01\n\tGetLabels\x12+.ai.verta.modeldb.metadata.GetLabelsRequest\x1a\x34.ai.verta.modeldb.metadata.GetLabelsRequest.Response\"\x1b\x82\xd3\xe4\x93\x02\x15\x12\x13/v1/metadata/labels\x12\x8e\x01\n\tAddLabels\x12+.ai.verta.modeldb.metadata.AddLabelsRequest\x1a\x34.ai.verta.modeldb.metadata.AddLabelsRequest.Response\"\x1e\x82\xd3\xe4\x93\x02\x18\x1a\x13/v1/metadata/labels:\x01*\x12\x97\x01\n\x0c\x44\x65leteLabels\x12..ai.verta.modeldb.metadata.DeleteLabelsRequest\x1a\x37.ai.verta.modeldb.metadata.DeleteLabelsRequest.Response\"\x1e\x82\xd3\xe4\x93\x02\x18*\x13/v1/metadata/labels:\x01*BKP\x01ZGgithub.com/VertaAI/modeldb/protos/gen/go/protos/public/modeldb/metadatab\x06proto3' , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _IDTYPEENUM_IDTYPE = _descriptor.EnumDescriptor( name='IDType', full_name='ai.verta.modeldb.metadata.IDTypeEnum.IDType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNKNOWN', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERSIONING_REPOSITORY', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERSIONING_COMMIT', index=2, number=2, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=113, serialized_end=184, ) _sym_db.RegisterEnumDescriptor(_IDTYPEENUM_IDTYPE) _IDTYPEENUM = _descriptor.Descriptor( name='IDTypeEnum', full_name='ai.verta.modeldb.metadata.IDTypeEnum', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ _IDTYPEENUM_IDTYPE, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=99, serialized_end=184, ) _IDENTIFICATIONTYPE = _descriptor.Descriptor( name='IdentificationType', full_name='ai.verta.modeldb.metadata.IdentificationType', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id_type', full_name='ai.verta.modeldb.metadata.IdentificationType.id_type', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='int_id', full_name='ai.verta.modeldb.metadata.IdentificationType.int_id', index=1, number=2, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='string_id', full_name='ai.verta.modeldb.metadata.IdentificationType.string_id', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ _descriptor.OneofDescriptor( name='id', full_name='ai.verta.modeldb.metadata.IdentificationType.id', index=0, containing_type=None, fields=[]), ], serialized_start=187, serialized_end=315, ) _GETLABELSREQUEST_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.modeldb.metadata.GetLabelsRequest.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='labels', full_name='ai.verta.modeldb.metadata.GetLabelsRequest.Response.labels', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=396, serialized_end=422, ) _GETLABELSREQUEST = _descriptor.Descriptor( name='GetLabelsRequest', full_name='ai.verta.modeldb.metadata.GetLabelsRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.modeldb.metadata.GetLabelsRequest.id', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_GETLABELSREQUEST_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=317, serialized_end=422, ) _ADDLABELSREQUEST_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.modeldb.metadata.AddLabelsRequest.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='ai.verta.modeldb.metadata.AddLabelsRequest.Response.status', index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=519, serialized_end=545, ) _ADDLABELSREQUEST = _descriptor.Descriptor( name='AddLabelsRequest', full_name='ai.verta.modeldb.metadata.AddLabelsRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.modeldb.metadata.AddLabelsRequest.id', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='labels', full_name='ai.verta.modeldb.metadata.AddLabelsRequest.labels', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_ADDLABELSREQUEST_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=424, serialized_end=545, ) _DELETELABELSREQUEST_RESPONSE = _descriptor.Descriptor( name='Response', full_name='ai.verta.modeldb.metadata.DeleteLabelsRequest.Response', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='ai.verta.modeldb.metadata.DeleteLabelsRequest.Response.status', index=0, number=1, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=519, serialized_end=545, ) _DELETELABELSREQUEST = _descriptor.Descriptor( name='DeleteLabelsRequest', full_name='ai.verta.modeldb.metadata.DeleteLabelsRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ai.verta.modeldb.metadata.DeleteLabelsRequest.id', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='labels', full_name='ai.verta.modeldb.metadata.DeleteLabelsRequest.labels', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_DELETELABELSREQUEST_RESPONSE, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=547, serialized_end=671, ) _IDTYPEENUM_IDTYPE.containing_type = _IDTYPEENUM _IDENTIFICATIONTYPE.fields_by_name['id_type'].enum_type = _IDTYPEENUM_IDTYPE _IDENTIFICATIONTYPE.oneofs_by_name['id'].fields.append( _IDENTIFICATIONTYPE.fields_by_name['int_id']) _IDENTIFICATIONTYPE.fields_by_name['int_id'].containing_oneof = _IDENTIFICATIONTYPE.oneofs_by_name['id'] _IDENTIFICATIONTYPE.oneofs_by_name['id'].fields.append( _IDENTIFICATIONTYPE.fields_by_name['string_id']) _IDENTIFICATIONTYPE.fields_by_name['string_id'].containing_oneof = _IDENTIFICATIONTYPE.oneofs_by_name['id'] _GETLABELSREQUEST_RESPONSE.containing_type = _GETLABELSREQUEST _GETLABELSREQUEST.fields_by_name['id'].message_type = _IDENTIFICATIONTYPE _ADDLABELSREQUEST_RESPONSE.containing_type = _ADDLABELSREQUEST _ADDLABELSREQUEST.fields_by_name['id'].message_type = _IDENTIFICATIONTYPE _DELETELABELSREQUEST_RESPONSE.containing_type = _DELETELABELSREQUEST _DELETELABELSREQUEST.fields_by_name['id'].message_type = _IDENTIFICATIONTYPE
DESCRIPTOR.message_types_by_name['IDTypeEnum'] = _IDTYPEENUM DESCRIPTOR.message_types_by_name['IdentificationType'] = _IDENTIFICATIONTYPE DESCRIPTOR.message_types_by_name['GetLabelsRequest'] = _GETLABELSREQUEST DESCRIPTOR.message_types_by_name['AddLabelsRequest'] = _ADDLABELSREQUEST DESCRIPTOR.message_types_by_name['DeleteLabelsRequest'] = _DELETELABELSREQUEST _sym_db.RegisterFileDescriptor(DESCRIPTOR) IDTypeEnum = _reflection.GeneratedProtocolMessageType('IDTypeEnum', (_message.Message,), { 'DESCRIPTOR' : _IDTYPEENUM, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.IDTypeEnum) }) _sym_db.RegisterMessage(IDTypeEnum) IdentificationType = _reflection.GeneratedProtocolMessageType('IdentificationType', (_message.Message,), { 'DESCRIPTOR' : _IDENTIFICATIONTYPE, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.IdentificationType) }) _sym_db.RegisterMessage(IdentificationType) GetLabelsRequest = _reflection.GeneratedProtocolMessageType('GetLabelsRequest', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _GETLABELSREQUEST_RESPONSE, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.GetLabelsRequest.Response) }) , 'DESCRIPTOR' : _GETLABELSREQUEST, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.GetLabelsRequest) }) _sym_db.RegisterMessage(GetLabelsRequest) _sym_db.RegisterMessage(GetLabelsRequest.Response) AddLabelsRequest = _reflection.GeneratedProtocolMessageType('AddLabelsRequest', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _ADDLABELSREQUEST_RESPONSE, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.AddLabelsRequest.Response) }) , 'DESCRIPTOR' : _ADDLABELSREQUEST, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.AddLabelsRequest) }) _sym_db.RegisterMessage(AddLabelsRequest) _sym_db.RegisterMessage(AddLabelsRequest.Response) DeleteLabelsRequest = _reflection.GeneratedProtocolMessageType('DeleteLabelsRequest', (_message.Message,), { 'Response' : _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), { 'DESCRIPTOR' : _DELETELABELSREQUEST_RESPONSE, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.DeleteLabelsRequest.Response) }) , 'DESCRIPTOR' : _DELETELABELSREQUEST, '__module__' : 'modeldb.metadata.MetadataService_pb2' # @@protoc_insertion_point(class_scope:ai.verta.modeldb.metadata.DeleteLabelsRequest) }) _sym_db.RegisterMessage(DeleteLabelsRequest) _sym_db.RegisterMessage(DeleteLabelsRequest.Response) DESCRIPTOR._options = None _METADATASERVICE = _descriptor.ServiceDescriptor( name='MetadataService', full_name='ai.verta.modeldb.metadata.MetadataService', file=DESCRIPTOR, index=0, serialized_options=None, serialized_start=674, serialized_end=1132, methods=[ _descriptor.MethodDescriptor( name='GetLabels', full_name='ai.verta.modeldb.metadata.MetadataService.GetLabels', index=0, containing_service=None, input_type=_GETLABELSREQUEST, output_type=_GETLABELSREQUEST_RESPONSE, serialized_options=b'\202\323\344\223\002\025\022\023/v1/metadata/labels', ), _descriptor.MethodDescriptor( name='AddLabels', full_name='ai.verta.modeldb.metadata.MetadataService.AddLabels', index=1, containing_service=None, input_type=_ADDLABELSREQUEST, output_type=_ADDLABELSREQUEST_RESPONSE, serialized_options=b'\202\323\344\223\002\030\032\023/v1/metadata/labels:\001*', ), _descriptor.MethodDescriptor( name='DeleteLabels', full_name='ai.verta.modeldb.metadata.MetadataService.DeleteLabels', index=2, containing_service=None, input_type=_DELETELABELSREQUEST, output_type=_DELETELABELSREQUEST_RESPONSE, serialized_options=b'\202\323\344\223\002\030*\023/v1/metadata/labels:\001*', ), ]) _sym_db.RegisterServiceDescriptor(_METADATASERVICE) DESCRIPTOR.services_by_name['MetadataService'] = _METADATASERVICE # @@protoc_insertion_point(module_scope)
libasciidoc_test.go
package libasciidoc_test import ( "bytes" "context" "strings" "time" . "github.com/bytesparadise/libasciidoc" "github.com/bytesparadise/libasciidoc/renderer" . "github.com/onsi/ginkgo" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var _ = Describe("Documents", func() { Context("Document Body", func() { It("empty document", func() { // main title alone is not rendered in the body source := "" expectedContent := "" verifyDocumentBody(GinkgoT(), nil, expectedContent, source) }) It("document with no section", func() { // main title alone is not rendered in the body source := "= a document title" expectedTitle := "a document title" expectedContent := "" verifyDocumentBody(GinkgoT(), &expectedTitle, expectedContent, source) }) It("section levels 0 and 1", func() { source := `= a document title == Section A a paragraph with *bold content*` expectedTitle := "a document title" expectedContent := `<div class="sect1"> <h2 id="_section_a">Section A</h2> <div class="sectionbody"> <div class="paragraph"> <p>a paragraph with <strong>bold content</strong></p> </div> </div> </div>` verifyDocumentBody(GinkgoT(), &expectedTitle, expectedContent, source) }) It("section level 1 with a paragraph", func() { source := `== Section A a paragraph with *bold content*` expectedContent := `<div class="sect1"> <h2 id="_section_a">Section A</h2> <div class="sectionbody"> <div class="paragraph"> <p>a paragraph with <strong>bold content</strong></p> </div> </div> </div>` verifyDocumentBody(GinkgoT(), nil, expectedContent, source) }) It("section levels 0, 1 and 3", func() { source := `= a document title == Section A a paragraph with *bold content* ==== Section A.a.a a paragraph` expectedTitle := "a document title" expectedContent := `<div class="sect1"> <h2 id="_section_a">Section A</h2> <div class="sectionbody"> <div class="paragraph"> <p>a paragraph with <strong>bold content</strong></p> </div> <div class="sect3"> <h4 id="_section_a_a_a">Section A.a.a</h4> <div class="paragraph"> <p>a paragraph</p> </div> </div> </div> </div>` verifyDocumentBody(GinkgoT(), &expectedTitle, expectedContent, source) }) It("section levels 1, 2, 3 and 2", func() { source := `= a document title == Section A a paragraph with *bold content* === Section A.a a paragraph == Section B a paragraph with _italic content_` expectedTitle := "a document title" expectedContent := `<div class="sect1"> <h2 id="_section_a">Section A</h2> <div class="sectionbody"> <div class="paragraph"> <p>a paragraph with <strong>bold content</strong></p> </div> <div class="sect2"> <h3 id="_section_a_a">Section A.a</h3> <div class="paragraph"> <p>a paragraph</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="_section_b">Section B</h2> <div class="sectionbody"> <div class="paragraph"> <p>a paragraph with <em>italic content</em></p> </div> </div> </div>` verifyDocumentBody(GinkgoT(), &expectedTitle, expectedContent, source) }) }) Context("Complete Document ", func() { It("section levels 0 and 5", func() { source := `= a document title ====== Section A a paragraph with *bold content*` expectedContent := `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="libasciidoc"> <title>a document title</title> <body class="article"> <div id="header"> <h1>a document title</h1> </div> <div id="content"> <div class="sect5"> <h6 id="_section_a">Section A</h6> <div class="paragraph"> <p>a paragraph with <strong>bold content</strong></p> </div> </div> </div> <div id="footer"> <div id="footer-text"> Last updated {{.LastUpdated}} </div> </div> </body> </html>` verifyCompleteDocument(GinkgoT(), expectedContent, source) }) }) }) func verifyDocumentBody(t GinkgoTInterface, expectedRenderedTitle *string, expectedContent, source string)
func verifyCompleteDocument(t GinkgoTInterface, expectedContent, source string) { t.Logf("processing '%s'", source) sourceReader := strings.NewReader(source) resultWriter := bytes.NewBuffer(nil) lastUpdated := time.Now() _, err := ConvertToHTML(context.Background(), sourceReader, resultWriter, renderer.LastUpdated(lastUpdated)) require.Nil(t, err, "Error found while parsing the document") t.Log("Done processing document") result := resultWriter.String() t.Logf("** Actual output:\n`%s`\n", result) require.Nil(t, err) expectedContent = strings.Replace(expectedContent, "{{.LastUpdated}}", lastUpdated.Format(renderer.LastUpdatedFormat), 1) t.Logf("** expectedContent output:\n`%s`\n", expectedContent) assert.Equal(t, expectedContent, result) }
{ t.Logf("processing '%s'", source) sourceReader := strings.NewReader(source) resultWriter := bytes.NewBuffer(nil) metadata, err := ConvertToHTMLBody(context.Background(), sourceReader, resultWriter) require.Nil(t, err, "Error found while parsing the document") require.NotNil(t, metadata) t.Log("Done processing document") result := string(resultWriter.Bytes()) t.Logf("** Actual output:\n`%s`\n", result) t.Logf("** expectedContent output:\n`%s`\n", expectedContent) assert.Equal(t, expectedContent, result) actualTitle := metadata["doctitle"] if expectedRenderedTitle == nil { assert.Nil(t, actualTitle) } else { t.Logf("Actual title: %v", actualTitle) t.Logf("Expected title: %v", *expectedRenderedTitle) assert.Equal(t, *expectedRenderedTitle, actualTitle) } }
client.rs
use structopt::StructOpt; use tokio::time::{delay_for, Duration}; use yarws::{Client, Error}; #[derive(StructOpt, Debug)] struct Args { #[structopt(default_value = "ws://127.0.0.1:9001")] url: String, #[structopt(short = "r", long = "repeat", default_value = "0")] // <0 repeates forever repeat: isize, #[structopt(short = "n", long = "no-wait")] no_wait: bool, } // send different sizes of text messages to the echo server // and expect response to match the request #[tokio::main] async fn
() -> Result<(), Error> { let args = Args::from_args(); let mut repeat = args.repeat; loop { { let mut socket = Client::new(&args.url).default_logger().connect().await?.into_text(); // show headers // for (key, value) in socket.headers.iter() { // println!("{}: {}", key, value) // } let data = "01234567890abcdefghijklmnopqrstuvwxyz"; //36 characters let sizes = vec![1, 36, 125, 126, 127, 65535, 65536, 65537, 1048576]; for size in sizes { let rep = size / data.len() + 1; let req = &data.repeat(rep)[0..size]; socket.send(req).await?; let rsp = socket.try_recv().await?; assert_eq!(req, rsp); } } if repeat == 0 { break; } repeat -= 1; if !args.no_wait { delay_for(Duration::from_secs(1)).await; } } Ok(()) }
main
dict.rs
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://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. */ //! Methods for the `dict` type. use std::{intrinsics::unlikely, mem}; use anyhow::anyhow; use gazebo::cell::ARef; use crate as starlark; use crate::{ environment::MethodsBuilder, values::{dict::Dict, none::NoneType, Value}, }; #[starlark_module] pub(crate) fn dict_methods(registry: &mut MethodsBuilder) { /// [dict.clear]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·clear /// ): clear a dictionary /// /// `D.clear()` removes all the entries of dictionary D and returns `None`. /// It fails if the dictionary is frozen or if there are active iterators. /// /// /// `dict·clear` is not provided by the Java implementation. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// x.clear() /// x == {} /// # "#); /// ``` fn clear(this: Value) -> NoneType { let mut this = Dict::from_value_mut(this)?.unwrap(); this.clear(); Ok(NoneType) } /// [dict.get]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·get /// ): return an element from the dictionary. /// /// `D.get(key[, default])` returns the dictionary value corresponding to /// the given key. If the dictionary contains no such value, `get` /// returns `None`, or the value of the optional `default` parameter if /// present. /// /// `get` fails if `key` is unhashable. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// # ( /// x.get("one") == 1 /// # and /// x.get("three") == None /// # and /// x.get("three", 0) == 0 /// # )"#); /// ``` #[starlark(speculative_exec_safe)] fn get(this: ARef<Dict>, ref key: Value, ref default: Option<Value>) -> Value<'v> { match this.get(key)? { None => Ok(default.unwrap_or_else(Value::new_none)), Some(x) => Ok(x), } } /// [dict.items]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·items /// ): get list of (key, value) pairs. /// /// `D.items()` returns a new list of key/value pairs, one per element in /// dictionary D, in the same order as they would be returned by a `for` /// loop. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// x.items() == [("one", 1), ("two", 2)] /// # "#); /// ``` #[starlark(speculative_exec_safe)] fn items(this: ARef<Dict>) -> Value<'v> { Ok(heap.alloc_list_iter(this.iter().map(|(k, v)| heap.alloc((k, v))))) } /// [dict.keys]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·keys /// ): get the list of keys of the dictionary. /// /// `D.keys()` returns a new list containing the keys of dictionary D, in /// the same order as they would be returned by a `for` loop. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// x.keys() == ["one", "two"] /// # "#); /// ``` #[starlark(speculative_exec_safe)] fn keys(this: ARef<Dict>) -> Value<'v> { Ok(heap.alloc_list_iter(this.keys())) } /// [dict.pop]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·pop /// ): return an element and remove it from a dictionary. /// /// `D.pop(key[, default])` returns the value corresponding to the specified /// key, and removes it from the dictionary. If the dictionary contains no /// such value, and the optional `default` parameter is present, `pop` /// returns that value; otherwise, it fails. /// /// `pop` fails if `key` is unhashable, or the dictionary is frozen or has /// active iterators. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// # ( /// x.pop("one") == 1 /// # and /// x == {"two": 2} /// # and /// x.pop("three", 0) == 0 /// # and /// x.pop("three", None) == None /// # )"#); /// ``` /// /// Failure: /// /// ``` /// # starlark::assert::fail(r#" /// {'one': 1}.pop('four') # error: not found /// # "#, "not found"); /// ``` fn pop(this: Value, ref key: Value, ref default: Option<Value>) -> Value<'v> {
/// [dict.popitem]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·popitem /// ): returns and removes the first key/value pair of a dictionary. /// /// `D.popitem()` returns the first key/value pair, removing it from the /// dictionary. /// /// `popitem` fails if the dictionary is empty, frozen, or has active /// iterators. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// # ( /// x.popitem() == ("one", 1) /// # and /// x.popitem() == ("two", 2) /// # and /// x == {} /// # )"#); /// ``` /// /// Failure: /// /// ``` /// # starlark::assert::fail(r#" /// {}.popitem() # error: empty dict /// # "#, "empty dict"); /// ``` fn popitem(this: Value) -> (Value<'v>, Value<'v>) { let mut this = Dict::from_value_mut(this)?.unwrap(); let key = this.iter_hashed().next().map(|(k, _)| k); match key { Some(k) => Ok((*k.key(), this.remove_hashed(k).unwrap())), None => Err(anyhow!("Cannot .popitem() on an empty dictionary")), } } /// [dict.setdefault]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·setdefault /// ): get a value from a dictionary, setting it to a new value if not /// present. /// /// `D.setdefault(key[, default])` returns the dictionary value /// corresponding to the given key. If the dictionary contains no such /// value, `setdefault`, like `get`, returns `None` or the value of the /// optional `default` parameter if present; `setdefault` additionally /// inserts the new key/value entry into the dictionary. /// /// `setdefault` fails if the key is unhashable or if the dictionary is /// frozen. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// # ( /// x.setdefault("one") == 1 /// # and /// x.setdefault("three", 0) == 0 /// # and /// x == {"one": 1, "two": 2, "three": 0} /// # and /// x.setdefault("four") == None /// # and /// x == {"one": 1, "two": 2, "three": 0, "four": None} /// # )"#) /// ``` fn setdefault(this: Value, ref key: Value, ref default: Option<Value>) -> Value<'v> { let mut this = Dict::from_value_mut(this)?.unwrap(); let key = key.get_hashed()?; if let Some(r) = this.get_hashed(key) { return Ok(r); } let def = default.unwrap_or_else(Value::new_none); this.insert_hashed(key, def); Ok(def) } /// [dict.update]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·update /// ): update values in the dictionary. /// /// `D.update([pairs][, name=value[, ...])` makes a sequence of key/value /// insertions into dictionary D, then returns `None.` /// /// If the positional argument `pairs` is present, it must be `None`, /// another `dict`, or some other iterable. /// If it is another `dict`, then its key/value pairs are inserted into D. /// If it is an iterable, it must provide a sequence of pairs (or other /// iterables of length 2), each of which is treated as a key/value pair /// to be inserted into D. /// /// For each `name=value` argument present, the name is converted to a /// string and used as the key for an insertion into D, with its /// corresponding value being `value`. /// /// `update` fails if the dictionary is frozen. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {} /// x.update([("a", 1), ("b", 2)], c=3) /// x.update({"d": 4}) /// x.update(e=5) /// x == {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5} /// # "#); /// ``` fn update(this: Value, ref pairs: Option<Value>, kwargs: ARef<Dict>) -> NoneType { let pairs = if pairs.map(|x| x.ptr_eq(this)) == Some(true) { // someone has done `x.update(x)` - that isn't illegal, but we will have issues // with trying to iterate over x while holding x for mutation, and it doesn't do // anything useful, so just change pairs back to None None } else { pairs }; let mut this = Dict::from_value_mut(this)?.unwrap(); if let Some(pairs) = pairs { if let Some(dict) = Dict::from_value(pairs) { for (k, v) in dict.iter_hashed() { this.insert_hashed(k, v); } } else { for v in pairs.iterate(heap)? { let mut it = v.iterate(heap)?; let k = it.next(); let v = if k.is_some() { it.next() } else { None }; if unlikely(v.is_none() || it.next().is_some()) { return Err(anyhow!( "dict.update expect a list of pairs or a dictionary as first argument, got a list of non-pairs.", )); }; this.insert_hashed(k.unwrap().get_hashed()?, v.unwrap()); } } } for (k, v) in kwargs.iter_hashed() { this.insert_hashed(k, v); } Ok(NoneType) } /// [dict.values]( /// https://github.com/google/skylark/blob/3705afa472e466b8b061cce44b47c9ddc6db696d/doc/spec.md#dict·values /// ): get the list of values of the dictionary. /// /// `D.values()` returns a new list containing the dictionary's values, in /// the same order as they would be returned by a `for` loop over the /// dictionary. /// /// Examples: /// /// ``` /// # starlark::assert::is_true(r#" /// x = {"one": 1, "two": 2} /// x.values() == [1, 2] /// # "#); /// ``` #[starlark(speculative_exec_safe)] fn values(this: ARef<Dict>) -> Value<'v> { Ok(heap.alloc_list_iter(this.values())) } } #[cfg(test)] mod tests { use crate::assert; #[test] fn test_error_codes() { assert::fail(r#"x = {"one": 1}; x.pop("four")"#, "not found"); assert::fail("x = {}; x.popitem()", "empty"); } #[test] fn test_dict_add() { assert::fail("{1: 2} + {3: 4}", "not supported"); } #[test] fn test_dict_with_duplicates() { // In Starlark spec this is a runtime error. In Python it's fine. // We make it a runtime error, plus have a lint that checks for it statically. assert::fails("{40+2: 2, 6*7: 3}", &["key repeated", "42"]); // Also check we fail if the entire dictionary is static (a different code path). assert::fails("{42: 2, 42: 3}", &["key repeated", "42"]); } }
let mut me = Dict::from_value_mut(this)?.unwrap(); match me.remove_hashed(key.get_hashed()?) { Some(x) => Ok(x), None => match default { Some(v) => Ok(v), None => { mem::drop(me); Err(anyhow!( "Key `{}` not found in dictionary `{}`", key.to_repr(), this.to_repr() )) } }, } }
iter.rs
use crate::util::check_return; use crate::PosixACL; use acl_sys::{acl_entry_t, acl_get_entry, ACL_FIRST_ENTRY, ACL_NEXT_ENTRY}; use std::ptr::null_mut; #[allow(clippy::upper_case_acronyms)] pub(crate) struct RawACLIterator<'a> { acl: &'a PosixACL, next: i32, } impl<'a> RawACLIterator<'a> { pub(crate) fn new(acl: &'a PosixACL) -> RawACLIterator
} impl<'a> Iterator for RawACLIterator<'a> { type Item = acl_entry_t; fn next(&mut self) -> Option<Self::Item> { let mut entry: acl_entry_t = null_mut(); // The returned entry is owned by the ACL itself, no need to free it. let ret = unsafe { acl_get_entry(self.acl.acl, self.next, &mut entry) }; if ret == 0 { return None; } else if ret != 1 { check_return(ret, "acl_get_entry"); } // OK, ret == 1 self.next = ACL_NEXT_ENTRY; Some(entry) } } /** Demonstrate that multiple iterators cannot exist in parallel :( */ #[test] #[should_panic(expected = "assertion failed: ")] fn multi_iterator() { let acl = PosixACL::new(0o640); let iter1 = unsafe { acl.raw_iter() }; let iter2 = unsafe { acl.raw_iter() }; iter1.zip(iter2).for_each(|(a, b)| assert_eq!(a, b)) }
{ RawACLIterator { acl, next: ACL_FIRST_ENTRY, } }
conventions.py
""" A few practical conventions common to all printers. """ from __future__ import print_function, division import re import collections _name_with_digits_p = re.compile(r'^([a-zA-Z]+)([0-9]+)$') def split_super_sub(text):
def requires_partial(expr): """Return whether a partial derivative symbol is required for printing This requires checking how many free variables there are, filtering out the ones that are integers. Some expressions don't have free variables. In that case, check its variable list explicitly to get the context of the expression. """ if not isinstance(expr.free_symbols, collections.Iterable): return len(set(expr.variables)) > 1 return sum(not s.is_integer for s in expr.free_symbols) > 1
"""Split a symbol name into a name, superscripts and subscripts The first part of the symbol name is considered to be its actual 'name', followed by super- and subscripts. Each superscript is preceded with a "^" character or by "__". Each subscript is preceded by a "_" character. The three return values are the actual name, a list with superscripts and a list with subscripts. >>> from sympy.printing.conventions import split_super_sub >>> split_super_sub('a_x^1') ('a', ['1'], ['x']) >>> split_super_sub('var_sub1__sup_sub2') ('var', ['sup'], ['sub1', 'sub2']) """ if len(text) == 0: return text, [], [] pos = 0 name = None supers = [] subs = [] while pos < len(text): start = pos + 1 if text[pos:pos + 2] == "__": start += 1 pos_hat = text.find("^", start) if pos_hat < 0: pos_hat = len(text) pos_usc = text.find("_", start) if pos_usc < 0: pos_usc = len(text) pos_next = min(pos_hat, pos_usc) part = text[pos:pos_next] pos = pos_next if name is None: name = part elif part.startswith("^"): supers.append(part[1:]) elif part.startswith("__"): supers.append(part[2:]) elif part.startswith("_"): subs.append(part[1:]) else: raise RuntimeError("This should never happen.") # make a little exception when a name ends with digits, i.e. treat them # as a subscript too. m = _name_with_digits_p.match(name) if m: name, sub = m.groups() subs.insert(0, sub) return name, supers, subs
constants.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware 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. ############################################################################### # flake8: noqa: E501 class
(object): DISEASE_STUDIES = { # 'Study Abbreviation': 'Study Name', 'LAML': 'Acute Myeloid Leukemia', 'ACC': 'Adrenocortical carcinoma', 'BLCA': 'Bladder Urothelial Carcinoma', 'LGG': 'Brain Lower Grade Glioma', 'BRCA': 'Breast invasive carcinoma', 'CESC': 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'CHOL': 'Cholangiocarcinoma', 'LCML': 'Chronic Myelogenous Leukemia', 'COAD': 'Colon adenocarcinoma', 'CNTL': 'Controls', 'ESCA': 'Esophageal carcinoma ', 'FPPP': 'FFPE Pilot Phase II', 'GBM': 'Glioblastoma multiforme', 'HNSC': 'Head and Neck squamous cell carcinoma', 'KICH': 'Kidney Chromophobe', 'KIRC': 'Kidney renal clear cell carcinoma', 'KIRP': 'Kidney renal papillary cell carcinoma', 'LIHC': 'Liver hepatocellular carcinoma', 'LUAD': 'Lung adenocarcinoma', 'LUSC': 'Lung squamous cell carcinoma', 'DLBC': 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'MESO': 'Mesothelioma', 'MISC': 'Miscellaneous', 'OV': 'Ovarian serous cystadenocarcinoma', 'PAAD': 'Pancreatic adenocarcinoma', 'PCPG': 'Pheochromocytoma and Paraganglioma', 'PRAD': 'Prostate adenocarcinoma', 'READ': 'Rectum adenocarcinoma', 'SARC': 'Sarcoma', 'SKCM': 'Skin Cutaneous Melanoma', 'STAD': 'Stomach adenocarcinoma', 'TGCT': 'Testicular Germ Cell Tumors', 'THYM': 'Thymoma', 'THCA': 'Thyroid carcinoma', 'UCS': 'Uterine Carcinosarcoma', 'UCEC': 'Uterine Corpus Endometrial Carcinoma', 'UVM': 'Uveal Melanoma', } REPOSITORY_TYPES = { 'bcr', # 'Biospecimen Core Resource' 'cgcc', 'gsc', } DATA_PROVIDERS = { 'biotab', # Clinical metadata, skip 'intgen.org', 'nationwidechildrens.org', 'genome.wustl.edu', 'supplemental' # unknown, appears under 'tumor/ov/bcr/', skip } DATA_TYPES = { 'bio', # XML format clinical metadata, skip 'biotab', # CSV format clinical metadata, skip 'pathology_reports', # PDF format pathology reports, skip 'diagnostic_images', # SVS format images, use 'tissue_images', # SVS format images, use 'minbio' # unknown, appears under 'tumor/gbm/bcr/intgen.org/', skip } SLIDE_LOCATION = { 'TS': 'Top Slide', 'MS': 'Middle Slide', 'BS': 'Bottom Slide', 'DX': 'Top Slide', } TISSUE_SOURCE_SITE = { # 'TSS Code': ('Source Site', 'Study Name', 'BCR'), '01': ('International Genomics Consortium', 'Ovarian serous cystadenocarcinoma', 'IGC'), '02': ('MD Anderson Cancer Center', 'Glioblastoma multiforme', 'IGC'), '04': ('Gynecologic Oncology Group', 'Ovarian serous cystadenocarcinoma', 'IGC'), '05': ('Indivumed', 'Lung adenocarcinoma', 'IGC'), '06': ('Henry Ford Hospital', 'Glioblastoma multiforme', 'IGC'), '07': ('TGen', 'Cell Line Control', 'IGC'), '08': ('UCSF', 'Glioblastoma multiforme', 'IGC'), '09': ('UCSF', 'Ovarian serous cystadenocarcinoma', 'IGC'), '10': ('MD Anderson Cancer Center', 'Ovarian serous cystadenocarcinoma', 'IGC'), '11': ('MD Anderson Cancer Center', 'Lung squamous cell carcinoma', 'IGC'), '12': ('Duke', 'Glioblastoma multiforme', 'IGC'), '13': ('Memorial Sloan Kettering', 'Ovarian serous cystadenocarcinoma', 'IGC'), '14': ('Emory University', 'Glioblastoma multiforme', 'IGC'), '15': ('Mayo Clinic - Rochester', 'Glioblastoma multiforme', 'IGC'), '16': ('Toronto Western Hospital', 'Glioblastoma multiforme', 'IGC'), '17': ('Washington University', 'Lung adenocarcinoma', 'IGC'), '18': ('Princess Margaret Hospital (Canada)', 'Lung squamous cell carcinoma', 'IGC'), '19': ('Case Western', 'Glioblastoma multiforme', 'IGC'), '1Z': ('Johns Hopkins', 'Thymoma', 'NCH'), '20': ('Fox Chase Cancer Center', 'Ovarian serous cystadenocarcinoma', 'IGC'), '21': ('Fox Chase Cancer Center', 'Lung squamous cell carcinoma', 'IGC'), '22': ('Mayo Clinic - Rochester', 'Lung squamous cell carcinoma', 'IGC'), '23': ('Cedars Sinai', 'Ovarian serous cystadenocarcinoma', 'IGC'), '24': ('Washington University', 'Ovarian serous cystadenocarcinoma', 'IGC'), '25': ('Mayo Clinic - Rochester', 'Ovarian serous cystadenocarcinoma', 'IGC'), '26': ('University of Florida', 'Glioblastoma multiforme', 'IGC'), '27': ('Milan - Italy, Fondazione IRCCS Instituto Neuroligico C. Besta', 'Glioblastoma multiforme', 'IGC'), '28': ('Cedars Sinai', 'Glioblastoma multiforme', 'IGC'), '29': ('Duke', 'Ovarian serous cystadenocarcinoma', 'IGC'), '2A': ('Memorial Sloan Kettering Cancer Center', 'Prostate adenocarcinoma', 'NCH'), '2E': ('University of Kansas Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), '2F': ('Erasmus MC', 'Bladder Urothelial Carcinoma', 'NCH'), '2G': ('Erasmus MC', 'Testicular Germ Cell Tumors', 'NCH'), '2H': ('Erasmus MC', 'Esophageal carcinoma ', 'NCH'), '2J': ('Mayo Clinic', 'Pancreatic adenocarcinoma', 'NCH'), '2K': ('Greenville Health System', 'Kidney renal papillary cell carcinoma', 'NCH'), '2L': ('Technical University of Munich', 'Pancreatic adenocarcinoma', 'NCH'), '2M': ('Technical University of Munich', 'Esophageal carcinoma ', 'NCH'), '2N': ('Technical University of Munich', 'Stomach adenocarcinoma', 'NCH'), '2P': ('University of California San Diego', 'Pancreatic adenocarcinoma', 'NCH'), '2V': ('University of California San Diego', 'Liver hepatocellular carcinoma', 'NCH'), '2W': ('University of New Mexico', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), '2X': ('ABS IUPUI', 'Testicular Germ Cell Tumors', 'NCH'), '2Y': ('Moffitt Cancer Center', 'Liver hepatocellular carcinoma', 'NCH'), '2Z': ('Moffitt Cancer Center', 'Kidney renal papillary cell carcinoma', 'NCH'), '30': ('Harvard', 'Ovarian serous cystadenocarcinoma', 'IGC'), '31': ('Imperial College', 'Ovarian serous cystadenocarcinoma', 'IGC'), '32': ('St. Joseph\'s Hospital (AZ)', 'Glioblastoma multiforme', 'IGC'), '33': ('Johns Hopkins', 'Lung squamous cell carcinoma', 'IGC'), '34': ('University of Pittsburgh', 'Lung squamous cell carcinoma', 'IGC'), '35': ('Cureline', 'Lung adenocarcinoma', 'IGC'), '36': ('BC Cancer Agency', 'Ovarian serous cystadenocarcinoma', 'IGC'), '37': ('Cureline', 'Lung squamous cell carcinoma', 'IGC'), '38': ('UNC', 'Lung adenocarcinoma', 'IGC'), '39': ('MSKCC', 'Lung squamous cell carcinoma', 'IGC'), '3A': ('Moffitt Cancer Center', 'Pancreatic adenocarcinoma', 'NCH'), '3B': ('Moffitt Cancer Center', 'Sarcoma', 'NCH'), '3C': ('Columbia University', 'Breast invasive carcinoma', 'NCH'), '3E': ('Columbia University', 'Pancreatic adenocarcinoma', 'NCH'), '3G': ('MD Anderson Cancer Center', 'Thymoma', 'NCH'), '3H': ('MD Anderson Cancer Center', 'Mesothelioma', 'NCH'), '3J': ('Carle Cancer Center', 'Breast invasive carcinoma', 'NCH'), '3K': ('Boston Medical Center', 'Liver hepatocellular carcinoma', 'NCH'), '3L': ('Albert Einstein Medical Center', 'Colon adenocarcinoma', 'NCH'), '3M': ('University of Kansas Medical Center', 'Stomach adenocarcinoma', 'NCH'), '3N': ('Greenville Health System', 'Skin Cutaneous Melanoma', 'NCH'), '3P': ('Greenville Health System', 'Ovarian serous cystadenocarcinoma', 'NCH'), '3Q': ('Greenville Health Systems', 'Thymoma', 'NCH'), '3R': ('University of New Mexico', 'Sarcoma', 'NCH'), '3S': ('University of New Mexico', 'Thymoma', 'NCH'), '3T': ('Emory University', 'Thymoma', 'NCH'), '3U': ('University of Chicago', 'Mesothelioma', 'NCH'), '3W': ('University of California San Diego', 'Sarcoma', 'NCH'), '3X': ('Alberta Health Services', 'Cholangiocarcinoma', 'NCH'), '3Z': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Kidney renal clear cell carcinoma', 'NCH'), '41': ('Christiana Healthcare', 'Glioblastoma multiforme', 'IGC'), '42': ('Christiana Healthcare', 'Ovarian serous cystadenocarcinoma', 'IGC'), '43': ('Christiana Healthcare', 'Lung squamous cell carcinoma', 'IGC'), '44': ('Christiana Healthcare', 'Lung adenocarcinoma', 'IGC'), '46': ('St. Joseph\'s Medical Center (MD)', 'Lung squamous cell carcinoma', 'IGC'), '49': ('Johns Hopkins', 'Lung adenocarcinoma', 'IGC'), '4A': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Kidney renal papillary cell carcinoma', 'NCH'), '4B': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Lung adenocarcinoma', 'NCH'), '4C': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Thyroid carcinoma', 'NCH'), '4D': ('Molecular Response', 'Ovarian serous cystadenocarcinoma', 'NCH'), '4E': ('Molecular Response', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), '4G': ('Sapienza University of Rome', 'Cholangiocarcinoma', 'NCH'), '4H': ('Proteogenex, Inc.', 'Breast invasive carcinoma', 'NCH'), '4J': ('Proteogenex, Inc.', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), '4K': ('Proteogenex, Inc.', 'Testicular Germ Cell Tumors', 'NCH'), '4L': ('Proteogenex, Inc.', 'Prostate adenocarcinoma', 'NCH'), '4N': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Colon adenocarcinoma', 'NCH'), '4P': ('Duke University', 'Head and Neck squamous cell carcinoma', 'NCH'), '4Q': ('Duke University', 'Sarcoma', 'NCH'), '4R': ('Duke University', 'Liver hepatocellular carcinoma', 'NCH'), '4S': ('Duke University', 'Prostate adenocarcinoma', 'NCH'), '4T': ('Duke University', 'Colon adenocarcinoma', 'NCH'), '4V': ('Hospital Louis Pradel', 'Thymoma', 'NCH'), '4W': ('University of Miami', 'Glioblastoma multiforme', 'NCH'), '4X': ('Yale University', 'Thymoma', 'NCH'), '4Y': ('Medical College of Wisconsin', 'Sarcoma', 'NCH'), '4Z': ('Barretos Cancer Hospital', 'Bladder Urothelial Carcinoma', 'NCH'), '50': ('University of Pittsburgh', 'Lung adenocarcinoma', 'IGC'), '51': ('UNC', 'Lung squamous cell carcinoma', 'IGC'), '52': ('University of Miami', 'Lung squamous cell carcinoma', 'IGC'), '53': ('University of Miami', 'Lung adenocarcinoma', 'IGC'), '55': ('International Genomics Consortium', 'Lung adenocarcinoma', 'IGC'), '56': ('International Genomics Consortium', 'Lung squamous cell carcinoma', 'IGC'), '57': ('International Genomics Consortium', 'Ovarian serous cystadenocarcinoma', 'IGC'), '58': ('Thoraxklinik at University Hospital Heidelberg', 'Lung squamous cell carcinoma', 'IGC'), '59': ('Roswell Park', 'Ovarian serous cystadenocarcinoma', 'IGC'), '5A': ('Wake Forest University', 'Cholangiocarcinoma', 'NCH'), '5B': ('Medical College of Wisconsin', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), '5C': ('Cureline', 'Liver hepatocellular carcinoma', 'NCH'), '5D': ('University of Miami', 'Sarcoma', 'NCH'), '5F': ('Duke University', 'Thyroid carcinoma', 'NCH'), '5G': ('Cleveland Clinic Foundation', 'Thymoma', 'NCH'), '5H': ('Retina Consultants Houston', 'Uveal Melanoma', 'NCH'), '5J': ('Cureline', 'Acute Myeloid Leukemia', 'NCH'), '5K': ('St. Joseph\'s Hospital AZ', 'Thymoma', 'NCH'), '5L': ('University of Sao Paulo', 'Breast invasive carcinoma', 'NCH'), '5M': ('University of Sao Paulo', 'Colon adenocarcinoma', 'NCH'), '5N': ('University Hospital Erlangen', 'Bladder Urothelial Carcinoma', 'NCH'), '5P': ('University Hospital Erlangen', 'Kidney renal papillary cell carcinoma', 'NCH'), '5Q': ('Proteogenex, Inc', 'Pancreatic adenocarcinoma', 'NCH'), '5R': ('Proteogenex, Inc', 'Liver hepatocellular carcinoma', 'NCH'), '5S': ('Holy Cross', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), '5T': ('Holy Cross', 'Breast invasive carcinoma', 'NCH'), '5U': ('Regina Elena National Cancer Institute', 'Thymoma', 'NCH'), '5V': ('Roswell Park', 'Thymoma', 'NCH'), '5W': ('University of Alabama', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), '5X': ('University of Alabama', 'Ovarian serous cystadenocarcinoma', 'NCH'), '60': ('Roswell Park', 'Lung squamous cell carcinoma', 'IGC'), '61': ('University of Pittsburgh', 'Ovarian serous cystadenocarcinoma', 'IGC'), '62': ('Thoraxklinik at University Hospital Heidelberg', 'Lung adenocarcinoma', 'IGC'), '63': ('Ontario Institute for Cancer Research', 'Lung squamous cell carcinoma', 'IGC'), '64': ('Fox Chase', 'Lung adenocarcinoma', 'IGC'), '65': ('Roswell Park', 'Glioblastoma multiforme', 'IGC'), '66': ('Indivumed', 'Lung squamous cell carcinoma', 'IGC'), '67': ('St Joseph\'s Medical Center (MD)', 'Lung adenocarcinoma', 'IGC'), '68': ('Washington University - Cleveland Clinic', 'Lung squamous cell carcinoma', 'IGC'), '69': ('Washington University - Cleveland Clinic', 'Lung adenocarcinoma', 'IGC'), '6A': ('University of Kansas', 'Lung squamous cell carcinoma', 'NCH'), '6D': ('University of Oklahoma HSC', 'Kidney renal clear cell carcinoma', 'NCH'), '6G': ('University of Sao Paulo', 'Rectum adenocarcinoma', 'NCH'), '70': ('ILSBio', 'Lung squamous cell carcinoma', 'IGC'), '71': ('ILSBio', 'Lung adenocarcinoma', 'IGC'), '72': ('NCH', 'Ovarian serous cystadenocarcinoma', 'IGC'), '73': ('Roswell Park', 'Lung adenocarcinoma', 'IGC'), '74': ('Swedish Neurosciences', 'Glioblastoma multiforme', 'IGC'), '75': ('Ontario Institute for Cancer Research (OICR)', 'Lung adenocarcinoma', 'IGC'), '76': ('Thomas Jefferson University', 'Glioblastoma multiforme', 'IGC'), '77': ('Prince Charles Hospital', 'Lung squamous cell carcinoma', 'IGC'), '78': ('Prince Charles Hospital', 'Lung adenocarcinoma', 'IGC'), '79': ('Ontario Institute for Cancer Research (OICR)/Ottawa', 'Lung squamous cell carcinoma', 'IGC'), '80': ('Ontario Institute for Cancer Research (OICR)/Ottawa', 'Lung adenocarcinoma', 'IGC'), '81': ('CHI-Penrose Colorado', 'Glioblastoma multiforme', 'IGC'), '82': ('CHI-Penrose Colorado', 'Lung squamous cell carcinoma', 'IGC'), '83': ('CHI-Penrose Colorado', 'Lung adenocarcinoma', 'IGC'), '85': ('Asterand', 'Lung squamous cell carcinoma', 'IGC'), '86': ('Asterand', 'Lung adenocarcinoma', 'IGC'), '87': ('International Genomics Consortium', 'Glioblastoma multiforme', 'IGC'), '90': ('ABS - IUPUI', 'Lung squamous cell carcinoma', 'IGC'), '91': ('ABS - IUPUI', 'Lung adenocarcinoma', 'IGC'), '92': ('Washington University - St. Louis', 'Lung squamous cell carcinoma', 'IGC'), '93': ('Washington University - St. Louis', 'Lung adenocarcinoma', 'IGC'), '94': ('Washington University - Emory', 'Lung squamous cell carcinoma', 'IGC'), '95': ('Washington University - Emory', 'Lung adenocarcinoma', 'IGC'), '96': ('Washington University - NYU', 'Lung squamous cell carcinoma', 'IGC'), '97': ('Washington University - NYU', 'Lung adenocarcinoma', 'IGC'), '98': ('Washington University - Alabama', 'Lung squamous cell carcinoma', 'IGC'), '99': ('Washington University - Alabama', 'Lung adenocarcinoma', 'IGC'), 'A1': ('UCSF', 'Breast invasive carcinoma', 'NCH'), 'A2': ('Walter Reed', 'Breast invasive carcinoma', 'NCH'), 'A3': ('International Genomics Consortium', 'Kidney renal clear cell carcinoma', 'IGC'), 'A4': ('International Genomics Consortium', 'Kidney renal papillary cell carcinoma', 'IGC'), 'A5': ('Cedars Sinai', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'A6': ('Christiana Healthcare', 'Colon adenocarcinoma', 'IGC'), 'A7': ('Christiana Healthcare', 'Breast invasive carcinoma', 'NCH'), 'A8': ('Indivumed', 'Breast invasive carcinoma', 'NCH'), 'AA': ('Indivumed', 'Colon adenocarcinoma', 'IGC'), 'AB': ('Washington University', 'Acute Myeloid Leukemia', 'NCH'), 'AC': ('International Genomics Consortium', 'Breast invasive carcinoma', 'NCH'), 'AD': ('International Genomics Consortium', 'Colon adenocarcinoma', 'IGC'), 'AF': ('Christiana Healthcare', 'Rectum adenocarcinoma', 'IGC'), 'AG': ('Indivumed', 'Rectum adenocarcinoma', 'IGC'), 'AH': ('International Genomics Consortium', 'Rectum adenocarcinoma', 'IGC'), 'AJ': ('International Genomics Conosrtium', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'AK': ('Fox Chase', 'Kidney renal clear cell carcinoma', 'IGC'), 'AL': ('Fox Chase', 'Kidney renal papillary cell carcinoma', 'IGC'), 'AM': ('Cureline', 'Colon adenocarcinoma', 'IGC'), 'AN': ('Cureline', 'Breast invasive carcinoma', 'NCH'), 'AO': ('MSKCC', 'Breast invasive carcinoma', 'NCH'), 'AP': ('MSKCC', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'AQ': ('UNC ', 'Breast invasive carcinoma', 'NCH'), 'AR': ('Mayo', 'Breast invasive carcinoma', 'NCH'), 'AS': ('St. Joseph\'s Medical Center-(MD)', 'Kidney renal clear cell carcinoma', 'IGC'), 'AT': ('St. Joseph\'s Medical Center-(MD)', 'Kidney renal papillary cell carcinoma', 'IGC'), 'AU': ('St. Joseph\'s Medical Center-(MD)', 'Colon adenocarcinoma', 'IGC'), 'AV': ('NCH', 'Cell Line Control', 'NCH'), 'AW': ('Cureline', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'AX': ('Gynecologic Oncology Group', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'AY': ('UNC', 'Colon adenocarcinoma', 'IGC'), 'AZ': ('University of Pittsburgh', 'Colon adenocarcinoma', 'IGC'), 'B0': ('University of Pittsburgh', 'Kidney renal clear cell carcinoma', 'IGC'), 'B1': ('University of Pittsburgh', 'Kidney renal papillary cell carcinoma', 'IGC'), 'B2': ('Christiana Healthcare', 'Kidney renal clear cell carcinoma', 'IGC'), 'B3': ('Christiana Healthcare', 'Kidney renal papillary cell carcinoma', 'IGC'), 'B4': ('Cureline', 'Kidney renal clear cell carcinoma', 'IGC'), 'B5': ('Duke', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'B6': ('Duke', 'Breast invasive carcinoma', 'NCH'), 'B7': ('Cureline', 'Stomach adenocarcinoma', 'IGC'), 'B8': ('UNC', 'Kidney renal clear cell carcinoma', 'IGC'), 'B9': ('UNC', 'Kidney renal papillary cell carcinoma', 'IGC'), 'BA': ('UNC', 'Head and Neck squamous cell carcinoma', 'IGC'), 'BB': ('Johns Hopkins', 'Head and Neck squamous cell carcinoma', 'IGC'), 'BC': ('UNC', 'Liver hepatocellular carcinoma', 'NCH'), 'BD': ('University of Pittsburgh', 'Liver hepatocellular carcinoma', 'NCH'), 'BF': ('Cureline', 'Skin Cutaneous Melanoma', 'NCH'), 'BG': ('University of Pittsburgh', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'BH': ('University of Pittsburgh', 'Breast invasive carcinoma', 'NCH'), 'BI': ('University of Pittsburgh', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'BJ': ('University of Pittsburgh', 'Thyroid carcinoma', 'IGC'), 'BK': ('Christiana Healthcare', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'BL': ('Christiana Healthcare', 'Bladder Urothelial Carcinoma', 'NCH'), 'BM': ('UNC', 'Rectum adenocarcinoma', 'IGC'), 'BP': ('MSKCC', 'Kidney renal clear cell carcinoma', 'IGC'), 'BQ': ('MSKCC', 'Kidney renal papillary cell carcinoma', 'IGC'), 'BR': ('Asterand', 'Stomach adenocarcinoma', 'IGC'), 'BS': ('University of Hawaii', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'BT': ('University of Pittsburgh', 'Bladder Urothelial Carcinoma', 'NCH'), 'BW': ('St. Joseph\'s Medical Center-(MD)', 'Liver hepatocellular carcinoma', 'NCH'), 'C4': ('Indivumed', 'Bladder Urothelial Carcinoma', 'NCH'), 'C5': ('Medical College of Wisconsin', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'C8': ('ILSBio', 'Breast invasive carcinoma', 'NCH'), 'C9': ('ILSBio', 'Head and Neck squamous cell carcinoma', 'NCH'), 'CA': ('ILSBio', 'Colon adenocarcinoma', 'IGC'), 'CB': ('ILSBio', 'Kidney renal clear cell carcinoma', 'IGC'), 'CC': ('ILSBio', 'Liver hepatocellular carcinoma', 'NCH'), 'CD': ('ILSBio', 'Stomach adenocarcinoma', 'IGC'), 'CE': ('ILSBio', 'Thyroid carcinoma', 'IGC'), 'CF': ('ILSBio', 'Bladder Urothelial Carcinoma', 'NCH'), 'CG': ('Indivumed', 'Stomach adenocarcinoma', 'IGC'), 'CH': ('Indivumed', 'Prostate adenocarcinoma', 'IGC'), 'CI': ('University of Pittsburgh', 'Rectum adenocarcinoma', 'IGC'), 'CJ': ('MD Anderson Cancer Center', 'Kidney renal clear cell carcinoma', 'IGC'), 'CK': ('Harvard', 'Colon adenocarcinoma', 'IGC'), 'CL': ('Harvard', 'Rectum adenocarcinoma', 'IGC'), 'CM': ('MSKCC', 'Colon adenocarcinoma', 'IGC'), 'CN': ('University of Pittsburgh', 'Head and Neck squamous cell carcinoma', 'IGC'), 'CQ': ('University Health Network, Toronto', 'Head and Neck squamous cell carcinoma', 'IGC'), 'CR': ('Vanderbilt University', 'Head and Neck squamous cell carcinoma', 'IGC'), 'CS': ('Thomas Jefferson University', 'Brain Lower Grade Glioma', 'IGC'), 'CU': ('UNC', 'Bladder Urothelial Carcinoma', 'NCH'), 'CV': ('MD Anderson Cancer Center', 'Head and Neck squamous cell carcinoma', 'IGC'), 'CW': ('Mayo Clinic - Rochester', 'Kidney renal clear cell carcinoma', 'IGC'), 'CX': ('Medical College of Georgia', 'Head and Neck squamous cell carcinoma', 'IGC'), 'CZ': ('Harvard', 'Kidney renal clear cell carcinoma', 'IGC'), 'D1': ('Mayo Clinic', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'D3': ('MD Anderson', 'Skin Cutaneous Melanoma', 'NCH'), 'D5': ('Greater Poland Cancer Center', 'Colon adenocarcinoma', 'IGC'), 'D6': ('Greater Poland Cancer Center', 'Head and Neck squamous cell carcinoma', 'IGC'), 'D7': ('Greater Poland Cancer Center', 'Stomach adenocarcinoma', 'IGC'), 'D8': ('Greater Poland Cancer Center', 'Breast invasive carcinoma', 'NCH'), 'D9': ('Greater Poland Cancer Center', 'Skin Cutaneous Melanoma', 'NCH'), 'DA': ('Yale', 'Skin Cutaneous Melanoma', 'NCH'), 'DB': ('Mayo Clinic - Rochester', 'Brain Lower Grade Glioma', 'IGC'), 'DC': ('MSKCC', 'Rectum adenocarcinoma', 'IGC'), 'DD': ('Mayo Clinic - Rochester', 'Liver hepatocellular carcinoma', 'NCH'), 'DE': ('University of North Carolina', 'Thyroid carcinoma', 'NCH'), 'DF': ('Ontario Institute for Cancer Research', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'DG': ('Ontario Institute for Cancer Research', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'DH': ('University of Florida', 'Brain Lower Grade Glioma', 'IGC'), 'DI': ('MD Anderson', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'DJ': ('Memorial Sloan Kettering', 'Thyroid carcinoma', 'NCH'), 'DK': ('Memorial Sloan Kettering', 'Bladder Urothelial Carcinoma', 'NCH'), 'DM': ('University Of Michigan', 'Colon adenocarcinoma', 'NCH'), 'DO': ('Medical College of Georgia', 'Thyroid carcinoma', 'NCH'), 'DQ': ('University Of Michigan', 'Head and Neck squamous cell carcinoma', 'IGC'), 'DR': ('University of Hawaii', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'DS': ('Cedars Sinai', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'DT': ('ILSBio', 'Rectum adenocarcinoma', 'IGC'), 'DU': ('Henry Ford Hospital', 'Brain Lower Grade Glioma', 'IGC'), 'DV': ('NCI Urologic Oncology Branch', 'Kidney renal clear cell carcinoma', 'IGC'), 'DW': ('NCI Urologic Oncology Branch', 'Kidney renal papillary cell carcinoma', 'IGC'), 'DX': ('Memorial Sloan Kettering', 'Sarcoma', 'NCH'), 'DY': ('University Of Michigan', 'Rectum adenocarcinoma', 'NCH'), 'DZ': ('Mayo Clinic - Rochester', 'Kidney renal papillary cell carcinoma', 'IGC'), 'E1': ('Duke', 'Brain Lower Grade Glioma', 'IGC'), 'E2': ('Roswell Park', 'Breast invasive carcinoma', 'NCH'), 'E3': ('Roswell Park', 'Thyroid carcinoma', 'NCH'), 'E5': ('Roswell Park', 'Bladder Urothelial Carcinoma', 'NCH'), 'E6': ('Roswell Park', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'E7': ('Asterand', 'Bladder Urothelial Carcinoma', 'NCH'), 'E8': ('Asterand', 'Thyroid carcinoma', 'NCH'), 'E9': ('Asterand', 'Breast invasive carcinoma', 'NCH'), 'EA': ('Asterand', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'EB': ('Asterand', 'Skin Cutaneous Melanoma', 'NCH'), 'EC': ('Asterand', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'ED': ('Asterand', 'Liver hepatocellular carcinoma', 'NCH'), 'EE': ('University of Sydney', 'Skin Cutaneous Melanoma', 'NCH'), 'EF': ('Cureline', 'Rectum adenocarcinoma', 'IGC'), 'EI': ('Greater Poland Cancer Center', 'Rectum adenocarcinoma', 'IGC'), 'EJ': ('University of Pittsburgh', 'Prostate adenocarcinoma', 'IGC'), 'EK': ('Gynecologic Oncology Group', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'EL': ('MD Anderson', 'Thyroid carcinoma', 'NCH'), 'EM': ('University Health Network', 'Thyroid carcinoma', 'NCH'), 'EO': ('University Health Network', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'EP': ('Christiana Healthcare', 'Liver hepatocellular carcinoma', 'NCH'), 'EQ': ('Christiana Healthcare', 'Stomach adenocarcinoma', 'IGC'), 'ER': ('University of Pittsburgh', 'Skin Cutaneous Melanoma', 'NCH'), 'ES': ('University of Florida', 'Liver hepatocellular carcinoma', 'NCH'), 'ET': ('Johns Hopkins', 'Thyroid carcinoma', 'NCH'), 'EU': ('CHI-Penrose Colorado', 'Kidney renal clear cell carcinoma', 'IGC'), 'EV': ('CHI-Penrose Colorado', 'Kidney renal papillary cell carcinoma', 'IGC'), 'EW': ('University of Miami', 'Breast invasive carcinoma', 'NCH'), 'EX': ('University of North Carolina', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'EY': ('University of North Carolina', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'EZ': ('UNC', 'Brain Lower Grade Glioma', 'IGC'), 'F1': ('UNC', 'Stomach adenocarcinoma', 'IGC'), 'F2': ('UNC', 'Pancreatic adenocarcinoma', 'IGC'), 'F4': ('Asterand', 'Colon adenocarcinoma', 'IGC'), 'F5': ('Asterand', 'Rectum adenocarcinoma', 'IGC'), 'F6': ('Asterand', 'Brain Lower Grade Glioma', 'IGC'), 'F7': ('Asterand', 'Head and Neck squamous cell carcinoma', 'IGC'), 'F9': ('Asterand', 'Kidney renal papillary cell carcinoma', 'IGC'), 'FA': ('Asterand', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'FB': ('Asterand', 'Pancreatic adenocarcinoma', 'IGC'), 'FC': ('Asterand', 'Prostate adenocarcinoma', 'IGC'), 'FD': ('BLN - University Of Chicago', 'Bladder Urothelial Carcinoma', 'NCH'), 'FE': ('Ohio State University', 'Thyroid carcinoma', 'NCH'), 'FF': ('SingHealth', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'FG': ('Case Western', 'Brain Lower Grade Glioma', 'IGC'), 'FH': ('CHI-Penrose Colorado', 'Thyroid carcinoma', 'NCH'), 'FI': ('Washington University', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'FJ': ('BLN - Baylor', 'Bladder Urothelial Carcinoma', 'NCH'), 'FK': ('Johns Hopkins', 'Thyroid carcinoma', 'NCH'), 'FL': ('University of Hawaii - Normal Study', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'FM': ('International Genomics Consortium', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'FN': ('International Genomics Consortium', 'Brain Lower Grade Glioma', 'IGC'), 'FP': ('International Genomics Consortium', 'Stomach adenocarcinoma', 'IGC'), 'FQ': ('Johns Hopkins', 'Pancreatic adenocarcinoma', 'IGC'), 'FR': ('University of North Carolina', 'Skin Cutaneous Melanoma', 'NCH'), 'FS': ('Essen', 'Skin Cutaneous Melanoma', 'NCH'), 'FT': ('BLN - University of Miami', 'Bladder Urothelial Carcinoma', 'NCH'), 'FU': ('International Genomics Consortium', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'FV': ('International Genomics Consortium', 'Liver hepatocellular carcinoma', 'NCH'), 'FW': ('International Genomics Consortium', 'Skin Cutaneous Melanoma', 'NCH'), 'FX': ('International Genomics Consortium', 'Sarcoma', 'NCH'), 'FY': ('International Genomics Consortium', 'Thyroid carcinoma', 'NCH'), 'FZ': ('University of Pittsburgh', 'Pancreatic adenocarcinoma', 'IGC'), 'G2': ('MD Anderson', 'Bladder Urothelial Carcinoma', 'NCH'), 'G3': ('Alberta Health Services', 'Liver hepatocellular carcinoma', 'NCH'), 'G4': ('Roswell Park', 'Colon adenocarcinoma', 'IGC'), 'G5': ('Roswell Park', 'Rectum adenocarcinoma', 'IGC'), 'G6': ('Roswell Park', 'Kidney renal clear cell carcinoma', 'IGC'), 'G7': ('Roswell Park', 'Kidney renal papillary cell carcinoma', 'IGC'), 'G8': ('Roswell Park', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'G9': ('Roswell Park', 'Prostate adenocarcinoma', 'IGC'), 'GC': ('International Genomics Consortium', 'Bladder Urothelial Carcinoma', 'NCH'), 'GD': ('ABS - IUPUI', 'Bladder Urothelial Carcinoma', 'NCH'), 'GE': ('ABS - IUPUI', 'Thyroid carcinoma', 'NCH'), 'GF': ('ABS - IUPUI', 'Skin Cutaneous Melanoma', 'NCH'), 'GG': ('ABS - IUPUI', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'GH': ('ABS - IUPUI', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'GI': ('ABS - IUPUI', 'Breast invasive carcinoma', 'NCH'), 'GJ': ('ABS - IUPUI', 'Liver hepatocellular carcinoma', 'NCH'), 'GK': ('ABS - IUPUI', 'Kidney renal clear cell carcinoma', 'IGC'), 'GL': ('ABS - IUPUI', 'Kidney renal papillary cell carcinoma', 'IGC'), 'GM': ('MD Anderson', 'Breast invasive carcinoma', 'NCH'), 'GN': ('Roswell', 'Skin Cutaneous Melanoma', 'NCH'), 'GP': ('MD Anderson', 'Acute Myeloid Leukemia', 'NCH'), 'GR': ('University of Nebraska Medical Center (UNMC)', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'GS': ('Fundacio Clinic per a la Recerca Biomedica', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'GU': ('BLN - UT Southwestern Medical Center at Dallas', 'Bladder Urothelial Carcinoma', 'NCH'), 'GV': ('BLN - Cleveland Clinic', 'Bladder Urothelial Carcinoma', 'NCH'), 'GZ': ('BC Cancer Agency', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'H1': ('Medical College of Georgia', 'Stomach adenocarcinoma', 'IGC'), 'H2': ('Christiana Healthcare', 'Thyroid carcinoma', 'NCH'), 'H3': ('ABS - IUPUI', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'IGC'), 'H4': ('Medical College of Georgia', 'Bladder Urothelial Carcinoma', 'NCH'), 'H5': ('Medical College of Georgia', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'H6': ('Christiana Healthcare', 'Pancreatic adenocarcinoma', 'IGC'), 'H7': ('ABS - IUPUI', 'Head and Neck squamous cell carcinoma', 'IGC'), 'H8': ('ABS - IUPUI', 'Pancreatic adenocarcinoma', 'IGC'), 'H9': ('ABS - IUPUI', 'Prostate adenocarcinoma', 'IGC'), 'HA': ('Alberta Health Services', 'Stomach adenocarcinoma', 'IGC'), 'HB': ('University of North Carolina', 'Sarcoma', 'NCH'), 'HC': ('International Genomics Consortium', 'Prostate adenocarcinoma', 'IGC'), 'HD': ('International Genomics Consortium', 'Head and Neck squamous cell carcinoma', 'IGC'), 'HE': ('Ontario Institute for Cancer Research (OICR)', 'Kidney renal papillary cell carcinoma', 'IGC'), 'HF': ('Ontario Institute for Cancer Research (OICR)', 'Stomach adenocarcinoma', 'IGC'), 'HG': ('Roswell Park', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'HH': ('Fox Chase', 'Stomach adenocarcinoma', 'IGC'), 'HI': ('Fox Chase', 'Prostate adenocarcinoma', 'IGC'), 'HJ': ('Fox Chase', 'Stomach adenocarcinoma', 'IGC'), 'HK': ('Fox Chase', 'Brain Lower Grade Glioma', 'IGC'), 'HL': ('Fox Chase', 'Head and Neck squamous cell carcinoma', 'IGC'), 'HM': ('Christiana Healthcare', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'HN': ('Ontario Institute for Cancer Research (OICR)', 'Breast invasive carcinoma', 'NCH'), 'HP': ('Ontario Institute for Cancer Research (OICR)', 'Liver hepatocellular carcinoma', 'NCH'), 'HQ': ('Ontario Institute for Cancer Research (OICR)', 'Bladder Urothelial Carcinoma', 'NCH'), 'HR': ('Ontario Institute for Cancer Research (OICR)', 'Skin Cutaneous Melanoma', 'NCH'), 'HS': ('Ontario Institute for Cancer Research (OICR)', 'Sarcoma', 'NCH'), 'HT': ('Case Western - St Joes', 'Brain Lower Grade Glioma', 'IGC'), 'HU': ('National Cancer Center Korea', 'Stomach adenocarcinoma', 'IGC'), 'HV': ('National Cancer Center Korea', 'Pancreatic adenocarcinoma', 'IGC'), 'HW': ('MSKCC', 'Brain Lower Grade Glioma', 'IGC'), 'HZ': ('International Genomics Consortium', 'Pancreatic adenocarcinoma', 'IGC'), 'IA': ('Cleveland Clinic', 'Kidney renal papillary cell carcinoma', 'IGC'), 'IB': ('Alberta Health Services', 'Pancreatic adenocarcinoma', 'IGC'), 'IC': ('University of Pittsburgh', 'Esophageal carcinoma ', 'NCH'), 'IE': ('ABS - IUPUI', 'Sarcoma', 'NCH'), 'IF': ('University of Texas MD Anderson Cancer Center', 'Sarcoma', 'NCH'), 'IG': ('Asterand', 'Esophageal carcinoma ', 'NCH'), 'IH': ('University of Miami', 'Skin Cutaneous Melanoma', 'NCH'), 'IJ': ('Christiana Healthcare', 'Acute Myeloid Leukemia', 'NCH'), 'IK': ('Christiana Healthcare', 'Brain Lower Grade Glioma', 'IGC'), 'IM': ('University of Miami', 'Thyroid carcinoma', 'NCH'), 'IN': ('University of Pittsburgh', 'Stomach adenocarcinoma', 'IGC'), 'IP': ('ABS - IUPUI', 'Stomach adenocarcinoma', 'IGC'), 'IQ': ('University of Miami', 'Head and Neck squamous cell carcinoma', 'IGC'), 'IR': ('Memorial Sloan Kettering', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'IS': ('Memorial Sloan Kettering', 'Sarcoma', 'NCH'), 'IW': ('Cedars Sinai', 'Sarcoma', 'NCH'), 'IZ': ('ABS - Lahey Clinic', 'Kidney renal papillary cell carcinoma', 'IGC'), 'J1': ('ABS - Lahey Clinic', 'Lung squamous cell carcinoma', 'IGC'), 'J2': ('ABS - Lahey Clinic', 'Lung adenocarcinoma', 'IGC'), 'J4': ('ABS - Lahey Clinic', 'Prostate adenocarcinoma', 'IGC'), 'J7': ('ILSBio', 'Kidney renal papillary cell carcinoma', 'IGC'), 'J8': ('Mayo Clinic', 'Thyroid carcinoma', 'NCH'), 'J9': ('Melbourne Health', 'Prostate adenocarcinoma', 'IGC'), 'JA': ('ABS - Research Metrics Pakistan', 'Head and Neck squamous cell carcinoma', 'IGC'), 'JL': ('ABS - Research Metrics Pakistan', 'Breast invasive carcinoma', 'NCH'), 'JU': ('BLN - Baylor', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'JV': ('BLN - Baylor', 'Sarcoma', 'NCH'), 'JW': ('BLN - Baylor', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'JX': ('Washington University', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'JY': ('University Health Network', 'Esophageal carcinoma ', 'NCH'), 'JZ': ('University of Rochester', 'Esophageal carcinoma ', 'NCH'), 'K1': ('University of Pittsburgh', 'Sarcoma', 'NCH'), 'K4': ('ABS - Lahey Clinic', 'Bladder Urothelial Carcinoma', 'NCH'), 'K6': ('ABS - Lahey Clinic', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'K7': ('ABS - Lahey Clinic', 'Liver hepatocellular carcinoma', 'NCH'), 'K8': ('ABS - Lahey Clinic', 'Skin Cutaneous Melanoma', 'NCH'), 'KA': ('ABS - Lahey Clinic', 'Esophageal carcinoma ', 'NCH'), 'KB': ('University Health Network, Toronto', 'Stomach adenocarcinoma', 'IGC'), 'KC': ('Cornell Medical College', 'Prostate adenocarcinoma', 'IGC'), 'KD': ('Mount Sinai School of Medicine', 'Sarcoma', 'NCH'), 'KE': ('Mount Sinai School of Medicine', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'KF': ('Christiana Healthcare', 'Sarcoma', 'NCH'), 'KG': ('Baylor Network', 'Pancreatic adenocarcinoma', 'IGC'), 'KH': ('Memorial Sloan Kettering', 'Esophageal carcinoma ', 'NCH'), 'KJ': ('University of Miami', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'KK': ('MD Anderson Cancer Center', 'Prostate adenocarcinoma', 'IGC'), 'KL': ('MSKCC', 'Kidney Chromophobe', 'IGC'), 'KM': ('NCI Urologic Oncology Branch', 'Kidney Chromophobe', 'IGC'), 'KN': ('Harvard', 'Kidney Chromophobe', 'IGC'), 'KO': ('MD Anderson Cancer Center', 'Kidney Chromophobe', 'IGC'), 'KP': ('British Columbia Cancer Agency', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'KQ': ('Cornell Medical College', 'Bladder Urothelial Carcinoma', 'NCH'), 'KR': ('University Of Michigan', 'Liver hepatocellular carcinoma', 'NCH'), 'KS': ('University Of Michigan', 'Thyroid carcinoma', 'NCH'), 'KT': ('Hartford', 'Brain Lower Grade Glioma', 'IGC'), 'KU': ('Hartford', 'Head and Neck squamous cell carcinoma', 'IGC'), 'KV': ('Hartford', 'Kidney renal papillary cell carcinoma', 'IGC'), 'KZ': ('Hartford', 'Stomach adenocarcinoma', 'IGC'), 'L1': ('Hartford', 'Pancreatic adenocarcinoma', 'IGC'), 'L3': ('Gundersen Lutheran Health System', 'Lung squamous cell carcinoma', 'IGC'), 'L4': ('Gundersen Lutheran Health System', 'Lung adenocarcinoma', 'IGC'), 'L5': ('University of Michigan', 'Esophageal carcinoma ', 'NCH'), 'L6': ('National Institutes of Health', 'Thyroid carcinoma', 'NCH'), 'L7': ('Christiana Care', 'Esophageal carcinoma ', 'NCH'), 'L8': ('University of Miami', 'Kidney renal papillary cell carcinoma', 'NCH'), 'L9': ('Candler', 'Lung adenocarcinoma', 'IGC'), 'LA': ('Candler', 'Lung squamous cell carcinoma', 'IGC'), 'LB': ('Candler', 'Pancreatic adenocarcinoma', 'IGC'), 'LC': ('Hartford Hospital', 'Bladder Urothelial Carcinoma', 'NCH'), 'LD': ('Hartford Hospital', 'Breast invasive carcinoma', 'NCH'), 'LG': ('Hartford Hospital', 'Liver hepatocellular carcinoma', 'NCH'), 'LH': ('Hartford Hospital', 'Skin Cutaneous Melanoma', 'NCH'), 'LI': ('Hartford Hospital', 'Sarcoma', 'NCH'), 'LK': ('University of Pittsburgh', 'Mesothelioma', 'NCH'), 'LL': ('Candler', 'Breast invasive carcinoma', 'NCH'), 'LN': ('ILSBIO', 'Esophageal carcinoma ', 'NCH'), 'LP': ('ILSBIO', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'LQ': ('Gundersen Lutheran Health System', 'Breast invasive carcinoma', 'NCH'), 'LS': ('Gundersen Lutheran Health System', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'LT': ('Gundersen Lutheran Health System', 'Bladder Urothelial Carcinoma', 'NCH'), 'M7': ('University of North Carolina', 'Prostate adenocarcinoma', 'NCH'), 'M8': ('Ontario Institute for Cancer Research (OICR)', 'Pancreatic adenocarcinoma', 'NCH'), 'M9': ('Ontario Institute for Cancer Research (OICR)', 'Esophageal carcinoma ', 'NCH'), 'MA': ('MD Anderson Cancer Center', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'MB': ('University of Minnesota', 'Sarcoma', 'NCH'), 'ME': ('University of Minnesota', 'Lung adenocarcinoma', 'NCH'), 'MF': ('University of Minnesota', 'Lung squamous cell carcinoma', 'NCH'), 'MG': ('BLN - Baylor', 'Prostate adenocarcinoma', 'NCH'), 'MH': ('BLN - Baylor', 'Kidney renal papillary cell carcinoma', 'NCH'), 'MI': ('BLN - Baylor', 'Liver hepatocellular carcinoma', 'NCH'), 'MJ': ('BLN - Baylor', 'Sarcoma', 'NCH'), 'MK': ('BLN - Baylor', 'Thyroid carcinoma', 'NCH'), 'ML': ('BLN - Baylor', 'Lung squamous cell carcinoma', 'NCH'), 'MM': ('BLN - Baylor', 'Kidney renal clear cell carcinoma', 'NCH'), 'MN': ('BLN - Baylor', 'Lung adenocarcinoma', 'NCH'), 'MO': ('ILSBio', 'Sarcoma', 'NCH'), 'MP': ('Washington University - Mayo Clinic', 'Lung adenocarcinoma', 'NCH'), 'MQ': ('Washington University - NYU', 'Mesothelioma', 'NCH'), 'MR': ('University of Minnesota', 'Liver hepatocellular carcinoma', 'NCH'), 'MS': ('University of Minnesota', 'Breast invasive carcinoma', 'NCH'), 'MT': ('University of Minnesota', 'Head and Neck squamous cell carcinoma', 'NCH'), 'MU': ('University of Minnesota', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'MV': ('University of Minnesota', 'Bladder Urothelial Carcinoma', 'NCH'), 'MW': ('University of Miami', 'Kidney renal clear cell carcinoma', 'NCH'), 'MX': ('MSKCC', 'Stomach adenocarcinoma', 'NCH'), 'MY': ('Montefiore Medical Center', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'MZ': ('Montefiore Medical Center', 'Head and Neck squamous cell carcinoma', 'NCH'), 'N1': ('Montefiore Medical Center', 'Sarcoma', 'NCH'), 'N5': ('MSKCC', 'Uterine Carcinosarcoma', 'NCH'), 'N6': ('University of Pittsburgh', 'Uterine Carcinosarcoma', 'NCH'), 'N7': ('Washington University', 'Uterine Carcinosarcoma', 'NCH'), 'N8': ('University of North Carolina', 'Uterine Carcinosarcoma', 'NCH'), 'N9': ('MD Anderson', 'Uterine Carcinosarcoma', 'NCH'), 'NA': ('Duke University', 'Uterine Carcinosarcoma', 'NCH'), 'NB': ('Washington University - CHUV', 'Lung adenocarcinoma', 'NCH'), 'NC': ('Washington University - CHUV', 'Lung squamous cell carcinoma', 'NCH'), 'ND': ('Cedars Sinai', 'Uterine Carcinosarcoma', 'NCH'), 'NF': ('Mayo Clinic - Rochester', 'Uterine Carcinosarcoma', 'NCH'), 'NG': ('Roswell Park', 'Uterine Carcinosarcoma', 'NCH'), 'NH': ('Candler', 'Colon adenocarcinoma', 'NCH'), 'NI': ('Roswell Park', 'Liver hepatocellular carcinoma', 'NCH'), 'NJ': ('Washington University - Rush University', 'Lung adenocarcinoma', 'NCH'), 'NK': ('Washington University - Rush University', 'Lung squamous cell carcinoma', 'NCH'), 'NM': ('Cambridge BioSource', 'Head and Neck squamous cell carcinoma', 'NCH'), 'NP': ('International Genomics Consortium', 'Kidney Chromophobe', 'NCH'), 'NQ': ('International Genomics Consortium', 'Mesothelioma', 'NCH'), 'NS': ('Gundersen Lutheran Health System', 'Skin Cutaneous Melanoma', 'NCH'), 'O1': ('Washington University - CALGB', 'Lung adenocarcinoma', 'NCH'), 'O2': ('Washington University - CALGB', 'Lung squamous cell carcinoma', 'NCH'), 'O8': ('Saint Mary\'s Health Care', 'Liver hepatocellular carcinoma', 'NCH'), 'O9': ('Saint Mary\'s Health Care', 'Kidney renal papillary cell carcinoma', 'NCH'), 'OC': ('Saint Mary\'s Health Care', 'Lung squamous cell carcinoma', 'NCH'), 'OD': ('Saint Mary\'s Health Care', 'Skin Cutaneous Melanoma', 'NCH'), 'OE': ('Saint Mary\'s Health Care', 'Pancreatic adenocarcinoma', 'NCH'), 'OJ': ('Saint Mary\'s Health Care', 'Thyroid carcinoma', 'NCH'), 'OK': ('Mount Sinai School of Medicine', 'Breast invasive carcinoma', 'NCH'), 'OL': ('University of Chicago', 'Breast invasive carcinoma', 'NCH'), 'OR': ('University of Michigan', 'Adrenocortical carcinoma', 'NCH'), 'OU': ('Roswell Park', 'Adrenocortical carcinoma', 'NCH'), 'OW': ('International Genomics Consortium', 'Miscellaneous', 'NCH'), 'OX': ('University of North Carolina', 'Glioblastoma multiforme', 'NCH'), 'OY': ('University of North Carolina', 'Ovarian serous cystadenocarcinoma', 'NCH'), 'P3': ('Fred Hutchinson', 'Head and Neck squamous cell carcinoma', 'NCH'), 'P4': ('MD Anderson Cancer Center', 'Kidney renal papillary cell carcinoma', 'NCH'), 'P5': ('Cureline', 'Brain Lower Grade Glioma', 'NCH'), 'P6': ('Translational Genomics Research Institute', 'Adrenocortical carcinoma', 'NCH'), 'P7': ('Translational Genomics Research Institute', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'P8': ('University of Pittsburgh', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'P9': ('University of Minnesota', 'Pancreatic adenocarcinoma', 'NCH'), 'PA': ('University of Minnesota', 'Adrenocortical carcinoma', 'NCH'), 'PB': ('University of Minnesota', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'), 'PC': ('Fox Chase', 'Sarcoma', 'NCH'), 'PD': ('Fox Chase', 'Liver hepatocellular carcinoma', 'NCH'), 'PE': ('Fox Chase', 'Breast invasive carcinoma', 'NCH'), 'PG': ('Montefiore Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'PH': ('Gundersen Lutheran', 'Acute Myeloid Leukemia', 'NCH'), 'PJ': ('Gundersen Lutheran', 'Kidney renal papillary cell carcinoma', 'NCH'), 'PK': ('University Health Network', 'Adrenocortical carcinoma', 'NCH'), 'PL': ('Institute of Human Virology Nigeria', 'Breast invasive carcinoma', 'NCH'), 'PN': ('Institute of Human Virology Nigeria', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'PQ': ('University of Colorado Denver', 'Bladder Urothelial Carcinoma', 'NCH'), 'PR': ('Roswell Park', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'PT': ('Maine Medical Center', 'Sarcoma', 'NCH'), 'PZ': ('ABS - Lahey Clinic', 'Pancreatic adenocarcinoma', 'NCH'), 'Q1': ('University of Oklahoma HSC', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'Q2': ('University of Oklahoma HSC', 'Kidney renal papillary cell carcinoma', 'NCH'), 'Q3': ('University of Oklahoma HSC', 'Pancreatic adenocarcinoma', 'NCH'), 'Q4': ('Emory University', 'Acute Myeloid Leukemia', 'NCH'), 'Q9': ('Emory University', 'Esophageal carcinoma ', 'NCH'), 'QA': ('Emory University', 'Liver hepatocellular carcinoma', 'NCH'), 'QB': ('Emory University', 'Skin Cutaneous Melanoma', 'NCH'), 'QC': ('Emory University', 'Sarcoma', 'NCH'), 'QD': ('Emory University', 'Thyroid carcinoma', 'NCH'), 'QF': ('BLN - Baylor', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'QG': ('BLN - Baylor', 'Colon adenocarcinoma', 'NCH'), 'QH': ('Fondazione-Besta', 'Brain Lower Grade Glioma', 'NCH'), 'QJ': ('Mount Sinai School of Medicine', 'Ovarian serous cystadenocarcinoma', 'NCH'), 'QK': ('Emory University - Winship Cancer Inst.', 'Head and Neck squamous cell carcinoma', 'NCH'), 'QL': ('University of Chicago', 'Colon adenocarcinoma', 'NCH'), 'QM': ('University of Oklahoma HSC', 'Uterine Carcinosarcoma', 'NCH'), 'QN': ('ILSBio', 'Uterine Carcinosarcoma', 'NCH'), 'QQ': ('Roswell Park', 'Sarcoma', 'NCH'), 'QR': ('National Institutes of Health', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'QS': ('Candler', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'QT': ('University of North Carolina', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'QU': ('Harvard Beth Israel', 'Prostate adenocarcinoma', 'NCH'), 'QV': ('Instituto Nacional de Cancerologia', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'QW': ('Instituto Nacional de Cancerologia', 'Stomach adenocarcinoma', 'NCH'), 'R1': ('CHI-Penrose Colorado', 'Colon adenocarcinoma', 'NCH'), 'R2': ('CHI-Penrose Colorado', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'R3': ('CHI-Penrose Colorado', 'Bladder Urothelial Carcinoma', 'NCH'), 'R5': ('MD Anderson Cancer Center', 'Stomach adenocarcinoma', 'NCH'), 'R6': ('MD Anderson Cancer Center', 'Esophageal carcinoma ', 'NCH'), 'R7': ('Gundersen Lutheran Health System', 'Head and Neck squamous cell carcinoma', 'NCH'), 'R8': ('MD Anderson', 'Brain Lower Grade Glioma', 'NCH'), 'R9': ('Candler', 'Ovarian serous cystadenocarcinoma', 'NCH'), 'RA': ('Candler', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'RB': ('Emory University', 'Pancreatic adenocarcinoma', 'NCH'), 'RC': ('University of Utah', 'Liver hepatocellular carcinoma', 'NCH'), 'RD': ('Peter MacCallum Cancer Center', 'Stomach adenocarcinoma', 'NCH'), 'RE': ('Peter MacCallum Cancer Center', 'Esophageal carcinoma ', 'NCH'), 'RG': ('Montefiore Medical Center', 'Liver hepatocellular carcinoma', 'NCH'), 'RH': ('BLN - Baylor', 'Head and Neck squamous cell carcinoma', 'NCH'), 'RL': ('St. Joseph\'s Hospital AZ', 'Pancreatic adenocarcinoma', 'NCH'), 'RM': ('St. Joseph\'s Hospital AZ', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'RN': ('St. Joseph\'s Hospital AZ', 'Sarcoma', 'NCH'), 'RP': ('St. Joseph\'s Hospital AZ', 'Skin Cutaneous Melanoma', 'NCH'), 'RQ': ('St. Joseph\'s Hospital AZ', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'), 'RR': ('St. Joseph\'s Hospital AZ', 'Glioblastoma multiforme', 'NCH'), 'RS': ('Memorial Sloan Kettering Cancer Center', 'Head and Neck squamous cell carcinoma', 'NCH'), 'RT': ('Cleveland Clinic Foundation', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'RU': ('Northwestern University', 'Colon adenocarcinoma', 'NCH'), 'RV': ('Northwestern University', 'Pancreatic adenocarcinoma', 'NCH'), 'RW': ('Michigan University', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'RX': ('University of Minnesota', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'RY': ('University of California San Francisco', 'Brain Lower Grade Glioma', 'NCH'), 'RZ': ('Wills Eye Institute', 'Uveal Melanoma', 'NCH'), 'S2': ('Albert Einstein Medical Center', 'Lung adenocarcinoma', 'NCH'), 'S3': ('Albert Einstein Medical Center', 'Breast invasive carcinoma', 'NCH'), 'S4': ('University of Chicago', 'Pancreatic adenocarcinoma', 'NCH'), 'S5': ('University of Oklahoma HSC', 'Bladder Urothelial Carcinoma', 'NCH'), 'S6': ('Gundersen Lutheran Health System', 'Testicular Germ Cell Tumors', 'NCH'), 'S7': ('University Hospital Motol', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'S8': ('ABS - IUPUI', 'Esophageal carcinoma ', 'NCH'), 'S9': ('Dept of Neurosurgery at University of Heidelberg', 'Brain Lower Grade Glioma', 'NCH'), 'SA': ('ABS - IUPUI', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'SB': ('Baylor College of Medicine', 'Testicular Germ Cell Tumors', 'NCH'), 'SC': ('Memorial Sloan Kettering', 'Mesothelioma', 'NCH'), 'SD': ('MD Anderson', 'Pancreatic adenocarcinoma', 'NCH'), 'SE': ('Boston Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'SG': ('Cleveland Clinic Foundation', 'Sarcoma', 'NCH'), 'SH': ('Papworth Hospital', 'Mesothelioma', 'NCH'), 'SI': ('Washington University St. Louis', 'Sarcoma', 'NCH'), 'SJ': ('Albert Einstein Medical Center', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'SK': ('St. Joseph\'s Hospital AZ', 'Colon adenocarcinoma', 'NCH'), 'SL': ('St. Joseph\'s Hospital AZ', 'Uterine Corpus Endometrial Carcinoma', 'NCH'), 'SN': ('BLN - Baylor', 'Testicular Germ Cell Tumors', 'NCH'), 'SO': ('University of Minnesota', 'Testicular Germ Cell Tumors', 'NCH'), 'SP': ('University Health Network', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'SQ': ('International Genomics Consortium', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'SR': ('Tufts Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'SS': ('Medical College of Georgia', 'Colon adenocarcinoma', 'NCH'), 'ST': ('Global Bioclinical-Moldova', 'Head and Neck squamous cell carcinoma', 'NCH'), 'SU': ('Global Bioclinical-Moldova', 'Prostate adenocarcinoma', 'NCH'), 'SW': ('Global Bioclinical-Moldova', 'Stomach adenocarcinoma', 'NCH'), 'SX': ('Mayo Clinic Arizona', 'Kidney renal papillary cell carcinoma', 'NCH'), 'SY': ('Mayo Clinic Arizona', 'Bladder Urothelial Carcinoma', 'NCH'), 'T1': ('St. Joseph\'s Hospital Arizona', 'Liver hepatocellular carcinoma', 'NCH'), 'T2': ('St. University of Colorado Denver', 'Head and Neck squamous cell carcinoma', 'NCH'), 'T3': ('Molecular Response', 'Head and Neck squamous cell carcinoma', 'NCH'), 'T6': ('Molecular Response', 'Lung adenocarcinoma', 'NCH'), 'T7': ('Molecular Response', 'Kidney renal clear cell carcinoma', 'NCH'), 'T9': ('Molecular Response', 'Colon adenocarcinoma', 'NCH'), 'TE': ('Global BioClinical - Georgia', 'Skin Cutaneous Melanoma', 'NCH'), 'TG': ('Global BioClinical - Georgia', 'Head and Neck squamous cell carcinoma', 'NCH'), 'TK': ('Global BioClinical - Georgia', 'Prostate adenocarcinoma', 'NCH'), 'TL': ('Global BioClinical - Georgia', 'Stomach adenocarcinoma', 'NCH'), 'TM': ('The University of New South Wales', 'Brain Lower Grade Glioma', 'NCH'), 'TN': ('Ohio State University', 'Head and Neck squamous cell carcinoma', 'NCH'), 'TP': ('Maine Medical Center', 'Prostate adenocarcinoma', 'NCH'), 'TQ': ('University of Sao Paulo', 'Brain Lower Grade Glioma', 'NCH'), 'TR': ('Global Bioclinical-Moldova', 'Skin Cutaneous Melanoma', 'NCH'), 'TS': ('University of Pennsylvania', 'Mesothelioma', 'NCH'), 'TT': ('University of Pennsylvania', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'TV': ('Wake Forest University', 'Breast invasive carcinoma', 'NCH'), 'UB': ('UCSF', 'Liver hepatocellular carcinoma', 'NCH'), 'UC': ('University of Washington', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'UD': ('University of Western Australia', 'Mesothelioma', 'NCH'), 'UE': ('Asterand', 'Sarcoma', 'NCH'), 'UF': ('Barretos Cancer Hospital', 'Head and Neck squamous cell carcinoma', 'NCH'), 'UJ': ('Boston Medical Center', 'Lung squamous cell carcinoma', 'NCH'), 'UL': ('Boston Medical Center', 'Breast invasive carcinoma', 'NCH'), 'UN': ('Boston Medical Center', 'Kidney renal papillary cell carcinoma', 'NCH'), 'UP': ('Boston Medical Center', 'Head and Neck squamous cell carcinoma', 'NCH'), 'UR': ('Boston Medical Center', 'Prostate adenocarcinoma', 'NCH'), 'US': ('Garvan Institute of Medical Research', 'Pancreatic adenocarcinoma', 'NCH'), 'UT': ('Asbestos Diseases Research Institute', 'Mesothelioma', 'NCH'), 'UU': ('Mary Bird Perkins Cancer Center - Our Lady of the Lake', 'Breast invasive carcinoma', 'NCH'), 'UV': ('Capital Biosciences', 'Liver hepatocellular carcinoma', 'NCH'), 'UW': ('University of North Carolina', 'Kidney Chromophobe', 'NCH'), 'UY': ('University of California San Francisco', 'Bladder Urothelial Carcinoma', 'NCH'), 'UZ': ('University of California San Francisco', 'Kidney renal papillary cell carcinoma', 'NCH'), 'V1': ('University of California San Francisco', 'Prostate adenocarcinoma', 'NCH'), 'V2': ('Cleveland Clinic Foundation', 'Prostate adenocarcinoma', 'NCH'), 'V3': ('Cleveland Clinic Foundation', 'Uveal Melanoma', 'NCH'), 'V4': ('Institut Curie', 'Uveal Melanoma', 'NCH'), 'V5': ('Duke University', 'Esophageal carcinoma ', 'NCH'), 'V6': ('Duke University', 'Stomach adenocarcinoma', 'NCH'), 'V7': ('Medical College of Georgia', 'Breast invasive carcinoma', 'NCH'), 'V8': ('Medical College of Georgia', 'Kidney renal clear cell carcinoma', 'NCH'), 'V9': ('Medical College of Georgia', 'Kidney renal papillary cell carcinoma', 'NCH'), 'VA': ('Alliance', 'Stomach adenocarcinoma', 'NCH'), 'VB': ('Global BioClinical - Georgia', 'Lymphoid Neoplasm Diffuse Large B-cell Lymphoma', 'NCH'), 'VD': ('University of Liverpool', 'Uveal Melanoma', 'NCH'), 'VF': ('University of Pennsylvania', 'Testicular Germ Cell Tumors', 'NCH'), 'VG': ('Institute of Human Virology Nigeria', 'Ovarian serous cystadenocarcinoma', 'NCH'), 'VK': ('Institute of Human Virology Nigeria', 'Colon adenocarcinoma', 'NCH'), 'VL': ('Institute of Human Virology Nigeria', 'Rectum adenocarcinoma', 'NCH'), 'VM': ('Huntsman Cancer Institute', 'Brain Lower Grade Glioma', 'NCH'), 'VN': ('NCI Urologic Oncology Branch', 'Prostate adenocarcinoma', 'NCH'), 'VP': ('Washington University', 'Prostate adenocarcinoma', 'NCH'), 'VQ': ('Barretos Cancer Hospital', 'Stomach adenocarcinoma', 'NCH'), 'VR': ('Barretos Cancer Hospital', 'Esophageal carcinoma ', 'NCH'), 'VS': ('Barretos Cancer Hospital', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'VT': ('Vanderbilt', 'Sarcoma', 'NCH'), 'VV': ('John Wayne Cancer Center', 'Brain Lower Grade Glioma', 'NCH'), 'VW': ('Northwestern University', 'Brain Lower Grade Glioma', 'NCH'), 'VX': ('Northwestern University', 'Stomach adenocarcinoma', 'NCH'), 'VZ': ('Albert Einstein Medical Center', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'W2': ('Medical College of Wisconsin', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'W3': ('John Wayne Cancer Center', 'Skin Cutaneous Melanoma', 'NCH'), 'W4': ('University of North Carolina', 'Testicular Germ Cell Tumors', 'NCH'), 'W5': ('Mayo Clinic Rochester', 'Cholangiocarcinoma', 'NCH'), 'W6': ('UCSF', 'Cholangiocarcinoma', 'NCH'), 'W7': ('Garvan Institute of Medical Research', 'Cholangiocarcinoma', 'NCH'), 'W8': ('Greenville Health System', 'Breast invasive carcinoma', 'NCH'), 'W9': ('University of Kansas', 'Brain Lower Grade Glioma', 'NCH'), 'WA': ('University of Schleswig-Holstein', 'Head and Neck squamous cell carcinoma', 'NCH'), 'WB': ('Erasmus MC', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'WC': ('MD Anderson', 'Uveal Melanoma', 'NCH'), 'WD': ('Emory University', 'Cholangiocarcinoma', 'NCH'), 'WE': ('Norfolk and Norwich Hospital', 'Skin Cutaneous Melanoma', 'NCH'), 'WF': ('Greenville Health System', 'Pancreatic adenocarcinoma', 'NCH'), 'WG': ('Greenville Health System', 'Lung squamous cell carcinoma', 'NCH'), 'WH': ('Greenville Health System', 'Brain Lower Grade Glioma', 'NCH'), 'WJ': ('Greenville Health System', 'Liver hepatocellular carcinoma', 'NCH'), 'WK': ('Brigham and Women\'s Hospital', 'Sarcoma', 'NCH'), 'WL': ('University of Kansas', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'WM': ('University of Kansas', 'Kidney renal clear cell carcinoma', 'NCH'), 'WN': ('University of Kansas', 'Kidney renal papillary cell carcinoma', 'NCH'), 'WP': ('University of Kansas', 'Sarcoma', 'NCH'), 'WQ': ('University of Kansas', 'Liver hepatocellular carcinoma', 'NCH'), 'WR': ('University of Kansas', 'Ovarian serous cystadenocarcinoma', 'NCH'), 'WS': ('University of Kansas', 'Colon adenocarcinoma', 'NCH'), 'WT': ('University of Kansas', 'Breast invasive carcinoma', 'NCH'), 'WU': ('Wake Forest University', 'Colon adenocarcinoma', 'NCH'), 'WW': ('Wake Forest University', 'Prostate adenocarcinoma', 'NCH'), 'WX': ('Yale University', 'Liver hepatocellular carcinoma', 'NCH'), 'WY': ('Johns Hopkins', 'Brain Lower Grade Glioma', 'NCH'), 'WZ': ('International Genomics Consortium', 'Testicular Germ Cell Tumors', 'NCH'), 'X2': ('University of Washington', 'Sarcoma', 'NCH'), 'X3': ('Cleveland Clinic Foundation', 'Testicular Germ Cell Tumors', 'NCH'), 'X4': ('Institute for Medical Research', 'Prostate adenocarcinoma', 'NCH'), 'X5': ('Institute of Human Virology Nigeria', 'Bladder Urothelial Carcinoma', 'NCH'), 'X6': ('University of Iowa', 'Sarcoma', 'NCH'), 'X7': ('ABS IUPUI', 'Thymoma', 'NCH'), 'X8': ('St. Joseph\'s Hospital Arizona', 'Esophageal carcinoma ', 'NCH'), 'X9': ('University of California, Davis', 'Sarcoma', 'NCH'), 'XA': ('University of Minnesota', 'Prostate adenocarcinoma', 'NCH'), 'XB': ('Albert Einstein Medical Center', 'Esophageal carcinoma ', 'NCH'), 'XC': ('Albert Einstein Medical Center', 'Lung squamous cell carcinoma', 'NCH'), 'XD': ('Providence Portland Medical Center', 'Pancreatic adenocarcinoma', 'NCH'), 'XE': ('University of Southern California', 'Testicular Germ Cell Tumors', 'NCH'), 'XF': ('University of Southern California', 'Bladder Urothelial Carcinoma', 'NCH'), 'XG': ('BLN UT Southwestern Medical Center at Dallas', 'Pheochromocytoma and Paraganglioma', 'NCH'), 'XH': ('BLN Baylor', 'Thymoma', 'NCH'), 'XJ': ('University of Kansas', 'Prostate adenocarcinoma', 'NCH'), 'XK': ('Mayo Clinic Arizona', 'Prostate adenocarcinoma', 'NCH'), 'XM': ('MSKCC', 'Thymoma', 'NCH'), 'XN': ('University of Sao Paulo', 'Pancreatic adenocarcinoma', 'NCH'), 'XP': ('University of Sao Paulo', 'Esophageal carcinoma ', 'NCH'), 'XQ': ('University of Sao Paulo', 'Prostate adenocarcinoma', 'NCH'), 'XR': ('University of Sao Paulo', 'Liver hepatocellular carcinoma', 'NCH'), 'XS': ('University of Sao Paulo', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'XT': ('Johns Hopkins', 'Mesothelioma', 'NCH'), 'XU': ('University Health Network', 'Thymoma', 'NCH'), 'XV': ('Capital Biosciences', 'Skin Cutaneous Melanoma', 'NCH'), 'XX': ('Spectrum Health', 'Breast invasive carcinoma', 'NCH'), 'XY': ('Spectrum Health', 'Testicular Germ Cell Tumors', 'NCH'), 'Y3': ('University of New Mexico', 'Acute Myeloid Leukemia', 'NCH'), 'Y5': ('University of Arizona', 'Sarcoma', 'NCH'), 'Y6': ('University of Arizona', 'Prostate adenocarcinoma', 'NCH'), 'Y8': ('Spectrum Health', 'Kidney renal papillary cell carcinoma', 'NCH'), 'YA': ('Spectrum Health', 'Liver hepatocellular carcinoma', 'NCH'), 'YB': ('Spectrum Health', 'Pancreatic adenocarcinoma', 'NCH'), 'YC': ('Spectrum Health', 'Bladder Urothelial Carcinoma', 'NCH'), 'YD': ('Spectrum Health', 'Skin Cutaneous Melanoma', 'NCH'), 'YF': ('University of Puerto Rico', 'Bladder Urothelial Carcinoma', 'NCH'), 'YG': ('University of Puerto Rico', 'Skin Cutaneous Melanoma', 'NCH'), 'YH': ('Stanford University', 'Pancreatic adenocarcinoma', 'NCH'), 'YJ': ('Stanford University', 'Prostate adenocarcinoma', 'NCH'), 'YL': ('PROCURE Biobank', 'Prostate adenocarcinoma', 'NCH'), 'YN': ('University of Arizona', 'Skin Cutaneous Melanoma', 'NCH'), 'YR': ('Barretos Cancer Hospital', 'Cholangiocarcinoma', 'NCH'), 'YS': ('Barretos Cancer Hospital', 'Mesothelioma', 'NCH'), 'YT': ('Barretos Cancer Hospital', 'Thymoma', 'NCH'), 'YU': ('Barretos Cancer Hospital', 'Testicular Germ Cell Tumors', 'NCH'), 'YV': ('MSKCC', 'Uveal Melanoma', 'NCH'), 'YW': ('Albert Einstein Medical Center', 'Sarcoma', 'NCH'), 'YX': ('Emory University', 'Stomach adenocarcinoma', 'NCH'), 'YY': ('Roswell Park', 'Pancreatic adenocarcinoma', 'NCH'), 'YZ': ('The Ohio State University', 'Uveal Melanoma', 'NCH'), 'Z2': ('IDI-IRCCS', 'Skin Cutaneous Melanoma', 'NCH'), 'Z3': ('UCLA', 'Sarcoma', 'NCH'), 'Z4': ('Cureline', 'Sarcoma', 'NCH'), 'Z5': ('Cureline', 'Pancreatic adenocarcinoma', 'NCH'), 'Z6': ('Cureline', 'Esophageal carcinoma ', 'NCH'), 'Z7': ('John Wayne Cancer Center', 'Breast invasive carcinoma', 'NCH'), 'Z8': ('John Wayne Cancer Center', 'Pancreatic adenocarcinoma', 'NCH'), 'ZA': ('Candler', 'Stomach adenocarcinoma', 'NCH'), 'ZB': ('Thoraxklinik', 'Thymoma', 'NCH'), 'ZC': ('University of Mannheim', 'Thymoma', 'NCH'), 'ZD': ('ILSbio', 'Cholangiocarcinoma', 'NCH'), 'ZE': ('Spectrum Health', 'Lung squamous cell carcinoma', 'NCH'), 'ZF': ('University of Sheffield', 'Bladder Urothelial Carcinoma', 'NCH'), 'ZG': ('University Medical Center Hamburg-Eppendorf', 'Prostate adenocarcinoma', 'NCH'), 'ZH': ('University of North Carolina', 'Cholangiocarcinoma', 'NCH'), 'ZJ': ('NCI HRE Branch', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), 'ZK': ('University of New Mexico', 'Cholangiocarcinoma', 'NCH'), 'ZL': ('Valley Hospital', 'Thymoma', 'NCH'), 'ZM': ('University of Ulm', 'Testicular Germ Cell Tumors', 'NCH'), 'ZN': ('Brigham and Women\'s Hospital Division of Thoracic Surgery', 'Mesothelioma', 'NCH'), 'ZP': ('Medical College of Wisconsin', 'Liver hepatocellular carcinoma', 'NCH'), 'ZQ': ('Tayside Tissue Bank', 'Stomach adenocarcinoma', 'NCH'), 'ZR': ('Tayside Tissue Bank', 'Esophageal carcinoma ', 'NCH'), 'ZS': ('Tayside Tissue Bank', 'Liver hepatocellular carcinoma', 'NCH'), 'ZT': ('International Genomics Consortium', 'Thymoma', 'NCH'), 'ZU': ('Spectrum Health', 'Cholangiocarcinoma', 'NCH'), 'ZW': ('University of Alabama', 'Pancreatic adenocarcinoma', 'NCH'), 'ZX': ('University of Alabama', 'Cervical squamous cell carcinoma and endocervical adenocarcinoma', 'NCH'), } SAMPLE_TYPE = { # 'Code': ('Definition', 'Short Letter Code'), '01': ('Primary solid Tumor', 'TP'), '02': ('Recurrent Solid Tumor', 'TR'), '03': ('Primary Blood Derived Cancer - Peripheral Blood', 'TB'), '04': ('Recurrent Blood Derived Cancer - Bone Marrow', 'TRBM'), '05': ('Additional - New Primary', 'TAP'), '06': ('Metastatic', 'TM'), '07': ('Additional Metastatic', 'TAM'), '08': ('Human Tumor Original Cells', 'THOC'), '09': ('Primary Blood Derived Cancer - Bone Marrow', 'TBM'), '10': ('Blood Derived Normal', 'NB'), '11': ('Solid Tissue Normal', 'NT'), '12': ('Buccal Cell Normal', 'NBC'), '13': ('EBV Immortalized Normal', 'NEBV'), '14': ('Bone Marrow Normal', 'NBM'), '20': ('Control Analyte', 'CELLC'), '40': ('Recurrent Blood Derived Cancer - Peripheral Blood', 'TRB'), '50': ('Cell Lines', 'CELL'), '60': ('Primary Xenograft Tissue', 'XP'), '61': ('Cell Line Derived Xenograft Tissue', 'XCL'), }
TcgaCodes
Home.js
import React, { Component } from 'react'; import PostList from './posts/PostList';
export default class Home extends Component { static displayName = Home.name; constructor(props) { super(props); this.state = { latestPosts: [] }; } componentWillMount() { fetch('api/Posts/GetList', { method: 'GET' }) .then((response) => response.json()) .then((data) => { this.setState({ latestPosts: data }); }); } render() { const { latestPosts } = this.state; return ( <div className="postsList"> <h1 className="main-title">Latest Posts</h1> <hr className="divider" /> {latestPosts.length > 0 ? ( <PostList posts={latestPosts} /> ) : ( <h1 className="main-title">There&apos;re no posts yet!</h1> )} </div> ); } }
StateProvider.tsx
import React, { createContext, useReducer } from "react"; const StateContext = createContext<any>({}); const StateProvider = ({ reducer, initialState, children }) => (
{children} </StateContext.Provider> ); export { StateProvider, StateContext };
<StateContext.Provider value={ useReducer(reducer, initialState) }>
kotlin-codegen-shared.ts
/** * @license * Copyright (c) 2020 Google Inc. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ // Includes reserve words for Entity Interface // https://kotlinlang.org/docs/reference/keyword-reference.html // [...document.getElementsByTagName('code')].map(x => x.innerHTML);
'as', 'as?', 'break', 'class', 'continue', 'do', 'else', 'false', 'for', 'fun', 'if', 'in', '!in', 'interface', 'is', '!is', 'null', 'object', 'package', 'return', 'super', 'this', 'throw', 'true', 'try', 'typealias', 'val', 'var', 'when', 'while', 'by', 'catch', 'constructor', 'delegate', 'dynamic', 'field', 'file', 'finally', 'get', 'import', 'init', 'param', 'property', 'receiver', 'set', 'setparam', 'where', 'actual', 'abstract', 'annotation', 'companion', 'const', 'crossinline', 'data', 'enum', 'expect', 'external', 'final', 'infix', 'inline', 'inner', 'internal', 'lateinit', 'noinline', 'open', 'operator', 'out', 'override', 'private', 'protected', 'public', 'reified', 'sealed', 'suspend', 'tailrec', 'vararg', 'it', 'entityId', 'creationTimestamp', 'expirationTimestamp' ]; export function escapeIdentifier(name: string): string { // TODO(cypher1): Check for complex keywords (e.g. cases where both 'final' and 'final_' are keywords). // TODO(cypher1): Check for name overlaps (e.g. 'final' and 'final_' should not be escaped to the same identifier. return name + (keywords.includes(name) ? '_' : ''); }
const keywords = [
parse_experimental.go
// +build experimental package runconfig import flag "github.com/emerald-ci/test-runner/Godeps/_workspace/src/github.com/docker/docker/pkg/mflag"
func attachExperimentalFlags(cmd *flag.FlagSet) *experimentalFlags { flags := make(map[string]interface{}) flags["publish-service"] = cmd.String([]string{"-publish-service"}, "", "Publish this container as a service") return &experimentalFlags{flags: flags} } func applyExperimentalFlags(exp *experimentalFlags, config *Config, hostConfig *HostConfig) { config.PublishService = *(exp.flags["publish-service"]).(*string) }
type experimentalFlags struct { flags map[string]interface{} }
iscsiutil.rs
use once_cell::sync::Lazy; use std::{env, path::Path, process::Command, thread, time}; // The iscsiadm executable invoked is dependent on the environment. // For the container we set it using and environment variable, // typically this is the "/bin/mayastor-iscsiadm" script, // created by the mayastor image build scripts. // For development hosts just setting it to iscsiadm works. static ISCSIADM: Lazy<String> = Lazy::new(|| { if env::var("ISCSIADM").is_err() { debug!("defaulting to using iscsiadm"); "iscsiadm".to_string() } else { debug!("using {}", env::var("ISCSIADM").unwrap()); env::var("ISCSIADM").unwrap() } }); fn wait_for_path_to_exist(devpath: &str, max_retries: i32) -> bool { let second = time::Duration::from_millis(1000); let device_path = Path::new(devpath); let mut retries: i32 = 0; let now = time::Instant::now(); while !device_path.exists() && retries < max_retries { thread::sleep(second); retries += 1; } trace!( "wait_for_path_to_exist for elapsed time is {:?}", now.elapsed() ); device_path.exists() } fn iscsi_realpath(path: String) -> String { match std::fs::read_link(path.as_str()) { Ok(linkpath) => { // For iscsi the root path is /dev/disk/by-path let mut devpath = std::path::PathBuf::from("/dev/disk/by-path"); devpath.push(linkpath); let absdevpath = std::fs::canonicalize(devpath).unwrap(); absdevpath.into_os_string().into_string().unwrap() } _ => path, } } fn attach_disk( ip_addr: &str, port: u16, iqn: &str, lun: &str, ) -> Result<String, String> { let tp = format!("{}:{}", ip_addr, port); let device_path = format!("/dev/disk/by-path/ip-{}-iscsi-{}-lun-{}", tp, iqn, lun); let iscsiadm = ISCSIADM.as_str(); // Rescan sessions to discover newly mapped LUNs // Do not specify the interface when rescanning // to avoid establishing additional sessions to the same target. let args_rescan = ["-m", "node", "-p", &tp, "-T", &iqn, "-R"]; trace!("iscsiadm {:?}", args_rescan); let _ = Command::new(&iscsiadm) .args(&args_rescan) .output() .expect("Failed iscsiadm rescan"); // If the device path exists then a previous invocation of this // method has succeeded. if wait_for_path_to_exist(device_path.as_str(), 1) { trace!("path already exists!"); return Ok(iscsi_realpath(device_path)); } let args_discoverydb_new = [ "-m", "discoverydb", "-t", "sendtargets", "-p", &tp, "-I", "default", "-o", "new", ]; trace!("iscsiadm {:?}", &args_discoverydb_new); let output = Command::new(&iscsiadm) .args(&args_discoverydb_new) .output() .expect("Failed iscsiadm discovery"); if !output.status.success() { return Err(String::from_utf8(output.stderr).unwrap()); } let args_discover = [ "-m", "discoverydb", "-t", "sendtargets", "-p", &tp, "-I", "default", "--discover", ]; trace!("iscsiadm {:?}", args_discover); // build discoverydb and discover iscsi target let output = Command::new(&iscsiadm) .args(&args_discover) .output() .expect("Failed iscsiadm discovery"); if !output.status.success() { let args_discover_del = [ "-m", "discoverydb", "-t", "sendtargets", "-p", &tp, "-I", "default", "-o", "delete", ]; // delete discoverydb record Command::new(&iscsiadm).args(&args_discover_del); return Err(String::from_utf8(output.stderr).unwrap()); } let args_login = [ "-m", "node", "-p", &tp, "-T", &iqn, "-I", "default", "--login", ]; trace!("iscsiadm {:?}", args_login); // login to iscsi target let output = Command::new(&iscsiadm) .args(&args_login) .output() .expect("Failed iscsiadm login"); if !output.status.success() { let args_login_del = [ "-m", "node", "-p", &tp, "-T", &iqn, "-I", "default", "-o", "delete", ]; // delete the node record from the database. Command::new(&iscsiadm).args(&args_login_del); return Err(String::from_utf8(output.stderr).unwrap()); } if wait_for_path_to_exist(device_path.as_str(), 10) { trace!("{} path exists!", device_path) } else { trace!("{} path does not exist after 10s!", device_path); return Err("Could not attach disk: Timeout after 10s".to_string()); } Ok(iscsi_realpath(device_path)) } /// Attaches a nexus iscsi target matching the uri specfied. /// Returns path to the device on which the nexus iscsi target /// has been mounted succesfully or error pub fn iscsi_attach_disk(iscsi_uri: &str) -> Result<String, String> { trace!("iscsi_attach_disk {}", iscsi_uri); if let Ok(url) = url::Url::parse(iscsi_uri) { if url.scheme() == "iscsi" { let tokens = url.path_segments().map(|c| c.collect::<Vec<_>>()).unwrap(); return attach_disk( url.host_str().unwrap(), url.port().unwrap(), tokens[0], tokens[1], ); } } Err(format!("Invalid iscsi URI {}", iscsi_uri)) } fn
(ip_addr: &str, port: &str, iqn: &str) -> Result<(), String> { let iscsiadm = ISCSIADM.as_str(); let tp = format!("{}:{}", ip_addr, port); let args_logout = ["-m", "node", "-T", &iqn, "-p", &tp, "-u"]; trace!("iscsiadm {:?}", args_logout); let output = Command::new(&iscsiadm) .args(&args_logout) .output() .expect("Failed iscsiadm logout"); if !output.status.success() { return Err(String::from_utf8(output.stderr).unwrap()); } let args_delete = ["-m", "node", "-o", "delete", "-T", &iqn]; trace!("iscsiadm {:?}", args_delete); let output = Command::new(&iscsiadm) .args(&args_delete) .output() .expect("Failed iscsiadm login"); if !output.status.success() { return Err(String::from_utf8(output.stderr).unwrap()); } Ok(()) } /// Detaches nexus iscsi target matching the volume id if has /// been mounted. /// Returns error is the nexus iscsi target was not mounted. pub fn iscsi_detach_disk(uuid: &str) -> Result<(), String> { trace!("iscsi_detach_disk {}", uuid); let device_path = match get_iscsi_device_path(uuid) { Some(devpath) => devpath, _ => return Err("Unknown iscsi device".to_string()), }; static RE_DEVICE_PATH: Lazy<regex::Regex> = Lazy::new(|| { regex::Regex::new( r"(?x) ip-(?P<ip>\d+.\d+.\d+.\d+):(?P<port>\d+)-iscsi-(?P<iqn>.*)-lun-(?P<lun>\d+) ", ) .unwrap() }); let caps = RE_DEVICE_PATH.captures(device_path.as_str()); match caps { Some(details) => { trace!("{:?}", details); detach_disk(&details["ip"], &details["port"], &details["iqn"]) } None => { trace!("Doh!"); Err(format!("Invalid device path: {}", device_path)) } } } fn get_iscsi_device_path(uuid: &str) -> Option<String> { let iscsiadm = ISCSIADM.as_str(); if which::which(&iscsiadm).is_err() { trace!("Cannot find {}", &iscsiadm); return None; } let output = Command::new(&iscsiadm) .args(&["-m", "node"]) .output() .expect("Failed iscsiadm"); if !output.status.success() { debug!( "iscsiadm failed: {}", String::from_utf8(output.stderr).unwrap() ); return None; } let op = String::from_utf8(output.stdout).unwrap(); static RE_TARGET: Lazy<regex::Regex> = Lazy::new(|| { regex::Regex::new( r"(?x) (?P<ip>\d+.\d+.\d+.\d+):(?P<port>\d+),(?P<lun>\d+)\s+(?P<iqn>.*:\w+)-(?P<uuid>.*) ", ) .unwrap() }); for cap in RE_TARGET.captures_iter(op.as_str()) { trace!("unstage: searching for {} got {}", uuid, &cap["uuid"]); if uuid == &cap["uuid"] { return Some(format!( "/dev/disk/by-path/ip-{}:{}-iscsi-{}-{}-lun-{}", &cap["ip"], &cap["port"], &cap["iqn"], &cap["uuid"], &cap["lun"], )); } } None } /// Search for and return path to the device on which a nexus iscsi /// target matching the volume id has been mounted or None. pub fn iscsi_find(uuid: &str) -> Option<String> { if let Some(path) = get_iscsi_device_path(uuid) { return Some(iscsi_realpath(path)); } None }
detach_disk
Task_Output.rs
#![allow(unused_imports, non_camel_case_types)] use crate::models::r4b::Address::Address; use crate::models::r4b::Age::Age; use crate::models::r4b::Annotation::Annotation; use crate::models::r4b::Attachment::Attachment; use crate::models::r4b::CodeableConcept::CodeableConcept; use crate::models::r4b::Coding::Coding; use crate::models::r4b::ContactDetail::ContactDetail; use crate::models::r4b::ContactPoint::ContactPoint; use crate::models::r4b::Contributor::Contributor; use crate::models::r4b::Count::Count; use crate::models::r4b::DataRequirement::DataRequirement; use crate::models::r4b::Distance::Distance; use crate::models::r4b::Dosage::Dosage; use crate::models::r4b::Duration::Duration; use crate::models::r4b::Element::Element; use crate::models::r4b::Expression::Expression; use crate::models::r4b::Extension::Extension; use crate::models::r4b::HumanName::HumanName; use crate::models::r4b::Identifier::Identifier; use crate::models::r4b::Meta::Meta; use crate::models::r4b::Money::Money; use crate::models::r4b::ParameterDefinition::ParameterDefinition; use crate::models::r4b::Period::Period; use crate::models::r4b::Quantity::Quantity; use crate::models::r4b::Range::Range; use crate::models::r4b::Ratio::Ratio; use crate::models::r4b::Reference::Reference; use crate::models::r4b::RelatedArtifact::RelatedArtifact; use crate::models::r4b::SampledData::SampledData; use crate::models::r4b::Signature::Signature; use crate::models::r4b::Timing::Timing; use crate::models::r4b::TriggerDefinition::TriggerDefinition; use crate::models::r4b::UsageContext::UsageContext; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; /// A task to be performed. #[derive(Debug)] pub struct Task_Output<'a> { pub(crate) value: Cow<'a, Value>, } impl Task_Output<'_> { pub fn new(value: &Value) -> Task_Output { Task_Output { value: Cow::Borrowed(value), } } pub fn to_json(&self) -> Value { (*self.value).clone() } /// Extensions for valueBase64Binary pub fn _value_base_64_binary(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueBase64Binary") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueBoolean pub fn _value_boolean(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueBoolean") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueCanonical pub fn _value_canonical(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueCanonical") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueCode pub fn _value_code(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueCode") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueDate pub fn _value_date(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueDate") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueDateTime pub fn _value_date_time(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueDateTime") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueDecimal pub fn _value_decimal(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueDecimal") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueId pub fn _value_id(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueId") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueInstant pub fn _value_instant(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueInstant") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueInteger pub fn _value_integer(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueInteger") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueMarkdown pub fn _value_markdown(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueMarkdown") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueOid pub fn _value_oid(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueOid") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valuePositiveInt pub fn _value_positive_int(&self) -> Option<Element> { if let Some(val) = self.value.get("_valuePositiveInt") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueString pub fn _value_string(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueString") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueTime pub fn _value_time(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueTime") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueUnsignedInt pub fn _value_unsigned_int(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueUnsignedInt") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueUri pub fn _value_uri(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueUri") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueUrl pub fn _value_url(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueUrl") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for valueUuid pub fn _value_uuid(&self) -> Option<Element> { if let Some(val) = self.value.get("_valueUuid") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element. To make the use of extensions safe and manageable, /// there is a strict set of governance applied to the definition and use of /// extensions. Though any implementer can define an extension, there is a set of /// requirements that SHALL be met as part of the definition of the extension. pub fn extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("extension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// Unique id for the element within a resource (for internal references). This may be /// any string value that does not contain spaces. pub fn id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("id") { return Some(string); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element and that modifies the understanding of the element /// in which it is contained and/or the understanding of the containing element's /// descendants. Usually modifier elements provide negation or qualification. To make /// the use of extensions safe and manageable, there is a strict set of governance /// applied to the definition and use of extensions. Though any implementer can define /// an extension, there is a set of requirements that SHALL be met as part of the /// definition of the extension. Applications processing a resource are required to /// check for modifier extensions. Modifier extensions SHALL NOT change the meaning /// of any elements on Resource or DomainResource (including cannot change the meaning /// of modifierExtension itself). pub fn modifier_extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("modifierExtension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// The name of the Output parameter. pub fn fhir_type(&self) -> CodeableConcept { CodeableConcept { value: Cow::Borrowed(&self.value["type"]), } } /// The value of the Output parameter as a basic type. pub fn value_address(&self) -> Option<Address> { if let Some(val) = self.value.get("valueAddress") { return Some(Address { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_age(&self) -> Option<Age> { if let Some(val) = self.value.get("valueAge") { return Some(Age { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_annotation(&self) -> Option<Annotation> { if let Some(val) = self.value.get("valueAnnotation") { return Some(Annotation { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_attachment(&self) -> Option<Attachment> { if let Some(val) = self.value.get("valueAttachment") { return Some(Attachment { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_base_64_binary(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueBase64Binary") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_boolean(&self) -> Option<bool> { if let Some(val) = self.value.get("valueBoolean") { return Some(val.as_bool().unwrap()); } return None;
pub fn value_canonical(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueCanonical") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_code(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueCode") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_codeable_concept(&self) -> Option<CodeableConcept> { if let Some(val) = self.value.get("valueCodeableConcept") { return Some(CodeableConcept { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_coding(&self) -> Option<Coding> { if let Some(val) = self.value.get("valueCoding") { return Some(Coding { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_contact_detail(&self) -> Option<ContactDetail> { if let Some(val) = self.value.get("valueContactDetail") { return Some(ContactDetail { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_contact_point(&self) -> Option<ContactPoint> { if let Some(val) = self.value.get("valueContactPoint") { return Some(ContactPoint { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_contributor(&self) -> Option<Contributor> { if let Some(val) = self.value.get("valueContributor") { return Some(Contributor { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_count(&self) -> Option<Count> { if let Some(val) = self.value.get("valueCount") { return Some(Count { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_data_requirement(&self) -> Option<DataRequirement> { if let Some(val) = self.value.get("valueDataRequirement") { return Some(DataRequirement { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_date(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueDate") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_date_time(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueDateTime") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_decimal(&self) -> Option<f64> { if let Some(val) = self.value.get("valueDecimal") { return Some(val.as_f64().unwrap()); } return None; } /// The value of the Output parameter as a basic type. pub fn value_distance(&self) -> Option<Distance> { if let Some(val) = self.value.get("valueDistance") { return Some(Distance { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_dosage(&self) -> Option<Dosage> { if let Some(val) = self.value.get("valueDosage") { return Some(Dosage { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_duration(&self) -> Option<Duration> { if let Some(val) = self.value.get("valueDuration") { return Some(Duration { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_expression(&self) -> Option<Expression> { if let Some(val) = self.value.get("valueExpression") { return Some(Expression { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_human_name(&self) -> Option<HumanName> { if let Some(val) = self.value.get("valueHumanName") { return Some(HumanName { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueId") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_identifier(&self) -> Option<Identifier> { if let Some(val) = self.value.get("valueIdentifier") { return Some(Identifier { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_instant(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueInstant") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_integer(&self) -> Option<f64> { if let Some(val) = self.value.get("valueInteger") { return Some(val.as_f64().unwrap()); } return None; } /// The value of the Output parameter as a basic type. pub fn value_markdown(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueMarkdown") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_meta(&self) -> Option<Meta> { if let Some(val) = self.value.get("valueMeta") { return Some(Meta { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_money(&self) -> Option<Money> { if let Some(val) = self.value.get("valueMoney") { return Some(Money { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_oid(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueOid") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_parameter_definition(&self) -> Option<ParameterDefinition> { if let Some(val) = self.value.get("valueParameterDefinition") { return Some(ParameterDefinition { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_period(&self) -> Option<Period> { if let Some(val) = self.value.get("valuePeriod") { return Some(Period { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_positive_int(&self) -> Option<f64> { if let Some(val) = self.value.get("valuePositiveInt") { return Some(val.as_f64().unwrap()); } return None; } /// The value of the Output parameter as a basic type. pub fn value_quantity(&self) -> Option<Quantity> { if let Some(val) = self.value.get("valueQuantity") { return Some(Quantity { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_range(&self) -> Option<Range> { if let Some(val) = self.value.get("valueRange") { return Some(Range { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_ratio(&self) -> Option<Ratio> { if let Some(val) = self.value.get("valueRatio") { return Some(Ratio { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_reference(&self) -> Option<Reference> { if let Some(val) = self.value.get("valueReference") { return Some(Reference { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_related_artifact(&self) -> Option<RelatedArtifact> { if let Some(val) = self.value.get("valueRelatedArtifact") { return Some(RelatedArtifact { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_sampled_data(&self) -> Option<SampledData> { if let Some(val) = self.value.get("valueSampledData") { return Some(SampledData { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_signature(&self) -> Option<Signature> { if let Some(val) = self.value.get("valueSignature") { return Some(Signature { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_string(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueString") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_time(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueTime") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_timing(&self) -> Option<Timing> { if let Some(val) = self.value.get("valueTiming") { return Some(Timing { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_trigger_definition(&self) -> Option<TriggerDefinition> { if let Some(val) = self.value.get("valueTriggerDefinition") { return Some(TriggerDefinition { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_unsigned_int(&self) -> Option<f64> { if let Some(val) = self.value.get("valueUnsignedInt") { return Some(val.as_f64().unwrap()); } return None; } /// The value of the Output parameter as a basic type. pub fn value_uri(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueUri") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_url(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueUrl") { return Some(string); } return None; } /// The value of the Output parameter as a basic type. pub fn value_usage_context(&self) -> Option<UsageContext> { if let Some(val) = self.value.get("valueUsageContext") { return Some(UsageContext { value: Cow::Borrowed(val), }); } return None; } /// The value of the Output parameter as a basic type. pub fn value_uuid(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("valueUuid") { return Some(string); } return None; } pub fn validate(&self) -> bool { if let Some(_val) = self._value_base_64_binary() { if !_val.validate() { return false; } } if let Some(_val) = self._value_boolean() { if !_val.validate() { return false; } } if let Some(_val) = self._value_canonical() { if !_val.validate() { return false; } } if let Some(_val) = self._value_code() { if !_val.validate() { return false; } } if let Some(_val) = self._value_date() { if !_val.validate() { return false; } } if let Some(_val) = self._value_date_time() { if !_val.validate() { return false; } } if let Some(_val) = self._value_decimal() { if !_val.validate() { return false; } } if let Some(_val) = self._value_id() { if !_val.validate() { return false; } } if let Some(_val) = self._value_instant() { if !_val.validate() { return false; } } if let Some(_val) = self._value_integer() { if !_val.validate() { return false; } } if let Some(_val) = self._value_markdown() { if !_val.validate() { return false; } } if let Some(_val) = self._value_oid() { if !_val.validate() { return false; } } if let Some(_val) = self._value_positive_int() { if !_val.validate() { return false; } } if let Some(_val) = self._value_string() { if !_val.validate() { return false; } } if let Some(_val) = self._value_time() { if !_val.validate() { return false; } } if let Some(_val) = self._value_unsigned_int() { if !_val.validate() { return false; } } if let Some(_val) = self._value_uri() { if !_val.validate() { return false; } } if let Some(_val) = self._value_url() { if !_val.validate() { return false; } } if let Some(_val) = self._value_uuid() { if !_val.validate() { return false; } } if let Some(_val) = self.extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.id() {} if let Some(_val) = self.modifier_extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if !self.fhir_type().validate() { return false; } if let Some(_val) = self.value_address() { if !_val.validate() { return false; } } if let Some(_val) = self.value_age() { if !_val.validate() { return false; } } if let Some(_val) = self.value_annotation() { if !_val.validate() { return false; } } if let Some(_val) = self.value_attachment() { if !_val.validate() { return false; } } if let Some(_val) = self.value_base_64_binary() {} if let Some(_val) = self.value_boolean() {} if let Some(_val) = self.value_canonical() {} if let Some(_val) = self.value_code() {} if let Some(_val) = self.value_codeable_concept() { if !_val.validate() { return false; } } if let Some(_val) = self.value_coding() { if !_val.validate() { return false; } } if let Some(_val) = self.value_contact_detail() { if !_val.validate() { return false; } } if let Some(_val) = self.value_contact_point() { if !_val.validate() { return false; } } if let Some(_val) = self.value_contributor() { if !_val.validate() { return false; } } if let Some(_val) = self.value_count() { if !_val.validate() { return false; } } if let Some(_val) = self.value_data_requirement() { if !_val.validate() { return false; } } if let Some(_val) = self.value_date() {} if let Some(_val) = self.value_date_time() {} if let Some(_val) = self.value_decimal() {} if let Some(_val) = self.value_distance() { if !_val.validate() { return false; } } if let Some(_val) = self.value_dosage() { if !_val.validate() { return false; } } if let Some(_val) = self.value_duration() { if !_val.validate() { return false; } } if let Some(_val) = self.value_expression() { if !_val.validate() { return false; } } if let Some(_val) = self.value_human_name() { if !_val.validate() { return false; } } if let Some(_val) = self.value_id() {} if let Some(_val) = self.value_identifier() { if !_val.validate() { return false; } } if let Some(_val) = self.value_instant() {} if let Some(_val) = self.value_integer() {} if let Some(_val) = self.value_markdown() {} if let Some(_val) = self.value_meta() { if !_val.validate() { return false; } } if let Some(_val) = self.value_money() { if !_val.validate() { return false; } } if let Some(_val) = self.value_oid() {} if let Some(_val) = self.value_parameter_definition() { if !_val.validate() { return false; } } if let Some(_val) = self.value_period() { if !_val.validate() { return false; } } if let Some(_val) = self.value_positive_int() {} if let Some(_val) = self.value_quantity() { if !_val.validate() { return false; } } if let Some(_val) = self.value_range() { if !_val.validate() { return false; } } if let Some(_val) = self.value_ratio() { if !_val.validate() { return false; } } if let Some(_val) = self.value_reference() { if !_val.validate() { return false; } } if let Some(_val) = self.value_related_artifact() { if !_val.validate() { return false; } } if let Some(_val) = self.value_sampled_data() { if !_val.validate() { return false; } } if let Some(_val) = self.value_signature() { if !_val.validate() { return false; } } if let Some(_val) = self.value_string() {} if let Some(_val) = self.value_time() {} if let Some(_val) = self.value_timing() { if !_val.validate() { return false; } } if let Some(_val) = self.value_trigger_definition() { if !_val.validate() { return false; } } if let Some(_val) = self.value_unsigned_int() {} if let Some(_val) = self.value_uri() {} if let Some(_val) = self.value_url() {} if let Some(_val) = self.value_usage_context() { if !_val.validate() { return false; } } if let Some(_val) = self.value_uuid() {} return true; } } #[derive(Debug)] pub struct Task_OutputBuilder { pub(crate) value: Value, } impl Task_OutputBuilder { pub fn build(&self) -> Task_Output { Task_Output { value: Cow::Owned(self.value.clone()), } } pub fn with(existing: Task_Output) -> Task_OutputBuilder { Task_OutputBuilder { value: (*existing.value).clone(), } } pub fn new(fhir_type: CodeableConcept) -> Task_OutputBuilder { let mut __value: Value = json!({}); __value["type"] = json!(fhir_type.value); return Task_OutputBuilder { value: __value }; } pub fn _value_base_64_binary<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueBase64Binary"] = json!(val.value); return self; } pub fn _value_boolean<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueBoolean"] = json!(val.value); return self; } pub fn _value_canonical<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueCanonical"] = json!(val.value); return self; } pub fn _value_code<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueCode"] = json!(val.value); return self; } pub fn _value_date<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueDate"] = json!(val.value); return self; } pub fn _value_date_time<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueDateTime"] = json!(val.value); return self; } pub fn _value_decimal<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueDecimal"] = json!(val.value); return self; } pub fn _value_id<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueId"] = json!(val.value); return self; } pub fn _value_instant<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueInstant"] = json!(val.value); return self; } pub fn _value_integer<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueInteger"] = json!(val.value); return self; } pub fn _value_markdown<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueMarkdown"] = json!(val.value); return self; } pub fn _value_oid<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueOid"] = json!(val.value); return self; } pub fn _value_positive_int<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valuePositiveInt"] = json!(val.value); return self; } pub fn _value_string<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueString"] = json!(val.value); return self; } pub fn _value_time<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueTime"] = json!(val.value); return self; } pub fn _value_unsigned_int<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueUnsignedInt"] = json!(val.value); return self; } pub fn _value_uri<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueUri"] = json!(val.value); return self; } pub fn _value_url<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueUrl"] = json!(val.value); return self; } pub fn _value_uuid<'a>(&'a mut self, val: Element) -> &'a mut Task_OutputBuilder { self.value["_valueUuid"] = json!(val.value); return self; } pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut Task_OutputBuilder { self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn id<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["id"] = json!(val); return self; } pub fn modifier_extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut Task_OutputBuilder { self.value["modifierExtension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn value_address<'a>(&'a mut self, val: Address) -> &'a mut Task_OutputBuilder { self.value["valueAddress"] = json!(val.value); return self; } pub fn value_age<'a>(&'a mut self, val: Age) -> &'a mut Task_OutputBuilder { self.value["valueAge"] = json!(val.value); return self; } pub fn value_annotation<'a>(&'a mut self, val: Annotation) -> &'a mut Task_OutputBuilder { self.value["valueAnnotation"] = json!(val.value); return self; } pub fn value_attachment<'a>(&'a mut self, val: Attachment) -> &'a mut Task_OutputBuilder { self.value["valueAttachment"] = json!(val.value); return self; } pub fn value_base_64_binary<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueBase64Binary"] = json!(val); return self; } pub fn value_boolean<'a>(&'a mut self, val: bool) -> &'a mut Task_OutputBuilder { self.value["valueBoolean"] = json!(val); return self; } pub fn value_canonical<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueCanonical"] = json!(val); return self; } pub fn value_code<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueCode"] = json!(val); return self; } pub fn value_codeable_concept<'a>( &'a mut self, val: CodeableConcept, ) -> &'a mut Task_OutputBuilder { self.value["valueCodeableConcept"] = json!(val.value); return self; } pub fn value_coding<'a>(&'a mut self, val: Coding) -> &'a mut Task_OutputBuilder { self.value["valueCoding"] = json!(val.value); return self; } pub fn value_contact_detail<'a>( &'a mut self, val: ContactDetail, ) -> &'a mut Task_OutputBuilder { self.value["valueContactDetail"] = json!(val.value); return self; } pub fn value_contact_point<'a>(&'a mut self, val: ContactPoint) -> &'a mut Task_OutputBuilder { self.value["valueContactPoint"] = json!(val.value); return self; } pub fn value_contributor<'a>(&'a mut self, val: Contributor) -> &'a mut Task_OutputBuilder { self.value["valueContributor"] = json!(val.value); return self; } pub fn value_count<'a>(&'a mut self, val: Count) -> &'a mut Task_OutputBuilder { self.value["valueCount"] = json!(val.value); return self; } pub fn value_data_requirement<'a>( &'a mut self, val: DataRequirement, ) -> &'a mut Task_OutputBuilder { self.value["valueDataRequirement"] = json!(val.value); return self; } pub fn value_date<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueDate"] = json!(val); return self; } pub fn value_date_time<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueDateTime"] = json!(val); return self; } pub fn value_decimal<'a>(&'a mut self, val: f64) -> &'a mut Task_OutputBuilder { self.value["valueDecimal"] = json!(val); return self; } pub fn value_distance<'a>(&'a mut self, val: Distance) -> &'a mut Task_OutputBuilder { self.value["valueDistance"] = json!(val.value); return self; } pub fn value_dosage<'a>(&'a mut self, val: Dosage) -> &'a mut Task_OutputBuilder { self.value["valueDosage"] = json!(val.value); return self; } pub fn value_duration<'a>(&'a mut self, val: Duration) -> &'a mut Task_OutputBuilder { self.value["valueDuration"] = json!(val.value); return self; } pub fn value_expression<'a>(&'a mut self, val: Expression) -> &'a mut Task_OutputBuilder { self.value["valueExpression"] = json!(val.value); return self; } pub fn value_human_name<'a>(&'a mut self, val: HumanName) -> &'a mut Task_OutputBuilder { self.value["valueHumanName"] = json!(val.value); return self; } pub fn value_id<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueId"] = json!(val); return self; } pub fn value_identifier<'a>(&'a mut self, val: Identifier) -> &'a mut Task_OutputBuilder { self.value["valueIdentifier"] = json!(val.value); return self; } pub fn value_instant<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueInstant"] = json!(val); return self; } pub fn value_integer<'a>(&'a mut self, val: f64) -> &'a mut Task_OutputBuilder { self.value["valueInteger"] = json!(val); return self; } pub fn value_markdown<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueMarkdown"] = json!(val); return self; } pub fn value_meta<'a>(&'a mut self, val: Meta) -> &'a mut Task_OutputBuilder { self.value["valueMeta"] = json!(val.value); return self; } pub fn value_money<'a>(&'a mut self, val: Money) -> &'a mut Task_OutputBuilder { self.value["valueMoney"] = json!(val.value); return self; } pub fn value_oid<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueOid"] = json!(val); return self; } pub fn value_parameter_definition<'a>( &'a mut self, val: ParameterDefinition, ) -> &'a mut Task_OutputBuilder { self.value["valueParameterDefinition"] = json!(val.value); return self; } pub fn value_period<'a>(&'a mut self, val: Period) -> &'a mut Task_OutputBuilder { self.value["valuePeriod"] = json!(val.value); return self; } pub fn value_positive_int<'a>(&'a mut self, val: f64) -> &'a mut Task_OutputBuilder { self.value["valuePositiveInt"] = json!(val); return self; } pub fn value_quantity<'a>(&'a mut self, val: Quantity) -> &'a mut Task_OutputBuilder { self.value["valueQuantity"] = json!(val.value); return self; } pub fn value_range<'a>(&'a mut self, val: Range) -> &'a mut Task_OutputBuilder { self.value["valueRange"] = json!(val.value); return self; } pub fn value_ratio<'a>(&'a mut self, val: Ratio) -> &'a mut Task_OutputBuilder { self.value["valueRatio"] = json!(val.value); return self; } pub fn value_reference<'a>(&'a mut self, val: Reference) -> &'a mut Task_OutputBuilder { self.value["valueReference"] = json!(val.value); return self; } pub fn value_related_artifact<'a>( &'a mut self, val: RelatedArtifact, ) -> &'a mut Task_OutputBuilder { self.value["valueRelatedArtifact"] = json!(val.value); return self; } pub fn value_sampled_data<'a>(&'a mut self, val: SampledData) -> &'a mut Task_OutputBuilder { self.value["valueSampledData"] = json!(val.value); return self; } pub fn value_signature<'a>(&'a mut self, val: Signature) -> &'a mut Task_OutputBuilder { self.value["valueSignature"] = json!(val.value); return self; } pub fn value_string<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueString"] = json!(val); return self; } pub fn value_time<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueTime"] = json!(val); return self; } pub fn value_timing<'a>(&'a mut self, val: Timing) -> &'a mut Task_OutputBuilder { self.value["valueTiming"] = json!(val.value); return self; } pub fn value_trigger_definition<'a>( &'a mut self, val: TriggerDefinition, ) -> &'a mut Task_OutputBuilder { self.value["valueTriggerDefinition"] = json!(val.value); return self; } pub fn value_unsigned_int<'a>(&'a mut self, val: f64) -> &'a mut Task_OutputBuilder { self.value["valueUnsignedInt"] = json!(val); return self; } pub fn value_uri<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueUri"] = json!(val); return self; } pub fn value_url<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueUrl"] = json!(val); return self; } pub fn value_usage_context<'a>(&'a mut self, val: UsageContext) -> &'a mut Task_OutputBuilder { self.value["valueUsageContext"] = json!(val.value); return self; } pub fn value_uuid<'a>(&'a mut self, val: &str) -> &'a mut Task_OutputBuilder { self.value["valueUuid"] = json!(val); return self; } }
} /// The value of the Output parameter as a basic type.
span.rs
use std::cmp::Ordering; use std::collections::HashSet; use std::ops::Range; use failure::Error; /// Span enum. /// /// Enum to represent the range of indices covered by a node. #[derive(Debug, PartialEq, Eq)] pub enum Span { /// Variant covering continuous indices. Continuous(ContinuousSpan), /// Variant covering discontinuous indices. Discontinuous(SkipSpan), } impl From<usize> for Span { fn from(idx: usize) -> Self { Span::new_continuous(idx, idx + 1) } } impl Clone for Span { fn clone(&self) -> Self { match self { Span::Continuous(span) => Span::Continuous(*span), Span::Discontinuous(span) => Span::Discontinuous(span.clone()), } } } impl Span { /// Return whether `index` is inside the `Span`. pub fn contains(&self, index: usize) -> bool { match self { Span::Continuous(span) => span.contains(index), Span::Discontinuous(span) => span.contains(index), } } /// Get this spans lower bounds. pub fn lower(&self) -> usize { match self { Span::Continuous(span) => span.lower, Span::Discontinuous(span) => span.lower, } } /// Get this spans upper bounds. pub fn upper(&self) -> usize { match self { Span::Continuous(span) => span.upper, Span::Discontinuous(span) => span.upper, } } /// Get this spans bounds as a tuple. pub fn bounds(&self) -> (usize, usize)
/// Get the number of indices covered. pub fn n_indices(&self) -> usize { match self { Span::Discontinuous(span) => span.upper - span.lower - span.skip.len(), Span::Continuous(span) => span.upper - span.lower, } } pub(crate) fn discontinuous(&self) -> Option<&SkipSpan> { if let Span::Discontinuous(span) = self { Some(span) } else { None } } // Internally used constructor to build a span from a vec. pub(crate) fn from_vec(mut coverage: Vec<usize>) -> Result<Self, Error> { coverage.sort(); let (lower, upper) = match (coverage.first(), coverage.last()) { (Some(first), Some(last)) => (*first, *last + 1), _ => return Err(format_err!("Can't build range from empty vec")), }; let mut skip = HashSet::new(); let mut prev = upper; for id in coverage.into_iter().rev() { if prev == id + 1 { prev = id; } else { // duplicate entries end up in this branch but don't get added since the range // (id + 1..prev) is empty skip.extend(id + 1..prev); prev = id; } } if !skip.is_empty() { Ok(Span::Discontinuous(SkipSpan::new(lower, upper, skip))) } else { Ok(Span::Continuous(ContinuousSpan::new(lower, upper))) } } // Method used internally to increment the upper bounds of a span. pub(crate) fn extend(&mut self) { match self { Span::Continuous(span) => span.upper += 1, Span::Discontinuous(span) => span.upper += 1, } } // Internally used constructor for convenience. pub(crate) fn new_continuous(lower: usize, upper: usize) -> Self { Span::Continuous(ContinuousSpan::new(lower, upper)) } } /// Struct representing the span covered by node attached to this edge #[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)] pub struct ContinuousSpan { pub lower: usize, pub upper: usize, } impl ContinuousSpan { pub(crate) fn new(lower: usize, upper: usize) -> Self { assert!(lower < upper); ContinuousSpan { lower, upper } } /// Return whether `index` is inside the `Span`. pub fn contains(&self, index: usize) -> bool { index < self.upper && index >= self.lower } /// Get this spans lower bounds. pub fn lower(&self) -> usize { self.lower } /// Get this spans upper bounds. pub fn upper(&self) -> usize { self.upper } /// Get this spans bounds as a tuple. pub fn bounds(&self) -> (usize, usize) { (self.lower, self.upper) } /// Number of covered indices. pub fn n_indices(&self) -> usize { self.upper - self.lower } } /// Struct representing discontinuous Coverage #[derive(Clone, Debug, PartialEq, Eq)] pub struct SkipSpan { lower: usize, upper: usize, skip: HashSet<usize>, } impl SkipSpan { // Internally used constructor for SkipSpan. pub(crate) fn new(lower: usize, upper: usize, skip: HashSet<usize>) -> Self { assert!(lower < upper); assert!( !skip.is_empty(), "SkipSpan hast to contain skipped indices." ); assert_ne!(skip.len(), upper - lower, "Can't skip all indices."); SkipSpan { lower, upper, skip } } /// Return whether `index` is inside the `Span`. pub fn contains(&self, index: usize) -> bool { index < self.upper && index >= self.lower && !self.skip.contains(&index) } /// Get this span's skipped indices. pub fn skips(&self) -> &HashSet<usize> { &self.skip } /// Get this spans lower bounds. pub fn lower(&self) -> usize { self.lower } /// Get this spans upper bounds. pub fn upper(&self) -> usize { self.upper } /// Get this spans bounds as a tuple. pub fn bounds(&self) -> (usize, usize) { (self.lower, self.upper) } /// Number of covered indices. pub fn n_indices(&self) -> usize { self.upper - self.lower - self.skip.len() } } impl Ord for Span { fn cmp(&self, other: &Span) -> Ordering { if self.lower() != other.lower() { self.lower().cmp(&other.lower()) } else if self.upper() != other.upper() { self.upper().cmp(&other.upper()) } else { self.n_indices().cmp(&other.n_indices()) } } } impl PartialOrd for Span { fn partial_cmp(&self, other: &Span) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> IntoIterator for &'a Span { type Item = usize; type IntoIter = SpanIter<'a>; fn into_iter(self) -> SpanIter<'a> { match self { Span::Discontinuous(span) => span.into_iter(), Span::Continuous(span) => span.into_iter(), } } } impl<'a> IntoIterator for &'a SkipSpan { type Item = usize; type IntoIter = SpanIter<'a>; fn into_iter(self) -> SpanIter<'a> { SpanIter { range: self.lower..self.upper, skip: Some(&self.skip), } } } impl<'a> IntoIterator for &'a ContinuousSpan { type Item = usize; type IntoIter = SpanIter<'a>; fn into_iter(self) -> SpanIter<'a> { SpanIter { range: self.lower..self.upper, skip: None, } } } /// Iterator over range excluding indices in `skip`. #[derive(Debug, Eq, PartialEq)] pub struct SpanIter<'a> { range: Range<usize>, skip: Option<&'a HashSet<usize>>, } impl<'a> Iterator for SpanIter<'a> { type Item = usize; fn next(&mut self) -> Option<Self::Item> { while let Some(next) = self.range.next() { if let Some(skip) = self.skip { if skip.contains(&next) { continue; } } return Some(next); } None } } #[cfg(test)] mod tests { use std::collections::HashSet; use crate::{ContinuousSpan, SkipSpan, Span}; #[test] #[should_panic] fn invalid_cont_span_2_1() { Span::new_continuous(2, 1); } #[test] #[should_panic] fn invalid_skip_span_2_1() { Span::new_continuous(2, 1); } #[test] #[should_panic] fn invalid_skip_full_span() { let mut skip = HashSet::new(); skip.insert(0); skip.insert(1); SkipSpan::new(0, 2, skip); } #[test] fn simple_test() { let mut skip = HashSet::new(); skip.insert(1); skip.insert(2); let span = Span::Discontinuous(SkipSpan::new(0, 4, skip)); assert_eq!(span.lower(), 0); assert_eq!(span.upper(), 4); assert_eq!(span.bounds(), (0, 4)); assert_eq!(span.into_iter().collect::<Vec<_>>(), vec![0, 3]); } #[test] fn contains_skipspan() { let skip = vec![3, 5].into_iter().collect::<HashSet<usize>>(); let span = SkipSpan::new(0, 10, skip); assert!(span.contains(0)); assert!(span.contains(1)); assert!(span.contains(2)); assert!(!span.contains(3)); assert!(span.contains(4)); assert!(!span.contains(5)); assert!(span.contains(6)); assert!(!span.contains(10)); } #[test] fn contains_contspan() { let span = ContinuousSpan::new(0, 10); assert!(span.contains(0)); assert!(span.contains(1)); assert!(span.contains(2)); assert!(span.contains(4)); assert!(span.contains(6)); assert!(!span.contains(10)) } #[test] fn contains_span() { let span = Span::new_continuous(0, 10); assert!(span.contains(0)); assert!(span.contains(1)); assert!(span.contains(2)); assert!(span.contains(4)); assert!(span.contains(6)); assert!(!span.contains(10)) } #[test] fn test_from_ordered_vec() { let v = vec![1, 2, 4, 6, 8, 10]; let span = Span::from_vec(v.clone()).unwrap(); for (target, test) in span.into_iter().zip(v) { assert_eq!(target, test) } } #[test] fn test_from_vec_duplicates() { let v = vec![1, 2, 4, 6, 8, 10]; let v_t = vec![1, 4, 2, 4, 6, 8, 8, 10]; let span = Span::from_vec(v_t).unwrap(); for (target, test) in span.into_iter().zip(v) { assert_eq!(target, test) } } #[test] fn test_from_vec_single() { let v = vec![1]; let span = Span::from_vec(v.clone()).unwrap(); for (target, test) in span.into_iter().zip(v) { assert_eq!(target, test) } } #[test] #[should_panic] fn test_empty_vec() { let v = vec![]; let span = Span::from_vec(v.clone()).unwrap(); for (target, test) in span.into_iter().zip(v) { assert_eq!(target, test) } } #[test] fn test_enum_fromvec() { let v = vec![1, 3]; let span = Span::from_vec(v.clone()).unwrap(); if let Span::Discontinuous(span) = span { for (target, test) in span.into_iter().zip(v) { assert_eq!(target, test); } } else { assert_eq!(0, 1); } } }
{ (self.lower(), self.upper()) }
arrayDestructuring.js
const address = ["1 1st Street", "Pallet Town", "Kanto", "777"]; const [, city, state] = address; console.log(`You are in ${city}, ${state}.`); const otherAddress = []; const [, , region = "Johto"] = otherAddress;
console.log(`You are in ${region}`);
v1_service_list.py
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.16 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class V1ServiceList(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 = { 'api_version': 'str', 'items': 'list[V1Service]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def
(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1ServiceList - 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._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1ServiceList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1ServiceList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1ServiceList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1ServiceList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1ServiceList. # noqa: E501 List of services # noqa: E501 :return: The items of this V1ServiceList. # noqa: E501 :rtype: list[V1Service] """ return self._items @items.setter def items(self, items): """Sets the items of this V1ServiceList. List of services # noqa: E501 :param items: The items of this V1ServiceList. # noqa: E501 :type: list[V1Service] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1ServiceList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1ServiceList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1ServiceList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1ServiceList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1ServiceList. # noqa: E501 :return: The metadata of this V1ServiceList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1ServiceList. :param metadata: The metadata of this V1ServiceList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata 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, V1ServiceList): 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, V1ServiceList): return True return self.to_dict() != other.to_dict()
__init__
lldb.py
# This file was automatically generated by SWIG (http://www.swig.org). # Version 4.0.2 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. """ The lldb module contains the public APIs for Python binding. Some of the important classes are described here: * :py:class:`SBTarget`: Represents the target program running under the debugger. * :py:class:`SBProcess`: Represents the process associated with the target program. * :py:class:`SBThread`: Represents a thread of execution. :py:class:`SBProcess` contains SBThreads. * :py:class:`SBFrame`: Represents one of the stack frames associated with a thread. :py:class:`SBThread` contains SBFrame(s). * :py:class:`SBSymbolContext`: A container that stores various debugger related info. * :py:class:`SBValue`: Represents the value of a variable, a register, or an expression. * :py:class:`SBModule`: Represents an executable image and its associated object and symbol files. :py:class:`SBTarget` contains SBModule. * :py:class:`SBBreakpoint`: Represents a logical breakpoint and its associated settings. :py:class:`SBTarget` contains SBBreakpoints. * :py:class:`SBSymbol`: Represents the symbol possibly associated with a stack frame. * :py:class:`SBCompileUnit`: Represents a compilation unit, or compiled source file. * :py:class:`SBFunction`: Represents a generic function, which can be inlined or not. * :py:class:`SBBlock`: Represents a lexical block. :py:class:`SBFunction` contains SBBlocks. * :py:class:`SBLineEntry`: Specifies an association with a contiguous range of instructions and a source file location. :py:class:`SBCompileUnit` contains SBLineEntry. The different enums in the `lldb` module are described in :doc:`python_api_enums`. """ from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError("Python 2.7 or later required") try: # Try an absolute import first. If we're being loaded from lldb, # _lldb should be a built-in module. import _lldb except ImportError: # Relative import should work if we are being loaded by Python. from . import _lldb try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) def _swig_setattr_nondynamic_instance_variable(set): def set_instance_attr(self, name, value): if name == "thisown": self.this.own(value) elif name == "this": set(self, name, value) elif hasattr(self, name) and isinstance(getattr(type(self), name), property): set(self, name, value) else: raise AttributeError("You cannot add instance attributes to %s" % self) return set_instance_attr def _swig_setattr_nondynamic_class_variable(set): def set_class_attr(cls, name, value): if hasattr(cls, name) and not isinstance(getattr(cls, name), property): set(cls, name, value) else: raise AttributeError("You cannot add class attributes to %s" % cls) return set_class_attr def _swig_add_metaclass(metaclass): """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" def wrapper(cls): return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) return wrapper class _SwigNonDynamicMeta(type): """Meta class to enforce nondynamic attributes (no new attributes) for a class""" __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) import uuid import re import os import six #SWIG_VERSION is written as a single hex number, but the components of it are #meant to be interpreted in decimal. So, 0x030012 is swig 3.0.12, and not #3.0.18. def _to_int(hex): return hex // 0x10 % 0x10 * 10 + hex % 0x10 swig_version = (_to_int(0x040002 // 0x10000), _to_int(0x040002 // 0x100), _to_int(0x040002)) del _to_int # =================================== # Iterator for lldb container objects # =================================== def lldb_iter(obj, getsize, getelem): """A generator adaptor to support iteration for lldb container objects.""" size = getattr(obj, getsize) elem = getattr(obj, getelem) for i in range(size()): yield elem(i) INT32_MAX = _lldb.INT32_MAX UINT32_MAX = _lldb.UINT32_MAX UINT64_MAX = _lldb.UINT64_MAX LLDB_GENERIC_ERROR = _lldb.LLDB_GENERIC_ERROR LLDB_INVALID_BREAK_ID = _lldb.LLDB_INVALID_BREAK_ID LLDB_DEFAULT_BREAK_SIZE = _lldb.LLDB_DEFAULT_BREAK_SIZE LLDB_INVALID_WATCH_ID = _lldb.LLDB_INVALID_WATCH_ID LLDB_WATCH_TYPE_READ = _lldb.LLDB_WATCH_TYPE_READ LLDB_WATCH_TYPE_WRITE = _lldb.LLDB_WATCH_TYPE_WRITE LLDB_REGNUM_GENERIC_PC = _lldb.LLDB_REGNUM_GENERIC_PC LLDB_REGNUM_GENERIC_SP = _lldb.LLDB_REGNUM_GENERIC_SP LLDB_REGNUM_GENERIC_FP = _lldb.LLDB_REGNUM_GENERIC_FP LLDB_REGNUM_GENERIC_RA = _lldb.LLDB_REGNUM_GENERIC_RA LLDB_REGNUM_GENERIC_FLAGS = _lldb.LLDB_REGNUM_GENERIC_FLAGS LLDB_REGNUM_GENERIC_ARG1 = _lldb.LLDB_REGNUM_GENERIC_ARG1 LLDB_REGNUM_GENERIC_ARG2 = _lldb.LLDB_REGNUM_GENERIC_ARG2 LLDB_REGNUM_GENERIC_ARG3 = _lldb.LLDB_REGNUM_GENERIC_ARG3 LLDB_REGNUM_GENERIC_ARG4 = _lldb.LLDB_REGNUM_GENERIC_ARG4 LLDB_REGNUM_GENERIC_ARG5 = _lldb.LLDB_REGNUM_GENERIC_ARG5 LLDB_REGNUM_GENERIC_ARG6 = _lldb.LLDB_REGNUM_GENERIC_ARG6 LLDB_REGNUM_GENERIC_ARG7 = _lldb.LLDB_REGNUM_GENERIC_ARG7 LLDB_REGNUM_GENERIC_ARG8 = _lldb.LLDB_REGNUM_GENERIC_ARG8 LLDB_INVALID_ADDRESS = _lldb.LLDB_INVALID_ADDRESS LLDB_INVALID_INDEX32 = _lldb.LLDB_INVALID_INDEX32 LLDB_INVALID_IVAR_OFFSET = _lldb.LLDB_INVALID_IVAR_OFFSET LLDB_INVALID_IMAGE_TOKEN = _lldb.LLDB_INVALID_IMAGE_TOKEN LLDB_INVALID_MODULE_VERSION = _lldb.LLDB_INVALID_MODULE_VERSION LLDB_INVALID_REGNUM = _lldb.LLDB_INVALID_REGNUM LLDB_INVALID_UID = _lldb.LLDB_INVALID_UID LLDB_INVALID_PROCESS_ID = _lldb.LLDB_INVALID_PROCESS_ID LLDB_INVALID_THREAD_ID = _lldb.LLDB_INVALID_THREAD_ID LLDB_INVALID_FRAME_ID = _lldb.LLDB_INVALID_FRAME_ID LLDB_INVALID_SIGNAL_NUMBER = _lldb.LLDB_INVALID_SIGNAL_NUMBER LLDB_INVALID_OFFSET = _lldb.LLDB_INVALID_OFFSET LLDB_INVALID_LINE_NUMBER = _lldb.LLDB_INVALID_LINE_NUMBER LLDB_INVALID_COLUMN_NUMBER = _lldb.LLDB_INVALID_COLUMN_NUMBER LLDB_INVALID_QUEUE_ID = _lldb.LLDB_INVALID_QUEUE_ID LLDB_ARCH_DEFAULT = _lldb.LLDB_ARCH_DEFAULT LLDB_ARCH_DEFAULT_32BIT = _lldb.LLDB_ARCH_DEFAULT_32BIT LLDB_ARCH_DEFAULT_64BIT = _lldb.LLDB_ARCH_DEFAULT_64BIT LLDB_INVALID_CPUTYPE = _lldb.LLDB_INVALID_CPUTYPE LLDB_MAX_NUM_OPTION_SETS = _lldb.LLDB_MAX_NUM_OPTION_SETS LLDB_OPT_SET_ALL = _lldb.LLDB_OPT_SET_ALL LLDB_OPT_SET_1 = _lldb.LLDB_OPT_SET_1 LLDB_OPT_SET_2 = _lldb.LLDB_OPT_SET_2 LLDB_OPT_SET_3 = _lldb.LLDB_OPT_SET_3 LLDB_OPT_SET_4 = _lldb.LLDB_OPT_SET_4 LLDB_OPT_SET_5 = _lldb.LLDB_OPT_SET_5 LLDB_OPT_SET_6 = _lldb.LLDB_OPT_SET_6 LLDB_OPT_SET_7 = _lldb.LLDB_OPT_SET_7 LLDB_OPT_SET_8 = _lldb.LLDB_OPT_SET_8 LLDB_OPT_SET_9 = _lldb.LLDB_OPT_SET_9 LLDB_OPT_SET_10 = _lldb.LLDB_OPT_SET_10 LLDB_OPT_SET_11 = _lldb.LLDB_OPT_SET_11 LLDB_OPT_SET_12 = _lldb.LLDB_OPT_SET_12 eStateInvalid = _lldb.eStateInvalid eStateUnloaded = _lldb.eStateUnloaded eStateConnected = _lldb.eStateConnected eStateAttaching = _lldb.eStateAttaching eStateLaunching = _lldb.eStateLaunching eStateStopped = _lldb.eStateStopped eStateRunning = _lldb.eStateRunning eStateStepping = _lldb.eStateStepping eStateCrashed = _lldb.eStateCrashed eStateDetached = _lldb.eStateDetached eStateExited = _lldb.eStateExited eStateSuspended = _lldb.eStateSuspended kLastStateType = _lldb.kLastStateType eLaunchFlagNone = _lldb.eLaunchFlagNone eLaunchFlagExec = _lldb.eLaunchFlagExec eLaunchFlagDebug = _lldb.eLaunchFlagDebug eLaunchFlagStopAtEntry = _lldb.eLaunchFlagStopAtEntry eLaunchFlagDisableASLR = _lldb.eLaunchFlagDisableASLR eLaunchFlagDisableSTDIO = _lldb.eLaunchFlagDisableSTDIO eLaunchFlagLaunchInTTY = _lldb.eLaunchFlagLaunchInTTY eLaunchFlagLaunchInShell = _lldb.eLaunchFlagLaunchInShell eLaunchFlagLaunchInSeparateProcessGroup = _lldb.eLaunchFlagLaunchInSeparateProcessGroup eLaunchFlagDontSetExitStatus = _lldb.eLaunchFlagDontSetExitStatus eLaunchFlagDetachOnError = _lldb.eLaunchFlagDetachOnError eLaunchFlagShellExpandArguments = _lldb.eLaunchFlagShellExpandArguments eLaunchFlagCloseTTYOnExit = _lldb.eLaunchFlagCloseTTYOnExit eLaunchFlagInheritTCCFromParent = _lldb.eLaunchFlagInheritTCCFromParent eOnlyThisThread = _lldb.eOnlyThisThread eAllThreads = _lldb.eAllThreads eOnlyDuringStepping = _lldb.eOnlyDuringStepping eByteOrderInvalid = _lldb.eByteOrderInvalid eByteOrderBig = _lldb.eByteOrderBig eByteOrderPDP = _lldb.eByteOrderPDP eByteOrderLittle = _lldb.eByteOrderLittle eEncodingInvalid = _lldb.eEncodingInvalid eEncodingUint = _lldb.eEncodingUint eEncodingSint = _lldb.eEncodingSint eEncodingIEEE754 = _lldb.eEncodingIEEE754 eEncodingVector = _lldb.eEncodingVector eFormatDefault = _lldb.eFormatDefault eFormatInvalid = _lldb.eFormatInvalid eFormatBoolean = _lldb.eFormatBoolean eFormatBinary = _lldb.eFormatBinary eFormatBytes = _lldb.eFormatBytes eFormatBytesWithASCII = _lldb.eFormatBytesWithASCII eFormatChar = _lldb.eFormatChar eFormatCharPrintable = _lldb.eFormatCharPrintable eFormatComplex = _lldb.eFormatComplex eFormatComplexFloat = _lldb.eFormatComplexFloat eFormatCString = _lldb.eFormatCString eFormatDecimal = _lldb.eFormatDecimal eFormatEnum = _lldb.eFormatEnum eFormatHex = _lldb.eFormatHex eFormatHexUppercase = _lldb.eFormatHexUppercase eFormatFloat = _lldb.eFormatFloat eFormatOctal = _lldb.eFormatOctal eFormatOSType = _lldb.eFormatOSType eFormatUnicode16 = _lldb.eFormatUnicode16 eFormatUnicode32 = _lldb.eFormatUnicode32 eFormatUnsigned = _lldb.eFormatUnsigned eFormatPointer = _lldb.eFormatPointer eFormatVectorOfChar = _lldb.eFormatVectorOfChar eFormatVectorOfSInt8 = _lldb.eFormatVectorOfSInt8 eFormatVectorOfUInt8 = _lldb.eFormatVectorOfUInt8 eFormatVectorOfSInt16 = _lldb.eFormatVectorOfSInt16 eFormatVectorOfUInt16 = _lldb.eFormatVectorOfUInt16 eFormatVectorOfSInt32 = _lldb.eFormatVectorOfSInt32 eFormatVectorOfUInt32 = _lldb.eFormatVectorOfUInt32 eFormatVectorOfSInt64 = _lldb.eFormatVectorOfSInt64 eFormatVectorOfUInt64 = _lldb.eFormatVectorOfUInt64 eFormatVectorOfFloat16 = _lldb.eFormatVectorOfFloat16 eFormatVectorOfFloat32 = _lldb.eFormatVectorOfFloat32 eFormatVectorOfFloat64 = _lldb.eFormatVectorOfFloat64 eFormatVectorOfUInt128 = _lldb.eFormatVectorOfUInt128 eFormatComplexInteger = _lldb.eFormatComplexInteger eFormatCharArray = _lldb.eFormatCharArray eFormatAddressInfo = _lldb.eFormatAddressInfo eFormatHexFloat = _lldb.eFormatHexFloat eFormatInstruction = _lldb.eFormatInstruction eFormatVoid = _lldb.eFormatVoid eFormatUnicode8 = _lldb.eFormatUnicode8 kNumFormats = _lldb.kNumFormats eDescriptionLevelBrief = _lldb.eDescriptionLevelBrief eDescriptionLevelFull = _lldb.eDescriptionLevelFull eDescriptionLevelVerbose = _lldb.eDescriptionLevelVerbose eDescriptionLevelInitial = _lldb.eDescriptionLevelInitial kNumDescriptionLevels = _lldb.kNumDescriptionLevels eScriptLanguageNone = _lldb.eScriptLanguageNone eScriptLanguagePython = _lldb.eScriptLanguagePython eScriptLanguageLua = _lldb.eScriptLanguageLua eScriptLanguageUnknown = _lldb.eScriptLanguageUnknown eScriptLanguageDefault = _lldb.eScriptLanguageDefault eRegisterKindEHFrame = _lldb.eRegisterKindEHFrame eRegisterKindDWARF = _lldb.eRegisterKindDWARF eRegisterKindGeneric = _lldb.eRegisterKindGeneric eRegisterKindProcessPlugin = _lldb.eRegisterKindProcessPlugin eRegisterKindLLDB = _lldb.eRegisterKindLLDB kNumRegisterKinds = _lldb.kNumRegisterKinds eStopReasonInvalid = _lldb.eStopReasonInvalid eStopReasonNone = _lldb.eStopReasonNone eStopReasonTrace = _lldb.eStopReasonTrace eStopReasonBreakpoint = _lldb.eStopReasonBreakpoint eStopReasonWatchpoint = _lldb.eStopReasonWatchpoint eStopReasonSignal = _lldb.eStopReasonSignal eStopReasonException = _lldb.eStopReasonException eStopReasonExec = _lldb.eStopReasonExec eStopReasonPlanComplete = _lldb.eStopReasonPlanComplete eStopReasonThreadExiting = _lldb.eStopReasonThreadExiting eStopReasonInstrumentation = _lldb.eStopReasonInstrumentation eReturnStatusInvalid = _lldb.eReturnStatusInvalid eReturnStatusSuccessFinishNoResult = _lldb.eReturnStatusSuccessFinishNoResult eReturnStatusSuccessFinishResult = _lldb.eReturnStatusSuccessFinishResult eReturnStatusSuccessContinuingNoResult = _lldb.eReturnStatusSuccessContinuingNoResult eReturnStatusSuccessContinuingResult = _lldb.eReturnStatusSuccessContinuingResult eReturnStatusStarted = _lldb.eReturnStatusStarted eReturnStatusFailed = _lldb.eReturnStatusFailed eReturnStatusQuit = _lldb.eReturnStatusQuit eExpressionCompleted = _lldb.eExpressionCompleted eExpressionSetupError = _lldb.eExpressionSetupError eExpressionParseError = _lldb.eExpressionParseError eExpressionDiscarded = _lldb.eExpressionDiscarded eExpressionInterrupted = _lldb.eExpressionInterrupted eExpressionHitBreakpoint = _lldb.eExpressionHitBreakpoint eExpressionTimedOut = _lldb.eExpressionTimedOut eExpressionResultUnavailable = _lldb.eExpressionResultUnavailable eExpressionStoppedForDebug = _lldb.eExpressionStoppedForDebug eExpressionThreadVanished = _lldb.eExpressionThreadVanished eSearchDepthInvalid = _lldb.eSearchDepthInvalid eSearchDepthTarget = _lldb.eSearchDepthTarget eSearchDepthModule = _lldb.eSearchDepthModule eSearchDepthCompUnit = _lldb.eSearchDepthCompUnit eSearchDepthFunction = _lldb.eSearchDepthFunction eSearchDepthBlock = _lldb.eSearchDepthBlock eSearchDepthAddress = _lldb.eSearchDepthAddress kLastSearchDepthKind = _lldb.kLastSearchDepthKind eConnectionStatusSuccess = _lldb.eConnectionStatusSuccess eConnectionStatusEndOfFile = _lldb.eConnectionStatusEndOfFile eConnectionStatusError = _lldb.eConnectionStatusError eConnectionStatusTimedOut = _lldb.eConnectionStatusTimedOut eConnectionStatusNoConnection = _lldb.eConnectionStatusNoConnection eConnectionStatusLostConnection = _lldb.eConnectionStatusLostConnection eConnectionStatusInterrupted = _lldb.eConnectionStatusInterrupted eErrorTypeInvalid = _lldb.eErrorTypeInvalid eErrorTypeGeneric = _lldb.eErrorTypeGeneric eErrorTypeMachKernel = _lldb.eErrorTypeMachKernel eErrorTypePOSIX = _lldb.eErrorTypePOSIX eErrorTypeExpression = _lldb.eErrorTypeExpression eErrorTypeWin32 = _lldb.eErrorTypeWin32 eValueTypeInvalid = _lldb.eValueTypeInvalid eValueTypeVariableGlobal = _lldb.eValueTypeVariableGlobal eValueTypeVariableStatic = _lldb.eValueTypeVariableStatic eValueTypeVariableArgument = _lldb.eValueTypeVariableArgument eValueTypeVariableLocal = _lldb.eValueTypeVariableLocal eValueTypeRegister = _lldb.eValueTypeRegister eValueTypeRegisterSet = _lldb.eValueTypeRegisterSet eValueTypeConstResult = _lldb.eValueTypeConstResult eValueTypeVariableThreadLocal = _lldb.eValueTypeVariableThreadLocal eInputReaderGranularityInvalid = _lldb.eInputReaderGranularityInvalid eInputReaderGranularityByte = _lldb.eInputReaderGranularityByte eInputReaderGranularityWord = _lldb.eInputReaderGranularityWord eInputReaderGranularityLine = _lldb.eInputReaderGranularityLine eInputReaderGranularityAll = _lldb.eInputReaderGranularityAll eSymbolContextTarget = _lldb.eSymbolContextTarget eSymbolContextModule = _lldb.eSymbolContextModule eSymbolContextCompUnit = _lldb.eSymbolContextCompUnit eSymbolContextFunction = _lldb.eSymbolContextFunction eSymbolContextBlock = _lldb.eSymbolContextBlock eSymbolContextLineEntry = _lldb.eSymbolContextLineEntry eSymbolContextSymbol = _lldb.eSymbolContextSymbol eSymbolContextEverything = _lldb.eSymbolContextEverything eSymbolContextVariable = _lldb.eSymbolContextVariable ePermissionsWritable = _lldb.ePermissionsWritable ePermissionsReadable = _lldb.ePermissionsReadable ePermissionsExecutable = _lldb.ePermissionsExecutable eInputReaderActivate = _lldb.eInputReaderActivate eInputReaderAsynchronousOutputWritten = _lldb.eInputReaderAsynchronousOutputWritten eInputReaderReactivate = _lldb.eInputReaderReactivate eInputReaderDeactivate = _lldb.eInputReaderDeactivate eInputReaderGotToken = _lldb.eInputReaderGotToken eInputReaderInterrupt = _lldb.eInputReaderInterrupt eInputReaderEndOfFile = _lldb.eInputReaderEndOfFile eInputReaderDone = _lldb.eInputReaderDone eBreakpointEventTypeInvalidType = _lldb.eBreakpointEventTypeInvalidType eBreakpointEventTypeAdded = _lldb.eBreakpointEventTypeAdded eBreakpointEventTypeRemoved = _lldb.eBreakpointEventTypeRemoved eBreakpointEventTypeLocationsAdded = _lldb.eBreakpointEventTypeLocationsAdded eBreakpointEventTypeLocationsRemoved = _lldb.eBreakpointEventTypeLocationsRemoved eBreakpointEventTypeLocationsResolved = _lldb.eBreakpointEventTypeLocationsResolved eBreakpointEventTypeEnabled = _lldb.eBreakpointEventTypeEnabled eBreakpointEventTypeDisabled = _lldb.eBreakpointEventTypeDisabled eBreakpointEventTypeCommandChanged = _lldb.eBreakpointEventTypeCommandChanged eBreakpointEventTypeConditionChanged = _lldb.eBreakpointEventTypeConditionChanged eBreakpointEventTypeIgnoreChanged = _lldb.eBreakpointEventTypeIgnoreChanged eBreakpointEventTypeThreadChanged = _lldb.eBreakpointEventTypeThreadChanged eBreakpointEventTypeAutoContinueChanged = _lldb.eBreakpointEventTypeAutoContinueChanged eWatchpointEventTypeInvalidType = _lldb.eWatchpointEventTypeInvalidType eWatchpointEventTypeAdded = _lldb.eWatchpointEventTypeAdded eWatchpointEventTypeRemoved = _lldb.eWatchpointEventTypeRemoved eWatchpointEventTypeEnabled = _lldb.eWatchpointEventTypeEnabled eWatchpointEventTypeDisabled = _lldb.eWatchpointEventTypeDisabled eWatchpointEventTypeCommandChanged = _lldb.eWatchpointEventTypeCommandChanged eWatchpointEventTypeConditionChanged = _lldb.eWatchpointEventTypeConditionChanged eWatchpointEventTypeIgnoreChanged = _lldb.eWatchpointEventTypeIgnoreChanged eWatchpointEventTypeThreadChanged = _lldb.eWatchpointEventTypeThreadChanged eWatchpointEventTypeTypeChanged = _lldb.eWatchpointEventTypeTypeChanged eLanguageTypeUnknown = _lldb.eLanguageTypeUnknown eLanguageTypeC89 = _lldb.eLanguageTypeC89 eLanguageTypeC = _lldb.eLanguageTypeC eLanguageTypeAda83 = _lldb.eLanguageTypeAda83 eLanguageTypeC_plus_plus = _lldb.eLanguageTypeC_plus_plus eLanguageTypeCobol74 = _lldb.eLanguageTypeCobol74 eLanguageTypeCobol85 = _lldb.eLanguageTypeCobol85 eLanguageTypeFortran77 = _lldb.eLanguageTypeFortran77 eLanguageTypeFortran90 = _lldb.eLanguageTypeFortran90 eLanguageTypePascal83 = _lldb.eLanguageTypePascal83 eLanguageTypeModula2 = _lldb.eLanguageTypeModula2 eLanguageTypeJava = _lldb.eLanguageTypeJava eLanguageTypeC99 = _lldb.eLanguageTypeC99 eLanguageTypeAda95 = _lldb.eLanguageTypeAda95 eLanguageTypeFortran95 = _lldb.eLanguageTypeFortran95 eLanguageTypePLI = _lldb.eLanguageTypePLI eLanguageTypeObjC = _lldb.eLanguageTypeObjC eLanguageTypeObjC_plus_plus = _lldb.eLanguageTypeObjC_plus_plus eLanguageTypeUPC = _lldb.eLanguageTypeUPC eLanguageTypeD = _lldb.eLanguageTypeD eLanguageTypePython = _lldb.eLanguageTypePython eLanguageTypeOpenCL = _lldb.eLanguageTypeOpenCL eLanguageTypeGo = _lldb.eLanguageTypeGo eLanguageTypeModula3 = _lldb.eLanguageTypeModula3 eLanguageTypeHaskell = _lldb.eLanguageTypeHaskell eLanguageTypeC_plus_plus_03 = _lldb.eLanguageTypeC_plus_plus_03 eLanguageTypeC_plus_plus_11 = _lldb.eLanguageTypeC_plus_plus_11 eLanguageTypeOCaml = _lldb.eLanguageTypeOCaml eLanguageTypeRust = _lldb.eLanguageTypeRust eLanguageTypeC11 = _lldb.eLanguageTypeC11 eLanguageTypeSwift = _lldb.eLanguageTypeSwift eLanguageTypeJulia = _lldb.eLanguageTypeJulia eLanguageTypeDylan = _lldb.eLanguageTypeDylan eLanguageTypeC_plus_plus_14 = _lldb.eLanguageTypeC_plus_plus_14 eLanguageTypeFortran03 = _lldb.eLanguageTypeFortran03 eLanguageTypeFortran08 = _lldb.eLanguageTypeFortran08 eLanguageTypeMipsAssembler = _lldb.eLanguageTypeMipsAssembler eLanguageTypeExtRenderScript = _lldb.eLanguageTypeExtRenderScript eNumLanguageTypes = _lldb.eNumLanguageTypes eInstrumentationRuntimeTypeAddressSanitizer = _lldb.eInstrumentationRuntimeTypeAddressSanitizer eInstrumentationRuntimeTypeThreadSanitizer = _lldb.eInstrumentationRuntimeTypeThreadSanitizer eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer = _lldb.eInstrumentationRuntimeTypeUndefinedBehaviorSanitizer eInstrumentationRuntimeTypeMainThreadChecker = _lldb.eInstrumentationRuntimeTypeMainThreadChecker eInstrumentationRuntimeTypeSwiftRuntimeReporting = _lldb.eInstrumentationRuntimeTypeSwiftRuntimeReporting eNumInstrumentationRuntimeTypes = _lldb.eNumInstrumentationRuntimeTypes eNoDynamicValues = _lldb.eNoDynamicValues eDynamicCanRunTarget = _lldb.eDynamicCanRunTarget eDynamicDontRunTarget = _lldb.eDynamicDontRunTarget eStopShowColumnAnsiOrCaret = _lldb.eStopShowColumnAnsiOrCaret eStopShowColumnAnsi = _lldb.eStopShowColumnAnsi eStopShowColumnCaret = _lldb.eStopShowColumnCaret eStopShowColumnNone = _lldb.eStopShowColumnNone eAccessNone = _lldb.eAccessNone eAccessPublic = _lldb.eAccessPublic eAccessPrivate = _lldb.eAccessPrivate eAccessProtected = _lldb.eAccessProtected eAccessPackage = _lldb.eAccessPackage eArgTypeAddress = _lldb.eArgTypeAddress eArgTypeAddressOrExpression = _lldb.eArgTypeAddressOrExpression eArgTypeAliasName = _lldb.eArgTypeAliasName eArgTypeAliasOptions = _lldb.eArgTypeAliasOptions eArgTypeArchitecture = _lldb.eArgTypeArchitecture eArgTypeBoolean = _lldb.eArgTypeBoolean eArgTypeBreakpointID = _lldb.eArgTypeBreakpointID eArgTypeBreakpointIDRange = _lldb.eArgTypeBreakpointIDRange eArgTypeBreakpointName = _lldb.eArgTypeBreakpointName eArgTypeByteSize = _lldb.eArgTypeByteSize eArgTypeClassName = _lldb.eArgTypeClassName eArgTypeCommandName = _lldb.eArgTypeCommandName eArgTypeCount = _lldb.eArgTypeCount eArgTypeDescriptionVerbosity = _lldb.eArgTypeDescriptionVerbosity eArgTypeDirectoryName = _lldb.eArgTypeDirectoryName eArgTypeDisassemblyFlavor = _lldb.eArgTypeDisassemblyFlavor eArgTypeEndAddress = _lldb.eArgTypeEndAddress eArgTypeExpression = _lldb.eArgTypeExpression eArgTypeExpressionPath = _lldb.eArgTypeExpressionPath eArgTypeExprFormat = _lldb.eArgTypeExprFormat eArgTypeFileLineColumn = _lldb.eArgTypeFileLineColumn eArgTypeFilename = _lldb.eArgTypeFilename eArgTypeFormat = _lldb.eArgTypeFormat eArgTypeFrameIndex = _lldb.eArgTypeFrameIndex eArgTypeFullName = _lldb.eArgTypeFullName eArgTypeFunctionName = _lldb.eArgTypeFunctionName eArgTypeFunctionOrSymbol = _lldb.eArgTypeFunctionOrSymbol eArgTypeGDBFormat = _lldb.eArgTypeGDBFormat eArgTypeHelpText = _lldb.eArgTypeHelpText eArgTypeIndex = _lldb.eArgTypeIndex eArgTypeLanguage = _lldb.eArgTypeLanguage eArgTypeLineNum = _lldb.eArgTypeLineNum eArgTypeLogCategory = _lldb.eArgTypeLogCategory eArgTypeLogChannel = _lldb.eArgTypeLogChannel eArgTypeMethod = _lldb.eArgTypeMethod eArgTypeName = _lldb.eArgTypeName eArgTypeNewPathPrefix = _lldb.eArgTypeNewPathPrefix eArgTypeNumLines = _lldb.eArgTypeNumLines eArgTypeNumberPerLine = _lldb.eArgTypeNumberPerLine eArgTypeOffset = _lldb.eArgTypeOffset eArgTypeOldPathPrefix = _lldb.eArgTypeOldPathPrefix eArgTypeOneLiner = _lldb.eArgTypeOneLiner eArgTypePath = _lldb.eArgTypePath eArgTypePermissionsNumber = _lldb.eArgTypePermissionsNumber eArgTypePermissionsString = _lldb.eArgTypePermissionsString eArgTypePid = _lldb.eArgTypePid eArgTypePlugin = _lldb.eArgTypePlugin eArgTypeProcessName = _lldb.eArgTypeProcessName eArgTypePythonClass = _lldb.eArgTypePythonClass eArgTypePythonFunction = _lldb.eArgTypePythonFunction eArgTypePythonScript = _lldb.eArgTypePythonScript eArgTypeQueueName = _lldb.eArgTypeQueueName eArgTypeRegisterName = _lldb.eArgTypeRegisterName eArgTypeRegularExpression = _lldb.eArgTypeRegularExpression eArgTypeRunArgs = _lldb.eArgTypeRunArgs eArgTypeRunMode = _lldb.eArgTypeRunMode eArgTypeScriptedCommandSynchronicity = _lldb.eArgTypeScriptedCommandSynchronicity eArgTypeScriptLang = _lldb.eArgTypeScriptLang eArgTypeSearchWord = _lldb.eArgTypeSearchWord eArgTypeSelector = _lldb.eArgTypeSelector eArgTypeSettingIndex = _lldb.eArgTypeSettingIndex eArgTypeSettingKey = _lldb.eArgTypeSettingKey eArgTypeSettingPrefix = _lldb.eArgTypeSettingPrefix eArgTypeSettingVariableName = _lldb.eArgTypeSettingVariableName eArgTypeShlibName = _lldb.eArgTypeShlibName eArgTypeSourceFile = _lldb.eArgTypeSourceFile eArgTypeSortOrder = _lldb.eArgTypeSortOrder eArgTypeStartAddress = _lldb.eArgTypeStartAddress eArgTypeSummaryString = _lldb.eArgTypeSummaryString eArgTypeSymbol = _lldb.eArgTypeSymbol eArgTypeThreadID = _lldb.eArgTypeThreadID eArgTypeThreadIndex = _lldb.eArgTypeThreadIndex eArgTypeThreadName = _lldb.eArgTypeThreadName eArgTypeTypeName = _lldb.eArgTypeTypeName eArgTypeUnsignedInteger = _lldb.eArgTypeUnsignedInteger eArgTypeUnixSignal = _lldb.eArgTypeUnixSignal eArgTypeVarName = _lldb.eArgTypeVarName eArgTypeValue = _lldb.eArgTypeValue eArgTypeWidth = _lldb.eArgTypeWidth eArgTypeNone = _lldb.eArgTypeNone eArgTypePlatform = _lldb.eArgTypePlatform eArgTypeWatchpointID = _lldb.eArgTypeWatchpointID eArgTypeWatchpointIDRange = _lldb.eArgTypeWatchpointIDRange eArgTypeWatchType = _lldb.eArgTypeWatchType eArgRawInput = _lldb.eArgRawInput eArgTypeCommand = _lldb.eArgTypeCommand eArgTypeColumnNum = _lldb.eArgTypeColumnNum eArgTypeModuleUUID = _lldb.eArgTypeModuleUUID eArgTypeLastArg = _lldb.eArgTypeLastArg eSymbolTypeAny = _lldb.eSymbolTypeAny eSymbolTypeInvalid = _lldb.eSymbolTypeInvalid eSymbolTypeAbsolute = _lldb.eSymbolTypeAbsolute eSymbolTypeCode = _lldb.eSymbolTypeCode eSymbolTypeResolver = _lldb.eSymbolTypeResolver eSymbolTypeData = _lldb.eSymbolTypeData eSymbolTypeTrampoline = _lldb.eSymbolTypeTrampoline eSymbolTypeRuntime = _lldb.eSymbolTypeRuntime eSymbolTypeException = _lldb.eSymbolTypeException eSymbolTypeSourceFile = _lldb.eSymbolTypeSourceFile eSymbolTypeHeaderFile = _lldb.eSymbolTypeHeaderFile eSymbolTypeObjectFile = _lldb.eSymbolTypeObjectFile eSymbolTypeCommonBlock = _lldb.eSymbolTypeCommonBlock eSymbolTypeBlock = _lldb.eSymbolTypeBlock eSymbolTypeLocal = _lldb.eSymbolTypeLocal eSymbolTypeParam = _lldb.eSymbolTypeParam eSymbolTypeVariable = _lldb.eSymbolTypeVariable eSymbolTypeVariableType = _lldb.eSymbolTypeVariableType eSymbolTypeLineEntry = _lldb.eSymbolTypeLineEntry eSymbolTypeLineHeader = _lldb.eSymbolTypeLineHeader eSymbolTypeScopeBegin = _lldb.eSymbolTypeScopeBegin eSymbolTypeScopeEnd = _lldb.eSymbolTypeScopeEnd eSymbolTypeAdditional = _lldb.eSymbolTypeAdditional eSymbolTypeCompiler = _lldb.eSymbolTypeCompiler eSymbolTypeInstrumentation = _lldb.eSymbolTypeInstrumentation eSymbolTypeUndefined = _lldb.eSymbolTypeUndefined eSymbolTypeObjCClass = _lldb.eSymbolTypeObjCClass eSymbolTypeObjCMetaClass = _lldb.eSymbolTypeObjCMetaClass eSymbolTypeObjCIVar = _lldb.eSymbolTypeObjCIVar eSymbolTypeReExported = _lldb.eSymbolTypeReExported eSymbolTypeASTFile = _lldb.eSymbolTypeASTFile eSectionTypeInvalid = _lldb.eSectionTypeInvalid eSectionTypeCode = _lldb.eSectionTypeCode eSectionTypeContainer = _lldb.eSectionTypeContainer eSectionTypeData = _lldb.eSectionTypeData eSectionTypeDataCString = _lldb.eSectionTypeDataCString eSectionTypeDataCStringPointers = _lldb.eSectionTypeDataCStringPointers eSectionTypeDataSymbolAddress = _lldb.eSectionTypeDataSymbolAddress eSectionTypeData4 = _lldb.eSectionTypeData4 eSectionTypeData8 = _lldb.eSectionTypeData8 eSectionTypeData16 = _lldb.eSectionTypeData16 eSectionTypeDataPointers = _lldb.eSectionTypeDataPointers eSectionTypeDebug = _lldb.eSectionTypeDebug eSectionTypeZeroFill = _lldb.eSectionTypeZeroFill eSectionTypeDataObjCMessageRefs = _lldb.eSectionTypeDataObjCMessageRefs eSectionTypeDataObjCCFStrings = _lldb.eSectionTypeDataObjCCFStrings eSectionTypeDWARFDebugAbbrev = _lldb.eSectionTypeDWARFDebugAbbrev eSectionTypeDWARFDebugAddr = _lldb.eSectionTypeDWARFDebugAddr eSectionTypeDWARFDebugAranges = _lldb.eSectionTypeDWARFDebugAranges eSectionTypeDWARFDebugCuIndex = _lldb.eSectionTypeDWARFDebugCuIndex eSectionTypeDWARFDebugFrame = _lldb.eSectionTypeDWARFDebugFrame eSectionTypeDWARFDebugInfo = _lldb.eSectionTypeDWARFDebugInfo eSectionTypeDWARFDebugLine = _lldb.eSectionTypeDWARFDebugLine eSectionTypeDWARFDebugLoc = _lldb.eSectionTypeDWARFDebugLoc eSectionTypeDWARFDebugMacInfo = _lldb.eSectionTypeDWARFDebugMacInfo eSectionTypeDWARFDebugMacro = _lldb.eSectionTypeDWARFDebugMacro eSectionTypeDWARFDebugPubNames = _lldb.eSectionTypeDWARFDebugPubNames eSectionTypeDWARFDebugPubTypes = _lldb.eSectionTypeDWARFDebugPubTypes eSectionTypeDWARFDebugRanges = _lldb.eSectionTypeDWARFDebugRanges eSectionTypeDWARFDebugStr = _lldb.eSectionTypeDWARFDebugStr eSectionTypeDWARFDebugStrOffsets = _lldb.eSectionTypeDWARFDebugStrOffsets eSectionTypeDWARFAppleNames = _lldb.eSectionTypeDWARFAppleNames eSectionTypeDWARFAppleTypes = _lldb.eSectionTypeDWARFAppleTypes eSectionTypeDWARFAppleNamespaces = _lldb.eSectionTypeDWARFAppleNamespaces eSectionTypeDWARFAppleObjC = _lldb.eSectionTypeDWARFAppleObjC eSectionTypeELFSymbolTable = _lldb.eSectionTypeELFSymbolTable eSectionTypeELFDynamicSymbols = _lldb.eSectionTypeELFDynamicSymbols eSectionTypeELFRelocationEntries = _lldb.eSectionTypeELFRelocationEntries eSectionTypeELFDynamicLinkInfo = _lldb.eSectionTypeELFDynamicLinkInfo eSectionTypeEHFrame = _lldb.eSectionTypeEHFrame eSectionTypeSwiftModules = _lldb.eSectionTypeSwiftModules eSectionTypeARMexidx = _lldb.eSectionTypeARMexidx eSectionTypeARMextab = _lldb.eSectionTypeARMextab eSectionTypeCompactUnwind = _lldb.eSectionTypeCompactUnwind eSectionTypeGoSymtab = _lldb.eSectionTypeGoSymtab eSectionTypeAbsoluteAddress = _lldb.eSectionTypeAbsoluteAddress eSectionTypeDWARFGNUDebugAltLink = _lldb.eSectionTypeDWARFGNUDebugAltLink eSectionTypeDWARFDebugTypes = _lldb.eSectionTypeDWARFDebugTypes eSectionTypeDWARFDebugNames = _lldb.eSectionTypeDWARFDebugNames eSectionTypeOther = _lldb.eSectionTypeOther eSectionTypeDWARFDebugLineStr = _lldb.eSectionTypeDWARFDebugLineStr eSectionTypeDWARFDebugRngLists = _lldb.eSectionTypeDWARFDebugRngLists eSectionTypeDWARFDebugLocLists = _lldb.eSectionTypeDWARFDebugLocLists eSectionTypeDWARFDebugAbbrevDwo = _lldb.eSectionTypeDWARFDebugAbbrevDwo eSectionTypeDWARFDebugInfoDwo = _lldb.eSectionTypeDWARFDebugInfoDwo eSectionTypeDWARFDebugStrDwo = _lldb.eSectionTypeDWARFDebugStrDwo eSectionTypeDWARFDebugStrOffsetsDwo = _lldb.eSectionTypeDWARFDebugStrOffsetsDwo eSectionTypeDWARFDebugTypesDwo = _lldb.eSectionTypeDWARFDebugTypesDwo eSectionTypeDWARFDebugRngListsDwo = _lldb.eSectionTypeDWARFDebugRngListsDwo eSectionTypeDWARFDebugLocDwo = _lldb.eSectionTypeDWARFDebugLocDwo eSectionTypeDWARFDebugLocListsDwo = _lldb.eSectionTypeDWARFDebugLocListsDwo eSectionTypeDWARFDebugTuIndex = _lldb.eSectionTypeDWARFDebugTuIndex eEmulateInstructionOptionNone = _lldb.eEmulateInstructionOptionNone eEmulateInstructionOptionAutoAdvancePC = _lldb.eEmulateInstructionOptionAutoAdvancePC eEmulateInstructionOptionIgnoreConditions = _lldb.eEmulateInstructionOptionIgnoreConditions eFunctionNameTypeNone = _lldb.eFunctionNameTypeNone eFunctionNameTypeAuto = _lldb.eFunctionNameTypeAuto eFunctionNameTypeFull = _lldb.eFunctionNameTypeFull eFunctionNameTypeBase = _lldb.eFunctionNameTypeBase eFunctionNameTypeMethod = _lldb.eFunctionNameTypeMethod eFunctionNameTypeSelector = _lldb.eFunctionNameTypeSelector eFunctionNameTypeAny = _lldb.eFunctionNameTypeAny eBasicTypeInvalid = _lldb.eBasicTypeInvalid eBasicTypeVoid = _lldb.eBasicTypeVoid eBasicTypeChar = _lldb.eBasicTypeChar eBasicTypeSignedChar = _lldb.eBasicTypeSignedChar eBasicTypeUnsignedChar = _lldb.eBasicTypeUnsignedChar eBasicTypeWChar = _lldb.eBasicTypeWChar eBasicTypeSignedWChar = _lldb.eBasicTypeSignedWChar eBasicTypeUnsignedWChar = _lldb.eBasicTypeUnsignedWChar eBasicTypeChar16 = _lldb.eBasicTypeChar16 eBasicTypeChar32 = _lldb.eBasicTypeChar32 eBasicTypeShort = _lldb.eBasicTypeShort eBasicTypeUnsignedShort = _lldb.eBasicTypeUnsignedShort eBasicTypeInt = _lldb.eBasicTypeInt eBasicTypeUnsignedInt = _lldb.eBasicTypeUnsignedInt eBasicTypeLong = _lldb.eBasicTypeLong eBasicTypeUnsignedLong = _lldb.eBasicTypeUnsignedLong eBasicTypeLongLong = _lldb.eBasicTypeLongLong eBasicTypeUnsignedLongLong = _lldb.eBasicTypeUnsignedLongLong eBasicTypeInt128 = _lldb.eBasicTypeInt128 eBasicTypeUnsignedInt128 = _lldb.eBasicTypeUnsignedInt128 eBasicTypeBool = _lldb.eBasicTypeBool eBasicTypeHalf = _lldb.eBasicTypeHalf eBasicTypeFloat = _lldb.eBasicTypeFloat eBasicTypeDouble = _lldb.eBasicTypeDouble eBasicTypeLongDouble = _lldb.eBasicTypeLongDouble eBasicTypeFloatComplex = _lldb.eBasicTypeFloatComplex eBasicTypeDoubleComplex = _lldb.eBasicTypeDoubleComplex eBasicTypeLongDoubleComplex = _lldb.eBasicTypeLongDoubleComplex eBasicTypeObjCID = _lldb.eBasicTypeObjCID eBasicTypeObjCClass = _lldb.eBasicTypeObjCClass eBasicTypeObjCSel = _lldb.eBasicTypeObjCSel eBasicTypeNullPtr = _lldb.eBasicTypeNullPtr eBasicTypeOther = _lldb.eBasicTypeOther eTraceTypeNone = _lldb.eTraceTypeNone eTraceTypeProcessorTrace = _lldb.eTraceTypeProcessorTrace eStructuredDataTypeInvalid = _lldb.eStructuredDataTypeInvalid eStructuredDataTypeNull = _lldb.eStructuredDataTypeNull eStructuredDataTypeGeneric = _lldb.eStructuredDataTypeGeneric eStructuredDataTypeArray = _lldb.eStructuredDataTypeArray eStructuredDataTypeInteger = _lldb.eStructuredDataTypeInteger eStructuredDataTypeFloat = _lldb.eStructuredDataTypeFloat eStructuredDataTypeBoolean = _lldb.eStructuredDataTypeBoolean eStructuredDataTypeString = _lldb.eStructuredDataTypeString eStructuredDataTypeDictionary = _lldb.eStructuredDataTypeDictionary eTypeClassInvalid = _lldb.eTypeClassInvalid eTypeClassArray = _lldb.eTypeClassArray eTypeClassBlockPointer = _lldb.eTypeClassBlockPointer eTypeClassBuiltin = _lldb.eTypeClassBuiltin eTypeClassClass = _lldb.eTypeClassClass eTypeClassComplexFloat = _lldb.eTypeClassComplexFloat eTypeClassComplexInteger = _lldb.eTypeClassComplexInteger eTypeClassEnumeration = _lldb.eTypeClassEnumeration eTypeClassFunction = _lldb.eTypeClassFunction eTypeClassMemberPointer = _lldb.eTypeClassMemberPointer eTypeClassObjCObject = _lldb.eTypeClassObjCObject eTypeClassObjCInterface = _lldb.eTypeClassObjCInterface eTypeClassObjCObjectPointer = _lldb.eTypeClassObjCObjectPointer eTypeClassPointer = _lldb.eTypeClassPointer eTypeClassReference = _lldb.eTypeClassReference eTypeClassStruct = _lldb.eTypeClassStruct eTypeClassTypedef = _lldb.eTypeClassTypedef eTypeClassUnion = _lldb.eTypeClassUnion eTypeClassVector = _lldb.eTypeClassVector eTypeClassOther = _lldb.eTypeClassOther eTypeClassAny = _lldb.eTypeClassAny eTemplateArgumentKindNull = _lldb.eTemplateArgumentKindNull eTemplateArgumentKindType = _lldb.eTemplateArgumentKindType eTemplateArgumentKindDeclaration = _lldb.eTemplateArgumentKindDeclaration eTemplateArgumentKindIntegral = _lldb.eTemplateArgumentKindIntegral eTemplateArgumentKindTemplate = _lldb.eTemplateArgumentKindTemplate eTemplateArgumentKindTemplateExpansion = _lldb.eTemplateArgumentKindTemplateExpansion eTemplateArgumentKindExpression = _lldb.eTemplateArgumentKindExpression eTemplateArgumentKindPack = _lldb.eTemplateArgumentKindPack eTemplateArgumentKindNullPtr = _lldb.eTemplateArgumentKindNullPtr eNullGenericKindType = _lldb.eNullGenericKindType eBoundGenericKindType = _lldb.eBoundGenericKindType eUnboundGenericKindType = _lldb.eUnboundGenericKindType eTypeOptionNone = _lldb.eTypeOptionNone eTypeOptionCascade = _lldb.eTypeOptionCascade eTypeOptionSkipPointers = _lldb.eTypeOptionSkipPointers eTypeOptionSkipReferences = _lldb.eTypeOptionSkipReferences eTypeOptionHideChildren = _lldb.eTypeOptionHideChildren eTypeOptionHideValue = _lldb.eTypeOptionHideValue eTypeOptionShowOneLiner = _lldb.eTypeOptionShowOneLiner eTypeOptionHideNames = _lldb.eTypeOptionHideNames eTypeOptionNonCacheable = _lldb.eTypeOptionNonCacheable eTypeOptionHideEmptyAggregates = _lldb.eTypeOptionHideEmptyAggregates eTypeOptionFrontEndWantsDereference = _lldb.eTypeOptionFrontEndWantsDereference eFrameCompareInvalid = _lldb.eFrameCompareInvalid eFrameCompareUnknown = _lldb.eFrameCompareUnknown eFrameCompareEqual = _lldb.eFrameCompareEqual eFrameCompareSameParent = _lldb.eFrameCompareSameParent eFrameCompareYounger = _lldb.eFrameCompareYounger eFrameCompareOlder = _lldb.eFrameCompareOlder eFilePermissionsUserRead = _lldb.eFilePermissionsUserRead eFilePermissionsUserWrite = _lldb.eFilePermissionsUserWrite eFilePermissionsUserExecute = _lldb.eFilePermissionsUserExecute eFilePermissionsGroupRead = _lldb.eFilePermissionsGroupRead eFilePermissionsGroupWrite = _lldb.eFilePermissionsGroupWrite eFilePermissionsGroupExecute = _lldb.eFilePermissionsGroupExecute eFilePermissionsWorldRead = _lldb.eFilePermissionsWorldRead eFilePermissionsWorldWrite = _lldb.eFilePermissionsWorldWrite eFilePermissionsWorldExecute = _lldb.eFilePermissionsWorldExecute eFilePermissionsUserRW = _lldb.eFilePermissionsUserRW eFileFilePermissionsUserRX = _lldb.eFileFilePermissionsUserRX eFilePermissionsUserRWX = _lldb.eFilePermissionsUserRWX eFilePermissionsGroupRW = _lldb.eFilePermissionsGroupRW eFilePermissionsGroupRX = _lldb.eFilePermissionsGroupRX eFilePermissionsGroupRWX = _lldb.eFilePermissionsGroupRWX eFilePermissionsWorldRW = _lldb.eFilePermissionsWorldRW eFilePermissionsWorldRX = _lldb.eFilePermissionsWorldRX eFilePermissionsWorldRWX = _lldb.eFilePermissionsWorldRWX eFilePermissionsEveryoneR = _lldb.eFilePermissionsEveryoneR eFilePermissionsEveryoneW = _lldb.eFilePermissionsEveryoneW eFilePermissionsEveryoneX = _lldb.eFilePermissionsEveryoneX eFilePermissionsEveryoneRW = _lldb.eFilePermissionsEveryoneRW eFilePermissionsEveryoneRX = _lldb.eFilePermissionsEveryoneRX eFilePermissionsEveryoneRWX = _lldb.eFilePermissionsEveryoneRWX eFilePermissionsFileDefault = _lldb.eFilePermissionsFileDefault eFilePermissionsDirectoryDefault = _lldb.eFilePermissionsDirectoryDefault eQueueItemKindUnknown = _lldb.eQueueItemKindUnknown eQueueItemKindFunction = _lldb.eQueueItemKindFunction eQueueItemKindBlock = _lldb.eQueueItemKindBlock eQueueKindUnknown = _lldb.eQueueKindUnknown eQueueKindSerial = _lldb.eQueueKindSerial eQueueKindConcurrent = _lldb.eQueueKindConcurrent eExpressionEvaluationParse = _lldb.eExpressionEvaluationParse eExpressionEvaluationIRGen = _lldb.eExpressionEvaluationIRGen eExpressionEvaluationExecution = _lldb.eExpressionEvaluationExecution eExpressionEvaluationComplete = _lldb.eExpressionEvaluationComplete eWatchpointKindWrite = _lldb.eWatchpointKindWrite eWatchpointKindRead = _lldb.eWatchpointKindRead eGdbSignalBadAccess = _lldb.eGdbSignalBadAccess eGdbSignalBadInstruction = _lldb.eGdbSignalBadInstruction eGdbSignalArithmetic = _lldb.eGdbSignalArithmetic eGdbSignalEmulation = _lldb.eGdbSignalEmulation eGdbSignalSoftware = _lldb.eGdbSignalSoftware eGdbSignalBreakpoint = _lldb.eGdbSignalBreakpoint ePathTypeLLDBShlibDir = _lldb.ePathTypeLLDBShlibDir ePathTypeSupportExecutableDir = _lldb.ePathTypeSupportExecutableDir ePathTypeHeaderDir = _lldb.ePathTypeHeaderDir ePathTypePythonDir = _lldb.ePathTypePythonDir ePathTypeLLDBSystemPlugins = _lldb.ePathTypeLLDBSystemPlugins ePathTypeLLDBUserPlugins = _lldb.ePathTypeLLDBUserPlugins ePathTypeLLDBTempSystemDir = _lldb.ePathTypeLLDBTempSystemDir ePathTypeGlobalLLDBTempSystemDir = _lldb.ePathTypeGlobalLLDBTempSystemDir ePathTypeClangDir = _lldb.ePathTypeClangDir ePathTypeSwiftDir = _lldb.ePathTypeSwiftDir eMemberFunctionKindUnknown = _lldb.eMemberFunctionKindUnknown eMemberFunctionKindConstructor = _lldb.eMemberFunctionKindConstructor eMemberFunctionKindDestructor = _lldb.eMemberFunctionKindDestructor eMemberFunctionKindInstanceMethod = _lldb.eMemberFunctionKindInstanceMethod eMemberFunctionKindStaticMethod = _lldb.eMemberFunctionKindStaticMethod eMatchTypeNormal = _lldb.eMatchTypeNormal eMatchTypeRegex = _lldb.eMatchTypeRegex eMatchTypeStartsWith = _lldb.eMatchTypeStartsWith eTypeHasChildren = _lldb.eTypeHasChildren eTypeHasValue = _lldb.eTypeHasValue eTypeIsArray = _lldb.eTypeIsArray eTypeIsBlock = _lldb.eTypeIsBlock eTypeIsBuiltIn = _lldb.eTypeIsBuiltIn eTypeIsClass = _lldb.eTypeIsClass eTypeIsCPlusPlus = _lldb.eTypeIsCPlusPlus eTypeIsEnumeration = _lldb.eTypeIsEnumeration eTypeIsFuncPrototype = _lldb.eTypeIsFuncPrototype eTypeIsMember = _lldb.eTypeIsMember eTypeIsObjC = _lldb.eTypeIsObjC eTypeIsPointer = _lldb.eTypeIsPointer eTypeIsReference = _lldb.eTypeIsReference eTypeIsStructUnion = _lldb.eTypeIsStructUnion eTypeIsTemplate = _lldb.eTypeIsTemplate eTypeIsTypedef = _lldb.eTypeIsTypedef eTypeIsVector = _lldb.eTypeIsVector eTypeIsScalar = _lldb.eTypeIsScalar eTypeIsInteger = _lldb.eTypeIsInteger eTypeIsFloat = _lldb.eTypeIsFloat eTypeIsComplex = _lldb.eTypeIsComplex eTypeIsSigned = _lldb.eTypeIsSigned eTypeInstanceIsPointer = _lldb.eTypeInstanceIsPointer eTypeIsSwift = _lldb.eTypeIsSwift eTypeIsGenericTypeParam = _lldb.eTypeIsGenericTypeParam eTypeIsProtocol = _lldb.eTypeIsProtocol eTypeIsTuple = _lldb.eTypeIsTuple eTypeIsMetatype = _lldb.eTypeIsMetatype eTypeIsGeneric = _lldb.eTypeIsGeneric eTypeIsBound = _lldb.eTypeIsBound eCommandRequiresTarget = _lldb.eCommandRequiresTarget eCommandRequiresProcess = _lldb.eCommandRequiresProcess eCommandRequiresThread = _lldb.eCommandRequiresThread eCommandRequiresFrame = _lldb.eCommandRequiresFrame eCommandRequiresRegContext = _lldb.eCommandRequiresRegContext eCommandTryTargetAPILock = _lldb.eCommandTryTargetAPILock eCommandProcessMustBeLaunched = _lldb.eCommandProcessMustBeLaunched eCommandProcessMustBePaused = _lldb.eCommandProcessMustBePaused eCommandProcessMustBeTraced = _lldb.eCommandProcessMustBeTraced eTypeSummaryCapped = _lldb.eTypeSummaryCapped eTypeSummaryUncapped = _lldb.eTypeSummaryUncapped eCommandInterpreterResultSuccess = _lldb.eCommandInterpreterResultSuccess eCommandInterpreterResultInferiorCrash = _lldb.eCommandInterpreterResultInferiorCrash eCommandInterpreterResultCommandError = _lldb.eCommandInterpreterResultCommandError eCommandInterpreterResultQuitRequested = _lldb.eCommandInterpreterResultQuitRequested class SBAddress(object): r""" A section + offset based address class. The SBAddress class allows addresses to be relative to a section that can move during runtime due to images (executables, shared libraries, bundles, frameworks) being loaded at different addresses than the addresses found in the object file that represents them on disk. There are currently two types of addresses for a section: * file addresses * load addresses File addresses represents the virtual addresses that are in the 'on disk' object files. These virtual addresses are converted to be relative to unique sections scoped to the object file so that when/if the addresses slide when the images are loaded/unloaded in memory, we can easily track these changes without having to update every object (compile unit ranges, line tables, function address ranges, lexical block and inlined subroutine address ranges, global and static variables) each time an image is loaded or unloaded. Load addresses represents the virtual addresses where each section ends up getting loaded at runtime. Before executing a program, it is common for all of the load addresses to be unresolved. When a DynamicLoader plug-in receives notification that shared libraries have been loaded/unloaded, the load addresses of the main executable and any images (shared libraries) will be resolved/unresolved. When this happens, breakpoints that are in one of these sections can be set/cleared. See docstring of SBFunction for example usage of SBAddress. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBAddress self) -> SBAddress __init__(SBAddress self, SBAddress rhs) -> SBAddress __init__(SBAddress self, SBSection section, lldb::addr_t offset) -> SBAddress __init__(SBAddress self, lldb::addr_t load_addr, SBTarget target) -> SBAddress Create an address by resolving a load address using the supplied target. """ _lldb.SBAddress_swiginit(self, _lldb.new_SBAddress(*args)) __swig_destroy__ = _lldb.delete_SBAddress def IsValid(self): r"""IsValid(SBAddress self) -> bool""" return _lldb.SBAddress_IsValid(self) def __nonzero__(self): return _lldb.SBAddress___nonzero__(self) __bool__ = __nonzero__ def __eq__(self, other): return not self.__ne__(other) def __ne__(self, rhs): r"""__ne__(SBAddress self, SBAddress rhs) -> bool""" return _lldb.SBAddress___ne__(self, rhs) def Clear(self): r"""Clear(SBAddress self)""" return _lldb.SBAddress_Clear(self) def GetFileAddress(self): r"""GetFileAddress(SBAddress self) -> lldb::addr_t""" return _lldb.SBAddress_GetFileAddress(self) def GetLoadAddress(self, target): r"""GetLoadAddress(SBAddress self, SBTarget target) -> lldb::addr_t""" return _lldb.SBAddress_GetLoadAddress(self, target) def SetLoadAddress(self, load_addr, target): r"""SetLoadAddress(SBAddress self, lldb::addr_t load_addr, SBTarget target)""" return _lldb.SBAddress_SetLoadAddress(self, load_addr, target) def OffsetAddress(self, offset): r"""OffsetAddress(SBAddress self, lldb::addr_t offset) -> bool""" return _lldb.SBAddress_OffsetAddress(self, offset) def GetDescription(self, description): r"""GetDescription(SBAddress self, SBStream description) -> bool""" return _lldb.SBAddress_GetDescription(self, description) def GetSection(self): r"""GetSection(SBAddress self) -> SBSection""" return _lldb.SBAddress_GetSection(self) def GetOffset(self): r"""GetOffset(SBAddress self) -> lldb::addr_t""" return _lldb.SBAddress_GetOffset(self) def SetAddress(self, section, offset): r"""SetAddress(SBAddress self, SBSection section, lldb::addr_t offset)""" return _lldb.SBAddress_SetAddress(self, section, offset) def GetSymbolContext(self, resolve_scope): r""" GetSymbolContext(SBAddress self, uint32_t resolve_scope) -> SBSymbolContext GetSymbolContext() and the following can lookup symbol information for a given address. An address might refer to code or data from an existing module, or it might refer to something on the stack or heap. The following functions will only return valid values if the address has been resolved to a code or data address using :py:class:`SBAddress.SetLoadAddress' or :py:class:`SBTarget.ResolveLoadAddress`. """ return _lldb.SBAddress_GetSymbolContext(self, resolve_scope) def GetModule(self): r""" GetModule(SBAddress self) -> SBModule GetModule() and the following grab individual objects for a given address and are less efficient if you want more than one symbol related objects. Use :py:class:`SBAddress.GetSymbolContext` or :py:class:`SBTarget.ResolveSymbolContextForAddress` when you want multiple debug symbol related objects for an address. One or more bits from the SymbolContextItem enumerations can be logically OR'ed together to more efficiently retrieve multiple symbol objects. """ return _lldb.SBAddress_GetModule(self) def GetCompileUnit(self): r"""GetCompileUnit(SBAddress self) -> SBCompileUnit""" return _lldb.SBAddress_GetCompileUnit(self) def GetFunction(self): r"""GetFunction(SBAddress self) -> SBFunction""" return _lldb.SBAddress_GetFunction(self) def GetBlock(self): r"""GetBlock(SBAddress self) -> SBBlock""" return _lldb.SBAddress_GetBlock(self) def GetSymbol(self): r"""GetSymbol(SBAddress self) -> SBSymbol""" return _lldb.SBAddress_GetSymbol(self) def GetLineEntry(self): r"""GetLineEntry(SBAddress self) -> SBLineEntry""" return _lldb.SBAddress_GetLineEntry(self) def __str__(self): r"""__str__(SBAddress self) -> std::string""" return _lldb.SBAddress___str__(self) __runtime_error_str = 'This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.' def __get_load_addr_property__ (self): '''Get the load address for a lldb.SBAddress using the current target. This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.''' if not target: raise RuntimeError(self.__runtime_error_str) return self.GetLoadAddress (target) def __set_load_addr_property__ (self, load_addr): '''Set the load address for a lldb.SBAddress using the current target. This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.''' if not target: raise RuntimeError(self.__runtime_error_str) return self.SetLoadAddress (load_addr, target) def __int__(self): '''Convert an address to a load address if there is a process and that process is alive, or to a file address otherwise. This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.''' if not process or not target: raise RuntimeError(self.__runtime_error_str) if process.is_alive: return self.GetLoadAddress (target) return self.GetFileAddress () def __oct__(self): '''Convert the address to an octal string. This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.''' return '%o' % int(self) def __hex__(self): '''Convert the address to an hex string. This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.''' return '0x%x' % int(self) module = property(GetModule, None, doc='''A read only property that returns an lldb object that represents the module (lldb.SBModule) that this address resides within.''') compile_unit = property(GetCompileUnit, None, doc='''A read only property that returns an lldb object that represents the compile unit (lldb.SBCompileUnit) that this address resides within.''') line_entry = property(GetLineEntry, None, doc='''A read only property that returns an lldb object that represents the line entry (lldb.SBLineEntry) that this address resides within.''') function = property(GetFunction, None, doc='''A read only property that returns an lldb object that represents the function (lldb.SBFunction) that this address resides within.''') block = property(GetBlock, None, doc='''A read only property that returns an lldb object that represents the block (lldb.SBBlock) that this address resides within.''') symbol = property(GetSymbol, None, doc='''A read only property that returns an lldb object that represents the symbol (lldb.SBSymbol) that this address resides within.''') offset = property(GetOffset, None, doc='''A read only property that returns the section offset in bytes as an integer.''') section = property(GetSection, None, doc='''A read only property that returns an lldb object that represents the section (lldb.SBSection) that this address resides within.''') file_addr = property(GetFileAddress, None, doc='''A read only property that returns file address for the section as an integer. This is the address that represents the address as it is found in the object file that defines it.''') load_addr = property(__get_load_addr_property__, __set_load_addr_property__, doc='''A read/write property that gets/sets the SBAddress using load address. This resolves the SBAddress using the SBTarget from lldb.target so this property can ONLY be used in the interactive script interpreter (i.e. under the lldb script command). For things like Python based commands and breakpoint callbacks use GetLoadAddress instead.''') # Register SBAddress in _lldb: _lldb.SBAddress_swigregister(SBAddress) class SBAttachInfo(object): r"""Describes how to attach when calling :py:class:`SBTarget.Attach`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBAttachInfo self) -> SBAttachInfo __init__(SBAttachInfo self, lldb::pid_t pid) -> SBAttachInfo __init__(SBAttachInfo self, char const * path, bool wait_for) -> SBAttachInfo __init__(SBAttachInfo self, char const * path, bool wait_for, bool _async) -> SBAttachInfo __init__(SBAttachInfo self, SBAttachInfo rhs) -> SBAttachInfo """ _lldb.SBAttachInfo_swiginit(self, _lldb.new_SBAttachInfo(*args)) def GetProcessID(self): r"""GetProcessID(SBAttachInfo self) -> lldb::pid_t""" return _lldb.SBAttachInfo_GetProcessID(self) def SetProcessID(self, pid): r"""SetProcessID(SBAttachInfo self, lldb::pid_t pid)""" return _lldb.SBAttachInfo_SetProcessID(self, pid) def SetExecutable(self, *args): r""" SetExecutable(SBAttachInfo self, char const * path) SetExecutable(SBAttachInfo self, SBFileSpec exe_file) """ return _lldb.SBAttachInfo_SetExecutable(self, *args) def GetWaitForLaunch(self): r"""GetWaitForLaunch(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_GetWaitForLaunch(self) def SetWaitForLaunch(self, *args): r""" SetWaitForLaunch(SBAttachInfo self, bool b) SetWaitForLaunch(SBAttachInfo self, bool b, bool _async) """ return _lldb.SBAttachInfo_SetWaitForLaunch(self, *args) def GetIgnoreExisting(self): r"""GetIgnoreExisting(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_GetIgnoreExisting(self) def SetIgnoreExisting(self, b): r"""SetIgnoreExisting(SBAttachInfo self, bool b)""" return _lldb.SBAttachInfo_SetIgnoreExisting(self, b) def GetResumeCount(self): r"""GetResumeCount(SBAttachInfo self) -> uint32_t""" return _lldb.SBAttachInfo_GetResumeCount(self) def SetResumeCount(self, c): r"""SetResumeCount(SBAttachInfo self, uint32_t c)""" return _lldb.SBAttachInfo_SetResumeCount(self, c) def GetProcessPluginName(self): r"""GetProcessPluginName(SBAttachInfo self) -> char const *""" return _lldb.SBAttachInfo_GetProcessPluginName(self) def SetProcessPluginName(self, plugin_name): r"""SetProcessPluginName(SBAttachInfo self, char const * plugin_name)""" return _lldb.SBAttachInfo_SetProcessPluginName(self, plugin_name) def GetUserID(self): r"""GetUserID(SBAttachInfo self) -> uint32_t""" return _lldb.SBAttachInfo_GetUserID(self) def GetGroupID(self): r"""GetGroupID(SBAttachInfo self) -> uint32_t""" return _lldb.SBAttachInfo_GetGroupID(self) def UserIDIsValid(self): r"""UserIDIsValid(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_UserIDIsValid(self) def GroupIDIsValid(self): r"""GroupIDIsValid(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_GroupIDIsValid(self) def SetUserID(self, uid): r"""SetUserID(SBAttachInfo self, uint32_t uid)""" return _lldb.SBAttachInfo_SetUserID(self, uid) def SetGroupID(self, gid): r"""SetGroupID(SBAttachInfo self, uint32_t gid)""" return _lldb.SBAttachInfo_SetGroupID(self, gid) def GetEffectiveUserID(self): r"""GetEffectiveUserID(SBAttachInfo self) -> uint32_t""" return _lldb.SBAttachInfo_GetEffectiveUserID(self) def GetEffectiveGroupID(self): r"""GetEffectiveGroupID(SBAttachInfo self) -> uint32_t""" return _lldb.SBAttachInfo_GetEffectiveGroupID(self) def EffectiveUserIDIsValid(self): r"""EffectiveUserIDIsValid(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_EffectiveUserIDIsValid(self) def EffectiveGroupIDIsValid(self): r"""EffectiveGroupIDIsValid(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_EffectiveGroupIDIsValid(self) def SetEffectiveUserID(self, uid): r"""SetEffectiveUserID(SBAttachInfo self, uint32_t uid)""" return _lldb.SBAttachInfo_SetEffectiveUserID(self, uid) def SetEffectiveGroupID(self, gid): r"""SetEffectiveGroupID(SBAttachInfo self, uint32_t gid)""" return _lldb.SBAttachInfo_SetEffectiveGroupID(self, gid) def GetParentProcessID(self): r"""GetParentProcessID(SBAttachInfo self) -> lldb::pid_t""" return _lldb.SBAttachInfo_GetParentProcessID(self) def SetParentProcessID(self, pid): r"""SetParentProcessID(SBAttachInfo self, lldb::pid_t pid)""" return _lldb.SBAttachInfo_SetParentProcessID(self, pid) def ParentProcessIDIsValid(self): r"""ParentProcessIDIsValid(SBAttachInfo self) -> bool""" return _lldb.SBAttachInfo_ParentProcessIDIsValid(self) def GetListener(self): r"""GetListener(SBAttachInfo self) -> SBListener""" return _lldb.SBAttachInfo_GetListener(self) def SetListener(self, listener): r"""SetListener(SBAttachInfo self, SBListener listener)""" return _lldb.SBAttachInfo_SetListener(self, listener) __swig_destroy__ = _lldb.delete_SBAttachInfo # Register SBAttachInfo in _lldb: _lldb.SBAttachInfo_swigregister(SBAttachInfo) class SBBlock(object): r"""Represents a lexical block. SBFunction contains SBBlock(s).""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBBlock self) -> SBBlock __init__(SBBlock self, SBBlock rhs) -> SBBlock """ _lldb.SBBlock_swiginit(self, _lldb.new_SBBlock(*args)) __swig_destroy__ = _lldb.delete_SBBlock def IsInlined(self): r""" IsInlined(SBBlock self) -> bool Is this block contained within an inlined function? """ return _lldb.SBBlock_IsInlined(self) def IsValid(self): r"""IsValid(SBBlock self) -> bool""" return _lldb.SBBlock_IsValid(self) def __nonzero__(self): return _lldb.SBBlock___nonzero__(self) __bool__ = __nonzero__ def GetInlinedName(self): r""" GetInlinedName(SBBlock self) -> char const * Get the function name if this block represents an inlined function; otherwise, return None. """ return _lldb.SBBlock_GetInlinedName(self) def GetInlinedCallSiteFile(self): r""" GetInlinedCallSiteFile(SBBlock self) -> SBFileSpec Get the call site file if this block represents an inlined function; otherwise, return an invalid file spec. """ return _lldb.SBBlock_GetInlinedCallSiteFile(self) def GetInlinedCallSiteLine(self): r""" GetInlinedCallSiteLine(SBBlock self) -> uint32_t Get the call site line if this block represents an inlined function; otherwise, return 0. """ return _lldb.SBBlock_GetInlinedCallSiteLine(self) def GetInlinedCallSiteColumn(self): r""" GetInlinedCallSiteColumn(SBBlock self) -> uint32_t Get the call site column if this block represents an inlined function; otherwise, return 0. """ return _lldb.SBBlock_GetInlinedCallSiteColumn(self) def GetParent(self): r""" GetParent(SBBlock self) -> SBBlock Get the parent block. """ return _lldb.SBBlock_GetParent(self) def GetContainingInlinedBlock(self): r""" GetContainingInlinedBlock(SBBlock self) -> SBBlock Get the inlined block that is or contains this block. """ return _lldb.SBBlock_GetContainingInlinedBlock(self) def GetSibling(self): r""" GetSibling(SBBlock self) -> SBBlock Get the sibling block for this block. """ return _lldb.SBBlock_GetSibling(self) def GetFirstChild(self): r""" GetFirstChild(SBBlock self) -> SBBlock Get the first child block. """ return _lldb.SBBlock_GetFirstChild(self) def GetNumRanges(self): r"""GetNumRanges(SBBlock self) -> uint32_t""" return _lldb.SBBlock_GetNumRanges(self) def GetRangeStartAddress(self, idx): r"""GetRangeStartAddress(SBBlock self, uint32_t idx) -> SBAddress""" return _lldb.SBBlock_GetRangeStartAddress(self, idx) def GetRangeEndAddress(self, idx): r"""GetRangeEndAddress(SBBlock self, uint32_t idx) -> SBAddress""" return _lldb.SBBlock_GetRangeEndAddress(self, idx) def GetRangeIndexForBlockAddress(self, block_addr): r"""GetRangeIndexForBlockAddress(SBBlock self, SBAddress block_addr) -> uint32_t""" return _lldb.SBBlock_GetRangeIndexForBlockAddress(self, block_addr) def GetDescription(self, description): r"""GetDescription(SBBlock self, SBStream description) -> bool""" return _lldb.SBBlock_GetDescription(self, description) def GetVariables(self, *args): r""" GetVariables(SBBlock self, SBFrame frame, bool arguments, bool locals, bool statics, lldb::DynamicValueType use_dynamic) -> SBValueList GetVariables(SBBlock self, SBTarget target, bool arguments, bool locals, bool statics) -> SBValueList """ return _lldb.SBBlock_GetVariables(self, *args) def __str__(self): r"""__str__(SBBlock self) -> std::string""" return _lldb.SBBlock___str__(self) def get_range_at_index(self, idx): if idx < self.GetNumRanges(): return [self.GetRangeStartAddress(idx), self.GetRangeEndAddress(idx)] return [] class ranges_access(object): '''A helper object that will lazily hand out an array of lldb.SBAddress that represent address ranges for a block.''' def __init__(self, sbblock): self.sbblock = sbblock def __len__(self): if self.sbblock: return int(self.sbblock.GetNumRanges()) return 0 def __getitem__(self, key): count = len(self) if type(key) is int: return self.sbblock.get_range_at_index (key); if isinstance(key, SBAddress): range_idx = self.sbblock.GetRangeIndexForBlockAddress(key); if range_idx < len(self): return [self.sbblock.GetRangeStartAddress(range_idx), self.sbblock.GetRangeEndAddress(range_idx)] else: print("error: unsupported item type: %s" % type(key)) return None def get_ranges_access_object(self): '''An accessor function that returns a ranges_access() object which allows lazy block address ranges access.''' return self.ranges_access (self) def get_ranges_array(self): '''An accessor function that returns an array object that contains all ranges in this block object.''' if not hasattr(self, 'ranges_array'): self.ranges_array = [] for idx in range(self.num_ranges): self.ranges_array.append ([self.GetRangeStartAddress(idx), self.GetRangeEndAddress(idx)]) return self.ranges_array def get_call_site(self): return declaration(self.GetInlinedCallSiteFile(), self.GetInlinedCallSiteLine(), self.GetInlinedCallSiteColumn()) parent = property(GetParent, None, doc='''A read only property that returns the same result as GetParent().''') first_child = property(GetFirstChild, None, doc='''A read only property that returns the same result as GetFirstChild().''') call_site = property(get_call_site, None, doc='''A read only property that returns a lldb.declaration object that contains the inlined call site file, line and column.''') sibling = property(GetSibling, None, doc='''A read only property that returns the same result as GetSibling().''') name = property(GetInlinedName, None, doc='''A read only property that returns the same result as GetInlinedName().''') inlined_block = property(GetContainingInlinedBlock, None, doc='''A read only property that returns the same result as GetContainingInlinedBlock().''') range = property(get_ranges_access_object, None, doc='''A read only property that allows item access to the address ranges for a block by integer (range = block.range[0]) and by lldb.SBAddress (find the range that contains the specified lldb.SBAddress like "pc_range = lldb.frame.block.range[frame.addr]").''') ranges = property(get_ranges_array, None, doc='''A read only property that returns a list() object that contains all of the address ranges for the block.''') num_ranges = property(GetNumRanges, None, doc='''A read only property that returns the same result as GetNumRanges().''') # Register SBBlock in _lldb: _lldb.SBBlock_swigregister(SBBlock) class SBBreakpoint(object): r""" Represents a logical breakpoint and its associated settings. For example (from test/functionalities/breakpoint/breakpoint_ignore_count/ TestBreakpointIgnoreCount.py),:: def breakpoint_ignore_count_python(self): '''Use Python APIs to set breakpoint ignore count.''' exe = os.path.join(os.getcwd(), 'a.out') # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateByName('c', 'a.out') self.assertTrue(breakpoint and breakpoint.GetNumLocations() == 1, VALID_BREAKPOINT) # Get the breakpoint location from breakpoint after we verified that, # indeed, it has one location. location = breakpoint.GetLocationAtIndex(0) self.assertTrue(location and location.IsEnabled(), VALID_BREAKPOINT_LOCATION) # Set the ignore count on the breakpoint location. location.SetIgnoreCount(2) self.assertTrue(location.GetIgnoreCount() == 2, 'SetIgnoreCount() works correctly') # Now launch the process, and do not stop at entry point. process = target.LaunchSimple(None, None, os.getcwd()) self.assertTrue(process, PROCESS_IS_VALID) # Frame#0 should be on main.c:37, frame#1 should be on main.c:25, and # frame#2 should be on main.c:48. #lldbutil.print_stacktraces(process) from lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue(thread != None, 'There should be a thread stopped due to breakpoint') frame0 = thread.GetFrameAtIndex(0) frame1 = thread.GetFrameAtIndex(1) frame2 = thread.GetFrameAtIndex(2) self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and frame1.GetLineEntry().GetLine() == self.line3 and frame2.GetLineEntry().GetLine() == self.line4, STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT) # The hit count for the breakpoint should be 3. self.assertTrue(breakpoint.GetHitCount() == 3) process.Continue() SBBreakpoint supports breakpoint location iteration, for example,:: for bl in breakpoint: print('breakpoint location load addr: %s' % hex(bl.GetLoadAddress())) print('breakpoint location condition: %s' % hex(bl.GetCondition())) and rich comparison methods which allow the API program to use,:: if aBreakpoint == bBreakpoint: ... to compare two breakpoints for equality. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBBreakpoint self) -> SBBreakpoint __init__(SBBreakpoint self, SBBreakpoint rhs) -> SBBreakpoint """ _lldb.SBBreakpoint_swiginit(self, _lldb.new_SBBreakpoint(*args)) __swig_destroy__ = _lldb.delete_SBBreakpoint def __eq__(self, rhs): r"""__eq__(SBBreakpoint self, SBBreakpoint rhs) -> bool""" return _lldb.SBBreakpoint___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBBreakpoint self, SBBreakpoint rhs) -> bool""" return _lldb.SBBreakpoint___ne__(self, rhs) def GetID(self): r"""GetID(SBBreakpoint self) -> lldb::break_id_t""" return _lldb.SBBreakpoint_GetID(self) def IsValid(self): r"""IsValid(SBBreakpoint self) -> bool""" return _lldb.SBBreakpoint_IsValid(self) def __nonzero__(self): return _lldb.SBBreakpoint___nonzero__(self) __bool__ = __nonzero__ def ClearAllBreakpointSites(self): r"""ClearAllBreakpointSites(SBBreakpoint self)""" return _lldb.SBBreakpoint_ClearAllBreakpointSites(self) def GetTarget(self): r"""GetTarget(SBBreakpoint self) -> SBTarget""" return _lldb.SBBreakpoint_GetTarget(self) def FindLocationByAddress(self, vm_addr): r"""FindLocationByAddress(SBBreakpoint self, lldb::addr_t vm_addr) -> SBBreakpointLocation""" return _lldb.SBBreakpoint_FindLocationByAddress(self, vm_addr) def FindLocationIDByAddress(self, vm_addr): r"""FindLocationIDByAddress(SBBreakpoint self, lldb::addr_t vm_addr) -> lldb::break_id_t""" return _lldb.SBBreakpoint_FindLocationIDByAddress(self, vm_addr) def FindLocationByID(self, bp_loc_id): r"""FindLocationByID(SBBreakpoint self, lldb::break_id_t bp_loc_id) -> SBBreakpointLocation""" return _lldb.SBBreakpoint_FindLocationByID(self, bp_loc_id) def GetLocationAtIndex(self, index): r"""GetLocationAtIndex(SBBreakpoint self, uint32_t index) -> SBBreakpointLocation""" return _lldb.SBBreakpoint_GetLocationAtIndex(self, index) def SetEnabled(self, enable): r"""SetEnabled(SBBreakpoint self, bool enable)""" return _lldb.SBBreakpoint_SetEnabled(self, enable) def IsEnabled(self): r"""IsEnabled(SBBreakpoint self) -> bool""" return _lldb.SBBreakpoint_IsEnabled(self) def SetOneShot(self, one_shot): r"""SetOneShot(SBBreakpoint self, bool one_shot)""" return _lldb.SBBreakpoint_SetOneShot(self, one_shot) def IsOneShot(self): r"""IsOneShot(SBBreakpoint self) -> bool""" return _lldb.SBBreakpoint_IsOneShot(self) def IsInternal(self): r"""IsInternal(SBBreakpoint self) -> bool""" return _lldb.SBBreakpoint_IsInternal(self) def GetHitCount(self): r"""GetHitCount(SBBreakpoint self) -> uint32_t""" return _lldb.SBBreakpoint_GetHitCount(self) def SetIgnoreCount(self, count): r"""SetIgnoreCount(SBBreakpoint self, uint32_t count)""" return _lldb.SBBreakpoint_SetIgnoreCount(self, count) def GetIgnoreCount(self): r"""GetIgnoreCount(SBBreakpoint self) -> uint32_t""" return _lldb.SBBreakpoint_GetIgnoreCount(self) def SetCondition(self, condition): r""" SetCondition(SBBreakpoint self, char const * condition) The breakpoint stops only if the condition expression evaluates to true. """ return _lldb.SBBreakpoint_SetCondition(self, condition) def GetCondition(self): r""" GetCondition(SBBreakpoint self) -> char const * Get the condition expression for the breakpoint. """ return _lldb.SBBreakpoint_GetCondition(self) def SetAutoContinue(self, auto_continue): r"""SetAutoContinue(SBBreakpoint self, bool auto_continue)""" return _lldb.SBBreakpoint_SetAutoContinue(self, auto_continue) def GetAutoContinue(self): r"""GetAutoContinue(SBBreakpoint self) -> bool""" return _lldb.SBBreakpoint_GetAutoContinue(self) def SetThreadID(self, sb_thread_id): r"""SetThreadID(SBBreakpoint self, lldb::tid_t sb_thread_id)""" return _lldb.SBBreakpoint_SetThreadID(self, sb_thread_id) def GetThreadID(self): r"""GetThreadID(SBBreakpoint self) -> lldb::tid_t""" return _lldb.SBBreakpoint_GetThreadID(self) def SetThreadIndex(self, index): r"""SetThreadIndex(SBBreakpoint self, uint32_t index)""" return _lldb.SBBreakpoint_SetThreadIndex(self, index) def GetThreadIndex(self): r"""GetThreadIndex(SBBreakpoint self) -> uint32_t""" return _lldb.SBBreakpoint_GetThreadIndex(self) def SetThreadName(self, thread_name): r"""SetThreadName(SBBreakpoint self, char const * thread_name)""" return _lldb.SBBreakpoint_SetThreadName(self, thread_name) def GetThreadName(self): r"""GetThreadName(SBBreakpoint self) -> char const *""" return _lldb.SBBreakpoint_GetThreadName(self) def SetQueueName(self, queue_name): r"""SetQueueName(SBBreakpoint self, char const * queue_name)""" return _lldb.SBBreakpoint_SetQueueName(self, queue_name) def GetQueueName(self): r"""GetQueueName(SBBreakpoint self) -> char const *""" return _lldb.SBBreakpoint_GetQueueName(self) def SetScriptCallbackFunction(self, *args): r""" SetScriptCallbackFunction(SBBreakpoint self, char const * callback_function_name) SetScriptCallbackFunction(SBBreakpoint self, char const * callback_function_name, SBStructuredData extra_args) -> SBError Set the name of the script function to be called when the breakpoint is hit. To use this variant, the function should take (frame, bp_loc, extra_args, internal_dict) and when the breakpoint is hit the extra_args will be passed to the callback function. """ return _lldb.SBBreakpoint_SetScriptCallbackFunction(self, *args) def SetScriptCallbackBody(self, script_body_text): r""" SetScriptCallbackBody(SBBreakpoint self, char const * script_body_text) -> SBError Provide the body for the script function to be called when the breakpoint is hit. The body will be wrapped in a function, which be passed two arguments: 'frame' - which holds the bottom-most SBFrame of the thread that hit the breakpoint 'bpno' - which is the SBBreakpointLocation to which the callback was attached. The error parameter is currently ignored, but will at some point hold the Python compilation diagnostics. Returns true if the body compiles successfully, false if not. """ return _lldb.SBBreakpoint_SetScriptCallbackBody(self, script_body_text) def SetCommandLineCommands(self, commands): r"""SetCommandLineCommands(SBBreakpoint self, SBStringList commands)""" return _lldb.SBBreakpoint_SetCommandLineCommands(self, commands) def GetCommandLineCommands(self, commands): r"""GetCommandLineCommands(SBBreakpoint self, SBStringList commands) -> bool""" return _lldb.SBBreakpoint_GetCommandLineCommands(self, commands) def AddName(self, new_name): r"""AddName(SBBreakpoint self, char const * new_name) -> bool""" return _lldb.SBBreakpoint_AddName(self, new_name) def AddNameWithErrorHandling(self, new_name): r"""AddNameWithErrorHandling(SBBreakpoint self, char const * new_name) -> SBError""" return _lldb.SBBreakpoint_AddNameWithErrorHandling(self, new_name) def RemoveName(self, name_to_remove): r"""RemoveName(SBBreakpoint self, char const * name_to_remove)""" return _lldb.SBBreakpoint_RemoveName(self, name_to_remove) def MatchesName(self, name): r"""MatchesName(SBBreakpoint self, char const * name) -> bool""" return _lldb.SBBreakpoint_MatchesName(self, name) def GetNames(self, names): r"""GetNames(SBBreakpoint self, SBStringList names)""" return _lldb.SBBreakpoint_GetNames(self, names) def GetNumResolvedLocations(self): r"""GetNumResolvedLocations(SBBreakpoint self) -> size_t""" return _lldb.SBBreakpoint_GetNumResolvedLocations(self) def GetNumLocations(self): r"""GetNumLocations(SBBreakpoint self) -> size_t""" return _lldb.SBBreakpoint_GetNumLocations(self) def GetDescription(self, *args): r""" GetDescription(SBBreakpoint self, SBStream description) -> bool GetDescription(SBBreakpoint self, SBStream description, bool include_locations) -> bool """ return _lldb.SBBreakpoint_GetDescription(self, *args) def AddLocation(self, address): r"""AddLocation(SBBreakpoint self, SBAddress address) -> SBError""" return _lldb.SBBreakpoint_AddLocation(self, address) def SerializeToStructuredData(self): r"""SerializeToStructuredData(SBBreakpoint self) -> SBStructuredData""" return _lldb.SBBreakpoint_SerializeToStructuredData(self) @staticmethod def EventIsBreakpointEvent(event): r"""EventIsBreakpointEvent(SBEvent event) -> bool""" return _lldb.SBBreakpoint_EventIsBreakpointEvent(event) @staticmethod def GetBreakpointEventTypeFromEvent(event): r"""GetBreakpointEventTypeFromEvent(SBEvent event) -> lldb::BreakpointEventType""" return _lldb.SBBreakpoint_GetBreakpointEventTypeFromEvent(event) @staticmethod def GetBreakpointFromEvent(event): r"""GetBreakpointFromEvent(SBEvent event) -> SBBreakpoint""" return _lldb.SBBreakpoint_GetBreakpointFromEvent(event) @staticmethod def GetBreakpointLocationAtIndexFromEvent(event, loc_idx): r"""GetBreakpointLocationAtIndexFromEvent(SBEvent event, uint32_t loc_idx) -> SBBreakpointLocation""" return _lldb.SBBreakpoint_GetBreakpointLocationAtIndexFromEvent(event, loc_idx) @staticmethod def GetNumBreakpointLocationsFromEvent(event_sp): r"""GetNumBreakpointLocationsFromEvent(SBEvent event_sp) -> uint32_t""" return _lldb.SBBreakpoint_GetNumBreakpointLocationsFromEvent(event_sp) def IsHardware(self): r"""IsHardware(SBBreakpoint self) -> bool""" return _lldb.SBBreakpoint_IsHardware(self) def __str__(self): r"""__str__(SBBreakpoint self) -> std::string""" return _lldb.SBBreakpoint___str__(self) class locations_access(object): '''A helper object that will lazily hand out locations for a breakpoint when supplied an index.''' def __init__(self, sbbreakpoint): self.sbbreakpoint = sbbreakpoint def __len__(self): if self.sbbreakpoint: return int(self.sbbreakpoint.GetNumLocations()) return 0 def __getitem__(self, key): if type(key) is int and key < len(self): return self.sbbreakpoint.GetLocationAtIndex(key) return None def get_locations_access_object(self): '''An accessor function that returns a locations_access() object which allows lazy location access from a lldb.SBBreakpoint object.''' return self.locations_access (self) def get_breakpoint_location_list(self): '''An accessor function that returns a list() that contains all locations in a lldb.SBBreakpoint object.''' locations = [] accessor = self.get_locations_access_object() for idx in range(len(accessor)): locations.append(accessor[idx]) return locations def __iter__(self): '''Iterate over all breakpoint locations in a lldb.SBBreakpoint object.''' return lldb_iter(self, 'GetNumLocations', 'GetLocationAtIndex') def __len__(self): '''Return the number of breakpoint locations in a lldb.SBBreakpoint object.''' return self.GetNumLocations() locations = property(get_breakpoint_location_list, None, doc='''A read only property that returns a list() of lldb.SBBreakpointLocation objects for this breakpoint.''') location = property(get_locations_access_object, None, doc='''A read only property that returns an object that can access locations by index (not location ID) (location = bkpt.location[12]).''') id = property(GetID, None, doc='''A read only property that returns the ID of this breakpoint.''') enabled = property(IsEnabled, SetEnabled, doc='''A read/write property that configures whether this breakpoint is enabled or not.''') one_shot = property(IsOneShot, SetOneShot, doc='''A read/write property that configures whether this breakpoint is one-shot (deleted when hit) or not.''') num_locations = property(GetNumLocations, None, doc='''A read only property that returns the count of locations of this breakpoint.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBBreakpoint in _lldb: _lldb.SBBreakpoint_swigregister(SBBreakpoint) def SBBreakpoint_EventIsBreakpointEvent(event): r"""SBBreakpoint_EventIsBreakpointEvent(SBEvent event) -> bool""" return _lldb.SBBreakpoint_EventIsBreakpointEvent(event) def SBBreakpoint_GetBreakpointEventTypeFromEvent(event): r"""SBBreakpoint_GetBreakpointEventTypeFromEvent(SBEvent event) -> lldb::BreakpointEventType""" return _lldb.SBBreakpoint_GetBreakpointEventTypeFromEvent(event) def SBBreakpoint_GetBreakpointFromEvent(event): r"""SBBreakpoint_GetBreakpointFromEvent(SBEvent event) -> SBBreakpoint""" return _lldb.SBBreakpoint_GetBreakpointFromEvent(event) def SBBreakpoint_GetBreakpointLocationAtIndexFromEvent(event, loc_idx): r"""SBBreakpoint_GetBreakpointLocationAtIndexFromEvent(SBEvent event, uint32_t loc_idx) -> SBBreakpointLocation""" return _lldb.SBBreakpoint_GetBreakpointLocationAtIndexFromEvent(event, loc_idx) def SBBreakpoint_GetNumBreakpointLocationsFromEvent(event_sp): r"""SBBreakpoint_GetNumBreakpointLocationsFromEvent(SBEvent event_sp) -> uint32_t""" return _lldb.SBBreakpoint_GetNumBreakpointLocationsFromEvent(event_sp) class SBBreakpointList(object): r"""Represents a list of :py:class:`SBBreakpoint`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, target): r"""__init__(SBBreakpointList self, SBTarget target) -> SBBreakpointList""" _lldb.SBBreakpointList_swiginit(self, _lldb.new_SBBreakpointList(target)) __swig_destroy__ = _lldb.delete_SBBreakpointList def GetSize(self): r"""GetSize(SBBreakpointList self) -> size_t""" return _lldb.SBBreakpointList_GetSize(self) def GetBreakpointAtIndex(self, idx): r"""GetBreakpointAtIndex(SBBreakpointList self, size_t idx) -> SBBreakpoint""" return _lldb.SBBreakpointList_GetBreakpointAtIndex(self, idx) def FindBreakpointByID(self, arg2): r"""FindBreakpointByID(SBBreakpointList self, lldb::break_id_t arg2) -> SBBreakpoint""" return _lldb.SBBreakpointList_FindBreakpointByID(self, arg2) def Append(self, sb_bkpt): r"""Append(SBBreakpointList self, SBBreakpoint sb_bkpt)""" return _lldb.SBBreakpointList_Append(self, sb_bkpt) def AppendIfUnique(self, sb_bkpt): r"""AppendIfUnique(SBBreakpointList self, SBBreakpoint sb_bkpt) -> bool""" return _lldb.SBBreakpointList_AppendIfUnique(self, sb_bkpt) def AppendByID(self, id): r"""AppendByID(SBBreakpointList self, lldb::break_id_t id)""" return _lldb.SBBreakpointList_AppendByID(self, id) def Clear(self): r"""Clear(SBBreakpointList self)""" return _lldb.SBBreakpointList_Clear(self) # Register SBBreakpointList in _lldb: _lldb.SBBreakpointList_swigregister(SBBreakpointList) class SBBreakpointLocation(object): r""" Represents one unique instance (by address) of a logical breakpoint. A breakpoint location is defined by the breakpoint that produces it, and the address that resulted in this particular instantiation. Each breakpoint location has its settable options. :py:class:`SBBreakpoint` contains SBBreakpointLocation(s). See docstring of SBBreakpoint for retrieval of an SBBreakpointLocation from an SBBreakpoint. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBBreakpointLocation self) -> SBBreakpointLocation __init__(SBBreakpointLocation self, SBBreakpointLocation rhs) -> SBBreakpointLocation """ _lldb.SBBreakpointLocation_swiginit(self, _lldb.new_SBBreakpointLocation(*args)) __swig_destroy__ = _lldb.delete_SBBreakpointLocation def GetID(self): r"""GetID(SBBreakpointLocation self) -> lldb::break_id_t""" return _lldb.SBBreakpointLocation_GetID(self) def IsValid(self): r"""IsValid(SBBreakpointLocation self) -> bool""" return _lldb.SBBreakpointLocation_IsValid(self) def __nonzero__(self): return _lldb.SBBreakpointLocation___nonzero__(self) __bool__ = __nonzero__ def GetAddress(self): r"""GetAddress(SBBreakpointLocation self) -> SBAddress""" return _lldb.SBBreakpointLocation_GetAddress(self) def GetLoadAddress(self): r"""GetLoadAddress(SBBreakpointLocation self) -> lldb::addr_t""" return _lldb.SBBreakpointLocation_GetLoadAddress(self) def SetEnabled(self, enabled): r"""SetEnabled(SBBreakpointLocation self, bool enabled)""" return _lldb.SBBreakpointLocation_SetEnabled(self, enabled) def IsEnabled(self): r"""IsEnabled(SBBreakpointLocation self) -> bool""" return _lldb.SBBreakpointLocation_IsEnabled(self) def GetHitCount(self): r"""GetHitCount(SBBreakpointLocation self) -> uint32_t""" return _lldb.SBBreakpointLocation_GetHitCount(self) def GetIgnoreCount(self): r"""GetIgnoreCount(SBBreakpointLocation self) -> uint32_t""" return _lldb.SBBreakpointLocation_GetIgnoreCount(self) def SetIgnoreCount(self, n): r"""SetIgnoreCount(SBBreakpointLocation self, uint32_t n)""" return _lldb.SBBreakpointLocation_SetIgnoreCount(self, n) def SetCondition(self, condition): r""" SetCondition(SBBreakpointLocation self, char const * condition) The breakpoint location stops only if the condition expression evaluates to true. """ return _lldb.SBBreakpointLocation_SetCondition(self, condition) def GetCondition(self): r""" GetCondition(SBBreakpointLocation self) -> char const * Get the condition expression for the breakpoint location. """ return _lldb.SBBreakpointLocation_GetCondition(self) def GetAutoContinue(self): r"""GetAutoContinue(SBBreakpointLocation self) -> bool""" return _lldb.SBBreakpointLocation_GetAutoContinue(self) def SetAutoContinue(self, auto_continue): r"""SetAutoContinue(SBBreakpointLocation self, bool auto_continue)""" return _lldb.SBBreakpointLocation_SetAutoContinue(self, auto_continue) def SetScriptCallbackFunction(self, *args): r""" SetScriptCallbackFunction(SBBreakpointLocation self, char const * callback_function_name) SetScriptCallbackFunction(SBBreakpointLocation self, char const * callback_function_name, SBStructuredData extra_args) -> SBError Set the name of the script function to be called when the breakpoint is hit. To use this variant, the function should take (frame, bp_loc, extra_args, internal_dict) and when the breakpoint is hit the extra_args will be passed to the callback function. """ return _lldb.SBBreakpointLocation_SetScriptCallbackFunction(self, *args) def SetScriptCallbackBody(self, script_body_text): r""" SetScriptCallbackBody(SBBreakpointLocation self, char const * script_body_text) -> SBError Provide the body for the script function to be called when the breakpoint location is hit. The body will be wrapped in a function, which be passed two arguments: 'frame' - which holds the bottom-most SBFrame of the thread that hit the breakpoint 'bpno' - which is the SBBreakpointLocation to which the callback was attached. The error parameter is currently ignored, but will at some point hold the Python compilation diagnostics. Returns true if the body compiles successfully, false if not. """ return _lldb.SBBreakpointLocation_SetScriptCallbackBody(self, script_body_text) def SetCommandLineCommands(self, commands): r"""SetCommandLineCommands(SBBreakpointLocation self, SBStringList commands)""" return _lldb.SBBreakpointLocation_SetCommandLineCommands(self, commands) def GetCommandLineCommands(self, commands): r"""GetCommandLineCommands(SBBreakpointLocation self, SBStringList commands) -> bool""" return _lldb.SBBreakpointLocation_GetCommandLineCommands(self, commands) def SetThreadID(self, sb_thread_id): r"""SetThreadID(SBBreakpointLocation self, lldb::tid_t sb_thread_id)""" return _lldb.SBBreakpointLocation_SetThreadID(self, sb_thread_id) def GetThreadID(self): r"""GetThreadID(SBBreakpointLocation self) -> lldb::tid_t""" return _lldb.SBBreakpointLocation_GetThreadID(self) def SetThreadIndex(self, index): r"""SetThreadIndex(SBBreakpointLocation self, uint32_t index)""" return _lldb.SBBreakpointLocation_SetThreadIndex(self, index) def GetThreadIndex(self): r"""GetThreadIndex(SBBreakpointLocation self) -> uint32_t""" return _lldb.SBBreakpointLocation_GetThreadIndex(self) def SetThreadName(self, thread_name): r"""SetThreadName(SBBreakpointLocation self, char const * thread_name)""" return _lldb.SBBreakpointLocation_SetThreadName(self, thread_name) def GetThreadName(self): r"""GetThreadName(SBBreakpointLocation self) -> char const *""" return _lldb.SBBreakpointLocation_GetThreadName(self) def SetQueueName(self, queue_name): r"""SetQueueName(SBBreakpointLocation self, char const * queue_name)""" return _lldb.SBBreakpointLocation_SetQueueName(self, queue_name) def GetQueueName(self): r"""GetQueueName(SBBreakpointLocation self) -> char const *""" return _lldb.SBBreakpointLocation_GetQueueName(self) def IsResolved(self): r"""IsResolved(SBBreakpointLocation self) -> bool""" return _lldb.SBBreakpointLocation_IsResolved(self) def GetDescription(self, description, level): r"""GetDescription(SBBreakpointLocation self, SBStream description, lldb::DescriptionLevel level) -> bool""" return _lldb.SBBreakpointLocation_GetDescription(self, description, level) def GetBreakpoint(self): r"""GetBreakpoint(SBBreakpointLocation self) -> SBBreakpoint""" return _lldb.SBBreakpointLocation_GetBreakpoint(self) def __str__(self): r"""__str__(SBBreakpointLocation self) -> std::string""" return _lldb.SBBreakpointLocation___str__(self) # Register SBBreakpointLocation in _lldb: _lldb.SBBreakpointLocation_swigregister(SBBreakpointLocation) class SBBreakpointName(object): r""" Represents a breakpoint name registered in a given :py:class:`SBTarget`. Breakpoint names provide a way to act on groups of breakpoints. When you add a name to a group of breakpoints, you can then use the name in all the command line lldb commands for that name. You can also configure the SBBreakpointName options and those options will be propagated to any :py:class:`SBBreakpoint` s currently using that name. Adding a name to a breakpoint will also apply any of the set options to that breakpoint. You can also set permissions on a breakpoint name to disable listing, deleting and disabling breakpoints. That will disallow the given operation for breakpoints except when the breakpoint is mentioned by ID. So for instance deleting all the breakpoints won't delete breakpoints so marked. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBBreakpointName self) -> SBBreakpointName __init__(SBBreakpointName self, SBTarget target, char const * name) -> SBBreakpointName __init__(SBBreakpointName self, SBBreakpoint bkpt, char const * name) -> SBBreakpointName __init__(SBBreakpointName self, SBBreakpointName rhs) -> SBBreakpointName """ _lldb.SBBreakpointName_swiginit(self, _lldb.new_SBBreakpointName(*args)) __swig_destroy__ = _lldb.delete_SBBreakpointName def __eq__(self, rhs): r"""__eq__(SBBreakpointName self, SBBreakpointName rhs) -> bool""" return _lldb.SBBreakpointName___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBBreakpointName self, SBBreakpointName rhs) -> bool""" return _lldb.SBBreakpointName___ne__(self, rhs) def __nonzero__(self): return _lldb.SBBreakpointName___nonzero__(self) __bool__ = __nonzero__ def IsValid(self): r"""IsValid(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_IsValid(self) def GetName(self): r"""GetName(SBBreakpointName self) -> char const *""" return _lldb.SBBreakpointName_GetName(self) def SetEnabled(self, enable): r"""SetEnabled(SBBreakpointName self, bool enable)""" return _lldb.SBBreakpointName_SetEnabled(self, enable) def IsEnabled(self): r"""IsEnabled(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_IsEnabled(self) def SetOneShot(self, one_shot): r"""SetOneShot(SBBreakpointName self, bool one_shot)""" return _lldb.SBBreakpointName_SetOneShot(self, one_shot) def IsOneShot(self): r"""IsOneShot(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_IsOneShot(self) def SetIgnoreCount(self, count): r"""SetIgnoreCount(SBBreakpointName self, uint32_t count)""" return _lldb.SBBreakpointName_SetIgnoreCount(self, count) def GetIgnoreCount(self): r"""GetIgnoreCount(SBBreakpointName self) -> uint32_t""" return _lldb.SBBreakpointName_GetIgnoreCount(self) def SetCondition(self, condition): r"""SetCondition(SBBreakpointName self, char const * condition)""" return _lldb.SBBreakpointName_SetCondition(self, condition) def GetCondition(self): r"""GetCondition(SBBreakpointName self) -> char const *""" return _lldb.SBBreakpointName_GetCondition(self) def SetAutoContinue(self, auto_continue): r"""SetAutoContinue(SBBreakpointName self, bool auto_continue)""" return _lldb.SBBreakpointName_SetAutoContinue(self, auto_continue) def GetAutoContinue(self): r"""GetAutoContinue(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_GetAutoContinue(self) def SetThreadID(self, sb_thread_id): r"""SetThreadID(SBBreakpointName self, lldb::tid_t sb_thread_id)""" return _lldb.SBBreakpointName_SetThreadID(self, sb_thread_id) def GetThreadID(self): r"""GetThreadID(SBBreakpointName self) -> lldb::tid_t""" return _lldb.SBBreakpointName_GetThreadID(self) def SetThreadIndex(self, index): r"""SetThreadIndex(SBBreakpointName self, uint32_t index)""" return _lldb.SBBreakpointName_SetThreadIndex(self, index) def GetThreadIndex(self): r"""GetThreadIndex(SBBreakpointName self) -> uint32_t""" return _lldb.SBBreakpointName_GetThreadIndex(self) def SetThreadName(self, thread_name): r"""SetThreadName(SBBreakpointName self, char const * thread_name)""" return _lldb.SBBreakpointName_SetThreadName(self, thread_name) def GetThreadName(self): r"""GetThreadName(SBBreakpointName self) -> char const *""" return _lldb.SBBreakpointName_GetThreadName(self) def SetQueueName(self, queue_name): r"""SetQueueName(SBBreakpointName self, char const * queue_name)""" return _lldb.SBBreakpointName_SetQueueName(self, queue_name) def GetQueueName(self): r"""GetQueueName(SBBreakpointName self) -> char const *""" return _lldb.SBBreakpointName_GetQueueName(self) def SetScriptCallbackFunction(self, *args): r""" SetScriptCallbackFunction(SBBreakpointName self, char const * callback_function_name) SetScriptCallbackFunction(SBBreakpointName self, char const * callback_function_name, SBStructuredData extra_args) -> SBError """ return _lldb.SBBreakpointName_SetScriptCallbackFunction(self, *args) def SetCommandLineCommands(self, commands): r"""SetCommandLineCommands(SBBreakpointName self, SBStringList commands)""" return _lldb.SBBreakpointName_SetCommandLineCommands(self, commands) def GetCommandLineCommands(self, commands): r"""GetCommandLineCommands(SBBreakpointName self, SBStringList commands) -> bool""" return _lldb.SBBreakpointName_GetCommandLineCommands(self, commands) def SetScriptCallbackBody(self, script_body_text): r"""SetScriptCallbackBody(SBBreakpointName self, char const * script_body_text) -> SBError""" return _lldb.SBBreakpointName_SetScriptCallbackBody(self, script_body_text) def GetHelpString(self): r"""GetHelpString(SBBreakpointName self) -> char const *""" return _lldb.SBBreakpointName_GetHelpString(self) def SetHelpString(self, help_string): r"""SetHelpString(SBBreakpointName self, char const * help_string)""" return _lldb.SBBreakpointName_SetHelpString(self, help_string) def GetAllowList(self): r"""GetAllowList(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_GetAllowList(self) def SetAllowList(self, value): r"""SetAllowList(SBBreakpointName self, bool value)""" return _lldb.SBBreakpointName_SetAllowList(self, value) def GetAllowDelete(self): r"""GetAllowDelete(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_GetAllowDelete(self) def SetAllowDelete(self, value): r"""SetAllowDelete(SBBreakpointName self, bool value)""" return _lldb.SBBreakpointName_SetAllowDelete(self, value) def GetAllowDisable(self): r"""GetAllowDisable(SBBreakpointName self) -> bool""" return _lldb.SBBreakpointName_GetAllowDisable(self) def SetAllowDisable(self, value): r"""SetAllowDisable(SBBreakpointName self, bool value)""" return _lldb.SBBreakpointName_SetAllowDisable(self, value) def GetDescription(self, description): r"""GetDescription(SBBreakpointName self, SBStream description) -> bool""" return _lldb.SBBreakpointName_GetDescription(self, description) def __str__(self): r"""__str__(SBBreakpointName self) -> std::string""" return _lldb.SBBreakpointName___str__(self) # Register SBBreakpointName in _lldb: _lldb.SBBreakpointName_swigregister(SBBreakpointName) class SBBroadcaster(object): r""" Represents an entity which can broadcast events. A default broadcaster is associated with an SBCommandInterpreter, SBProcess, and SBTarget. For example, use :: broadcaster = process.GetBroadcaster() to retrieve the process's broadcaster. See also SBEvent for example usage of interacting with a broadcaster. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBBroadcaster self) -> SBBroadcaster __init__(SBBroadcaster self, char const * name) -> SBBroadcaster __init__(SBBroadcaster self, SBBroadcaster rhs) -> SBBroadcaster """ _lldb.SBBroadcaster_swiginit(self, _lldb.new_SBBroadcaster(*args)) __swig_destroy__ = _lldb.delete_SBBroadcaster def IsValid(self): r"""IsValid(SBBroadcaster self) -> bool""" return _lldb.SBBroadcaster_IsValid(self) def __nonzero__(self): return _lldb.SBBroadcaster___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBBroadcaster self)""" return _lldb.SBBroadcaster_Clear(self) def BroadcastEventByType(self, event_type, unique=False): r"""BroadcastEventByType(SBBroadcaster self, uint32_t event_type, bool unique=False)""" return _lldb.SBBroadcaster_BroadcastEventByType(self, event_type, unique) def BroadcastEvent(self, event, unique=False): r"""BroadcastEvent(SBBroadcaster self, SBEvent event, bool unique=False)""" return _lldb.SBBroadcaster_BroadcastEvent(self, event, unique) def AddInitialEventsToListener(self, listener, requested_events): r"""AddInitialEventsToListener(SBBroadcaster self, SBListener listener, uint32_t requested_events)""" return _lldb.SBBroadcaster_AddInitialEventsToListener(self, listener, requested_events) def AddListener(self, listener, event_mask): r"""AddListener(SBBroadcaster self, SBListener listener, uint32_t event_mask) -> uint32_t""" return _lldb.SBBroadcaster_AddListener(self, listener, event_mask) def GetName(self): r"""GetName(SBBroadcaster self) -> char const *""" return _lldb.SBBroadcaster_GetName(self) def EventTypeHasListeners(self, event_type): r"""EventTypeHasListeners(SBBroadcaster self, uint32_t event_type) -> bool""" return _lldb.SBBroadcaster_EventTypeHasListeners(self, event_type) def RemoveListener(self, *args): r"""RemoveListener(SBBroadcaster self, SBListener listener, uint32_t event_mask=4294967295U) -> bool""" return _lldb.SBBroadcaster_RemoveListener(self, *args) def __eq__(self, rhs): r"""__eq__(SBBroadcaster self, SBBroadcaster rhs) -> bool""" return _lldb.SBBroadcaster___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBBroadcaster self, SBBroadcaster rhs) -> bool""" return _lldb.SBBroadcaster___ne__(self, rhs) def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBBroadcaster in _lldb: _lldb.SBBroadcaster_swigregister(SBBroadcaster) class SBCommandInterpreter(object): r""" SBCommandInterpreter handles/interprets commands for lldb. You get the command interpreter from the :py:class:`SBDebugger` instance. For example (from test/ python_api/interpreter/TestCommandInterpreterAPI.py),:: def command_interpreter_api(self): '''Test the SBCommandInterpreter APIs.''' exe = os.path.join(os.getcwd(), 'a.out') # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Retrieve the associated command interpreter from our debugger. ci = self.dbg.GetCommandInterpreter() self.assertTrue(ci, VALID_COMMAND_INTERPRETER) # Exercise some APIs.... self.assertTrue(ci.HasCommands()) self.assertTrue(ci.HasAliases()) self.assertTrue(ci.HasAliasOptions()) self.assertTrue(ci.CommandExists('breakpoint')) self.assertTrue(ci.CommandExists('target')) self.assertTrue(ci.CommandExists('platform')) self.assertTrue(ci.AliasExists('file')) self.assertTrue(ci.AliasExists('run')) self.assertTrue(ci.AliasExists('bt')) res = lldb.SBCommandReturnObject() ci.HandleCommand('breakpoint set -f main.c -l %d' % self.line, res) self.assertTrue(res.Succeeded()) ci.HandleCommand('process launch', res) self.assertTrue(res.Succeeded()) process = ci.GetProcess() self.assertTrue(process) ... The HandleCommand() instance method takes two args: the command string and an SBCommandReturnObject instance which encapsulates the result of command execution. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr eBroadcastBitThreadShouldExit = _lldb.SBCommandInterpreter_eBroadcastBitThreadShouldExit eBroadcastBitResetPrompt = _lldb.SBCommandInterpreter_eBroadcastBitResetPrompt eBroadcastBitQuitCommandReceived = _lldb.SBCommandInterpreter_eBroadcastBitQuitCommandReceived eBroadcastBitAsynchronousOutputData = _lldb.SBCommandInterpreter_eBroadcastBitAsynchronousOutputData eBroadcastBitAsynchronousErrorData = _lldb.SBCommandInterpreter_eBroadcastBitAsynchronousErrorData def __init__(self, rhs): r"""__init__(SBCommandInterpreter self, SBCommandInterpreter rhs) -> SBCommandInterpreter""" _lldb.SBCommandInterpreter_swiginit(self, _lldb.new_SBCommandInterpreter(rhs)) __swig_destroy__ = _lldb.delete_SBCommandInterpreter @staticmethod def GetArgumentTypeAsCString(arg_type): r"""GetArgumentTypeAsCString(lldb::CommandArgumentType const arg_type) -> char const *""" return _lldb.SBCommandInterpreter_GetArgumentTypeAsCString(arg_type) @staticmethod def GetArgumentDescriptionAsCString(arg_type): r"""GetArgumentDescriptionAsCString(lldb::CommandArgumentType const arg_type) -> char const *""" return _lldb.SBCommandInterpreter_GetArgumentDescriptionAsCString(arg_type) @staticmethod def EventIsCommandInterpreterEvent(event): r"""EventIsCommandInterpreterEvent(SBEvent event) -> bool""" return _lldb.SBCommandInterpreter_EventIsCommandInterpreterEvent(event) def IsValid(self): r"""IsValid(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_IsValid(self) def __nonzero__(self): return _lldb.SBCommandInterpreter___nonzero__(self) __bool__ = __nonzero__ def GetIOHandlerControlSequence(self, ch): r"""GetIOHandlerControlSequence(SBCommandInterpreter self, char ch) -> char const *""" return _lldb.SBCommandInterpreter_GetIOHandlerControlSequence(self, ch) def GetPromptOnQuit(self): r"""GetPromptOnQuit(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_GetPromptOnQuit(self) def SetPromptOnQuit(self, b): r"""SetPromptOnQuit(SBCommandInterpreter self, bool b)""" return _lldb.SBCommandInterpreter_SetPromptOnQuit(self, b) def AllowExitCodeOnQuit(self, b): r"""AllowExitCodeOnQuit(SBCommandInterpreter self, bool b)""" return _lldb.SBCommandInterpreter_AllowExitCodeOnQuit(self, b) def HasCustomQuitExitCode(self): r"""HasCustomQuitExitCode(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_HasCustomQuitExitCode(self) def GetQuitStatus(self): r"""GetQuitStatus(SBCommandInterpreter self) -> int""" return _lldb.SBCommandInterpreter_GetQuitStatus(self) def ResolveCommand(self, command_line, result): r"""ResolveCommand(SBCommandInterpreter self, char const * command_line, SBCommandReturnObject result)""" return _lldb.SBCommandInterpreter_ResolveCommand(self, command_line, result) def CommandExists(self, cmd): r"""CommandExists(SBCommandInterpreter self, char const * cmd) -> bool""" return _lldb.SBCommandInterpreter_CommandExists(self, cmd) def AliasExists(self, cmd): r"""AliasExists(SBCommandInterpreter self, char const * cmd) -> bool""" return _lldb.SBCommandInterpreter_AliasExists(self, cmd) def GetBroadcaster(self): r"""GetBroadcaster(SBCommandInterpreter self) -> SBBroadcaster""" return _lldb.SBCommandInterpreter_GetBroadcaster(self) @staticmethod def GetBroadcasterClass(): r"""GetBroadcasterClass() -> char const *""" return _lldb.SBCommandInterpreter_GetBroadcasterClass() def HasCommands(self): r"""HasCommands(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_HasCommands(self) def HasAliases(self): r"""HasAliases(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_HasAliases(self) def HasAliasOptions(self): r"""HasAliasOptions(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_HasAliasOptions(self) def GetProcess(self): r"""GetProcess(SBCommandInterpreter self) -> SBProcess""" return _lldb.SBCommandInterpreter_GetProcess(self) def GetDebugger(self): r"""GetDebugger(SBCommandInterpreter self) -> SBDebugger""" return _lldb.SBCommandInterpreter_GetDebugger(self) def SourceInitFileInHomeDirectory(self, result): r"""SourceInitFileInHomeDirectory(SBCommandInterpreter self, SBCommandReturnObject result)""" return _lldb.SBCommandInterpreter_SourceInitFileInHomeDirectory(self, result) def SourceInitFileInCurrentWorkingDirectory(self, result): r"""SourceInitFileInCurrentWorkingDirectory(SBCommandInterpreter self, SBCommandReturnObject result)""" return _lldb.SBCommandInterpreter_SourceInitFileInCurrentWorkingDirectory(self, result) def HandleCommand(self, *args): r""" HandleCommand(SBCommandInterpreter self, char const * command_line, SBCommandReturnObject result, bool add_to_history=False) -> lldb::ReturnStatus HandleCommand(SBCommandInterpreter self, char const * command_line, SBExecutionContext exe_ctx, SBCommandReturnObject result, bool add_to_history=False) -> lldb::ReturnStatus """ return _lldb.SBCommandInterpreter_HandleCommand(self, *args) def HandleCommandsFromFile(self, file, override_context, options, result): r"""HandleCommandsFromFile(SBCommandInterpreter self, SBFileSpec file, SBExecutionContext override_context, SBCommandInterpreterRunOptions options, SBCommandReturnObject result)""" return _lldb.SBCommandInterpreter_HandleCommandsFromFile(self, file, override_context, options, result) def HandleCompletion(self, current_line, cursor_pos, match_start_point, max_return_elements, matches): r"""HandleCompletion(SBCommandInterpreter self, char const * current_line, uint32_t cursor_pos, int match_start_point, int max_return_elements, SBStringList matches) -> int""" return _lldb.SBCommandInterpreter_HandleCompletion(self, current_line, cursor_pos, match_start_point, max_return_elements, matches) def HandleCompletionWithDescriptions(self, current_line, cursor_pos, match_start_point, max_return_elements, matches, descriptions): r"""HandleCompletionWithDescriptions(SBCommandInterpreter self, char const * current_line, uint32_t cursor_pos, int match_start_point, int max_return_elements, SBStringList matches, SBStringList descriptions) -> int""" return _lldb.SBCommandInterpreter_HandleCompletionWithDescriptions(self, current_line, cursor_pos, match_start_point, max_return_elements, matches, descriptions) def IsActive(self): r"""IsActive(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_IsActive(self) def WasInterrupted(self): r"""WasInterrupted(SBCommandInterpreter self) -> bool""" return _lldb.SBCommandInterpreter_WasInterrupted(self) # Register SBCommandInterpreter in _lldb: _lldb.SBCommandInterpreter_swigregister(SBCommandInterpreter) def SBCommandInterpreter_GetArgumentTypeAsCString(arg_type): r"""SBCommandInterpreter_GetArgumentTypeAsCString(lldb::CommandArgumentType const arg_type) -> char const *""" return _lldb.SBCommandInterpreter_GetArgumentTypeAsCString(arg_type) def SBCommandInterpreter_GetArgumentDescriptionAsCString(arg_type): r"""SBCommandInterpreter_GetArgumentDescriptionAsCString(lldb::CommandArgumentType const arg_type) -> char const *""" return _lldb.SBCommandInterpreter_GetArgumentDescriptionAsCString(arg_type) def SBCommandInterpreter_EventIsCommandInterpreterEvent(event): r"""SBCommandInterpreter_EventIsCommandInterpreterEvent(SBEvent event) -> bool""" return _lldb.SBCommandInterpreter_EventIsCommandInterpreterEvent(event) def SBCommandInterpreter_GetBroadcasterClass(): r"""SBCommandInterpreter_GetBroadcasterClass() -> char const *""" return _lldb.SBCommandInterpreter_GetBroadcasterClass() class SBCommandInterpreterRunOptions(object): r""" SBCommandInterpreterRunOptions controls how the RunCommandInterpreter runs the code it is fed. A default SBCommandInterpreterRunOptions object has: * StopOnContinue: false * StopOnError: false * StopOnCrash: false * EchoCommands: true * PrintResults: true * PrintErrors: true * AddToHistory: true """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r"""__init__(SBCommandInterpreterRunOptions self) -> SBCommandInterpreterRunOptions""" _lldb.SBCommandInterpreterRunOptions_swiginit(self, _lldb.new_SBCommandInterpreterRunOptions()) __swig_destroy__ = _lldb.delete_SBCommandInterpreterRunOptions def GetStopOnContinue(self): r"""GetStopOnContinue(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetStopOnContinue(self) def SetStopOnContinue(self, arg2): r"""SetStopOnContinue(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetStopOnContinue(self, arg2) def GetStopOnError(self): r"""GetStopOnError(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetStopOnError(self) def SetStopOnError(self, arg2): r"""SetStopOnError(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetStopOnError(self, arg2) def GetStopOnCrash(self): r"""GetStopOnCrash(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetStopOnCrash(self) def SetStopOnCrash(self, arg2): r"""SetStopOnCrash(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetStopOnCrash(self, arg2) def GetEchoCommands(self): r"""GetEchoCommands(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetEchoCommands(self) def SetEchoCommands(self, arg2): r"""SetEchoCommands(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetEchoCommands(self, arg2) def GetPrintResults(self): r"""GetPrintResults(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetPrintResults(self) def SetPrintResults(self, arg2): r"""SetPrintResults(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetPrintResults(self, arg2) def GetPrintErrors(self): r"""GetPrintErrors(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetPrintErrors(self) def SetPrintErrors(self, arg2): r"""SetPrintErrors(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetPrintErrors(self, arg2) def GetAddToHistory(self): r"""GetAddToHistory(SBCommandInterpreterRunOptions self) -> bool""" return _lldb.SBCommandInterpreterRunOptions_GetAddToHistory(self) def SetAddToHistory(self, arg2): r"""SetAddToHistory(SBCommandInterpreterRunOptions self, bool arg2)""" return _lldb.SBCommandInterpreterRunOptions_SetAddToHistory(self, arg2) # Register SBCommandInterpreterRunOptions in _lldb: _lldb.SBCommandInterpreterRunOptions_swigregister(SBCommandInterpreterRunOptions) class SBCommandReturnObject(object): r""" Represents a container which holds the result from command execution. It works with :py:class:`SBCommandInterpreter.HandleCommand()` to encapsulate the result of command execution. See :py:class:`SBCommandInterpreter` for example usage of SBCommandReturnObject. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBCommandReturnObject self) -> SBCommandReturnObject __init__(SBCommandReturnObject self, SBCommandReturnObject rhs) -> SBCommandReturnObject """ _lldb.SBCommandReturnObject_swiginit(self, _lldb.new_SBCommandReturnObject(*args)) __swig_destroy__ = _lldb.delete_SBCommandReturnObject def IsValid(self): r"""IsValid(SBCommandReturnObject self) -> bool""" return _lldb.SBCommandReturnObject_IsValid(self) def __nonzero__(self): return _lldb.SBCommandReturnObject___nonzero__(self) __bool__ = __nonzero__ def GetOutputSize(self): r"""GetOutputSize(SBCommandReturnObject self) -> size_t""" return _lldb.SBCommandReturnObject_GetOutputSize(self) def GetErrorSize(self): r"""GetErrorSize(SBCommandReturnObject self) -> size_t""" return _lldb.SBCommandReturnObject_GetErrorSize(self) def GetOutput(self, *args): r""" GetOutput(SBCommandReturnObject self) -> char const GetOutput(SBCommandReturnObject self, bool only_if_no_immediate) -> char const * """ return _lldb.SBCommandReturnObject_GetOutput(self, *args) def GetError(self, *args): r""" GetError(SBCommandReturnObject self) -> char const GetError(SBCommandReturnObject self, bool if_no_immediate) -> char const * """ return _lldb.SBCommandReturnObject_GetError(self, *args) def PutOutput(self, *args): r""" PutOutput(SBCommandReturnObject self, SBFile file) -> size_t PutOutput(SBCommandReturnObject self, lldb::FileSP BORROWED) -> size_t """ return _lldb.SBCommandReturnObject_PutOutput(self, *args) def PutError(self, *args): r""" PutError(SBCommandReturnObject self, SBFile file) -> size_t PutError(SBCommandReturnObject self, lldb::FileSP BORROWED) -> size_t """ return _lldb.SBCommandReturnObject_PutError(self, *args) def Clear(self): r"""Clear(SBCommandReturnObject self)""" return _lldb.SBCommandReturnObject_Clear(self) def SetStatus(self, status): r"""SetStatus(SBCommandReturnObject self, lldb::ReturnStatus status)""" return _lldb.SBCommandReturnObject_SetStatus(self, status) def SetError(self, *args): r""" SetError(SBCommandReturnObject self, SBError error, char const * fallback_error_cstr=None) SetError(SBCommandReturnObject self, char const * error_cstr) """ return _lldb.SBCommandReturnObject_SetError(self, *args) def GetStatus(self): r"""GetStatus(SBCommandReturnObject self) -> lldb::ReturnStatus""" return _lldb.SBCommandReturnObject_GetStatus(self) def Succeeded(self): r"""Succeeded(SBCommandReturnObject self) -> bool""" return _lldb.SBCommandReturnObject_Succeeded(self) def HasResult(self): r"""HasResult(SBCommandReturnObject self) -> bool""" return _lldb.SBCommandReturnObject_HasResult(self) def AppendMessage(self, message): r"""AppendMessage(SBCommandReturnObject self, char const * message)""" return _lldb.SBCommandReturnObject_AppendMessage(self, message) def AppendWarning(self, message): r"""AppendWarning(SBCommandReturnObject self, char const * message)""" return _lldb.SBCommandReturnObject_AppendWarning(self, message) def GetDescription(self, description): r"""GetDescription(SBCommandReturnObject self, SBStream description) -> bool""" return _lldb.SBCommandReturnObject_GetDescription(self, description) def __str__(self): r"""__str__(SBCommandReturnObject self) -> std::string""" return _lldb.SBCommandReturnObject___str__(self) def SetImmediateOutputFile(self, *args): r""" SetImmediateOutputFile(SBCommandReturnObject self, SBFile file) SetImmediateOutputFile(SBCommandReturnObject self, lldb::FileSP BORROWED) SetImmediateOutputFile(SBCommandReturnObject self, lldb::FileSP BORROWED, bool transfer_ownership) """ return _lldb.SBCommandReturnObject_SetImmediateOutputFile(self, *args) def SetImmediateErrorFile(self, *args): r""" SetImmediateErrorFile(SBCommandReturnObject self, SBFile file) SetImmediateErrorFile(SBCommandReturnObject self, lldb::FileSP BORROWED) SetImmediateErrorFile(SBCommandReturnObject self, lldb::FileSP BORROWED, bool transfer_ownership) """ return _lldb.SBCommandReturnObject_SetImmediateErrorFile(self, *args) def PutCString(self, string): r"""PutCString(SBCommandReturnObject self, char const * string)""" return _lldb.SBCommandReturnObject_PutCString(self, string) def Print(self, str): r"""Print(SBCommandReturnObject self, char const * str)""" return _lldb.SBCommandReturnObject_Print(self, str) def write(self, str): r"""write(SBCommandReturnObject self, char const * str)""" return _lldb.SBCommandReturnObject_write(self, str) def flush(self): r"""flush(SBCommandReturnObject self)""" return _lldb.SBCommandReturnObject_flush(self) # Register SBCommandReturnObject in _lldb: _lldb.SBCommandReturnObject_swigregister(SBCommandReturnObject) class SBCommunication(object): r"""Allows sending/receiving data.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr eBroadcastBitDisconnected = _lldb.SBCommunication_eBroadcastBitDisconnected eBroadcastBitReadThreadGotBytes = _lldb.SBCommunication_eBroadcastBitReadThreadGotBytes eBroadcastBitReadThreadDidExit = _lldb.SBCommunication_eBroadcastBitReadThreadDidExit eBroadcastBitReadThreadShouldExit = _lldb.SBCommunication_eBroadcastBitReadThreadShouldExit eBroadcastBitPacketAvailable = _lldb.SBCommunication_eBroadcastBitPacketAvailable eAllEventBits = _lldb.SBCommunication_eAllEventBits def __init__(self, *args): r""" __init__(SBCommunication self) -> SBCommunication __init__(SBCommunication self, char const * broadcaster_name) -> SBCommunication """ _lldb.SBCommunication_swiginit(self, _lldb.new_SBCommunication(*args)) __swig_destroy__ = _lldb.delete_SBCommunication def IsValid(self): r"""IsValid(SBCommunication self) -> bool""" return _lldb.SBCommunication_IsValid(self) def __nonzero__(self): return _lldb.SBCommunication___nonzero__(self) __bool__ = __nonzero__ def GetBroadcaster(self): r"""GetBroadcaster(SBCommunication self) -> SBBroadcaster""" return _lldb.SBCommunication_GetBroadcaster(self) @staticmethod def GetBroadcasterClass(): r"""GetBroadcasterClass() -> char const *""" return _lldb.SBCommunication_GetBroadcasterClass() def AdoptFileDesriptor(self, fd, owns_fd): r"""AdoptFileDesriptor(SBCommunication self, int fd, bool owns_fd) -> lldb::ConnectionStatus""" return _lldb.SBCommunication_AdoptFileDesriptor(self, fd, owns_fd) def Connect(self, url): r"""Connect(SBCommunication self, char const * url) -> lldb::ConnectionStatus""" return _lldb.SBCommunication_Connect(self, url) def Disconnect(self): r"""Disconnect(SBCommunication self) -> lldb::ConnectionStatus""" return _lldb.SBCommunication_Disconnect(self) def IsConnected(self): r"""IsConnected(SBCommunication self) -> bool""" return _lldb.SBCommunication_IsConnected(self) def GetCloseOnEOF(self): r"""GetCloseOnEOF(SBCommunication self) -> bool""" return _lldb.SBCommunication_GetCloseOnEOF(self) def SetCloseOnEOF(self, b): r"""SetCloseOnEOF(SBCommunication self, bool b)""" return _lldb.SBCommunication_SetCloseOnEOF(self, b) def Read(self, dst, dst_len, timeout_usec, status): r"""Read(SBCommunication self, void * dst, size_t dst_len, uint32_t timeout_usec, lldb::ConnectionStatus & status) -> size_t""" return _lldb.SBCommunication_Read(self, dst, dst_len, timeout_usec, status) def Write(self, src, src_len, status): r"""Write(SBCommunication self, void const * src, size_t src_len, lldb::ConnectionStatus & status) -> size_t""" return _lldb.SBCommunication_Write(self, src, src_len, status) def ReadThreadStart(self): r"""ReadThreadStart(SBCommunication self) -> bool""" return _lldb.SBCommunication_ReadThreadStart(self) def ReadThreadStop(self): r"""ReadThreadStop(SBCommunication self) -> bool""" return _lldb.SBCommunication_ReadThreadStop(self) def ReadThreadIsRunning(self): r"""ReadThreadIsRunning(SBCommunication self) -> bool""" return _lldb.SBCommunication_ReadThreadIsRunning(self) def SetReadThreadBytesReceivedCallback(self, callback, callback_baton): r"""SetReadThreadBytesReceivedCallback(SBCommunication self, lldb::SBCommunication::ReadThreadBytesReceived callback, void * callback_baton) -> bool""" return _lldb.SBCommunication_SetReadThreadBytesReceivedCallback(self, callback, callback_baton) # Register SBCommunication in _lldb: _lldb.SBCommunication_swigregister(SBCommunication) def SBCommunication_GetBroadcasterClass(): r"""SBCommunication_GetBroadcasterClass() -> char const *""" return _lldb.SBCommunication_GetBroadcasterClass() class SBCompileUnit(object): r""" Represents a compilation unit, or compiled source file. SBCompileUnit supports line entry iteration. For example,:: # Now get the SBSymbolContext from this frame. We want everything. :-) context = frame0.GetSymbolContext(lldb.eSymbolContextEverything) ... compileUnit = context.GetCompileUnit() for lineEntry in compileUnit: print('line entry: %s:%d' % (str(lineEntry.GetFileSpec()), lineEntry.GetLine())) print('start addr: %s' % str(lineEntry.GetStartAddress())) print('end addr: %s' % str(lineEntry.GetEndAddress())) produces: :: line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:20 start addr: a.out[0x100000d98] end addr: a.out[0x100000da3] line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:21 start addr: a.out[0x100000da3] end addr: a.out[0x100000da9] line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:22 start addr: a.out[0x100000da9] end addr: a.out[0x100000db6] line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:23 start addr: a.out[0x100000db6] end addr: a.out[0x100000dbc] ... See also :py:class:`SBSymbolContext` and :py:class:`SBLineEntry` """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBCompileUnit self) -> SBCompileUnit __init__(SBCompileUnit self, SBCompileUnit rhs) -> SBCompileUnit """ _lldb.SBCompileUnit_swiginit(self, _lldb.new_SBCompileUnit(*args)) __swig_destroy__ = _lldb.delete_SBCompileUnit def IsValid(self): r"""IsValid(SBCompileUnit self) -> bool""" return _lldb.SBCompileUnit_IsValid(self) def __nonzero__(self): return _lldb.SBCompileUnit___nonzero__(self) __bool__ = __nonzero__ def GetFileSpec(self): r"""GetFileSpec(SBCompileUnit self) -> SBFileSpec""" return _lldb.SBCompileUnit_GetFileSpec(self) def GetNumLineEntries(self): r"""GetNumLineEntries(SBCompileUnit self) -> uint32_t""" return _lldb.SBCompileUnit_GetNumLineEntries(self) def GetLineEntryAtIndex(self, idx): r"""GetLineEntryAtIndex(SBCompileUnit self, uint32_t idx) -> SBLineEntry""" return _lldb.SBCompileUnit_GetLineEntryAtIndex(self, idx) def FindLineEntryIndex(self, *args): r""" FindLineEntryIndex(SBCompileUnit self, uint32_t start_idx, uint32_t line, SBFileSpec inline_file_spec) -> uint32_t FindLineEntryIndex(SBCompileUnit self, uint32_t start_idx, uint32_t line, SBFileSpec inline_file_spec, bool exact) -> uint32_t """ return _lldb.SBCompileUnit_FindLineEntryIndex(self, *args) def GetSupportFileAtIndex(self, idx): r"""GetSupportFileAtIndex(SBCompileUnit self, uint32_t idx) -> SBFileSpec""" return _lldb.SBCompileUnit_GetSupportFileAtIndex(self, idx) def GetNumSupportFiles(self): r"""GetNumSupportFiles(SBCompileUnit self) -> uint32_t""" return _lldb.SBCompileUnit_GetNumSupportFiles(self) def FindSupportFileIndex(self, start_idx, sb_file, full): r"""FindSupportFileIndex(SBCompileUnit self, uint32_t start_idx, SBFileSpec sb_file, bool full) -> uint32_t""" return _lldb.SBCompileUnit_FindSupportFileIndex(self, start_idx, sb_file, full) def GetTypes(self, *args): r""" GetTypes(SBCompileUnit self, uint32_t type_mask=eTypeClassAny) -> SBTypeList Get all types matching type_mask from debug info in this compile unit. @param[in] type_mask A bitfield that consists of one or more bits logically OR'ed together from the lldb::TypeClass enumeration. This allows you to request only structure types, or only class, struct and union types. Passing in lldb::eTypeClassAny will return all types found in the debug information for this compile unit. @return A list of types in this compile unit that match type_mask """ return _lldb.SBCompileUnit_GetTypes(self, *args) def GetLanguage(self): r"""GetLanguage(SBCompileUnit self) -> lldb::LanguageType""" return _lldb.SBCompileUnit_GetLanguage(self) def GetDescription(self, description): r"""GetDescription(SBCompileUnit self, SBStream description) -> bool""" return _lldb.SBCompileUnit_GetDescription(self, description) def __eq__(self, rhs): r"""__eq__(SBCompileUnit self, SBCompileUnit rhs) -> bool""" return _lldb.SBCompileUnit___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBCompileUnit self, SBCompileUnit rhs) -> bool""" return _lldb.SBCompileUnit___ne__(self, rhs) def __str__(self): r"""__str__(SBCompileUnit self) -> std::string""" return _lldb.SBCompileUnit___str__(self) def __iter__(self): '''Iterate over all line entries in a lldb.SBCompileUnit object.''' return lldb_iter(self, 'GetNumLineEntries', 'GetLineEntryAtIndex') def __len__(self): '''Return the number of line entries in a lldb.SBCompileUnit object.''' return self.GetNumLineEntries() file = property(GetFileSpec, None, doc='''A read only property that returns the same result an lldb object that represents the source file (lldb.SBFileSpec) for the compile unit.''') num_line_entries = property(GetNumLineEntries, None, doc='''A read only property that returns the number of line entries in a compile unit as an integer.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBCompileUnit in _lldb: _lldb.SBCompileUnit_swigregister(SBCompileUnit) class SBData(object): r"""Represents a data buffer.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBData self) -> SBData __init__(SBData self, SBData rhs) -> SBData """ _lldb.SBData_swiginit(self, _lldb.new_SBData(*args)) __swig_destroy__ = _lldb.delete_SBData def GetAddressByteSize(self): r"""GetAddressByteSize(SBData self) -> uint8_t""" return _lldb.SBData_GetAddressByteSize(self) def SetAddressByteSize(self, addr_byte_size): r"""SetAddressByteSize(SBData self, uint8_t addr_byte_size)""" return _lldb.SBData_SetAddressByteSize(self, addr_byte_size) def Clear(self): r"""Clear(SBData self)""" return _lldb.SBData_Clear(self) def IsValid(self): r"""IsValid(SBData self) -> bool""" return _lldb.SBData_IsValid(self) def __nonzero__(self): return _lldb.SBData___nonzero__(self) __bool__ = __nonzero__ def GetByteSize(self): r"""GetByteSize(SBData self) -> size_t""" return _lldb.SBData_GetByteSize(self) def GetByteOrder(self): r"""GetByteOrder(SBData self) -> lldb::ByteOrder""" return _lldb.SBData_GetByteOrder(self) def SetByteOrder(self, endian): r"""SetByteOrder(SBData self, lldb::ByteOrder endian)""" return _lldb.SBData_SetByteOrder(self, endian) def GetFloat(self, error, offset): r"""GetFloat(SBData self, SBError error, lldb::offset_t offset) -> float""" return _lldb.SBData_GetFloat(self, error, offset) def GetDouble(self, error, offset): r"""GetDouble(SBData self, SBError error, lldb::offset_t offset) -> double""" return _lldb.SBData_GetDouble(self, error, offset) def GetLongDouble(self, error, offset): r"""GetLongDouble(SBData self, SBError error, lldb::offset_t offset) -> long double""" return _lldb.SBData_GetLongDouble(self, error, offset) def GetAddress(self, error, offset): r"""GetAddress(SBData self, SBError error, lldb::offset_t offset) -> lldb::addr_t""" return _lldb.SBData_GetAddress(self, error, offset) def GetUnsignedInt8(self, error, offset): r"""GetUnsignedInt8(SBData self, SBError error, lldb::offset_t offset) -> uint8_t""" return _lldb.SBData_GetUnsignedInt8(self, error, offset) def GetUnsignedInt16(self, error, offset): r"""GetUnsignedInt16(SBData self, SBError error, lldb::offset_t offset) -> uint16_t""" return _lldb.SBData_GetUnsignedInt16(self, error, offset) def GetUnsignedInt32(self, error, offset): r"""GetUnsignedInt32(SBData self, SBError error, lldb::offset_t offset) -> uint32_t""" return _lldb.SBData_GetUnsignedInt32(self, error, offset) def GetUnsignedInt64(self, error, offset): r"""GetUnsignedInt64(SBData self, SBError error, lldb::offset_t offset) -> uint64_t""" return _lldb.SBData_GetUnsignedInt64(self, error, offset) def GetSignedInt8(self, error, offset): r"""GetSignedInt8(SBData self, SBError error, lldb::offset_t offset) -> int8_t""" return _lldb.SBData_GetSignedInt8(self, error, offset) def GetSignedInt16(self, error, offset): r"""GetSignedInt16(SBData self, SBError error, lldb::offset_t offset) -> int16_t""" return _lldb.SBData_GetSignedInt16(self, error, offset) def GetSignedInt32(self, error, offset): r"""GetSignedInt32(SBData self, SBError error, lldb::offset_t offset) -> int32_t""" return _lldb.SBData_GetSignedInt32(self, error, offset) def GetSignedInt64(self, error, offset): r"""GetSignedInt64(SBData self, SBError error, lldb::offset_t offset) -> int64_t""" return _lldb.SBData_GetSignedInt64(self, error, offset) def GetString(self, error, offset): r"""GetString(SBData self, SBError error, lldb::offset_t offset) -> char const *""" return _lldb.SBData_GetString(self, error, offset) def GetDescription(self, description, base_addr): r"""GetDescription(SBData self, SBStream description, lldb::addr_t base_addr) -> bool""" return _lldb.SBData_GetDescription(self, description, base_addr) def ReadRawData(self, error, offset, buf): r"""ReadRawData(SBData self, SBError error, lldb::offset_t offset, void * buf) -> size_t""" return _lldb.SBData_ReadRawData(self, error, offset, buf) def SetData(self, error, buf, endian, addr_size): r"""SetData(SBData self, SBError error, void const * buf, lldb::ByteOrder endian, uint8_t addr_size)""" return _lldb.SBData_SetData(self, error, buf, endian, addr_size) def Append(self, rhs): r"""Append(SBData self, SBData rhs) -> bool""" return _lldb.SBData_Append(self, rhs) @staticmethod def CreateDataFromCString(endian, addr_byte_size, data): r"""CreateDataFromCString(lldb::ByteOrder endian, uint32_t addr_byte_size, char const * data) -> SBData""" return _lldb.SBData_CreateDataFromCString(endian, addr_byte_size, data) @staticmethod def CreateDataFromUInt64Array(endian, addr_byte_size, array): r"""CreateDataFromUInt64Array(lldb::ByteOrder endian, uint32_t addr_byte_size, uint64_t * array) -> SBData""" return _lldb.SBData_CreateDataFromUInt64Array(endian, addr_byte_size, array) @staticmethod def CreateDataFromUInt32Array(endian, addr_byte_size, array): r"""CreateDataFromUInt32Array(lldb::ByteOrder endian, uint32_t addr_byte_size, uint32_t * array) -> SBData""" return _lldb.SBData_CreateDataFromUInt32Array(endian, addr_byte_size, array) @staticmethod def CreateDataFromSInt64Array(endian, addr_byte_size, array): r"""CreateDataFromSInt64Array(lldb::ByteOrder endian, uint32_t addr_byte_size, int64_t * array) -> SBData""" return _lldb.SBData_CreateDataFromSInt64Array(endian, addr_byte_size, array) @staticmethod def CreateDataFromSInt32Array(endian, addr_byte_size, array): r"""CreateDataFromSInt32Array(lldb::ByteOrder endian, uint32_t addr_byte_size, int32_t * array) -> SBData""" return _lldb.SBData_CreateDataFromSInt32Array(endian, addr_byte_size, array) @staticmethod def CreateDataFromDoubleArray(endian, addr_byte_size, array): r"""CreateDataFromDoubleArray(lldb::ByteOrder endian, uint32_t addr_byte_size, double * array) -> SBData""" return _lldb.SBData_CreateDataFromDoubleArray(endian, addr_byte_size, array) def SetDataFromCString(self, data): r"""SetDataFromCString(SBData self, char const * data) -> bool""" return _lldb.SBData_SetDataFromCString(self, data) def SetDataFromUInt64Array(self, array): r"""SetDataFromUInt64Array(SBData self, uint64_t * array) -> bool""" return _lldb.SBData_SetDataFromUInt64Array(self, array) def SetDataFromUInt32Array(self, array): r"""SetDataFromUInt32Array(SBData self, uint32_t * array) -> bool""" return _lldb.SBData_SetDataFromUInt32Array(self, array) def SetDataFromSInt64Array(self, array): r"""SetDataFromSInt64Array(SBData self, int64_t * array) -> bool""" return _lldb.SBData_SetDataFromSInt64Array(self, array) def SetDataFromSInt32Array(self, array): r"""SetDataFromSInt32Array(SBData self, int32_t * array) -> bool""" return _lldb.SBData_SetDataFromSInt32Array(self, array) def SetDataFromDoubleArray(self, array): r"""SetDataFromDoubleArray(SBData self, double * array) -> bool""" return _lldb.SBData_SetDataFromDoubleArray(self, array) def __str__(self): r"""__str__(SBData self) -> std::string""" return _lldb.SBData___str__(self) class read_data_helper: def __init__(self, sbdata, readerfunc, item_size): self.sbdata = sbdata self.readerfunc = readerfunc self.item_size = item_size def __getitem__(self,key): if isinstance(key,slice): list = [] for x in range(*key.indices(self.__len__())): list.append(self.__getitem__(x)) return list if not (isinstance(key,six.integer_types)): raise TypeError('must be int') key = key * self.item_size # SBData uses byte-based indexes, but we want to use itemsize-based indexes here error = SBError() my_data = self.readerfunc(self.sbdata,error,key) if error.Fail(): raise IndexError(error.GetCString()) else: return my_data def __len__(self): return int(self.sbdata.GetByteSize()/self.item_size) def all(self): return self[0:len(self)] @classmethod def CreateDataFromInt (cls, value, size = None, target = None, ptr_size = None, endian = None): import sys lldbmodule = sys.modules[cls.__module__] lldbdict = lldbmodule.__dict__ if 'target' in lldbdict: lldbtarget = lldbdict['target'] else: lldbtarget = None if target == None and lldbtarget != None and lldbtarget.IsValid(): target = lldbtarget if ptr_size == None: if target and target.IsValid(): ptr_size = target.addr_size else: ptr_size = 8 if endian == None: if target and target.IsValid(): endian = target.byte_order else: endian = lldbdict['eByteOrderLittle'] if size == None: if value > 2147483647: size = 8 elif value < -2147483648: size = 8 elif value > 4294967295: size = 8 else: size = 4 if size == 4: if value < 0: return SBData().CreateDataFromSInt32Array(endian, ptr_size, [value]) return SBData().CreateDataFromUInt32Array(endian, ptr_size, [value]) if size == 8: if value < 0: return SBData().CreateDataFromSInt64Array(endian, ptr_size, [value]) return SBData().CreateDataFromUInt64Array(endian, ptr_size, [value]) return None def _make_helper(self, sbdata, getfunc, itemsize): return self.read_data_helper(sbdata, getfunc, itemsize) def _make_helper_uint8(self): return self._make_helper(self, SBData.GetUnsignedInt8, 1) def _make_helper_uint16(self): return self._make_helper(self, SBData.GetUnsignedInt16, 2) def _make_helper_uint32(self): return self._make_helper(self, SBData.GetUnsignedInt32, 4) def _make_helper_uint64(self): return self._make_helper(self, SBData.GetUnsignedInt64, 8) def _make_helper_sint8(self): return self._make_helper(self, SBData.GetSignedInt8, 1) def _make_helper_sint16(self): return self._make_helper(self, SBData.GetSignedInt16, 2) def _make_helper_sint32(self): return self._make_helper(self, SBData.GetSignedInt32, 4) def _make_helper_sint64(self): return self._make_helper(self, SBData.GetSignedInt64, 8) def _make_helper_float(self): return self._make_helper(self, SBData.GetFloat, 4) def _make_helper_double(self): return self._make_helper(self, SBData.GetDouble, 8) def _read_all_uint8(self): return self._make_helper_uint8().all() def _read_all_uint16(self): return self._make_helper_uint16().all() def _read_all_uint32(self): return self._make_helper_uint32().all() def _read_all_uint64(self): return self._make_helper_uint64().all() def _read_all_sint8(self): return self._make_helper_sint8().all() def _read_all_sint16(self): return self._make_helper_sint16().all() def _read_all_sint32(self): return self._make_helper_sint32().all() def _read_all_sint64(self): return self._make_helper_sint64().all() def _read_all_float(self): return self._make_helper_float().all() def _read_all_double(self): return self._make_helper_double().all() uint8 = property(_make_helper_uint8, None, doc='''A read only property that returns an array-like object out of which you can read uint8 values.''') uint16 = property(_make_helper_uint16, None, doc='''A read only property that returns an array-like object out of which you can read uint16 values.''') uint32 = property(_make_helper_uint32, None, doc='''A read only property that returns an array-like object out of which you can read uint32 values.''') uint64 = property(_make_helper_uint64, None, doc='''A read only property that returns an array-like object out of which you can read uint64 values.''') sint8 = property(_make_helper_sint8, None, doc='''A read only property that returns an array-like object out of which you can read sint8 values.''') sint16 = property(_make_helper_sint16, None, doc='''A read only property that returns an array-like object out of which you can read sint16 values.''') sint32 = property(_make_helper_sint32, None, doc='''A read only property that returns an array-like object out of which you can read sint32 values.''') sint64 = property(_make_helper_sint64, None, doc='''A read only property that returns an array-like object out of which you can read sint64 values.''') float = property(_make_helper_float, None, doc='''A read only property that returns an array-like object out of which you can read float values.''') double = property(_make_helper_double, None, doc='''A read only property that returns an array-like object out of which you can read double values.''') uint8s = property(_read_all_uint8, None, doc='''A read only property that returns an array with all the contents of this SBData represented as uint8 values.''') uint16s = property(_read_all_uint16, None, doc='''A read only property that returns an array with all the contents of this SBData represented as uint16 values.''') uint32s = property(_read_all_uint32, None, doc='''A read only property that returns an array with all the contents of this SBData represented as uint32 values.''') uint64s = property(_read_all_uint64, None, doc='''A read only property that returns an array with all the contents of this SBData represented as uint64 values.''') sint8s = property(_read_all_sint8, None, doc='''A read only property that returns an array with all the contents of this SBData represented as sint8 values.''') sint16s = property(_read_all_sint16, None, doc='''A read only property that returns an array with all the contents of this SBData represented as sint16 values.''') sint32s = property(_read_all_sint32, None, doc='''A read only property that returns an array with all the contents of this SBData represented as sint32 values.''') sint64s = property(_read_all_sint64, None, doc='''A read only property that returns an array with all the contents of this SBData represented as sint64 values.''') floats = property(_read_all_float, None, doc='''A read only property that returns an array with all the contents of this SBData represented as float values.''') doubles = property(_read_all_double, None, doc='''A read only property that returns an array with all the contents of this SBData represented as double values.''') byte_order = property(GetByteOrder, SetByteOrder, doc='''A read/write property getting and setting the endianness of this SBData (data.byte_order = lldb.eByteOrderLittle).''') size = property(GetByteSize, None, doc='''A read only property that returns the size the same result as GetByteSize().''') # Register SBData in _lldb: _lldb.SBData_swigregister(SBData) def SBData_CreateDataFromCString(endian, addr_byte_size, data): r"""SBData_CreateDataFromCString(lldb::ByteOrder endian, uint32_t addr_byte_size, char const * data) -> SBData""" return _lldb.SBData_CreateDataFromCString(endian, addr_byte_size, data) def SBData_CreateDataFromUInt64Array(endian, addr_byte_size, array): r"""SBData_CreateDataFromUInt64Array(lldb::ByteOrder endian, uint32_t addr_byte_size, uint64_t * array) -> SBData""" return _lldb.SBData_CreateDataFromUInt64Array(endian, addr_byte_size, array) def SBData_CreateDataFromUInt32Array(endian, addr_byte_size, array): r"""SBData_CreateDataFromUInt32Array(lldb::ByteOrder endian, uint32_t addr_byte_size, uint32_t * array) -> SBData""" return _lldb.SBData_CreateDataFromUInt32Array(endian, addr_byte_size, array) def SBData_CreateDataFromSInt64Array(endian, addr_byte_size, array): r"""SBData_CreateDataFromSInt64Array(lldb::ByteOrder endian, uint32_t addr_byte_size, int64_t * array) -> SBData""" return _lldb.SBData_CreateDataFromSInt64Array(endian, addr_byte_size, array) def SBData_CreateDataFromSInt32Array(endian, addr_byte_size, array): r"""SBData_CreateDataFromSInt32Array(lldb::ByteOrder endian, uint32_t addr_byte_size, int32_t * array) -> SBData""" return _lldb.SBData_CreateDataFromSInt32Array(endian, addr_byte_size, array) def SBData_CreateDataFromDoubleArray(endian, addr_byte_size, array): r"""SBData_CreateDataFromDoubleArray(lldb::ByteOrder endian, uint32_t addr_byte_size, double * array) -> SBData""" return _lldb.SBData_CreateDataFromDoubleArray(endian, addr_byte_size, array) class SBDebugger(object): r""" SBDebugger is the primordial object that creates SBTargets and provides access to them. It also manages the overall debugging experiences. For example (from example/disasm.py),:: import lldb import os import sys def disassemble_instructions (insts): for i in insts: print i ... # Create a new debugger instance debugger = lldb.SBDebugger.Create() # When we step or continue, don't return from the function until the process # stops. We do this by setting the async mode to false. debugger.SetAsync (False) # Create a target from a file and arch print('Creating a target for '%s'' % exe) target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT) if target: # If the target is valid set a breakpoint at main main_bp = target.BreakpointCreateByName (fname, target.GetExecutable().GetFilename()); print main_bp # Launch the process. Since we specified synchronous mode, we won't return # from this function until we hit the breakpoint at main process = target.LaunchSimple (None, None, os.getcwd()) # Make sure the launch went ok if process: # Print some simple process info state = process.GetState () print process if state == lldb.eStateStopped: # Get the first thread thread = process.GetThreadAtIndex (0) if thread: # Print some simple thread info print thread # Get the first frame frame = thread.GetFrameAtIndex (0) if frame: # Print some simple frame info print frame function = frame.GetFunction() # See if we have debug info (a function) if function: # We do have a function, print some info for the function print function # Now get all instructions for this function and print them insts = function.GetInstructions(target) disassemble_instructions (insts) else: # See if we have a symbol in the symbol table for where we stopped symbol = frame.GetSymbol(); if symbol: # We do have a symbol, print some info for the symbol print symbol # Now get all instructions for this symbol and print them insts = symbol.GetInstructions(target) disassemble_instructions (insts) registerList = frame.GetRegisters() print('Frame registers (size of register set = %d):' % registerList.GetSize()) for value in registerList: #print value print('%s (number of children = %d):' % (value.GetName(), value.GetNumChildren())) for child in value: print('Name: ', child.GetName(), ' Value: ', child.GetValue()) print('Hit the breakpoint at main, enter to continue and wait for program to exit or 'Ctrl-D'/'quit' to terminate the program') next = sys.stdin.readline() if not next or next.rstrip('\n') == 'quit': print('Terminating the inferior process...') process.Kill() else: # Now continue to the program exit process.Continue() # When we return from the above function we will hopefully be at the # program exit. Print out some process info print process elif state == lldb.eStateExited: print('Didn't hit the breakpoint at main, program has exited...') else: print('Unexpected process state: %s, killing process...' % debugger.StateAsCString (state)) process.Kill() Sometimes you need to create an empty target that will get filled in later. The most common use for this is to attach to a process by name or pid where you don't know the executable up front. The most convenient way to do this is: :: target = debugger.CreateTarget('') error = lldb.SBError() process = target.AttachToProcessWithName(debugger.GetListener(), 'PROCESS_NAME', False, error) or the equivalent arguments for :py:class:`SBTarget.AttachToProcessWithID` . """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr @staticmethod def Initialize(): r"""Initialize()""" return _lldb.SBDebugger_Initialize() @staticmethod def InitializeWithErrorHandling(): r"""InitializeWithErrorHandling() -> SBError""" return _lldb.SBDebugger_InitializeWithErrorHandling() @staticmethod def Terminate(): r"""Terminate()""" return _lldb.SBDebugger_Terminate() @staticmethod def Create(*args): r""" Create() -> SBDebugger Create(bool source_init_files) -> SBDebugger Create(bool source_init_files, lldb::LogOutputCallback log_callback) -> SBDebugger """ return _lldb.SBDebugger_Create(*args) @staticmethod def Destroy(debugger): r"""Destroy(SBDebugger debugger)""" return _lldb.SBDebugger_Destroy(debugger) @staticmethod def MemoryPressureDetected(): r"""MemoryPressureDetected()""" return _lldb.SBDebugger_MemoryPressureDetected() def __init__(self, *args): r""" __init__(SBDebugger self) -> SBDebugger __init__(SBDebugger self, SBDebugger rhs) -> SBDebugger """ _lldb.SBDebugger_swiginit(self, _lldb.new_SBDebugger(*args)) __swig_destroy__ = _lldb.delete_SBDebugger def IsValid(self): r"""IsValid(SBDebugger self) -> bool""" return _lldb.SBDebugger_IsValid(self) def __nonzero__(self): return _lldb.SBDebugger___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBDebugger self)""" return _lldb.SBDebugger_Clear(self) def SetAsync(self, b): r"""SetAsync(SBDebugger self, bool b)""" return _lldb.SBDebugger_SetAsync(self, b) def GetAsync(self): r"""GetAsync(SBDebugger self) -> bool""" return _lldb.SBDebugger_GetAsync(self) def SkipLLDBInitFiles(self, b): r"""SkipLLDBInitFiles(SBDebugger self, bool b)""" return _lldb.SBDebugger_SkipLLDBInitFiles(self, b) def SetOutputFileHandle(self, file, transfer_ownership): "DEPRECATED, use SetOutputFile" if file is None: import sys file = sys.stdout self.SetOutputFile(SBFile.Create(file, borrow=True)) def SetInputFileHandle(self, file, transfer_ownership): "DEPRECATED, use SetInputFile" if file is None: import sys file = sys.stdin self.SetInputFile(SBFile.Create(file, borrow=True)) def SetErrorFileHandle(self, file, transfer_ownership): "DEPRECATED, use SetErrorFile" if file is None: import sys file = sys.stderr self.SetErrorFile(SBFile.Create(file, borrow=True)) def GetInputFileHandle(self): r"""GetInputFileHandle(SBDebugger self) -> lldb::FileSP""" return _lldb.SBDebugger_GetInputFileHandle(self) def GetOutputFileHandle(self): r"""GetOutputFileHandle(SBDebugger self) -> lldb::FileSP""" return _lldb.SBDebugger_GetOutputFileHandle(self) def GetErrorFileHandle(self): r"""GetErrorFileHandle(SBDebugger self) -> lldb::FileSP""" return _lldb.SBDebugger_GetErrorFileHandle(self) def SetInputFile(self, *args): r""" SetInputFile(SBDebugger self, SBFile file) -> SBError SetInputFile(SBDebugger self, lldb::FileSP file) -> SBError """ return _lldb.SBDebugger_SetInputFile(self, *args) def SetOutputFile(self, *args): r""" SetOutputFile(SBDebugger self, SBFile file) -> SBError SetOutputFile(SBDebugger self, lldb::FileSP file) -> SBError """ return _lldb.SBDebugger_SetOutputFile(self, *args) def SetErrorFile(self, *args): r""" SetErrorFile(SBDebugger self, SBFile file) -> SBError SetErrorFile(SBDebugger self, lldb::FileSP file) -> SBError """ return _lldb.SBDebugger_SetErrorFile(self, *args) def GetInputFile(self): r"""GetInputFile(SBDebugger self) -> SBFile""" return _lldb.SBDebugger_GetInputFile(self) def GetOutputFile(self): r"""GetOutputFile(SBDebugger self) -> SBFile""" return _lldb.SBDebugger_GetOutputFile(self) def GetErrorFile(self): r"""GetErrorFile(SBDebugger self) -> SBFile""" return _lldb.SBDebugger_GetErrorFile(self) def GetCommandInterpreter(self): r"""GetCommandInterpreter(SBDebugger self) -> SBCommandInterpreter""" return _lldb.SBDebugger_GetCommandInterpreter(self) def HandleCommand(self, command): r"""HandleCommand(SBDebugger self, char const * command)""" return _lldb.SBDebugger_HandleCommand(self, command) def GetListener(self): r"""GetListener(SBDebugger self) -> SBListener""" return _lldb.SBDebugger_GetListener(self) def HandleProcessEvent(self, *args): r""" HandleProcessEvent(SBDebugger self, SBProcess process, SBEvent event, SBFile out, SBFile err) HandleProcessEvent(SBDebugger self, SBProcess process, SBEvent event, lldb::FileSP arg4, lldb::FileSP arg5) """ return _lldb.SBDebugger_HandleProcessEvent(self, *args) def CreateTargetWithFileAndTargetTriple(self, filename, target_triple): r"""CreateTargetWithFileAndTargetTriple(SBDebugger self, char const * filename, char const * target_triple) -> SBTarget""" return _lldb.SBDebugger_CreateTargetWithFileAndTargetTriple(self, filename, target_triple) def CreateTargetWithFileAndArch(self, filename, archname): r"""CreateTargetWithFileAndArch(SBDebugger self, char const * filename, char const * archname) -> SBTarget""" return _lldb.SBDebugger_CreateTargetWithFileAndArch(self, filename, archname) def CreateTarget(self, *args): r""" CreateTarget(SBDebugger self, char const * filename, char const * target_triple, char const * platform_name, bool add_dependent_modules, SBError sb_error) -> SBTarget CreateTarget(SBDebugger self, char const * filename) -> SBTarget """ return _lldb.SBDebugger_CreateTarget(self, *args) def GetDummyTarget(self): r""" GetDummyTarget(SBDebugger self) -> SBTarget The dummy target holds breakpoints and breakpoint names that will prime newly created targets. """ return _lldb.SBDebugger_GetDummyTarget(self) def DeleteTarget(self, target): r""" DeleteTarget(SBDebugger self, SBTarget target) -> bool Return true if target is deleted from the target list of the debugger. """ return _lldb.SBDebugger_DeleteTarget(self, target) def GetTargetAtIndex(self, idx): r"""GetTargetAtIndex(SBDebugger self, uint32_t idx) -> SBTarget""" return _lldb.SBDebugger_GetTargetAtIndex(self, idx) def GetIndexOfTarget(self, target): r"""GetIndexOfTarget(SBDebugger self, SBTarget target) -> uint32_t""" return _lldb.SBDebugger_GetIndexOfTarget(self, target) def FindTargetWithProcessID(self, pid): r"""FindTargetWithProcessID(SBDebugger self, lldb::pid_t pid) -> SBTarget""" return _lldb.SBDebugger_FindTargetWithProcessID(self, pid) def FindTargetWithFileAndArch(self, filename, arch): r"""FindTargetWithFileAndArch(SBDebugger self, char const * filename, char const * arch) -> SBTarget""" return _lldb.SBDebugger_FindTargetWithFileAndArch(self, filename, arch) def GetNumTargets(self): r"""GetNumTargets(SBDebugger self) -> uint32_t""" return _lldb.SBDebugger_GetNumTargets(self) def GetSelectedTarget(self): r"""GetSelectedTarget(SBDebugger self) -> SBTarget""" return _lldb.SBDebugger_GetSelectedTarget(self) def SetSelectedTarget(self, target): r"""SetSelectedTarget(SBDebugger self, SBTarget target)""" return _lldb.SBDebugger_SetSelectedTarget(self, target) def GetSelectedPlatform(self): r"""GetSelectedPlatform(SBDebugger self) -> SBPlatform""" return _lldb.SBDebugger_GetSelectedPlatform(self) def SetSelectedPlatform(self, platform): r"""SetSelectedPlatform(SBDebugger self, SBPlatform platform)""" return _lldb.SBDebugger_SetSelectedPlatform(self, platform) def GetNumPlatforms(self): r""" GetNumPlatforms(SBDebugger self) -> uint32_t Get the number of currently active platforms. """ return _lldb.SBDebugger_GetNumPlatforms(self) def GetPlatformAtIndex(self, idx): r""" GetPlatformAtIndex(SBDebugger self, uint32_t idx) -> SBPlatform Get one of the currently active platforms. """ return _lldb.SBDebugger_GetPlatformAtIndex(self, idx) def GetNumAvailablePlatforms(self): r""" GetNumAvailablePlatforms(SBDebugger self) -> uint32_t Get the number of available platforms. """ return _lldb.SBDebugger_GetNumAvailablePlatforms(self) def GetAvailablePlatformInfoAtIndex(self, idx): r""" GetAvailablePlatformInfoAtIndex(SBDebugger self, uint32_t idx) -> SBStructuredData Get the name and description of one of the available platforms. @param idx Zero-based index of the platform for which info should be retrieved, must be less than the value returned by GetNumAvailablePlatforms(). """ return _lldb.SBDebugger_GetAvailablePlatformInfoAtIndex(self, idx) def GetSourceManager(self): r"""GetSourceManager(SBDebugger self) -> SBSourceManager""" return _lldb.SBDebugger_GetSourceManager(self) def SetCurrentPlatform(self, platform_name): r"""SetCurrentPlatform(SBDebugger self, char const * platform_name) -> SBError""" return _lldb.SBDebugger_SetCurrentPlatform(self, platform_name) def SetCurrentPlatformSDKRoot(self, sysroot): r"""SetCurrentPlatformSDKRoot(SBDebugger self, char const * sysroot) -> bool""" return _lldb.SBDebugger_SetCurrentPlatformSDKRoot(self, sysroot) def SetUseExternalEditor(self, input): r"""SetUseExternalEditor(SBDebugger self, bool input) -> bool""" return _lldb.SBDebugger_SetUseExternalEditor(self, input) def GetUseExternalEditor(self): r"""GetUseExternalEditor(SBDebugger self) -> bool""" return _lldb.SBDebugger_GetUseExternalEditor(self) def SetUseColor(self, use_color): r"""SetUseColor(SBDebugger self, bool use_color) -> bool""" return _lldb.SBDebugger_SetUseColor(self, use_color) def GetUseColor(self): r"""GetUseColor(SBDebugger self) -> bool""" return _lldb.SBDebugger_GetUseColor(self) @staticmethod def GetDefaultArchitecture(arch_name, arch_name_len): r"""GetDefaultArchitecture(char * arch_name, size_t arch_name_len) -> bool""" return _lldb.SBDebugger_GetDefaultArchitecture(arch_name, arch_name_len) @staticmethod def SetDefaultArchitecture(arch_name): r"""SetDefaultArchitecture(char const * arch_name) -> bool""" return _lldb.SBDebugger_SetDefaultArchitecture(arch_name) def GetScriptingLanguage(self, script_language_name): r"""GetScriptingLanguage(SBDebugger self, char const * script_language_name) -> lldb::ScriptLanguage""" return _lldb.SBDebugger_GetScriptingLanguage(self, script_language_name) @staticmethod def GetVersionString(): r"""GetVersionString() -> char const *""" return _lldb.SBDebugger_GetVersionString() @staticmethod def StateAsCString(state): r"""StateAsCString(lldb::StateType state) -> char const *""" return _lldb.SBDebugger_StateAsCString(state) @staticmethod def GetBuildConfiguration(): r"""GetBuildConfiguration() -> SBStructuredData""" return _lldb.SBDebugger_GetBuildConfiguration() @staticmethod def StateIsRunningState(state): r"""StateIsRunningState(lldb::StateType state) -> bool""" return _lldb.SBDebugger_StateIsRunningState(state) @staticmethod def StateIsStoppedState(state): r"""StateIsStoppedState(lldb::StateType state) -> bool""" return _lldb.SBDebugger_StateIsStoppedState(state) def EnableLog(self, channel, types): r"""EnableLog(SBDebugger self, char const * channel, char const ** types) -> bool""" return _lldb.SBDebugger_EnableLog(self, channel, types) def SetLoggingCallback(self, log_callback): r"""SetLoggingCallback(SBDebugger self, lldb::LogOutputCallback log_callback)""" return _lldb.SBDebugger_SetLoggingCallback(self, log_callback) def DispatchInput(self, data): r"""DispatchInput(SBDebugger self, void const * data)""" return _lldb.SBDebugger_DispatchInput(self, data) def DispatchInputInterrupt(self): r"""DispatchInputInterrupt(SBDebugger self)""" return _lldb.SBDebugger_DispatchInputInterrupt(self) def DispatchInputEndOfFile(self): r"""DispatchInputEndOfFile(SBDebugger self)""" return _lldb.SBDebugger_DispatchInputEndOfFile(self) def GetInstanceName(self): r"""GetInstanceName(SBDebugger self) -> char const *""" return _lldb.SBDebugger_GetInstanceName(self) @staticmethod def FindDebuggerWithID(id): r"""FindDebuggerWithID(int id) -> SBDebugger""" return _lldb.SBDebugger_FindDebuggerWithID(id) @staticmethod def SetInternalVariable(var_name, value, debugger_instance_name): r"""SetInternalVariable(char const * var_name, char const * value, char const * debugger_instance_name) -> SBError""" return _lldb.SBDebugger_SetInternalVariable(var_name, value, debugger_instance_name) @staticmethod def GetInternalVariableValue(var_name, debugger_instance_name): r"""GetInternalVariableValue(char const * var_name, char const * debugger_instance_name) -> SBStringList""" return _lldb.SBDebugger_GetInternalVariableValue(var_name, debugger_instance_name) def GetDescription(self, description): r"""GetDescription(SBDebugger self, SBStream description) -> bool""" return _lldb.SBDebugger_GetDescription(self, description) def GetTerminalWidth(self): r"""GetTerminalWidth(SBDebugger self) -> uint32_t""" return _lldb.SBDebugger_GetTerminalWidth(self) def SetTerminalWidth(self, term_width): r"""SetTerminalWidth(SBDebugger self, uint32_t term_width)""" return _lldb.SBDebugger_SetTerminalWidth(self, term_width) def GetID(self): r"""GetID(SBDebugger self) -> lldb::user_id_t""" return _lldb.SBDebugger_GetID(self) def GetPrompt(self): r"""GetPrompt(SBDebugger self) -> char const *""" return _lldb.SBDebugger_GetPrompt(self) def SetPrompt(self, prompt): r"""SetPrompt(SBDebugger self, char const * prompt)""" return _lldb.SBDebugger_SetPrompt(self, prompt) def GetReproducerPath(self): r"""GetReproducerPath(SBDebugger self) -> char const *""" return _lldb.SBDebugger_GetReproducerPath(self) def GetScriptLanguage(self): r"""GetScriptLanguage(SBDebugger self) -> lldb::ScriptLanguage""" return _lldb.SBDebugger_GetScriptLanguage(self) def SetScriptLanguage(self, script_lang): r"""SetScriptLanguage(SBDebugger self, lldb::ScriptLanguage script_lang)""" return _lldb.SBDebugger_SetScriptLanguage(self, script_lang) def GetCloseInputOnEOF(self): r"""GetCloseInputOnEOF(SBDebugger self) -> bool""" return _lldb.SBDebugger_GetCloseInputOnEOF(self) def SetCloseInputOnEOF(self, b): r"""SetCloseInputOnEOF(SBDebugger self, bool b)""" return _lldb.SBDebugger_SetCloseInputOnEOF(self, b) def GetCategory(self, *args): r""" GetCategory(SBDebugger self, char const * category_name) -> SBTypeCategory GetCategory(SBDebugger self, lldb::LanguageType lang_type) -> SBTypeCategory """ return _lldb.SBDebugger_GetCategory(self, *args) def CreateCategory(self, category_name): r"""CreateCategory(SBDebugger self, char const * category_name) -> SBTypeCategory""" return _lldb.SBDebugger_CreateCategory(self, category_name) def DeleteCategory(self, category_name): r"""DeleteCategory(SBDebugger self, char const * category_name) -> bool""" return _lldb.SBDebugger_DeleteCategory(self, category_name) def GetNumCategories(self): r"""GetNumCategories(SBDebugger self) -> uint32_t""" return _lldb.SBDebugger_GetNumCategories(self) def GetCategoryAtIndex(self, arg2): r"""GetCategoryAtIndex(SBDebugger self, uint32_t arg2) -> SBTypeCategory""" return _lldb.SBDebugger_GetCategoryAtIndex(self, arg2) def GetDefaultCategory(self): r"""GetDefaultCategory(SBDebugger self) -> SBTypeCategory""" return _lldb.SBDebugger_GetDefaultCategory(self) def GetFormatForType(self, arg2): r"""GetFormatForType(SBDebugger self, SBTypeNameSpecifier arg2) -> SBTypeFormat""" return _lldb.SBDebugger_GetFormatForType(self, arg2) def GetSummaryForType(self, arg2): r"""GetSummaryForType(SBDebugger self, SBTypeNameSpecifier arg2) -> SBTypeSummary""" return _lldb.SBDebugger_GetSummaryForType(self, arg2) def GetFilterForType(self, arg2): r"""GetFilterForType(SBDebugger self, SBTypeNameSpecifier arg2) -> SBTypeFilter""" return _lldb.SBDebugger_GetFilterForType(self, arg2) def GetSyntheticForType(self, arg2): r"""GetSyntheticForType(SBDebugger self, SBTypeNameSpecifier arg2) -> SBTypeSynthetic""" return _lldb.SBDebugger_GetSyntheticForType(self, arg2) def __str__(self): r"""__str__(SBDebugger self) -> std::string""" return _lldb.SBDebugger___str__(self) def RunCommandInterpreter(self, auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash): r""" RunCommandInterpreter(SBDebugger self, bool auto_handle_events, bool spawn_thread, SBCommandInterpreterRunOptions options, int & num_errors, bool & quit_requested, bool & stopped_for_crash) Launch a command interpreter session. Commands are read from standard input or from the input handle specified for the debugger object. Output/errors are similarly redirected to standard output/error or the configured handles. @param[in] auto_handle_events If true, automatically handle resulting events. @param[in] spawn_thread If true, start a new thread for IO handling. @param[in] options Parameter collection of type SBCommandInterpreterRunOptions. @param[in] num_errors Initial error counter. @param[in] quit_requested Initial quit request flag. @param[in] stopped_for_crash Initial crash flag. @return A tuple with the number of errors encountered by the interpreter, a boolean indicating whether quitting the interpreter was requested and another boolean set to True in case of a crash. Example: :: # Start an interactive lldb session from a script (with a valid debugger object # created beforehand): n_errors, quit_requested, has_crashed = debugger.RunCommandInterpreter(True, False, lldb.SBCommandInterpreterRunOptions(), 0, False, False) """ return _lldb.SBDebugger_RunCommandInterpreter(self, auto_handle_events, spawn_thread, options, num_errors, quit_requested, stopped_for_crash) def RunREPL(self, language, repl_options): r"""RunREPL(SBDebugger self, lldb::LanguageType language, char const * repl_options) -> SBError""" return _lldb.SBDebugger_RunREPL(self, language, repl_options) def __iter__(self): '''Iterate over all targets in a lldb.SBDebugger object.''' return lldb_iter(self, 'GetNumTargets', 'GetTargetAtIndex') def __len__(self): '''Return the number of targets in a lldb.SBDebugger object.''' return self.GetNumTargets() # Register SBDebugger in _lldb: _lldb.SBDebugger_swigregister(SBDebugger) def SBDebugger_Initialize(): r"""SBDebugger_Initialize()""" return _lldb.SBDebugger_Initialize() def SBDebugger_InitializeWithErrorHandling(): r"""SBDebugger_InitializeWithErrorHandling() -> SBError""" return _lldb.SBDebugger_InitializeWithErrorHandling() def SBDebugger_Terminate(): r"""SBDebugger_Terminate()""" return _lldb.SBDebugger_Terminate() def SBDebugger_Create(*args): r""" SBDebugger_Create() -> SBDebugger SBDebugger_Create(bool source_init_files) -> SBDebugger SBDebugger_Create(bool source_init_files, lldb::LogOutputCallback log_callback) -> SBDebugger """ return _lldb.SBDebugger_Create(*args) def SBDebugger_Destroy(debugger): r"""SBDebugger_Destroy(SBDebugger debugger)""" return _lldb.SBDebugger_Destroy(debugger) def SBDebugger_MemoryPressureDetected(): r"""SBDebugger_MemoryPressureDetected()""" return _lldb.SBDebugger_MemoryPressureDetected() def SBDebugger_GetDefaultArchitecture(arch_name, arch_name_len): r"""SBDebugger_GetDefaultArchitecture(char * arch_name, size_t arch_name_len) -> bool""" return _lldb.SBDebugger_GetDefaultArchitecture(arch_name, arch_name_len) def SBDebugger_SetDefaultArchitecture(arch_name): r"""SBDebugger_SetDefaultArchitecture(char const * arch_name) -> bool""" return _lldb.SBDebugger_SetDefaultArchitecture(arch_name) def SBDebugger_GetVersionString(): r"""SBDebugger_GetVersionString() -> char const *""" return _lldb.SBDebugger_GetVersionString() def SBDebugger_StateAsCString(state): r"""SBDebugger_StateAsCString(lldb::StateType state) -> char const *""" return _lldb.SBDebugger_StateAsCString(state) def SBDebugger_GetBuildConfiguration(): r"""SBDebugger_GetBuildConfiguration() -> SBStructuredData""" return _lldb.SBDebugger_GetBuildConfiguration() def SBDebugger_StateIsRunningState(state): r"""SBDebugger_StateIsRunningState(lldb::StateType state) -> bool""" return _lldb.SBDebugger_StateIsRunningState(state) def SBDebugger_StateIsStoppedState(state): r"""SBDebugger_StateIsStoppedState(lldb::StateType state) -> bool""" return _lldb.SBDebugger_StateIsStoppedState(state) def SBDebugger_FindDebuggerWithID(id): r"""SBDebugger_FindDebuggerWithID(int id) -> SBDebugger""" return _lldb.SBDebugger_FindDebuggerWithID(id) def SBDebugger_SetInternalVariable(var_name, value, debugger_instance_name): r"""SBDebugger_SetInternalVariable(char const * var_name, char const * value, char const * debugger_instance_name) -> SBError""" return _lldb.SBDebugger_SetInternalVariable(var_name, value, debugger_instance_name) def SBDebugger_GetInternalVariableValue(var_name, debugger_instance_name): r"""SBDebugger_GetInternalVariableValue(char const * var_name, char const * debugger_instance_name) -> SBStringList""" return _lldb.SBDebugger_GetInternalVariableValue(var_name, debugger_instance_name) class SBDeclaration(object): r"""Specifies an association with a line and column for a variable.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBDeclaration self) -> SBDeclaration __init__(SBDeclaration self, SBDeclaration rhs) -> SBDeclaration """ _lldb.SBDeclaration_swiginit(self, _lldb.new_SBDeclaration(*args)) __swig_destroy__ = _lldb.delete_SBDeclaration def IsValid(self): r"""IsValid(SBDeclaration self) -> bool""" return _lldb.SBDeclaration_IsValid(self) def __nonzero__(self): return _lldb.SBDeclaration___nonzero__(self) __bool__ = __nonzero__ def GetFileSpec(self): r"""GetFileSpec(SBDeclaration self) -> SBFileSpec""" return _lldb.SBDeclaration_GetFileSpec(self) def GetLine(self): r"""GetLine(SBDeclaration self) -> uint32_t""" return _lldb.SBDeclaration_GetLine(self) def GetColumn(self): r"""GetColumn(SBDeclaration self) -> uint32_t""" return _lldb.SBDeclaration_GetColumn(self) def GetDescription(self, description): r"""GetDescription(SBDeclaration self, SBStream description) -> bool""" return _lldb.SBDeclaration_GetDescription(self, description) def SetFileSpec(self, filespec): r"""SetFileSpec(SBDeclaration self, SBFileSpec filespec)""" return _lldb.SBDeclaration_SetFileSpec(self, filespec) def SetLine(self, line): r"""SetLine(SBDeclaration self, uint32_t line)""" return _lldb.SBDeclaration_SetLine(self, line) def SetColumn(self, column): r"""SetColumn(SBDeclaration self, uint32_t column)""" return _lldb.SBDeclaration_SetColumn(self, column) def __eq__(self, rhs): r"""__eq__(SBDeclaration self, SBDeclaration rhs) -> bool""" return _lldb.SBDeclaration___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBDeclaration self, SBDeclaration rhs) -> bool""" return _lldb.SBDeclaration___ne__(self, rhs) def __str__(self): r"""__str__(SBDeclaration self) -> std::string""" return _lldb.SBDeclaration___str__(self) file = property(GetFileSpec, None, doc='''A read only property that returns an lldb object that represents the file (lldb.SBFileSpec) for this line entry.''') line = property(GetLine, None, doc='''A read only property that returns the 1 based line number for this line entry, a return value of zero indicates that no line information is available.''') column = property(GetColumn, None, doc='''A read only property that returns the 1 based column number for this line entry, a return value of zero indicates that no column information is available.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBDeclaration in _lldb: _lldb.SBDeclaration_swigregister(SBDeclaration) class SBError(object): r""" Represents a container for holding any error code. For example (from test/python_api/hello_world/TestHelloWorld.py), :: def hello_world_attach_with_id_api(self): '''Create target, spawn a process, and attach to it by id.''' target = self.dbg.CreateTarget(self.exe) # Spawn a new process and don't display the stdout if not in TraceOn() mode. import subprocess popen = subprocess.Popen([self.exe, 'abc', 'xyz'], stdout = open(os.devnull, 'w') if not self.TraceOn() else None) listener = lldb.SBListener('my.attach.listener') error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) # Let's check the stack traces of the attached process. import lldbutil stacktraces = lldbutil.print_stacktraces(process, string_buffer=True) self.expect(stacktraces, exe=False, substrs = ['main.c:%d' % self.line2, '(int)argc=3']) listener = lldb.SBListener('my.attach.listener') error = lldb.SBError() process = target.AttachToProcessWithID(listener, popen.pid, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) checks that after the attach, there is no error condition by asserting that error.Success() is True and we get back a valid process object. And (from test/python_api/event/TestEvent.py), :: # Now launch the process, and do not stop at entry point. error = lldb.SBError() process = target.Launch(listener, None, None, None, None, None, None, 0, False, error) self.assertTrue(error.Success() and process, PROCESS_IS_VALID) checks that after calling the target.Launch() method there's no error condition and we get back a void process object. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBError self) -> SBError __init__(SBError self, SBError rhs) -> SBError """ _lldb.SBError_swiginit(self, _lldb.new_SBError(*args)) __swig_destroy__ = _lldb.delete_SBError def GetCString(self): r"""GetCString(SBError self) -> char const *""" return _lldb.SBError_GetCString(self) def Clear(self): r"""Clear(SBError self)""" return _lldb.SBError_Clear(self) def Fail(self): r"""Fail(SBError self) -> bool""" return _lldb.SBError_Fail(self) def Success(self): r"""Success(SBError self) -> bool""" return _lldb.SBError_Success(self) def GetError(self): r"""GetError(SBError self) -> uint32_t""" return _lldb.SBError_GetError(self) def GetType(self): r"""GetType(SBError self) -> lldb::ErrorType""" return _lldb.SBError_GetType(self) def SetError(self, err, type): r"""SetError(SBError self, uint32_t err, lldb::ErrorType type)""" return _lldb.SBError_SetError(self, err, type) def SetErrorToErrno(self): r"""SetErrorToErrno(SBError self)""" return _lldb.SBError_SetErrorToErrno(self) def SetErrorToGenericError(self): r"""SetErrorToGenericError(SBError self)""" return _lldb.SBError_SetErrorToGenericError(self) def SetErrorString(self, err_str): r"""SetErrorString(SBError self, char const * err_str)""" return _lldb.SBError_SetErrorString(self, err_str) def SetErrorStringWithFormat(self, format, str1=None, str2=None, str3=None): r"""SetErrorStringWithFormat(SBError self, char const * format, char * str1=None, char * str2=None, char * str3=None) -> int""" return _lldb.SBError_SetErrorStringWithFormat(self, format, str1, str2, str3) def IsValid(self): r"""IsValid(SBError self) -> bool""" return _lldb.SBError_IsValid(self) def __nonzero__(self): return _lldb.SBError___nonzero__(self) __bool__ = __nonzero__ def GetDescription(self, description): r"""GetDescription(SBError self, SBStream description) -> bool""" return _lldb.SBError_GetDescription(self, description) def __str__(self): r"""__str__(SBError self) -> std::string""" return _lldb.SBError___str__(self) value = property(GetError, None, doc='''A read only property that returns the same result as GetError().''') fail = property(Fail, None, doc='''A read only property that returns the same result as Fail().''') success = property(Success, None, doc='''A read only property that returns the same result as Success().''') description = property(GetCString, None, doc='''A read only property that returns the same result as GetCString().''') type = property(GetType, None, doc='''A read only property that returns the same result as GetType().''') # Register SBError in _lldb: _lldb.SBError_swigregister(SBError) class SBEnvironment(object): r""" Represents the environment of a certain process. Example: :: for entry in lldb.debugger.GetSelectedTarget().GetEnvironment().GetEntries(): print(entry) """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBEnvironment self) -> SBEnvironment __init__(SBEnvironment self, SBEnvironment rhs) -> SBEnvironment """ _lldb.SBEnvironment_swiginit(self, _lldb.new_SBEnvironment(*args)) __swig_destroy__ = _lldb.delete_SBEnvironment def GetNumValues(self): r"""GetNumValues(SBEnvironment self) -> size_t""" return _lldb.SBEnvironment_GetNumValues(self) def Get(self, name): r"""Get(SBEnvironment self, char const * name) -> char const *""" return _lldb.SBEnvironment_Get(self, name) def GetNameAtIndex(self, index): r"""GetNameAtIndex(SBEnvironment self, size_t index) -> char const *""" return _lldb.SBEnvironment_GetNameAtIndex(self, index) def GetValueAtIndex(self, index): r"""GetValueAtIndex(SBEnvironment self, size_t index) -> char const *""" return _lldb.SBEnvironment_GetValueAtIndex(self, index) def GetEntries(self): r"""GetEntries(SBEnvironment self) -> SBStringList""" return _lldb.SBEnvironment_GetEntries(self) def PutEntry(self, name_and_value): r"""PutEntry(SBEnvironment self, char const * name_and_value)""" return _lldb.SBEnvironment_PutEntry(self, name_and_value) def SetEntries(self, entries, append): r"""SetEntries(SBEnvironment self, SBStringList entries, bool append)""" return _lldb.SBEnvironment_SetEntries(self, entries, append) def Set(self, name, value, overwrite): r"""Set(SBEnvironment self, char const * name, char const * value, bool overwrite) -> bool""" return _lldb.SBEnvironment_Set(self, name, value, overwrite) def Unset(self, name): r"""Unset(SBEnvironment self, char const * name) -> bool""" return _lldb.SBEnvironment_Unset(self, name) def Clear(self): r"""Clear(SBEnvironment self)""" return _lldb.SBEnvironment_Clear(self) # Register SBEnvironment in _lldb: _lldb.SBEnvironment_swigregister(SBEnvironment) class SBEvent(object): r""" API clients can register to receive events. For example, check out the following output: :: Try wait for event... Event description: 0x103d0bb70 Event: broadcaster = 0x1009c8410, type = 0x00000001, data = { process = 0x1009c8400 (pid = 21528), state = running} Event data flavor: Process::ProcessEventData Process state: running Try wait for event... Event description: 0x103a700a0 Event: broadcaster = 0x1009c8410, type = 0x00000001, data = { process = 0x1009c8400 (pid = 21528), state = stopped} Event data flavor: Process::ProcessEventData Process state: stopped Try wait for event... Event description: 0x103d0d4a0 Event: broadcaster = 0x1009c8410, type = 0x00000001, data = { process = 0x1009c8400 (pid = 21528), state = exited} Event data flavor: Process::ProcessEventData Process state: exited Try wait for event... timeout occurred waiting for event... from test/python_api/event/TestEventspy: :: def do_listen_for_and_print_event(self): '''Create a listener and use SBEvent API to print the events received.''' exe = os.path.join(os.getcwd(), 'a.out') # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateByName('c', 'a.out') # Now launch the process, and do not stop at the entry point. process = target.LaunchSimple(None, None, os.getcwd()) self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED) # Get a handle on the process's broadcaster. broadcaster = process.GetBroadcaster() # Create an empty event object. event = lldb.SBEvent() # Create a listener object and register with the broadcaster. listener = lldb.SBListener('my listener') rc = broadcaster.AddListener(listener, lldb.SBProcess.eBroadcastBitStateChanged) self.assertTrue(rc, 'AddListener successfully retruns') traceOn = self.TraceOn() if traceOn: lldbutil.print_stacktraces(process) # Create MyListeningThread class to wait for any kind of event. import threading class MyListeningThread(threading.Thread): def run(self): count = 0 # Let's only try at most 4 times to retrieve any kind of event. # After that, the thread exits. while not count > 3: if traceOn: print('Try wait for event...') if listener.WaitForEventForBroadcasterWithType(5, broadcaster, lldb.SBProcess.eBroadcastBitStateChanged, event): if traceOn: desc = lldbutil.get_description(event)) print('Event description:', desc) print('Event data flavor:', event.GetDataFlavor()) print('Process state:', lldbutil.state_type_to_str(process.GetState())) print() else: if traceOn: print 'timeout occurred waiting for event...' count = count + 1 return # Let's start the listening thread to retrieve the events. my_thread = MyListeningThread() my_thread.start() # Use Python API to continue the process. The listening thread should be # able to receive the state changed events. process.Continue() # Use Python API to kill the process. The listening thread should be # able to receive the state changed event, too. process.Kill() # Wait until the 'MyListeningThread' terminates. my_thread.join() """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBEvent self) -> SBEvent __init__(SBEvent self, SBEvent rhs) -> SBEvent__init__(self, int type, str data) -> SBEvent (make an event that contains a C string) """ _lldb.SBEvent_swiginit(self, _lldb.new_SBEvent(*args)) __swig_destroy__ = _lldb.delete_SBEvent def IsValid(self): r"""IsValid(SBEvent self) -> bool""" return _lldb.SBEvent_IsValid(self) def __nonzero__(self): return _lldb.SBEvent___nonzero__(self) __bool__ = __nonzero__ def GetDataFlavor(self): r"""GetDataFlavor(SBEvent self) -> char const *""" return _lldb.SBEvent_GetDataFlavor(self) def GetType(self): r"""GetType(SBEvent self) -> uint32_t""" return _lldb.SBEvent_GetType(self) def GetBroadcaster(self): r"""GetBroadcaster(SBEvent self) -> SBBroadcaster""" return _lldb.SBEvent_GetBroadcaster(self) def GetBroadcasterClass(self): r"""GetBroadcasterClass(SBEvent self) -> char const *""" return _lldb.SBEvent_GetBroadcasterClass(self) def BroadcasterMatchesRef(self, broadcaster): r"""BroadcasterMatchesRef(SBEvent self, SBBroadcaster broadcaster) -> bool""" return _lldb.SBEvent_BroadcasterMatchesRef(self, broadcaster) def Clear(self): r"""Clear(SBEvent self)""" return _lldb.SBEvent_Clear(self) @staticmethod def GetCStringFromEvent(event): r"""GetCStringFromEvent(SBEvent event) -> char const *""" return _lldb.SBEvent_GetCStringFromEvent(event) def GetDescription(self, description): r"""GetDescription(SBEvent self, SBStream description) -> bool""" return _lldb.SBEvent_GetDescription(self, description) # Register SBEvent in _lldb: _lldb.SBEvent_swigregister(SBEvent) def SBEvent_GetCStringFromEvent(event): r"""SBEvent_GetCStringFromEvent(SBEvent event) -> char const *""" return _lldb.SBEvent_GetCStringFromEvent(event) class SBExecutionContext(object): r"""Describes the program context in which a command should be executed.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBExecutionContext self) -> SBExecutionContext __init__(SBExecutionContext self, SBExecutionContext rhs) -> SBExecutionContext __init__(SBExecutionContext self, SBTarget target) -> SBExecutionContext __init__(SBExecutionContext self, SBProcess process) -> SBExecutionContext __init__(SBExecutionContext self, SBThread thread) -> SBExecutionContext __init__(SBExecutionContext self, SBFrame frame) -> SBExecutionContext """ _lldb.SBExecutionContext_swiginit(self, _lldb.new_SBExecutionContext(*args)) __swig_destroy__ = _lldb.delete_SBExecutionContext def GetTarget(self): r"""GetTarget(SBExecutionContext self) -> SBTarget""" return _lldb.SBExecutionContext_GetTarget(self) def GetProcess(self): r"""GetProcess(SBExecutionContext self) -> SBProcess""" return _lldb.SBExecutionContext_GetProcess(self) def GetThread(self): r"""GetThread(SBExecutionContext self) -> SBThread""" return _lldb.SBExecutionContext_GetThread(self) def GetFrame(self): r"""GetFrame(SBExecutionContext self) -> SBFrame""" return _lldb.SBExecutionContext_GetFrame(self) target = property(GetTarget, None, doc='''A read only property that returns the same result as GetTarget().''') process = property(GetProcess, None, doc='''A read only property that returns the same result as GetProcess().''') thread = property(GetThread, None, doc='''A read only property that returns the same result as GetThread().''') frame = property(GetFrame, None, doc='''A read only property that returns the same result as GetFrame().''') # Register SBExecutionContext in _lldb: _lldb.SBExecutionContext_swigregister(SBExecutionContext) class SBExpressionOptions(object): r"""A container for options to use when evaluating expressions.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBExpressionOptions self) -> SBExpressionOptions __init__(SBExpressionOptions self, SBExpressionOptions rhs) -> SBExpressionOptions """ _lldb.SBExpressionOptions_swiginit(self, _lldb.new_SBExpressionOptions(*args)) __swig_destroy__ = _lldb.delete_SBExpressionOptions def GetCoerceResultToId(self): r"""GetCoerceResultToId(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetCoerceResultToId(self) def SetCoerceResultToId(self, coerce=True): r""" SetCoerceResultToId(SBExpressionOptions self, bool coerce=True) Sets whether to coerce the expression result to ObjC id type after evaluation. """ return _lldb.SBExpressionOptions_SetCoerceResultToId(self, coerce) def GetUnwindOnError(self): r"""GetUnwindOnError(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetUnwindOnError(self) def SetUnwindOnError(self, unwind=True): r""" SetUnwindOnError(SBExpressionOptions self, bool unwind=True) Sets whether to unwind the expression stack on error. """ return _lldb.SBExpressionOptions_SetUnwindOnError(self, unwind) def GetIgnoreBreakpoints(self): r"""GetIgnoreBreakpoints(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetIgnoreBreakpoints(self) def SetIgnoreBreakpoints(self, ignore=True): r"""SetIgnoreBreakpoints(SBExpressionOptions self, bool ignore=True)""" return _lldb.SBExpressionOptions_SetIgnoreBreakpoints(self, ignore) def GetFetchDynamicValue(self): r"""GetFetchDynamicValue(SBExpressionOptions self) -> lldb::DynamicValueType""" return _lldb.SBExpressionOptions_GetFetchDynamicValue(self) def SetFetchDynamicValue(self, *args): r""" SetFetchDynamicValue(SBExpressionOptions self, lldb::DynamicValueType dynamic=eDynamicCanRunTarget) Sets whether to cast the expression result to its dynamic type. """ return _lldb.SBExpressionOptions_SetFetchDynamicValue(self, *args) def GetTimeoutInMicroSeconds(self): r"""GetTimeoutInMicroSeconds(SBExpressionOptions self) -> uint32_t""" return _lldb.SBExpressionOptions_GetTimeoutInMicroSeconds(self) def SetTimeoutInMicroSeconds(self, timeout=0): r""" SetTimeoutInMicroSeconds(SBExpressionOptions self, uint32_t timeout=0) Sets the timeout in microseconds to run the expression for. If try all threads is set to true and the expression doesn't complete within the specified timeout, all threads will be resumed for the same timeout to see if the expression will finish. """ return _lldb.SBExpressionOptions_SetTimeoutInMicroSeconds(self, timeout) def GetOneThreadTimeoutInMicroSeconds(self): r"""GetOneThreadTimeoutInMicroSeconds(SBExpressionOptions self) -> uint32_t""" return _lldb.SBExpressionOptions_GetOneThreadTimeoutInMicroSeconds(self) def SetOneThreadTimeoutInMicroSeconds(self, timeout=0): r"""SetOneThreadTimeoutInMicroSeconds(SBExpressionOptions self, uint32_t timeout=0)""" return _lldb.SBExpressionOptions_SetOneThreadTimeoutInMicroSeconds(self, timeout) def GetTryAllThreads(self): r"""GetTryAllThreads(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetTryAllThreads(self) def SetTryAllThreads(self, run_others=True): r""" SetTryAllThreads(SBExpressionOptions self, bool run_others=True) Sets whether to run all threads if the expression does not complete on one thread. """ return _lldb.SBExpressionOptions_SetTryAllThreads(self, run_others) def GetStopOthers(self): r"""GetStopOthers(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetStopOthers(self) def SetStopOthers(self, stop_others=True): r"""SetStopOthers(SBExpressionOptions self, bool stop_others=True)""" return _lldb.SBExpressionOptions_SetStopOthers(self, stop_others) def GetTrapExceptions(self): r"""GetTrapExceptions(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetTrapExceptions(self) def SetTrapExceptions(self, trap_exceptions=True): r"""SetTrapExceptions(SBExpressionOptions self, bool trap_exceptions=True)""" return _lldb.SBExpressionOptions_SetTrapExceptions(self, trap_exceptions) def GetPlaygroundTransformEnabled(self): r"""GetPlaygroundTransformEnabled(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetPlaygroundTransformEnabled(self) def SetPlaygroundTransformEnabled(self, enable_playground_transform=True): r"""SetPlaygroundTransformEnabled(SBExpressionOptions self, bool enable_playground_transform=True)""" return _lldb.SBExpressionOptions_SetPlaygroundTransformEnabled(self, enable_playground_transform) def GetREPLMode(self): r"""GetREPLMode(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetREPLMode(self) def SetREPLMode(self, enable_repl=True): r"""SetREPLMode(SBExpressionOptions self, bool enable_repl=True)""" return _lldb.SBExpressionOptions_SetREPLMode(self, enable_repl) def SetLanguage(self, language): r""" SetLanguage(SBExpressionOptions self, lldb::LanguageType language) Sets the language that LLDB should assume the expression is written in """ return _lldb.SBExpressionOptions_SetLanguage(self, language) def GetGenerateDebugInfo(self): r"""GetGenerateDebugInfo(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetGenerateDebugInfo(self) def SetGenerateDebugInfo(self, b=True): r""" SetGenerateDebugInfo(SBExpressionOptions self, bool b=True) Sets whether to generate debug information for the expression and also controls if a SBModule is generated. """ return _lldb.SBExpressionOptions_SetGenerateDebugInfo(self, b) def GetSuppressPersistentResult(self): r"""GetSuppressPersistentResult(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetSuppressPersistentResult(self) def SetSuppressPersistentResult(self, b=False): r""" SetSuppressPersistentResult(SBExpressionOptions self, bool b=False) Sets whether to produce a persistent result that can be used in future expressions. """ return _lldb.SBExpressionOptions_SetSuppressPersistentResult(self, b) def GetPrefix(self): r""" GetPrefix(SBExpressionOptions self) -> char const * Gets the prefix to use for this expression. """ return _lldb.SBExpressionOptions_GetPrefix(self) def SetPrefix(self, prefix): r""" SetPrefix(SBExpressionOptions self, char const * prefix) Sets the prefix to use for this expression. This prefix gets inserted after the 'target.expr-prefix' prefix contents, but before the wrapped expression function body. """ return _lldb.SBExpressionOptions_SetPrefix(self, prefix) def SetAutoApplyFixIts(self, b=True): r""" SetAutoApplyFixIts(SBExpressionOptions self, bool b=True) Sets whether to auto-apply fix-it hints to the expression being evaluated. """ return _lldb.SBExpressionOptions_SetAutoApplyFixIts(self, b) def GetAutoApplyFixIts(self): r""" GetAutoApplyFixIts(SBExpressionOptions self) -> bool Gets whether to auto-apply fix-it hints to an expression. """ return _lldb.SBExpressionOptions_GetAutoApplyFixIts(self) def SetRetriesWithFixIts(self, retries): r""" SetRetriesWithFixIts(SBExpressionOptions self, uint64_t retries) Sets how often LLDB should retry applying fix-its to an expression. """ return _lldb.SBExpressionOptions_SetRetriesWithFixIts(self, retries) def GetRetriesWithFixIts(self): r""" GetRetriesWithFixIts(SBExpressionOptions self) -> uint64_t Gets how often LLDB will retry applying fix-its to an expression. """ return _lldb.SBExpressionOptions_GetRetriesWithFixIts(self) def GetTopLevel(self): r"""GetTopLevel(SBExpressionOptions self) -> bool""" return _lldb.SBExpressionOptions_GetTopLevel(self) def SetTopLevel(self, b=True): r"""SetTopLevel(SBExpressionOptions self, bool b=True)""" return _lldb.SBExpressionOptions_SetTopLevel(self, b) def GetAllowJIT(self): r""" GetAllowJIT(SBExpressionOptions self) -> bool Gets whether to JIT an expression if it cannot be interpreted. """ return _lldb.SBExpressionOptions_GetAllowJIT(self) def SetAllowJIT(self, allow): r""" SetAllowJIT(SBExpressionOptions self, bool allow) Sets whether to JIT an expression if it cannot be interpreted. """ return _lldb.SBExpressionOptions_SetAllowJIT(self, allow) # Register SBExpressionOptions in _lldb: _lldb.SBExpressionOptions_swigregister(SBExpressionOptions) class SBFile(object): r"""Represents a file.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBFile self) -> SBFile __init__(SBFile self, int fd, char const * mode, bool transfer_ownership) -> SBFile __init__(SBFile self, lldb::FileSP file) -> SBFile initialize a SBFile from a python file object """ _lldb.SBFile_swiginit(self, _lldb.new_SBFile(*args)) @staticmethod def MakeBorrowed(BORROWED): r""" MakeBorrowed(lldb::FileSP BORROWED) -> SBFile initialize a SBFile from a python file object """ return _lldb.SBFile_MakeBorrowed(BORROWED) @staticmethod def MakeForcingIOMethods(FORCE_IO_METHODS): r""" MakeForcingIOMethods(lldb::FileSP FORCE_IO_METHODS) -> SBFile initialize a SBFile from a python file object """ return _lldb.SBFile_MakeForcingIOMethods(FORCE_IO_METHODS) @staticmethod def MakeBorrowedForcingIOMethods(BORROWED_FORCE_IO_METHODS): r""" MakeBorrowedForcingIOMethods(lldb::FileSP BORROWED_FORCE_IO_METHODS) -> SBFile initialize a SBFile from a python file object """ return _lldb.SBFile_MakeBorrowedForcingIOMethods(BORROWED_FORCE_IO_METHODS) @classmethod def Create(cls, file, borrow=False, force_io_methods=False): """ Create a SBFile from a python file object, with options. If borrow is set then the underlying file will not be closed when the SBFile is closed or destroyed. If force_scripting_io is set then the python read/write methods will be called even if a file descriptor is available. """ if borrow: if force_io_methods: return cls.MakeBorrowedForcingIOMethods(file) else: return cls.MakeBorrowed(file) else: if force_io_methods: return cls.MakeForcingIOMethods(file) else: return cls(file) __swig_destroy__ = _lldb.delete_SBFile def Read(self, buf): r""" Read(buffer) -> SBError, bytes_read initialize a SBFile from a python file object """ return _lldb.SBFile_Read(self, buf) def Write(self, buf): r""" Write(buffer) -> SBError, written_read initialize a SBFile from a python file object """ return _lldb.SBFile_Write(self, buf) def Flush(self): r""" Flush(SBFile self) initialize a SBFile from a python file object """ return _lldb.SBFile_Flush(self) def IsValid(self): r""" IsValid(SBFile self) -> bool initialize a SBFile from a python file object """ return _lldb.SBFile_IsValid(self) def __nonzero__(self): return _lldb.SBFile___nonzero__(self) __bool__ = __nonzero__ def Close(self): r""" Close(SBFile self) -> SBError initialize a SBFile from a python file object """ return _lldb.SBFile_Close(self) def GetFile(self): r""" GetFile(SBFile self) -> lldb::FileSP Convert this SBFile into a python io.IOBase file object. If the SBFile is itself a wrapper around a python file object, this will return that original object. The file returned from here should be considered borrowed, in the sense that you may read and write to it, and flush it, etc, but you should not close it. If you want to close the SBFile, call SBFile.Close(). If there is no underlying python file to unwrap, GetFile will use the file descriptor, if available to create a new python file object using ``open(fd, mode=..., closefd=False)`` """ return _lldb.SBFile_GetFile(self) # Register SBFile in _lldb: _lldb.SBFile_swigregister(SBFile) def SBFile_MakeBorrowed(BORROWED): r""" SBFile_MakeBorrowed(lldb::FileSP BORROWED) -> SBFile initialize a SBFile from a python file object """ return _lldb.SBFile_MakeBorrowed(BORROWED) def SBFile_MakeForcingIOMethods(FORCE_IO_METHODS): r""" SBFile_MakeForcingIOMethods(lldb::FileSP FORCE_IO_METHODS) -> SBFile initialize a SBFile from a python file object """ return _lldb.SBFile_MakeForcingIOMethods(FORCE_IO_METHODS) def SBFile_MakeBorrowedForcingIOMethods(BORROWED_FORCE_IO_METHODS): r""" SBFile_MakeBorrowedForcingIOMethods(lldb::FileSP BORROWED_FORCE_IO_METHODS) -> SBFile initialize a SBFile from a python file object """ return _lldb.SBFile_MakeBorrowedForcingIOMethods(BORROWED_FORCE_IO_METHODS) class SBFileSpec(object): r""" Represents a file specification that divides the path into a directory and basename. The string values of the paths are put into uniqued string pools for fast comparisons and efficient memory usage. For example, the following code :: lineEntry = context.GetLineEntry() self.expect(lineEntry.GetFileSpec().GetDirectory(), 'The line entry should have the correct directory', exe=False, substrs = [self.mydir]) self.expect(lineEntry.GetFileSpec().GetFilename(), 'The line entry should have the correct filename', exe=False, substrs = ['main.c']) self.assertTrue(lineEntry.GetLine() == self.line, 'The line entry's line number should match ') gets the line entry from the symbol context when a thread is stopped. It gets the file spec corresponding to the line entry and checks that the filename and the directory matches what we expect. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBFileSpec self) -> SBFileSpec __init__(SBFileSpec self, SBFileSpec rhs) -> SBFileSpec __init__(SBFileSpec self, char const * path) -> SBFileSpec __init__(SBFileSpec self, char const * path, bool resolve) -> SBFileSpec """ _lldb.SBFileSpec_swiginit(self, _lldb.new_SBFileSpec(*args)) __swig_destroy__ = _lldb.delete_SBFileSpec def __eq__(self, rhs): r"""__eq__(SBFileSpec self, SBFileSpec rhs) -> bool""" return _lldb.SBFileSpec___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBFileSpec self, SBFileSpec rhs) -> bool""" return _lldb.SBFileSpec___ne__(self, rhs) def IsValid(self): r"""IsValid(SBFileSpec self) -> bool""" return _lldb.SBFileSpec_IsValid(self) def __nonzero__(self): return _lldb.SBFileSpec___nonzero__(self) __bool__ = __nonzero__ def Exists(self): r"""Exists(SBFileSpec self) -> bool""" return _lldb.SBFileSpec_Exists(self) def ResolveExecutableLocation(self): r"""ResolveExecutableLocation(SBFileSpec self) -> bool""" return _lldb.SBFileSpec_ResolveExecutableLocation(self) def GetFilename(self): r"""GetFilename(SBFileSpec self) -> char const *""" return _lldb.SBFileSpec_GetFilename(self) def GetDirectory(self): r"""GetDirectory(SBFileSpec self) -> char const *""" return _lldb.SBFileSpec_GetDirectory(self) def SetFilename(self, filename): r"""SetFilename(SBFileSpec self, char const * filename)""" return _lldb.SBFileSpec_SetFilename(self, filename) def SetDirectory(self, directory): r"""SetDirectory(SBFileSpec self, char const * directory)""" return _lldb.SBFileSpec_SetDirectory(self, directory) def GetPath(self, dst_path, dst_len): r"""GetPath(SBFileSpec self, char * dst_path, size_t dst_len) -> uint32_t""" return _lldb.SBFileSpec_GetPath(self, dst_path, dst_len) @staticmethod def ResolvePath(src_path, dst_path, dst_len): r"""ResolvePath(char const * src_path, char * dst_path, size_t dst_len) -> int""" return _lldb.SBFileSpec_ResolvePath(src_path, dst_path, dst_len) def GetDescription(self, description): r"""GetDescription(SBFileSpec self, SBStream description) -> bool""" return _lldb.SBFileSpec_GetDescription(self, description) def AppendPathComponent(self, file_or_directory): r"""AppendPathComponent(SBFileSpec self, char const * file_or_directory)""" return _lldb.SBFileSpec_AppendPathComponent(self, file_or_directory) def __str__(self): r"""__str__(SBFileSpec self) -> std::string""" return _lldb.SBFileSpec___str__(self) def __get_fullpath__(self): spec_dir = self.GetDirectory() spec_file = self.GetFilename() if spec_dir and spec_file: return '%s/%s' % (spec_dir, spec_file) elif spec_dir: return spec_dir elif spec_file: return spec_file return None fullpath = property(__get_fullpath__, None, doc='''A read only property that returns the fullpath as a python string.''') basename = property(GetFilename, None, doc='''A read only property that returns the path basename as a python string.''') dirname = property(GetDirectory, None, doc='''A read only property that returns the path directory name as a python string.''') exists = property(Exists, None, doc='''A read only property that returns a boolean value that indicates if the file exists.''') # Register SBFileSpec in _lldb: _lldb.SBFileSpec_swigregister(SBFileSpec) def SBFileSpec_ResolvePath(src_path, dst_path, dst_len): r"""SBFileSpec_ResolvePath(char const * src_path, char * dst_path, size_t dst_len) -> int""" return _lldb.SBFileSpec_ResolvePath(src_path, dst_path, dst_len) class SBFileSpecList(object): r"""Represents a list of :py:class:`SBFileSpec`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBFileSpecList self) -> SBFileSpecList __init__(SBFileSpecList self, SBFileSpecList rhs) -> SBFileSpecList """ _lldb.SBFileSpecList_swiginit(self, _lldb.new_SBFileSpecList(*args)) __swig_destroy__ = _lldb.delete_SBFileSpecList def GetSize(self): r"""GetSize(SBFileSpecList self) -> uint32_t""" return _lldb.SBFileSpecList_GetSize(self) def GetDescription(self, description): r"""GetDescription(SBFileSpecList self, SBStream description) -> bool""" return _lldb.SBFileSpecList_GetDescription(self, description) def Append(self, sb_file): r"""Append(SBFileSpecList self, SBFileSpec sb_file)""" return _lldb.SBFileSpecList_Append(self, sb_file) def AppendIfUnique(self, sb_file): r"""AppendIfUnique(SBFileSpecList self, SBFileSpec sb_file) -> bool""" return _lldb.SBFileSpecList_AppendIfUnique(self, sb_file) def Clear(self): r"""Clear(SBFileSpecList self)""" return _lldb.SBFileSpecList_Clear(self) def FindFileIndex(self, idx, sb_file, full): r"""FindFileIndex(SBFileSpecList self, uint32_t idx, SBFileSpec sb_file, bool full) -> uint32_t""" return _lldb.SBFileSpecList_FindFileIndex(self, idx, sb_file, full) def GetFileSpecAtIndex(self, idx): r"""GetFileSpecAtIndex(SBFileSpecList self, uint32_t idx) -> SBFileSpec""" return _lldb.SBFileSpecList_GetFileSpecAtIndex(self, idx) # Register SBFileSpecList in _lldb: _lldb.SBFileSpecList_swigregister(SBFileSpecList) class SBFrame(object): r""" Represents one of the stack frames associated with a thread. SBThread contains SBFrame(s). For example (from test/lldbutil.py), :: def print_stacktrace(thread, string_buffer = False): '''Prints a simple stack trace of this thread.''' ... for i in range(depth): frame = thread.GetFrameAtIndex(i) function = frame.GetFunction() load_addr = addrs[i].GetLoadAddress(target) if not function: file_addr = addrs[i].GetFileAddress() start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress() symbol_offset = file_addr - start_addr print >> output, ' frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}'.format( num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset) else: print >> output, ' frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}'.format( num=i, addr=load_addr, mod=mods[i], func='%s [inlined]' % funcs[i] if frame.IsInlined() else funcs[i], file=files[i], line=lines[i], args=get_args_as_string(frame, showFuncName=False) if not frame.IsInlined() else '()') ... And, :: for frame in thread: print frame See also SBThread. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBFrame self) -> SBFrame __init__(SBFrame self, SBFrame rhs) -> SBFrame """ _lldb.SBFrame_swiginit(self, _lldb.new_SBFrame(*args)) __swig_destroy__ = _lldb.delete_SBFrame def IsEqual(self, rhs): r"""IsEqual(SBFrame self, SBFrame rhs) -> bool""" return _lldb.SBFrame_IsEqual(self, rhs) def IsValid(self): r"""IsValid(SBFrame self) -> bool""" return _lldb.SBFrame_IsValid(self) def __nonzero__(self): return _lldb.SBFrame___nonzero__(self) __bool__ = __nonzero__ def GetFrameID(self): r"""GetFrameID(SBFrame self) -> uint32_t""" return _lldb.SBFrame_GetFrameID(self) def GetCFA(self): r""" GetCFA(SBFrame self) -> lldb::addr_t Get the Canonical Frame Address for this stack frame. This is the DWARF standard's definition of a CFA, a stack address that remains constant throughout the lifetime of the function. Returns an lldb::addr_t stack address, or LLDB_INVALID_ADDRESS if the CFA cannot be determined. """ return _lldb.SBFrame_GetCFA(self) def GetPC(self): r"""GetPC(SBFrame self) -> lldb::addr_t""" return _lldb.SBFrame_GetPC(self) def SetPC(self, new_pc): r"""SetPC(SBFrame self, lldb::addr_t new_pc) -> bool""" return _lldb.SBFrame_SetPC(self, new_pc) def GetSP(self): r"""GetSP(SBFrame self) -> lldb::addr_t""" return _lldb.SBFrame_GetSP(self) def GetFP(self): r"""GetFP(SBFrame self) -> lldb::addr_t""" return _lldb.SBFrame_GetFP(self) def GetPCAddress(self): r"""GetPCAddress(SBFrame self) -> SBAddress""" return _lldb.SBFrame_GetPCAddress(self) def GetSymbolContext(self, resolve_scope): r"""GetSymbolContext(SBFrame self, uint32_t resolve_scope) -> SBSymbolContext""" return _lldb.SBFrame_GetSymbolContext(self, resolve_scope) def GetModule(self): r"""GetModule(SBFrame self) -> SBModule""" return _lldb.SBFrame_GetModule(self) def GetCompileUnit(self): r"""GetCompileUnit(SBFrame self) -> SBCompileUnit""" return _lldb.SBFrame_GetCompileUnit(self) def GetFunction(self): r"""GetFunction(SBFrame self) -> SBFunction""" return _lldb.SBFrame_GetFunction(self) def GetSymbol(self): r"""GetSymbol(SBFrame self) -> SBSymbol""" return _lldb.SBFrame_GetSymbol(self) def GetBlock(self): r""" GetBlock(SBFrame self) -> SBBlock Gets the deepest block that contains the frame PC. See also GetFrameBlock(). """ return _lldb.SBFrame_GetBlock(self) def GetDisplayFunctionName(self): r"""GetDisplayFunctionName(SBFrame self) -> char const *""" return _lldb.SBFrame_GetDisplayFunctionName(self) def GetFunctionName(self, *args): r""" GetFunctionName(SBFrame self) -> char const GetFunctionName(SBFrame self) -> char const * Get the appropriate function name for this frame. Inlined functions in LLDB are represented by Blocks that have inlined function information, so just looking at the SBFunction or SBSymbol for a frame isn't enough. This function will return the appropriate function, symbol or inlined function name for the frame. This function returns: - the name of the inlined function (if there is one) - the name of the concrete function (if there is one) - the name of the symbol (if there is one) - NULL See also IsInlined(). """ return _lldb.SBFrame_GetFunctionName(self, *args) def GuessLanguage(self): r""" GuessLanguage(SBFrame self) -> lldb::LanguageType Returns the language of the frame's SBFunction, or if there. is no SBFunction, guess the language from the mangled name. . """ return _lldb.SBFrame_GuessLanguage(self) def IsInlined(self, *args): r""" IsInlined(SBFrame self) -> bool IsInlined(SBFrame self) -> bool Return true if this frame represents an inlined function. See also GetFunctionName(). """ return _lldb.SBFrame_IsInlined(self, *args) def IsArtificial(self, *args): r""" IsArtificial(SBFrame self) -> bool IsArtificial(SBFrame self) -> bool Return true if this frame is artificial (e.g a frame synthesized to capture a tail call). Local variables may not be available in an artificial frame. """ return _lldb.SBFrame_IsArtificial(self, *args) def EvaluateExpression(self, *args): r""" EvaluateExpression(SBFrame self, char const * expr) -> SBValue EvaluateExpression(SBFrame self, char const * expr, lldb::DynamicValueType use_dynamic) -> SBValue EvaluateExpression(SBFrame self, char const * expr, lldb::DynamicValueType use_dynamic, bool unwind_on_error) -> SBValue EvaluateExpression(SBFrame self, char const * expr, SBExpressionOptions options) -> SBValue The version that doesn't supply a 'use_dynamic' value will use the target's default. """ return _lldb.SBFrame_EvaluateExpression(self, *args) def GetFrameBlock(self): r""" GetFrameBlock(SBFrame self) -> SBBlock Gets the lexical block that defines the stack frame. Another way to think of this is it will return the block that contains all of the variables for a stack frame. Inlined functions are represented as SBBlock objects that have inlined function information: the name of the inlined function, where it was called from. The block that is returned will be the first block at or above the block for the PC (SBFrame::GetBlock()) that defines the scope of the frame. When a function contains no inlined functions, this will be the top most lexical block that defines the function. When a function has inlined functions and the PC is currently in one of those inlined functions, this method will return the inlined block that defines this frame. If the PC isn't currently in an inlined function, the lexical block that defines the function is returned. """ return _lldb.SBFrame_GetFrameBlock(self) def GetLineEntry(self): r"""GetLineEntry(SBFrame self) -> SBLineEntry""" return _lldb.SBFrame_GetLineEntry(self) def GetThread(self): r"""GetThread(SBFrame self) -> SBThread""" return _lldb.SBFrame_GetThread(self) def Disassemble(self): r"""Disassemble(SBFrame self) -> char const *""" return _lldb.SBFrame_Disassemble(self) def Clear(self): r"""Clear(SBFrame self)""" return _lldb.SBFrame_Clear(self) def __eq__(self, rhs): r"""__eq__(SBFrame self, SBFrame rhs) -> bool""" return _lldb.SBFrame___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBFrame self, SBFrame rhs) -> bool""" return _lldb.SBFrame___ne__(self, rhs) def GetVariables(self, *args): r""" GetVariables(SBFrame self, bool arguments, bool locals, bool statics, bool in_scope_only) -> SBValueList GetVariables(SBFrame self, bool arguments, bool locals, bool statics, bool in_scope_only, lldb::DynamicValueType use_dynamic) -> SBValueList GetVariables(SBFrame self, SBVariablesOptions options) -> SBValueList The version that doesn't supply a 'use_dynamic' value will use the target's default. """ return _lldb.SBFrame_GetVariables(self, *args) def GetRegisters(self): r"""GetRegisters(SBFrame self) -> SBValueList""" return _lldb.SBFrame_GetRegisters(self) def FindVariable(self, *args): r""" FindVariable(SBFrame self, char const * var_name) -> SBValue FindVariable(SBFrame self, char const * var_name, lldb::DynamicValueType use_dynamic) -> SBValue The version that doesn't supply a 'use_dynamic' value will use the target's default. """ return _lldb.SBFrame_FindVariable(self, *args) def FindRegister(self, name): r"""FindRegister(SBFrame self, char const * name) -> SBValue""" return _lldb.SBFrame_FindRegister(self, name) def GetValueForVariablePath(self, *args): r""" GetValueForVariablePath(SBFrame self, char const * var_path) -> SBValue GetValueForVariablePath(SBFrame self, char const * var_path, lldb::DynamicValueType use_dynamic) -> SBValue Get a lldb.SBValue for a variable path. Variable paths can include access to pointer or instance members: :: rect_ptr->origin.y pt.x Pointer dereferences: :: *this->foo_ptr **argv Address of: :: &pt &my_array[3].x Array accesses and treating pointers as arrays: :: int_array[1] pt_ptr[22].x Unlike `EvaluateExpression()` which returns :py:class:`SBValue` objects with constant copies of the values at the time of evaluation, the result of this function is a value that will continue to track the current value of the value as execution progresses in the current frame. """ return _lldb.SBFrame_GetValueForVariablePath(self, *args) def FindValue(self, *args): r""" FindValue(SBFrame self, char const * name, lldb::ValueType value_type) -> SBValue FindValue(SBFrame self, char const * name, lldb::ValueType value_type, lldb::DynamicValueType use_dynamic) -> SBValue Find variables, register sets, registers, or persistent variables using the frame as the scope. The version that doesn't supply a ``use_dynamic`` value will use the target's default. """ return _lldb.SBFrame_FindValue(self, *args) def GetDescription(self, description): r"""GetDescription(SBFrame self, SBStream description) -> bool""" return _lldb.SBFrame_GetDescription(self, description) def GetLanguageSpecificData(self): r"""GetLanguageSpecificData(SBFrame self) -> SBStructuredData""" return _lldb.SBFrame_GetLanguageSpecificData(self) def __str__(self): r"""__str__(SBFrame self) -> std::string""" return _lldb.SBFrame___str__(self) def get_all_variables(self): return self.GetVariables(True,True,True,True) def get_parent_frame(self): parent_idx = self.idx + 1 if parent_idx >= 0 and parent_idx < len(self.thread.frame): return self.thread.frame[parent_idx] else: return SBFrame() def get_arguments(self): return self.GetVariables(True,False,False,False) def get_locals(self): return self.GetVariables(False,True,False,False) def get_statics(self): return self.GetVariables(False,False,True,False) def var(self, var_expr_path): '''Calls through to lldb.SBFrame.GetValueForVariablePath() and returns a value that represents the variable expression path''' return self.GetValueForVariablePath(var_expr_path) def get_registers_access(self): class registers_access(object): '''A helper object that exposes a flattened view of registers, masking away the notion of register sets for easy scripting.''' def __init__(self, regs): self.regs = regs def __getitem__(self, key): if type(key) is str: for i in range(0,len(self.regs)): rs = self.regs[i] for j in range (0,rs.num_children): reg = rs.GetChildAtIndex(j) if reg.name == key: return reg else: return lldb.SBValue() return registers_access(self.registers) pc = property(GetPC, SetPC) addr = property(GetPCAddress, None, doc='''A read only property that returns the program counter (PC) as a section offset address (lldb.SBAddress).''') fp = property(GetFP, None, doc='''A read only property that returns the frame pointer (FP) as an unsigned integer.''') sp = property(GetSP, None, doc='''A read only property that returns the stack pointer (SP) as an unsigned integer.''') module = property(GetModule, None, doc='''A read only property that returns an lldb object that represents the module (lldb.SBModule) for this stack frame.''') compile_unit = property(GetCompileUnit, None, doc='''A read only property that returns an lldb object that represents the compile unit (lldb.SBCompileUnit) for this stack frame.''') function = property(GetFunction, None, doc='''A read only property that returns an lldb object that represents the function (lldb.SBFunction) for this stack frame.''') symbol = property(GetSymbol, None, doc='''A read only property that returns an lldb object that represents the symbol (lldb.SBSymbol) for this stack frame.''') block = property(GetBlock, None, doc='''A read only property that returns an lldb object that represents the block (lldb.SBBlock) for this stack frame.''') is_inlined = property(IsInlined, None, doc='''A read only property that returns an boolean that indicates if the block frame is an inlined function.''') name = property(GetFunctionName, None, doc='''A read only property that retuns the name for the function that this frame represents. Inlined stack frame might have a concrete function that differs from the name of the inlined function (a named lldb.SBBlock).''') line_entry = property(GetLineEntry, None, doc='''A read only property that returns an lldb object that represents the line table entry (lldb.SBLineEntry) for this stack frame.''') thread = property(GetThread, None, doc='''A read only property that returns an lldb object that represents the thread (lldb.SBThread) for this stack frame.''') disassembly = property(Disassemble, None, doc='''A read only property that returns the disassembly for this stack frame as a python string.''') idx = property(GetFrameID, None, doc='''A read only property that returns the zero based stack frame index.''') variables = property(get_all_variables, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the variables in this stack frame.''') vars = property(get_all_variables, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the variables in this stack frame.''') locals = property(get_locals, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the local variables in this stack frame.''') args = property(get_arguments, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the argument variables in this stack frame.''') arguments = property(get_arguments, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the argument variables in this stack frame.''') statics = property(get_statics, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the static variables in this stack frame.''') registers = property(GetRegisters, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the CPU registers for this stack frame.''') regs = property(GetRegisters, None, doc='''A read only property that returns a list() that contains a collection of lldb.SBValue objects that represent the CPU registers for this stack frame.''') register = property(get_registers_access, None, doc='''A read only property that returns an helper object providing a flattened indexable view of the CPU registers for this stack frame.''') reg = property(get_registers_access, None, doc='''A read only property that returns an helper object providing a flattened indexable view of the CPU registers for this stack frame''') parent = property(get_parent_frame, None, doc='''A read only property that returns the parent (caller) frame of the current frame.''') # Register SBFrame in _lldb: _lldb.SBFrame_swigregister(SBFrame) class SBFunction(object): r""" Represents a generic function, which can be inlined or not. For example (from test/lldbutil.py, but slightly modified for doc purpose),:: ... frame = thread.GetFrameAtIndex(i) addr = frame.GetPCAddress() load_addr = addr.GetLoadAddress(target) function = frame.GetFunction() mod_name = frame.GetModule().GetFileSpec().GetFilename() if not function: # No debug info for 'function'. symbol = frame.GetSymbol() file_addr = addr.GetFileAddress() start_addr = symbol.GetStartAddress().GetFileAddress() symbol_name = symbol.GetName() symbol_offset = file_addr - start_addr print >> output, ' frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}'.format( num=i, addr=load_addr, mod=mod_name, symbol=symbol_name, offset=symbol_offset) else: # Debug info is available for 'function'. func_name = frame.GetFunctionName() file_name = frame.GetLineEntry().GetFileSpec().GetFilename() line_num = frame.GetLineEntry().GetLine() print >> output, ' frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}'.format( num=i, addr=load_addr, mod=mod_name, func='%s [inlined]' % func_name] if frame.IsInlined() else func_name, file=file_name, line=line_num, args=get_args_as_string(frame, showFuncName=False)) ... """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBFunction self) -> SBFunction __init__(SBFunction self, SBFunction rhs) -> SBFunction """ _lldb.SBFunction_swiginit(self, _lldb.new_SBFunction(*args)) __swig_destroy__ = _lldb.delete_SBFunction def IsValid(self): r"""IsValid(SBFunction self) -> bool""" return _lldb.SBFunction_IsValid(self) def __nonzero__(self): return _lldb.SBFunction___nonzero__(self) __bool__ = __nonzero__ def GetName(self): r"""GetName(SBFunction self) -> char const *""" return _lldb.SBFunction_GetName(self) def GetDisplayName(self): r"""GetDisplayName(SBFunction self) -> char const *""" return _lldb.SBFunction_GetDisplayName(self) def GetMangledName(self): r"""GetMangledName(SBFunction self) -> char const *""" return _lldb.SBFunction_GetMangledName(self) def GetInstructions(self, *args): r""" GetInstructions(SBFunction self, SBTarget target) -> SBInstructionList GetInstructions(SBFunction self, SBTarget target, char const * flavor) -> SBInstructionList """ return _lldb.SBFunction_GetInstructions(self, *args) def GetStartAddress(self): r"""GetStartAddress(SBFunction self) -> SBAddress""" return _lldb.SBFunction_GetStartAddress(self) def GetEndAddress(self): r"""GetEndAddress(SBFunction self) -> SBAddress""" return _lldb.SBFunction_GetEndAddress(self) def GetArgumentName(self, arg_idx): r"""GetArgumentName(SBFunction self, uint32_t arg_idx) -> char const *""" return _lldb.SBFunction_GetArgumentName(self, arg_idx) def GetPrologueByteSize(self): r"""GetPrologueByteSize(SBFunction self) -> uint32_t""" return _lldb.SBFunction_GetPrologueByteSize(self) def GetType(self): r"""GetType(SBFunction self) -> SBType""" return _lldb.SBFunction_GetType(self) def GetBlock(self): r"""GetBlock(SBFunction self) -> SBBlock""" return _lldb.SBFunction_GetBlock(self) def GetLanguage(self): r"""GetLanguage(SBFunction self) -> lldb::LanguageType""" return _lldb.SBFunction_GetLanguage(self) def GetIsOptimized(self): r""" GetIsOptimized(SBFunction self) -> bool Returns true if the function was compiled with optimization. Optimization, in this case, is meant to indicate that the debugger experience may be confusing for the user -- variables optimized away, stepping jumping between source lines -- and the driver may want to provide some guidance to the user about this. Returns false if unoptimized, or unknown. """ return _lldb.SBFunction_GetIsOptimized(self) def GetCanThrow(self): r"""GetCanThrow(SBFunction self) -> bool""" return _lldb.SBFunction_GetCanThrow(self) def GetDescription(self, description): r"""GetDescription(SBFunction self, SBStream description) -> bool""" return _lldb.SBFunction_GetDescription(self, description) def __eq__(self, rhs): r"""__eq__(SBFunction self, SBFunction rhs) -> bool""" return _lldb.SBFunction___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBFunction self, SBFunction rhs) -> bool""" return _lldb.SBFunction___ne__(self, rhs) def __str__(self): r"""__str__(SBFunction self) -> std::string""" return _lldb.SBFunction___str__(self) def get_instructions_from_current_target (self): return self.GetInstructions (target) addr = property(GetStartAddress, None, doc='''A read only property that returns an lldb object that represents the start address (lldb.SBAddress) for this function.''') end_addr = property(GetEndAddress, None, doc='''A read only property that returns an lldb object that represents the end address (lldb.SBAddress) for this function.''') block = property(GetBlock, None, doc='''A read only property that returns an lldb object that represents the top level lexical block (lldb.SBBlock) for this function.''') instructions = property(get_instructions_from_current_target, None, doc='''A read only property that returns an lldb object that represents the instructions (lldb.SBInstructionList) for this function.''') mangled = property(GetMangledName, None, doc='''A read only property that returns the mangled (linkage) name for this function as a string.''') name = property(GetName, None, doc='''A read only property that returns the name for this function as a string.''') prologue_size = property(GetPrologueByteSize, None, doc='''A read only property that returns the size in bytes of the prologue instructions as an unsigned integer.''') type = property(GetType, None, doc='''A read only property that returns an lldb object that represents the return type (lldb.SBType) for this function.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBFunction in _lldb: _lldb.SBFunction_swigregister(SBFunction) class SBHostOS(object): r"""Provides information about the host system.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr @staticmethod def GetProgramFileSpec(): r"""GetProgramFileSpec() -> SBFileSpec""" return _lldb.SBHostOS_GetProgramFileSpec() @staticmethod def GetLLDBPythonPath(): r"""GetLLDBPythonPath() -> SBFileSpec""" return _lldb.SBHostOS_GetLLDBPythonPath() @staticmethod def GetLLDBPath(path_type): r"""GetLLDBPath(lldb::PathType path_type) -> SBFileSpec""" return _lldb.SBHostOS_GetLLDBPath(path_type) @staticmethod def GetUserHomeDirectory(): r"""GetUserHomeDirectory() -> SBFileSpec""" return _lldb.SBHostOS_GetUserHomeDirectory() @staticmethod def ThreadCreated(name): r"""ThreadCreated(char const * name)""" return _lldb.SBHostOS_ThreadCreated(name) @staticmethod def ThreadCreate(name, arg2, thread_arg, err): r"""ThreadCreate(char const * name, lldb::thread_func_t arg2, void * thread_arg, SBError err) -> lldb::thread_t""" return _lldb.SBHostOS_ThreadCreate(name, arg2, thread_arg, err) @staticmethod def ThreadCancel(thread, err): r"""ThreadCancel(lldb::thread_t thread, SBError err) -> bool""" return _lldb.SBHostOS_ThreadCancel(thread, err) @staticmethod def ThreadDetach(thread, err): r"""ThreadDetach(lldb::thread_t thread, SBError err) -> bool""" return _lldb.SBHostOS_ThreadDetach(thread, err) @staticmethod def ThreadJoin(thread, result, err): r"""ThreadJoin(lldb::thread_t thread, lldb::thread_result_t * result, SBError err) -> bool""" return _lldb.SBHostOS_ThreadJoin(thread, result, err) def __init__(self): r"""__init__(SBHostOS self) -> SBHostOS""" _lldb.SBHostOS_swiginit(self, _lldb.new_SBHostOS()) __swig_destroy__ = _lldb.delete_SBHostOS # Register SBHostOS in _lldb: _lldb.SBHostOS_swigregister(SBHostOS) def SBHostOS_GetProgramFileSpec(): r"""SBHostOS_GetProgramFileSpec() -> SBFileSpec""" return _lldb.SBHostOS_GetProgramFileSpec() def SBHostOS_GetLLDBPythonPath(): r"""SBHostOS_GetLLDBPythonPath() -> SBFileSpec""" return _lldb.SBHostOS_GetLLDBPythonPath() def SBHostOS_GetLLDBPath(path_type): r"""SBHostOS_GetLLDBPath(lldb::PathType path_type) -> SBFileSpec""" return _lldb.SBHostOS_GetLLDBPath(path_type) def SBHostOS_GetUserHomeDirectory(): r"""SBHostOS_GetUserHomeDirectory() -> SBFileSpec""" return _lldb.SBHostOS_GetUserHomeDirectory() def SBHostOS_ThreadCreated(name): r"""SBHostOS_ThreadCreated(char const * name)""" return _lldb.SBHostOS_ThreadCreated(name) def SBHostOS_ThreadCreate(name, arg2, thread_arg, err): r"""SBHostOS_ThreadCreate(char const * name, lldb::thread_func_t arg2, void * thread_arg, SBError err) -> lldb::thread_t""" return _lldb.SBHostOS_ThreadCreate(name, arg2, thread_arg, err) def SBHostOS_ThreadCancel(thread, err): r"""SBHostOS_ThreadCancel(lldb::thread_t thread, SBError err) -> bool""" return _lldb.SBHostOS_ThreadCancel(thread, err) def SBHostOS_ThreadDetach(thread, err): r"""SBHostOS_ThreadDetach(lldb::thread_t thread, SBError err) -> bool""" return _lldb.SBHostOS_ThreadDetach(thread, err) def SBHostOS_ThreadJoin(thread, result, err): r"""SBHostOS_ThreadJoin(lldb::thread_t thread, lldb::thread_result_t * result, SBError err) -> bool""" return _lldb.SBHostOS_ThreadJoin(thread, result, err) class SBInstruction(object): r"""Represents a (machine language) instruction.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBInstruction self) -> SBInstruction __init__(SBInstruction self, SBInstruction rhs) -> SBInstruction """ _lldb.SBInstruction_swiginit(self, _lldb.new_SBInstruction(*args)) __swig_destroy__ = _lldb.delete_SBInstruction def IsValid(self): r"""IsValid(SBInstruction self) -> bool""" return _lldb.SBInstruction_IsValid(self) def __nonzero__(self): return _lldb.SBInstruction___nonzero__(self) __bool__ = __nonzero__ def GetAddress(self): r"""GetAddress(SBInstruction self) -> SBAddress""" return _lldb.SBInstruction_GetAddress(self) def GetMnemonic(self, target): r"""GetMnemonic(SBInstruction self, SBTarget target) -> char const *""" return _lldb.SBInstruction_GetMnemonic(self, target) def GetOperands(self, target): r"""GetOperands(SBInstruction self, SBTarget target) -> char const *""" return _lldb.SBInstruction_GetOperands(self, target) def GetComment(self, target): r"""GetComment(SBInstruction self, SBTarget target) -> char const *""" return _lldb.SBInstruction_GetComment(self, target) def GetData(self, target): r"""GetData(SBInstruction self, SBTarget target) -> SBData""" return _lldb.SBInstruction_GetData(self, target) def GetByteSize(self): r"""GetByteSize(SBInstruction self) -> size_t""" return _lldb.SBInstruction_GetByteSize(self) def DoesBranch(self): r"""DoesBranch(SBInstruction self) -> bool""" return _lldb.SBInstruction_DoesBranch(self) def HasDelaySlot(self): r"""HasDelaySlot(SBInstruction self) -> bool""" return _lldb.SBInstruction_HasDelaySlot(self) def CanSetBreakpoint(self): r"""CanSetBreakpoint(SBInstruction self) -> bool""" return _lldb.SBInstruction_CanSetBreakpoint(self) def Print(self, *args): r""" Print(SBInstruction self, SBFile out) Print(SBInstruction self, lldb::FileSP BORROWED) """ return _lldb.SBInstruction_Print(self, *args) def GetDescription(self, description): r"""GetDescription(SBInstruction self, SBStream description) -> bool""" return _lldb.SBInstruction_GetDescription(self, description) def EmulateWithFrame(self, frame, evaluate_options): r"""EmulateWithFrame(SBInstruction self, SBFrame frame, uint32_t evaluate_options) -> bool""" return _lldb.SBInstruction_EmulateWithFrame(self, frame, evaluate_options) def DumpEmulation(self, triple): r"""DumpEmulation(SBInstruction self, char const * triple) -> bool""" return _lldb.SBInstruction_DumpEmulation(self, triple) def TestEmulation(self, output_stream, test_file): r"""TestEmulation(SBInstruction self, SBStream output_stream, char const * test_file) -> bool""" return _lldb.SBInstruction_TestEmulation(self, output_stream, test_file) def __str__(self): r"""__str__(SBInstruction self) -> std::string""" return _lldb.SBInstruction___str__(self) def __mnemonic_property__ (self): return self.GetMnemonic (target) def __operands_property__ (self): return self.GetOperands (target) def __comment_property__ (self): return self.GetComment (target) def __file_addr_property__ (self): return self.GetAddress ().GetFileAddress() def __load_adrr_property__ (self): return self.GetComment (target) mnemonic = property(__mnemonic_property__, None, doc='''A read only property that returns the mnemonic for this instruction as a string.''') operands = property(__operands_property__, None, doc='''A read only property that returns the operands for this instruction as a string.''') comment = property(__comment_property__, None, doc='''A read only property that returns the comment for this instruction as a string.''') addr = property(GetAddress, None, doc='''A read only property that returns an lldb object that represents the address (lldb.SBAddress) for this instruction.''') size = property(GetByteSize, None, doc='''A read only property that returns the size in bytes for this instruction as an integer.''') is_branch = property(DoesBranch, None, doc='''A read only property that returns a boolean value that indicates if this instruction is a branch instruction.''') # Register SBInstruction in _lldb: _lldb.SBInstruction_swigregister(SBInstruction) class SBInstructionList(object): r""" Represents a list of machine instructions. SBFunction and SBSymbol have GetInstructions() methods which return SBInstructionList instances. SBInstructionList supports instruction (:py:class:`SBInstruction` instance) iteration. For example (see also :py:class:`SBDebugger` for a more complete example), :: def disassemble_instructions (insts): for i in insts: print i defines a function which takes an SBInstructionList instance and prints out the machine instructions in assembly format. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBInstructionList self) -> SBInstructionList __init__(SBInstructionList self, SBInstructionList rhs) -> SBInstructionList """ _lldb.SBInstructionList_swiginit(self, _lldb.new_SBInstructionList(*args)) __swig_destroy__ = _lldb.delete_SBInstructionList def IsValid(self): r"""IsValid(SBInstructionList self) -> bool""" return _lldb.SBInstructionList_IsValid(self) def __nonzero__(self): return _lldb.SBInstructionList___nonzero__(self) __bool__ = __nonzero__ def GetSize(self): r"""GetSize(SBInstructionList self) -> size_t""" return _lldb.SBInstructionList_GetSize(self) def GetInstructionAtIndex(self, idx): r"""GetInstructionAtIndex(SBInstructionList self, uint32_t idx) -> SBInstruction""" return _lldb.SBInstructionList_GetInstructionAtIndex(self, idx) def GetInstructionsCount(self, start, end, canSetBreakpoint): r"""GetInstructionsCount(SBInstructionList self, SBAddress start, SBAddress end, bool canSetBreakpoint) -> size_t""" return _lldb.SBInstructionList_GetInstructionsCount(self, start, end, canSetBreakpoint) def Clear(self): r"""Clear(SBInstructionList self)""" return _lldb.SBInstructionList_Clear(self) def AppendInstruction(self, inst): r"""AppendInstruction(SBInstructionList self, SBInstruction inst)""" return _lldb.SBInstructionList_AppendInstruction(self, inst) def Print(self, *args): r""" Print(SBInstructionList self, SBFile out) Print(SBInstructionList self, lldb::FileSP BORROWED) """ return _lldb.SBInstructionList_Print(self, *args) def GetDescription(self, description): r"""GetDescription(SBInstructionList self, SBStream description) -> bool""" return _lldb.SBInstructionList_GetDescription(self, description) def DumpEmulationForAllInstructions(self, triple): r"""DumpEmulationForAllInstructions(SBInstructionList self, char const * triple) -> bool""" return _lldb.SBInstructionList_DumpEmulationForAllInstructions(self, triple) def __str__(self): r"""__str__(SBInstructionList self) -> std::string""" return _lldb.SBInstructionList___str__(self) def __iter__(self): '''Iterate over all instructions in a lldb.SBInstructionList object.''' return lldb_iter(self, 'GetSize', 'GetInstructionAtIndex') def __len__(self): '''Access len of the instruction list.''' return int(self.GetSize()) def __getitem__(self, key): '''Access instructions by integer index for array access or by lldb.SBAddress to find an instruction that matches a section offset address object.''' if type(key) is int: # Find an instruction by index if key < len(self): return self.GetInstructionAtIndex(key) elif type(key) is SBAddress: # Find an instruction using a lldb.SBAddress object lookup_file_addr = key.file_addr closest_inst = None for idx in range(self.GetSize()): inst = self.GetInstructionAtIndex(idx) inst_file_addr = inst.addr.file_addr if inst_file_addr == lookup_file_addr: return inst elif inst_file_addr > lookup_file_addr: return closest_inst else: closest_inst = inst return None # Register SBInstructionList in _lldb: _lldb.SBInstructionList_swigregister(SBInstructionList) class SBLanguageRuntime(object): r"""Utility functions for :ref:`LanguageType`""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr @staticmethod def GetLanguageTypeFromString(string): r"""GetLanguageTypeFromString(char const * string) -> lldb::LanguageType""" return _lldb.SBLanguageRuntime_GetLanguageTypeFromString(string) @staticmethod def GetNameForLanguageType(language): r"""GetNameForLanguageType(lldb::LanguageType language) -> char const *""" return _lldb.SBLanguageRuntime_GetNameForLanguageType(language) def __init__(self): r"""__init__(SBLanguageRuntime self) -> SBLanguageRuntime""" _lldb.SBLanguageRuntime_swiginit(self, _lldb.new_SBLanguageRuntime()) __swig_destroy__ = _lldb.delete_SBLanguageRuntime # Register SBLanguageRuntime in _lldb: _lldb.SBLanguageRuntime_swigregister(SBLanguageRuntime) def SBLanguageRuntime_GetLanguageTypeFromString(string): r"""SBLanguageRuntime_GetLanguageTypeFromString(char const * string) -> lldb::LanguageType""" return _lldb.SBLanguageRuntime_GetLanguageTypeFromString(string) def SBLanguageRuntime_GetNameForLanguageType(language): r"""SBLanguageRuntime_GetNameForLanguageType(lldb::LanguageType language) -> char const *""" return _lldb.SBLanguageRuntime_GetNameForLanguageType(language) class SBLaunchInfo(object): r"""Describes how a target or program should be launched.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, argv): r"""__init__(SBLaunchInfo self, char const ** argv) -> SBLaunchInfo""" _lldb.SBLaunchInfo_swiginit(self, _lldb.new_SBLaunchInfo(argv)) def GetProcessID(self): r"""GetProcessID(SBLaunchInfo self) -> lldb::pid_t""" return _lldb.SBLaunchInfo_GetProcessID(self) def GetUserID(self): r"""GetUserID(SBLaunchInfo self) -> uint32_t""" return _lldb.SBLaunchInfo_GetUserID(self) def GetGroupID(self): r"""GetGroupID(SBLaunchInfo self) -> uint32_t""" return _lldb.SBLaunchInfo_GetGroupID(self) def UserIDIsValid(self): r"""UserIDIsValid(SBLaunchInfo self) -> bool""" return _lldb.SBLaunchInfo_UserIDIsValid(self) def GroupIDIsValid(self): r"""GroupIDIsValid(SBLaunchInfo self) -> bool""" return _lldb.SBLaunchInfo_GroupIDIsValid(self) def SetUserID(self, uid): r"""SetUserID(SBLaunchInfo self, uint32_t uid)""" return _lldb.SBLaunchInfo_SetUserID(self, uid) def SetGroupID(self, gid): r"""SetGroupID(SBLaunchInfo self, uint32_t gid)""" return _lldb.SBLaunchInfo_SetGroupID(self, gid) def GetExecutableFile(self): r"""GetExecutableFile(SBLaunchInfo self) -> SBFileSpec""" return _lldb.SBLaunchInfo_GetExecutableFile(self) def SetExecutableFile(self, exe_file, add_as_first_arg): r"""SetExecutableFile(SBLaunchInfo self, SBFileSpec exe_file, bool add_as_first_arg)""" return _lldb.SBLaunchInfo_SetExecutableFile(self, exe_file, add_as_first_arg) def GetListener(self): r"""GetListener(SBLaunchInfo self) -> SBListener""" return _lldb.SBLaunchInfo_GetListener(self) def SetListener(self, listener): r"""SetListener(SBLaunchInfo self, SBListener listener)""" return _lldb.SBLaunchInfo_SetListener(self, listener) def GetNumArguments(self): r"""GetNumArguments(SBLaunchInfo self) -> uint32_t""" return _lldb.SBLaunchInfo_GetNumArguments(self) def GetArgumentAtIndex(self, idx): r"""GetArgumentAtIndex(SBLaunchInfo self, uint32_t idx) -> char const *""" return _lldb.SBLaunchInfo_GetArgumentAtIndex(self, idx) def SetArguments(self, argv, append): r"""SetArguments(SBLaunchInfo self, char const ** argv, bool append)""" return _lldb.SBLaunchInfo_SetArguments(self, argv, append) def GetNumEnvironmentEntries(self): r"""GetNumEnvironmentEntries(SBLaunchInfo self) -> uint32_t""" return _lldb.SBLaunchInfo_GetNumEnvironmentEntries(self) def GetEnvironmentEntryAtIndex(self, idx): r"""GetEnvironmentEntryAtIndex(SBLaunchInfo self, uint32_t idx) -> char const *""" return _lldb.SBLaunchInfo_GetEnvironmentEntryAtIndex(self, idx) def SetEnvironmentEntries(self, envp, append): r"""SetEnvironmentEntries(SBLaunchInfo self, char const ** envp, bool append)""" return _lldb.SBLaunchInfo_SetEnvironmentEntries(self, envp, append) def SetEnvironment(self, env, append): r"""SetEnvironment(SBLaunchInfo self, SBEnvironment env, bool append)""" return _lldb.SBLaunchInfo_SetEnvironment(self, env, append) def GetEnvironment(self): r"""GetEnvironment(SBLaunchInfo self) -> SBEnvironment""" return _lldb.SBLaunchInfo_GetEnvironment(self) def Clear(self): r"""Clear(SBLaunchInfo self)""" return _lldb.SBLaunchInfo_Clear(self) def GetWorkingDirectory(self): r"""GetWorkingDirectory(SBLaunchInfo self) -> char const *""" return _lldb.SBLaunchInfo_GetWorkingDirectory(self) def SetWorkingDirectory(self, working_dir): r"""SetWorkingDirectory(SBLaunchInfo self, char const * working_dir)""" return _lldb.SBLaunchInfo_SetWorkingDirectory(self, working_dir) def GetLaunchFlags(self): r"""GetLaunchFlags(SBLaunchInfo self) -> uint32_t""" return _lldb.SBLaunchInfo_GetLaunchFlags(self) def SetLaunchFlags(self, flags): r"""SetLaunchFlags(SBLaunchInfo self, uint32_t flags)""" return _lldb.SBLaunchInfo_SetLaunchFlags(self, flags) def GetProcessPluginName(self): r"""GetProcessPluginName(SBLaunchInfo self) -> char const *""" return _lldb.SBLaunchInfo_GetProcessPluginName(self) def SetProcessPluginName(self, plugin_name): r"""SetProcessPluginName(SBLaunchInfo self, char const * plugin_name)""" return _lldb.SBLaunchInfo_SetProcessPluginName(self, plugin_name) def GetShell(self): r"""GetShell(SBLaunchInfo self) -> char const *""" return _lldb.SBLaunchInfo_GetShell(self) def SetShell(self, path): r"""SetShell(SBLaunchInfo self, char const * path)""" return _lldb.SBLaunchInfo_SetShell(self, path) def GetShellExpandArguments(self): r"""GetShellExpandArguments(SBLaunchInfo self) -> bool""" return _lldb.SBLaunchInfo_GetShellExpandArguments(self) def SetShellExpandArguments(self, expand): r"""SetShellExpandArguments(SBLaunchInfo self, bool expand)""" return _lldb.SBLaunchInfo_SetShellExpandArguments(self, expand) def GetResumeCount(self): r"""GetResumeCount(SBLaunchInfo self) -> uint32_t""" return _lldb.SBLaunchInfo_GetResumeCount(self) def SetResumeCount(self, c): r"""SetResumeCount(SBLaunchInfo self, uint32_t c)""" return _lldb.SBLaunchInfo_SetResumeCount(self, c) def AddCloseFileAction(self, fd): r"""AddCloseFileAction(SBLaunchInfo self, int fd) -> bool""" return _lldb.SBLaunchInfo_AddCloseFileAction(self, fd) def AddDuplicateFileAction(self, fd, dup_fd): r"""AddDuplicateFileAction(SBLaunchInfo self, int fd, int dup_fd) -> bool""" return _lldb.SBLaunchInfo_AddDuplicateFileAction(self, fd, dup_fd) def AddOpenFileAction(self, fd, path, read, write): r"""AddOpenFileAction(SBLaunchInfo self, int fd, char const * path, bool read, bool write) -> bool""" return _lldb.SBLaunchInfo_AddOpenFileAction(self, fd, path, read, write) def AddSuppressFileAction(self, fd, read, write): r"""AddSuppressFileAction(SBLaunchInfo self, int fd, bool read, bool write) -> bool""" return _lldb.SBLaunchInfo_AddSuppressFileAction(self, fd, read, write) def SetLaunchEventData(self, data): r"""SetLaunchEventData(SBLaunchInfo self, char const * data)""" return _lldb.SBLaunchInfo_SetLaunchEventData(self, data) def GetLaunchEventData(self): r"""GetLaunchEventData(SBLaunchInfo self) -> char const *""" return _lldb.SBLaunchInfo_GetLaunchEventData(self) def GetDetachOnError(self): r"""GetDetachOnError(SBLaunchInfo self) -> bool""" return _lldb.SBLaunchInfo_GetDetachOnError(self) def SetDetachOnError(self, enable): r"""SetDetachOnError(SBLaunchInfo self, bool enable)""" return _lldb.SBLaunchInfo_SetDetachOnError(self, enable) __swig_destroy__ = _lldb.delete_SBLaunchInfo # Register SBLaunchInfo in _lldb: _lldb.SBLaunchInfo_swigregister(SBLaunchInfo) class SBLineEntry(object): r""" Specifies an association with a contiguous range of instructions and a source file location. :py:class:`SBCompileUnit` contains SBLineEntry(s). For example, :: for lineEntry in compileUnit: print('line entry: %s:%d' % (str(lineEntry.GetFileSpec()), lineEntry.GetLine())) print('start addr: %s' % str(lineEntry.GetStartAddress())) print('end addr: %s' % str(lineEntry.GetEndAddress())) produces: :: line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:20 start addr: a.out[0x100000d98] end addr: a.out[0x100000da3] line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:21 start addr: a.out[0x100000da3] end addr: a.out[0x100000da9] line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:22 start addr: a.out[0x100000da9] end addr: a.out[0x100000db6] line entry: /Volumes/data/lldb/svn/trunk/test/python_api/symbol-context/main.c:23 start addr: a.out[0x100000db6] end addr: a.out[0x100000dbc] ... See also :py:class:`SBCompileUnit` . """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBLineEntry self) -> SBLineEntry __init__(SBLineEntry self, SBLineEntry rhs) -> SBLineEntry """ _lldb.SBLineEntry_swiginit(self, _lldb.new_SBLineEntry(*args)) __swig_destroy__ = _lldb.delete_SBLineEntry def GetStartAddress(self): r"""GetStartAddress(SBLineEntry self) -> SBAddress""" return _lldb.SBLineEntry_GetStartAddress(self) def GetEndAddress(self): r"""GetEndAddress(SBLineEntry self) -> SBAddress""" return _lldb.SBLineEntry_GetEndAddress(self) def IsValid(self): r"""IsValid(SBLineEntry self) -> bool""" return _lldb.SBLineEntry_IsValid(self) def __nonzero__(self): return _lldb.SBLineEntry___nonzero__(self) __bool__ = __nonzero__ def GetFileSpec(self): r"""GetFileSpec(SBLineEntry self) -> SBFileSpec""" return _lldb.SBLineEntry_GetFileSpec(self) def GetLine(self): r"""GetLine(SBLineEntry self) -> uint32_t""" return _lldb.SBLineEntry_GetLine(self) def GetColumn(self): r"""GetColumn(SBLineEntry self) -> uint32_t""" return _lldb.SBLineEntry_GetColumn(self) def GetDescription(self, description): r"""GetDescription(SBLineEntry self, SBStream description) -> bool""" return _lldb.SBLineEntry_GetDescription(self, description) def SetFileSpec(self, filespec): r"""SetFileSpec(SBLineEntry self, SBFileSpec filespec)""" return _lldb.SBLineEntry_SetFileSpec(self, filespec) def SetLine(self, line): r"""SetLine(SBLineEntry self, uint32_t line)""" return _lldb.SBLineEntry_SetLine(self, line) def SetColumn(self, column): r"""SetColumn(SBLineEntry self, uint32_t column)""" return _lldb.SBLineEntry_SetColumn(self, column) def __eq__(self, rhs): r"""__eq__(SBLineEntry self, SBLineEntry rhs) -> bool""" return _lldb.SBLineEntry___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBLineEntry self, SBLineEntry rhs) -> bool""" return _lldb.SBLineEntry___ne__(self, rhs) def __str__(self): r"""__str__(SBLineEntry self) -> std::string""" return _lldb.SBLineEntry___str__(self) file = property(GetFileSpec, None, doc='''A read only property that returns an lldb object that represents the file (lldb.SBFileSpec) for this line entry.''') line = property(GetLine, None, doc='''A read only property that returns the 1 based line number for this line entry, a return value of zero indicates that no line information is available.''') column = property(GetColumn, None, doc='''A read only property that returns the 1 based column number for this line entry, a return value of zero indicates that no column information is available.''') addr = property(GetStartAddress, None, doc='''A read only property that returns an lldb object that represents the start address (lldb.SBAddress) for this line entry.''') end_addr = property(GetEndAddress, None, doc='''A read only property that returns an lldb object that represents the end address (lldb.SBAddress) for this line entry.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBLineEntry in _lldb: _lldb.SBLineEntry_swigregister(SBLineEntry) class SBListener(object): r""" API clients can register its own listener to debugger events. See also :py:class:`SBEvent` for example usage of creating and adding a listener. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBListener self) -> SBListener __init__(SBListener self, char const * name) -> SBListener __init__(SBListener self, SBListener rhs) -> SBListener """ _lldb.SBListener_swiginit(self, _lldb.new_SBListener(*args)) __swig_destroy__ = _lldb.delete_SBListener def AddEvent(self, event): r"""AddEvent(SBListener self, SBEvent event)""" return _lldb.SBListener_AddEvent(self, event) def Clear(self): r"""Clear(SBListener self)""" return _lldb.SBListener_Clear(self) def IsValid(self): r"""IsValid(SBListener self) -> bool""" return _lldb.SBListener_IsValid(self) def __nonzero__(self): return _lldb.SBListener___nonzero__(self) __bool__ = __nonzero__ def StartListeningForEventClass(self, debugger, broadcaster_class, event_mask): r"""StartListeningForEventClass(SBListener self, SBDebugger debugger, char const * broadcaster_class, uint32_t event_mask) -> uint32_t""" return _lldb.SBListener_StartListeningForEventClass(self, debugger, broadcaster_class, event_mask) def StopListeningForEventClass(self, debugger, broadcaster_class, event_mask): r"""StopListeningForEventClass(SBListener self, SBDebugger debugger, char const * broadcaster_class, uint32_t event_mask) -> uint32_t""" return _lldb.SBListener_StopListeningForEventClass(self, debugger, broadcaster_class, event_mask) def StartListeningForEvents(self, broadcaster, event_mask): r"""StartListeningForEvents(SBListener self, SBBroadcaster broadcaster, uint32_t event_mask) -> uint32_t""" return _lldb.SBListener_StartListeningForEvents(self, broadcaster, event_mask) def StopListeningForEvents(self, broadcaster, event_mask): r"""StopListeningForEvents(SBListener self, SBBroadcaster broadcaster, uint32_t event_mask) -> bool""" return _lldb.SBListener_StopListeningForEvents(self, broadcaster, event_mask) def WaitForEvent(self, num_seconds, event): r"""WaitForEvent(SBListener self, uint32_t num_seconds, SBEvent event) -> bool""" return _lldb.SBListener_WaitForEvent(self, num_seconds, event) def WaitForEventForBroadcaster(self, num_seconds, broadcaster, sb_event): r"""WaitForEventForBroadcaster(SBListener self, uint32_t num_seconds, SBBroadcaster broadcaster, SBEvent sb_event) -> bool""" return _lldb.SBListener_WaitForEventForBroadcaster(self, num_seconds, broadcaster, sb_event) def WaitForEventForBroadcasterWithType(self, num_seconds, broadcaster, event_type_mask, sb_event): r"""WaitForEventForBroadcasterWithType(SBListener self, uint32_t num_seconds, SBBroadcaster broadcaster, uint32_t event_type_mask, SBEvent sb_event) -> bool""" return _lldb.SBListener_WaitForEventForBroadcasterWithType(self, num_seconds, broadcaster, event_type_mask, sb_event) def PeekAtNextEvent(self, sb_event): r"""PeekAtNextEvent(SBListener self, SBEvent sb_event) -> bool""" return _lldb.SBListener_PeekAtNextEvent(self, sb_event) def PeekAtNextEventForBroadcaster(self, broadcaster, sb_event): r"""PeekAtNextEventForBroadcaster(SBListener self, SBBroadcaster broadcaster, SBEvent sb_event) -> bool""" return _lldb.SBListener_PeekAtNextEventForBroadcaster(self, broadcaster, sb_event) def PeekAtNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event): r"""PeekAtNextEventForBroadcasterWithType(SBListener self, SBBroadcaster broadcaster, uint32_t event_type_mask, SBEvent sb_event) -> bool""" return _lldb.SBListener_PeekAtNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event) def GetNextEvent(self, sb_event): r"""GetNextEvent(SBListener self, SBEvent sb_event) -> bool""" return _lldb.SBListener_GetNextEvent(self, sb_event) def GetNextEventForBroadcaster(self, broadcaster, sb_event): r"""GetNextEventForBroadcaster(SBListener self, SBBroadcaster broadcaster, SBEvent sb_event) -> bool""" return _lldb.SBListener_GetNextEventForBroadcaster(self, broadcaster, sb_event) def GetNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event): r"""GetNextEventForBroadcasterWithType(SBListener self, SBBroadcaster broadcaster, uint32_t event_type_mask, SBEvent sb_event) -> bool""" return _lldb.SBListener_GetNextEventForBroadcasterWithType(self, broadcaster, event_type_mask, sb_event) def HandleBroadcastEvent(self, event): r"""HandleBroadcastEvent(SBListener self, SBEvent event) -> bool""" return _lldb.SBListener_HandleBroadcastEvent(self, event) # Register SBListener in _lldb: _lldb.SBListener_swigregister(SBListener) class SBMemoryRegionInfo(object): r"""API clients can get information about memory regions in processes.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBMemoryRegionInfo self) -> SBMemoryRegionInfo __init__(SBMemoryRegionInfo self, SBMemoryRegionInfo rhs) -> SBMemoryRegionInfo """ _lldb.SBMemoryRegionInfo_swiginit(self, _lldb.new_SBMemoryRegionInfo(*args)) __swig_destroy__ = _lldb.delete_SBMemoryRegionInfo def Clear(self): r"""Clear(SBMemoryRegionInfo self)""" return _lldb.SBMemoryRegionInfo_Clear(self) def GetRegionBase(self): r"""GetRegionBase(SBMemoryRegionInfo self) -> lldb::addr_t""" return _lldb.SBMemoryRegionInfo_GetRegionBase(self) def GetRegionEnd(self): r"""GetRegionEnd(SBMemoryRegionInfo self) -> lldb::addr_t""" return _lldb.SBMemoryRegionInfo_GetRegionEnd(self) def IsReadable(self): r"""IsReadable(SBMemoryRegionInfo self) -> bool""" return _lldb.SBMemoryRegionInfo_IsReadable(self) def IsWritable(self): r"""IsWritable(SBMemoryRegionInfo self) -> bool""" return _lldb.SBMemoryRegionInfo_IsWritable(self) def IsExecutable(self): r"""IsExecutable(SBMemoryRegionInfo self) -> bool""" return _lldb.SBMemoryRegionInfo_IsExecutable(self) def IsMapped(self): r"""IsMapped(SBMemoryRegionInfo self) -> bool""" return _lldb.SBMemoryRegionInfo_IsMapped(self) def GetName(self): r"""GetName(SBMemoryRegionInfo self) -> char const *""" return _lldb.SBMemoryRegionInfo_GetName(self) def __eq__(self, rhs): r"""__eq__(SBMemoryRegionInfo self, SBMemoryRegionInfo rhs) -> bool""" return _lldb.SBMemoryRegionInfo___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBMemoryRegionInfo self, SBMemoryRegionInfo rhs) -> bool""" return _lldb.SBMemoryRegionInfo___ne__(self, rhs) def GetDescription(self, description): r"""GetDescription(SBMemoryRegionInfo self, SBStream description) -> bool""" return _lldb.SBMemoryRegionInfo_GetDescription(self, description) def __str__(self): r"""__str__(SBMemoryRegionInfo self) -> std::string""" return _lldb.SBMemoryRegionInfo___str__(self) # Register SBMemoryRegionInfo in _lldb: _lldb.SBMemoryRegionInfo_swigregister(SBMemoryRegionInfo) class SBMemoryRegionInfoList(object): r"""Represents a list of :py:class:`SBMemoryRegionInfo`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBMemoryRegionInfoList self) -> SBMemoryRegionInfoList __init__(SBMemoryRegionInfoList self, SBMemoryRegionInfoList rhs) -> SBMemoryRegionInfoList """ _lldb.SBMemoryRegionInfoList_swiginit(self, _lldb.new_SBMemoryRegionInfoList(*args)) __swig_destroy__ = _lldb.delete_SBMemoryRegionInfoList def GetSize(self): r"""GetSize(SBMemoryRegionInfoList self) -> uint32_t""" return _lldb.SBMemoryRegionInfoList_GetSize(self) def GetMemoryRegionAtIndex(self, idx, region_info): r"""GetMemoryRegionAtIndex(SBMemoryRegionInfoList self, uint32_t idx, SBMemoryRegionInfo region_info) -> bool""" return _lldb.SBMemoryRegionInfoList_GetMemoryRegionAtIndex(self, idx, region_info) def Append(self, *args): r""" Append(SBMemoryRegionInfoList self, SBMemoryRegionInfo region) Append(SBMemoryRegionInfoList self, SBMemoryRegionInfoList region_list) """ return _lldb.SBMemoryRegionInfoList_Append(self, *args) def Clear(self): r"""Clear(SBMemoryRegionInfoList self)""" return _lldb.SBMemoryRegionInfoList_Clear(self) # Register SBMemoryRegionInfoList in _lldb: _lldb.SBMemoryRegionInfoList_swigregister(SBMemoryRegionInfoList) # ================================== # Helper function for SBModule class # ================================== def in_range(symbol, section): """Test whether a symbol is within the range of a section.""" symSA = symbol.GetStartAddress().GetFileAddress() symEA = symbol.GetEndAddress().GetFileAddress() secSA = section.GetFileAddress() secEA = secSA + section.GetByteSize() if symEA != LLDB_INVALID_ADDRESS: if secSA <= symSA and symEA <= secEA: return True else: return False else: if secSA <= symSA and symSA < secEA: return True else: return False class SBModule(object): r""" Represents an executable image and its associated object and symbol files. The module is designed to be able to select a single slice of an executable image as it would appear on disk and during program execution. You can retrieve SBModule from :py:class:`SBSymbolContext` , which in turn is available from SBFrame. SBModule supports symbol iteration, for example, :: for symbol in module: name = symbol.GetName() saddr = symbol.GetStartAddress() eaddr = symbol.GetEndAddress() and rich comparison methods which allow the API program to use, :: if thisModule == thatModule: print('This module is the same as that module') to test module equality. A module also contains object file sections, namely :py:class:`SBSection` . SBModule supports section iteration through section_iter(), for example, :: print('Number of sections: %d' % module.GetNumSections()) for sec in module.section_iter(): print(sec) And to iterate the symbols within a SBSection, use symbol_in_section_iter(), :: # Iterates the text section and prints each symbols within each sub-section. for subsec in text_sec: print(INDENT + repr(subsec)) for sym in exe_module.symbol_in_section_iter(subsec): print(INDENT2 + repr(sym)) print(INDENT2 + 'symbol type: %s' % symbol_type_to_str(sym.GetType())) produces this following output: :: [0x0000000100001780-0x0000000100001d5c) a.out.__TEXT.__text id = {0x00000004}, name = 'mask_access(MaskAction, unsigned int)', range = [0x00000001000017c0-0x0000000100001870) symbol type: code id = {0x00000008}, name = 'thread_func(void*)', range = [0x0000000100001870-0x00000001000019b0) symbol type: code id = {0x0000000c}, name = 'main', range = [0x00000001000019b0-0x0000000100001d5c) symbol type: code id = {0x00000023}, name = 'start', address = 0x0000000100001780 symbol type: code [0x0000000100001d5c-0x0000000100001da4) a.out.__TEXT.__stubs id = {0x00000024}, name = '__stack_chk_fail', range = [0x0000000100001d5c-0x0000000100001d62) symbol type: trampoline id = {0x00000028}, name = 'exit', range = [0x0000000100001d62-0x0000000100001d68) symbol type: trampoline id = {0x00000029}, name = 'fflush', range = [0x0000000100001d68-0x0000000100001d6e) symbol type: trampoline id = {0x0000002a}, name = 'fgets', range = [0x0000000100001d6e-0x0000000100001d74) symbol type: trampoline id = {0x0000002b}, name = 'printf', range = [0x0000000100001d74-0x0000000100001d7a) symbol type: trampoline id = {0x0000002c}, name = 'pthread_create', range = [0x0000000100001d7a-0x0000000100001d80) symbol type: trampoline id = {0x0000002d}, name = 'pthread_join', range = [0x0000000100001d80-0x0000000100001d86) symbol type: trampoline id = {0x0000002e}, name = 'pthread_mutex_lock', range = [0x0000000100001d86-0x0000000100001d8c) symbol type: trampoline id = {0x0000002f}, name = 'pthread_mutex_unlock', range = [0x0000000100001d8c-0x0000000100001d92) symbol type: trampoline id = {0x00000030}, name = 'rand', range = [0x0000000100001d92-0x0000000100001d98) symbol type: trampoline id = {0x00000031}, name = 'strtoul', range = [0x0000000100001d98-0x0000000100001d9e) symbol type: trampoline id = {0x00000032}, name = 'usleep', range = [0x0000000100001d9e-0x0000000100001da4) symbol type: trampoline [0x0000000100001da4-0x0000000100001e2c) a.out.__TEXT.__stub_helper [0x0000000100001e2c-0x0000000100001f10) a.out.__TEXT.__cstring [0x0000000100001f10-0x0000000100001f68) a.out.__TEXT.__unwind_info [0x0000000100001f68-0x0000000100001ff8) a.out.__TEXT.__eh_frame """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBModule self) -> SBModule __init__(SBModule self, SBModule rhs) -> SBModule __init__(SBModule self, SBModuleSpec module_spec) -> SBModule __init__(SBModule self, SBProcess process, lldb::addr_t header_addr) -> SBModule """ _lldb.SBModule_swiginit(self, _lldb.new_SBModule(*args)) __swig_destroy__ = _lldb.delete_SBModule def IsValid(self): r"""IsValid(SBModule self) -> bool""" return _lldb.SBModule_IsValid(self) def __nonzero__(self): return _lldb.SBModule___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBModule self)""" return _lldb.SBModule_Clear(self) def GetFileSpec(self): r""" GetFileSpec(SBModule self) -> SBFileSpec Get const accessor for the module file specification. This function returns the file for the module on the host system that is running LLDB. This can differ from the path on the platform since we might be doing remote debugging. @return A const reference to the file specification object. """ return _lldb.SBModule_GetFileSpec(self) def GetPlatformFileSpec(self): r""" GetPlatformFileSpec(SBModule self) -> SBFileSpec Get accessor for the module platform file specification. Platform file refers to the path of the module as it is known on the remote system on which it is being debugged. For local debugging this is always the same as Module::GetFileSpec(). But remote debugging might mention a file '/usr/lib/liba.dylib' which might be locally downloaded and cached. In this case the platform file could be something like: '/tmp/lldb/platform-cache/remote.host.computer/usr/lib/liba.dylib' The file could also be cached in a local developer kit directory. @return A const reference to the file specification object. """ return _lldb.SBModule_GetPlatformFileSpec(self) def SetPlatformFileSpec(self, platform_file): r"""SetPlatformFileSpec(SBModule self, SBFileSpec platform_file) -> bool""" return _lldb.SBModule_SetPlatformFileSpec(self, platform_file) def GetRemoteInstallFileSpec(self): r"""GetRemoteInstallFileSpec(SBModule self) -> SBFileSpec""" return _lldb.SBModule_GetRemoteInstallFileSpec(self) def SetRemoteInstallFileSpec(self, file): r"""SetRemoteInstallFileSpec(SBModule self, SBFileSpec file) -> bool""" return _lldb.SBModule_SetRemoteInstallFileSpec(self, file) def GetUUIDString(self): r""" GetUUIDString(SBModule self) -> char const * Returns the UUID of the module as a Python string. """ return _lldb.SBModule_GetUUIDString(self) def __eq__(self, rhs): r"""__eq__(SBModule self, SBModule rhs) -> bool""" return _lldb.SBModule___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBModule self, SBModule rhs) -> bool""" return _lldb.SBModule___ne__(self, rhs) def FindSection(self, sect_name): r"""FindSection(SBModule self, char const * sect_name) -> SBSection""" return _lldb.SBModule_FindSection(self, sect_name) def ResolveFileAddress(self, vm_addr): r"""ResolveFileAddress(SBModule self, lldb::addr_t vm_addr) -> SBAddress""" return _lldb.SBModule_ResolveFileAddress(self, vm_addr) def ResolveSymbolContextForAddress(self, addr, resolve_scope): r"""ResolveSymbolContextForAddress(SBModule self, SBAddress addr, uint32_t resolve_scope) -> SBSymbolContext""" return _lldb.SBModule_ResolveSymbolContextForAddress(self, addr, resolve_scope) def GetDescription(self, description): r"""GetDescription(SBModule self, SBStream description) -> bool""" return _lldb.SBModule_GetDescription(self, description) def GetNumCompileUnits(self): r"""GetNumCompileUnits(SBModule self) -> uint32_t""" return _lldb.SBModule_GetNumCompileUnits(self) def GetCompileUnitAtIndex(self, arg2): r"""GetCompileUnitAtIndex(SBModule self, uint32_t arg2) -> SBCompileUnit""" return _lldb.SBModule_GetCompileUnitAtIndex(self, arg2) def FindCompileUnits(self, sb_file_spec): r""" FindCompileUnits(SBModule self, SBFileSpec sb_file_spec) -> SBSymbolContextList Find compile units related to this module and passed source file. @param[in] sb_file_spec A :py:class:`SBFileSpec` object that contains source file specification. @return A :py:class:`SBSymbolContextList` that gets filled in with all of the symbol contexts for all the matches. """ return _lldb.SBModule_FindCompileUnits(self, sb_file_spec) def GetNumSymbols(self): r"""GetNumSymbols(SBModule self) -> size_t""" return _lldb.SBModule_GetNumSymbols(self) def GetSymbolAtIndex(self, idx): r"""GetSymbolAtIndex(SBModule self, size_t idx) -> SBSymbol""" return _lldb.SBModule_GetSymbolAtIndex(self, idx) def FindSymbol(self, *args): r"""FindSymbol(SBModule self, char const * name, lldb::SymbolType type=eSymbolTypeAny) -> SBSymbol""" return _lldb.SBModule_FindSymbol(self, *args) def FindSymbols(self, *args): r"""FindSymbols(SBModule self, char const * name, lldb::SymbolType type=eSymbolTypeAny) -> SBSymbolContextList""" return _lldb.SBModule_FindSymbols(self, *args) def GetNumSections(self): r"""GetNumSections(SBModule self) -> size_t""" return _lldb.SBModule_GetNumSections(self) def GetSectionAtIndex(self, idx): r"""GetSectionAtIndex(SBModule self, size_t idx) -> SBSection""" return _lldb.SBModule_GetSectionAtIndex(self, idx) def FindFunctions(self, *args): r""" FindFunctions(SBModule self, char const * name, uint32_t name_type_mask=eFunctionNameTypeAny) -> SBSymbolContextList Find functions by name. @param[in] name The name of the function we are looking for. @param[in] name_type_mask A logical OR of one or more FunctionNameType enum bits that indicate what kind of names should be used when doing the lookup. Bits include fully qualified names, base names, C++ methods, or ObjC selectors. See FunctionNameType for more details. @return A symbol context list that gets filled in with all of the matches. """ return _lldb.SBModule_FindFunctions(self, *args) def FindFirstType(self, name): r"""FindFirstType(SBModule self, char const * name) -> SBType""" return _lldb.SBModule_FindFirstType(self, name) def FindTypes(self, type): r"""FindTypes(SBModule self, char const * type) -> SBTypeList""" return _lldb.SBModule_FindTypes(self, type) def GetTypeByID(self, uid): r"""GetTypeByID(SBModule self, lldb::user_id_t uid) -> SBType""" return _lldb.SBModule_GetTypeByID(self, uid) def GetBasicType(self, type): r"""GetBasicType(SBModule self, lldb::BasicType type) -> SBType""" return _lldb.SBModule_GetBasicType(self, type) def GetTypes(self, *args): r""" GetTypes(SBModule self, uint32_t type_mask=eTypeClassAny) -> SBTypeList Get all types matching type_mask from debug info in this module. @param[in] type_mask A bitfield that consists of one or more bits logically OR'ed together from the lldb::TypeClass enumeration. This allows you to request only structure types, or only class, struct and union types. Passing in lldb::eTypeClassAny will return all types found in the debug information for this module. @return A list of types in this module that match type_mask """ return _lldb.SBModule_GetTypes(self, *args) def FindGlobalVariables(self, target, name, max_matches): r""" FindGlobalVariables(SBModule self, SBTarget target, char const * name, uint32_t max_matches) -> SBValueList Find global and static variables by name. @param[in] target A valid SBTarget instance representing the debuggee. @param[in] name The name of the global or static variable we are looking for. @param[in] max_matches Allow the number of matches to be limited to max_matches. @return A list of matched variables in an SBValueList. """ return _lldb.SBModule_FindGlobalVariables(self, target, name, max_matches) def FindFirstGlobalVariable(self, target, name): r""" FindFirstGlobalVariable(SBModule self, SBTarget target, char const * name) -> SBValue Find the first global (or static) variable by name. @param[in] target A valid SBTarget instance representing the debuggee. @param[in] name The name of the global or static variable we are looking for. @return An SBValue that gets filled in with the found variable (if any). """ return _lldb.SBModule_FindFirstGlobalVariable(self, target, name) def GetByteOrder(self): r"""GetByteOrder(SBModule self) -> lldb::ByteOrder""" return _lldb.SBModule_GetByteOrder(self) def GetAddressByteSize(self): r"""GetAddressByteSize(SBModule self) -> uint32_t""" return _lldb.SBModule_GetAddressByteSize(self) def GetTriple(self): r"""GetTriple(SBModule self) -> char const *""" return _lldb.SBModule_GetTriple(self) def GetVersion(self): r"""GetVersion(SBModule self) -> uint32_t""" return _lldb.SBModule_GetVersion(self) def GetSymbolFileSpec(self): r"""GetSymbolFileSpec(SBModule self) -> SBFileSpec""" return _lldb.SBModule_GetSymbolFileSpec(self) def GetObjectFileHeaderAddress(self): r"""GetObjectFileHeaderAddress(SBModule self) -> SBAddress""" return _lldb.SBModule_GetObjectFileHeaderAddress(self) def IsTypeSystemCompatible(self, language): r"""IsTypeSystemCompatible(SBModule self, lldb::LanguageType language) -> SBError""" return _lldb.SBModule_IsTypeSystemCompatible(self, language) def GetObjectFileEntryPointAddress(self): r"""GetObjectFileEntryPointAddress(SBModule self) -> SBAddress""" return _lldb.SBModule_GetObjectFileEntryPointAddress(self) @staticmethod def GetNumberAllocatedModules(): r""" GetNumberAllocatedModules() -> uint32_t Returns the number of modules in the module cache. This is an implementation detail exposed for testing and should not be relied upon. @return The number of modules in the module cache. """ return _lldb.SBModule_GetNumberAllocatedModules() @staticmethod def GarbageCollectAllocatedModules(): r""" GarbageCollectAllocatedModules() Removes all modules which are no longer needed by any part of LLDB from the module cache. This is an implementation detail exposed for testing and should not be relied upon. Use SBDebugger::MemoryPressureDetected instead to reduce LLDB's memory consumption during execution. """ return _lldb.SBModule_GarbageCollectAllocatedModules() def __str__(self): r"""__str__(SBModule self) -> std::string""" return _lldb.SBModule___str__(self) def __len__(self): '''Return the number of symbols in a lldb.SBModule object.''' return self.GetNumSymbols() def __iter__(self): '''Iterate over all symbols in a lldb.SBModule object.''' return lldb_iter(self, 'GetNumSymbols', 'GetSymbolAtIndex') def section_iter(self): '''Iterate over all sections in a lldb.SBModule object.''' return lldb_iter(self, 'GetNumSections', 'GetSectionAtIndex') def compile_unit_iter(self): '''Iterate over all compile units in a lldb.SBModule object.''' return lldb_iter(self, 'GetNumCompileUnits', 'GetCompileUnitAtIndex') def symbol_in_section_iter(self, section): '''Given a module and its contained section, returns an iterator on the symbols within the section.''' for sym in self: if in_range(sym, section): yield sym class symbols_access(object): re_compile_type = type(re.compile('.')) '''A helper object that will lazily hand out lldb.SBSymbol objects for a module when supplied an index, name, or regular expression.''' def __init__(self, sbmodule): self.sbmodule = sbmodule def __len__(self): if self.sbmodule: return int(self.sbmodule.GetNumSymbols()) return 0 def __getitem__(self, key): count = len(self) if type(key) is int: if key < count: return self.sbmodule.GetSymbolAtIndex(key) elif type(key) is str: matches = [] sc_list = self.sbmodule.FindSymbols(key) for sc in sc_list: symbol = sc.symbol if symbol: matches.append(symbol) return matches elif isinstance(key, self.re_compile_type): matches = [] for idx in range(count): symbol = self.sbmodule.GetSymbolAtIndex(idx) added = False name = symbol.name if name: re_match = key.search(name) if re_match: matches.append(symbol) added = True if not added: mangled = symbol.mangled if mangled: re_match = key.search(mangled) if re_match: matches.append(symbol) return matches else: print("error: unsupported item type: %s" % type(key)) return None def get_symbols_access_object(self): '''An accessor function that returns a symbols_access() object which allows lazy symbol access from a lldb.SBModule object.''' return self.symbols_access (self) def get_compile_units_access_object (self): '''An accessor function that returns a compile_units_access() object which allows lazy compile unit access from a lldb.SBModule object.''' return self.compile_units_access (self) def get_symbols_array(self): '''An accessor function that returns a list() that contains all symbols in a lldb.SBModule object.''' symbols = [] for idx in range(self.num_symbols): symbols.append(self.GetSymbolAtIndex(idx)) return symbols class sections_access(object): re_compile_type = type(re.compile('.')) '''A helper object that will lazily hand out lldb.SBSection objects for a module when supplied an index, name, or regular expression.''' def __init__(self, sbmodule): self.sbmodule = sbmodule def __len__(self): if self.sbmodule: return int(self.sbmodule.GetNumSections()) return 0 def __getitem__(self, key): count = len(self) if type(key) is int: if key < count: return self.sbmodule.GetSectionAtIndex(key) elif type(key) is str: for idx in range(count): section = self.sbmodule.GetSectionAtIndex(idx) if section.name == key: return section elif isinstance(key, self.re_compile_type): matches = [] for idx in range(count): section = self.sbmodule.GetSectionAtIndex(idx) name = section.name if name: re_match = key.search(name) if re_match: matches.append(section) return matches else: print("error: unsupported item type: %s" % type(key)) return None class compile_units_access(object): re_compile_type = type(re.compile('.')) '''A helper object that will lazily hand out lldb.SBCompileUnit objects for a module when supplied an index, full or partial path, or regular expression.''' def __init__(self, sbmodule): self.sbmodule = sbmodule def __len__(self): if self.sbmodule: return int(self.sbmodule.GetNumCompileUnits()) return 0 def __getitem__(self, key): count = len(self) if type(key) is int: if key < count: return self.sbmodule.GetCompileUnitAtIndex(key) elif type(key) is str: is_full_path = key[0] == '/' for idx in range(count): comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx) if is_full_path: if comp_unit.file.fullpath == key: return comp_unit else: if comp_unit.file.basename == key: return comp_unit elif isinstance(key, self.re_compile_type): matches = [] for idx in range(count): comp_unit = self.sbmodule.GetCompileUnitAtIndex(idx) fullpath = comp_unit.file.fullpath if fullpath: re_match = key.search(fullpath) if re_match: matches.append(comp_unit) return matches else: print("error: unsupported item type: %s" % type(key)) return None def get_sections_access_object(self): '''An accessor function that returns a sections_access() object which allows lazy section array access.''' return self.sections_access (self) def get_sections_array(self): '''An accessor function that returns an array object that contains all sections in this module object.''' if not hasattr(self, 'sections_array'): self.sections_array = [] for idx in range(self.num_sections): self.sections_array.append(self.GetSectionAtIndex(idx)) return self.sections_array def get_compile_units_array(self): '''An accessor function that returns an array object that contains all compile_units in this module object.''' if not hasattr(self, 'compile_units_array'): self.compile_units_array = [] for idx in range(self.GetNumCompileUnits()): self.compile_units_array.append(self.GetCompileUnitAtIndex(idx)) return self.compile_units_array symbols = property(get_symbols_array, None, doc='''A read only property that returns a list() of lldb.SBSymbol objects contained in this module.''') symbol = property(get_symbols_access_object, None, doc='''A read only property that can be used to access symbols by index ("symbol = module.symbol[0]"), name ("symbols = module.symbol['main']"), or using a regular expression ("symbols = module.symbol[re.compile(...)]"). The return value is a single lldb.SBSymbol object for array access, and a list() of lldb.SBSymbol objects for name and regular expression access''') sections = property(get_sections_array, None, doc='''A read only property that returns a list() of lldb.SBSection objects contained in this module.''') compile_units = property(get_compile_units_array, None, doc='''A read only property that returns a list() of lldb.SBCompileUnit objects contained in this module.''') section = property(get_sections_access_object, None, doc='''A read only property that can be used to access symbols by index ("section = module.section[0]"), name ("sections = module.section[\'main\']"), or using a regular expression ("sections = module.section[re.compile(...)]"). The return value is a single lldb.SBSection object for array access, and a list() of lldb.SBSection objects for name and regular expression access''') section = property(get_sections_access_object, None, doc='''A read only property that can be used to access compile units by index ("compile_unit = module.compile_unit[0]"), name ("compile_unit = module.compile_unit[\'main.cpp\']"), or using a regular expression ("compile_unit = module.compile_unit[re.compile(...)]"). The return value is a single lldb.SBCompileUnit object for array access or by full or partial path, and a list() of lldb.SBCompileUnit objects regular expressions.''') def get_uuid(self): return uuid.UUID (self.GetUUIDString()) uuid = property(get_uuid, None, doc='''A read only property that returns a standard python uuid.UUID object that represents the UUID of this module.''') file = property(GetFileSpec, None, doc='''A read only property that returns an lldb object that represents the file (lldb.SBFileSpec) for this object file for this module as it is represented where it is being debugged.''') platform_file = property(GetPlatformFileSpec, None, doc='''A read only property that returns an lldb object that represents the file (lldb.SBFileSpec) for this object file for this module as it is represented on the current host system.''') byte_order = property(GetByteOrder, None, doc='''A read only property that returns an lldb enumeration value (lldb.eByteOrderLittle, lldb.eByteOrderBig, lldb.eByteOrderInvalid) that represents the byte order for this module.''') addr_size = property(GetAddressByteSize, None, doc='''A read only property that returns the size in bytes of an address for this module.''') triple = property(GetTriple, None, doc='''A read only property that returns the target triple (arch-vendor-os) for this module.''') num_symbols = property(GetNumSymbols, None, doc='''A read only property that returns number of symbols in the module symbol table as an integer.''') num_sections = property(GetNumSections, None, doc='''A read only property that returns number of sections in the module as an integer.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBModule in _lldb: _lldb.SBModule_swigregister(SBModule) def SBModule_GetNumberAllocatedModules(): r""" SBModule_GetNumberAllocatedModules() -> uint32_t Returns the number of modules in the module cache. This is an implementation detail exposed for testing and should not be relied upon. @return The number of modules in the module cache. """ return _lldb.SBModule_GetNumberAllocatedModules() def SBModule_GarbageCollectAllocatedModules(): r""" SBModule_GarbageCollectAllocatedModules() Removes all modules which are no longer needed by any part of LLDB from the module cache. This is an implementation detail exposed for testing and should not be relied upon. Use SBDebugger::MemoryPressureDetected instead to reduce LLDB's memory consumption during execution. """ return _lldb.SBModule_GarbageCollectAllocatedModules() class SBModuleSpec(object): r"""Proxy of C++ lldb::SBModuleSpec class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBModuleSpec self) -> SBModuleSpec __init__(SBModuleSpec self, SBModuleSpec rhs) -> SBModuleSpec """ _lldb.SBModuleSpec_swiginit(self, _lldb.new_SBModuleSpec(*args)) __swig_destroy__ = _lldb.delete_SBModuleSpec def IsValid(self): r"""IsValid(SBModuleSpec self) -> bool""" return _lldb.SBModuleSpec_IsValid(self) def __nonzero__(self): return _lldb.SBModuleSpec___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBModuleSpec self)""" return _lldb.SBModuleSpec_Clear(self) def GetFileSpec(self): r""" GetFileSpec(SBModuleSpec self) -> SBFileSpec Get const accessor for the module file. This function returns the file for the module on the host system that is running LLDB. This can differ from the path on the platform since we might be doing remote debugging. @return A const reference to the file specification object. """ return _lldb.SBModuleSpec_GetFileSpec(self) def SetFileSpec(self, fspec): r"""SetFileSpec(SBModuleSpec self, SBFileSpec fspec)""" return _lldb.SBModuleSpec_SetFileSpec(self, fspec) def GetPlatformFileSpec(self): r""" GetPlatformFileSpec(SBModuleSpec self) -> SBFileSpec Get accessor for the module platform file. Platform file refers to the path of the module as it is known on the remote system on which it is being debugged. For local debugging this is always the same as Module::GetFileSpec(). But remote debugging might mention a file '/usr/lib/liba.dylib' which might be locally downloaded and cached. In this case the platform file could be something like: '/tmp/lldb/platform-cache/remote.host.computer/usr/lib/liba.dylib' The file could also be cached in a local developer kit directory. @return A const reference to the file specification object. """ return _lldb.SBModuleSpec_GetPlatformFileSpec(self) def SetPlatformFileSpec(self, fspec): r"""SetPlatformFileSpec(SBModuleSpec self, SBFileSpec fspec)""" return _lldb.SBModuleSpec_SetPlatformFileSpec(self, fspec) def GetSymbolFileSpec(self): r"""GetSymbolFileSpec(SBModuleSpec self) -> SBFileSpec""" return _lldb.SBModuleSpec_GetSymbolFileSpec(self) def SetSymbolFileSpec(self, fspec): r"""SetSymbolFileSpec(SBModuleSpec self, SBFileSpec fspec)""" return _lldb.SBModuleSpec_SetSymbolFileSpec(self, fspec) def GetObjectName(self): r"""GetObjectName(SBModuleSpec self) -> char const *""" return _lldb.SBModuleSpec_GetObjectName(self) def SetObjectName(self, name): r"""SetObjectName(SBModuleSpec self, char const * name)""" return _lldb.SBModuleSpec_SetObjectName(self, name) def GetTriple(self): r"""GetTriple(SBModuleSpec self) -> char const *""" return _lldb.SBModuleSpec_GetTriple(self) def SetTriple(self, triple): r"""SetTriple(SBModuleSpec self, char const * triple)""" return _lldb.SBModuleSpec_SetTriple(self, triple) def GetUUIDBytes(self): r"""GetUUIDBytes(SBModuleSpec self) -> uint8_t const *""" return _lldb.SBModuleSpec_GetUUIDBytes(self) def GetUUIDLength(self): r"""GetUUIDLength(SBModuleSpec self) -> size_t""" return _lldb.SBModuleSpec_GetUUIDLength(self) def SetUUIDBytes(self, uuid, uuid_len): r"""SetUUIDBytes(SBModuleSpec self, uint8_t const * uuid, size_t uuid_len) -> bool""" return _lldb.SBModuleSpec_SetUUIDBytes(self, uuid, uuid_len) def GetDescription(self, description): r"""GetDescription(SBModuleSpec self, SBStream description) -> bool""" return _lldb.SBModuleSpec_GetDescription(self, description) def __str__(self): r"""__str__(SBModuleSpec self) -> std::string""" return _lldb.SBModuleSpec___str__(self) # Register SBModuleSpec in _lldb: _lldb.SBModuleSpec_swigregister(SBModuleSpec) class SBModuleSpecList(object): r"""Represents a list of :py:class:`SBModuleSpec`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBModuleSpecList self) -> SBModuleSpecList __init__(SBModuleSpecList self, SBModuleSpecList rhs) -> SBModuleSpecList """ _lldb.SBModuleSpecList_swiginit(self, _lldb.new_SBModuleSpecList(*args)) __swig_destroy__ = _lldb.delete_SBModuleSpecList @staticmethod def GetModuleSpecifications(path): r"""GetModuleSpecifications(char const * path) -> SBModuleSpecList""" return _lldb.SBModuleSpecList_GetModuleSpecifications(path) def Append(self, *args): r""" Append(SBModuleSpecList self, SBModuleSpec spec) Append(SBModuleSpecList self, SBModuleSpecList spec_list) """ return _lldb.SBModuleSpecList_Append(self, *args) def FindFirstMatchingSpec(self, match_spec): r"""FindFirstMatchingSpec(SBModuleSpecList self, SBModuleSpec match_spec) -> SBModuleSpec""" return _lldb.SBModuleSpecList_FindFirstMatchingSpec(self, match_spec) def FindMatchingSpecs(self, match_spec): r"""FindMatchingSpecs(SBModuleSpecList self, SBModuleSpec match_spec) -> SBModuleSpecList""" return _lldb.SBModuleSpecList_FindMatchingSpecs(self, match_spec) def GetSize(self): r"""GetSize(SBModuleSpecList self) -> size_t""" return _lldb.SBModuleSpecList_GetSize(self) def GetSpecAtIndex(self, i): r"""GetSpecAtIndex(SBModuleSpecList self, size_t i) -> SBModuleSpec""" return _lldb.SBModuleSpecList_GetSpecAtIndex(self, i) def GetDescription(self, description): r"""GetDescription(SBModuleSpecList self, SBStream description) -> bool""" return _lldb.SBModuleSpecList_GetDescription(self, description) def __str__(self): r"""__str__(SBModuleSpecList self) -> std::string""" return _lldb.SBModuleSpecList___str__(self) # Register SBModuleSpecList in _lldb: _lldb.SBModuleSpecList_swigregister(SBModuleSpecList) def SBModuleSpecList_GetModuleSpecifications(path): r"""SBModuleSpecList_GetModuleSpecifications(char const * path) -> SBModuleSpecList""" return _lldb.SBModuleSpecList_GetModuleSpecifications(path) class SBPlatformConnectOptions(object): r"""Describes how :py:class:`SBPlatform.ConnectRemote` connects to a remote platform.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBPlatformConnectOptions self, char const * url) -> SBPlatformConnectOptions __init__(SBPlatformConnectOptions self, SBPlatformConnectOptions rhs) -> SBPlatformConnectOptions """ _lldb.SBPlatformConnectOptions_swiginit(self, _lldb.new_SBPlatformConnectOptions(*args)) __swig_destroy__ = _lldb.delete_SBPlatformConnectOptions def GetURL(self): r"""GetURL(SBPlatformConnectOptions self) -> char const *""" return _lldb.SBPlatformConnectOptions_GetURL(self) def SetURL(self, url): r"""SetURL(SBPlatformConnectOptions self, char const * url)""" return _lldb.SBPlatformConnectOptions_SetURL(self, url) def GetRsyncEnabled(self): r"""GetRsyncEnabled(SBPlatformConnectOptions self) -> bool""" return _lldb.SBPlatformConnectOptions_GetRsyncEnabled(self) def EnableRsync(self, options, remote_path_prefix, omit_remote_hostname): r"""EnableRsync(SBPlatformConnectOptions self, char const * options, char const * remote_path_prefix, bool omit_remote_hostname)""" return _lldb.SBPlatformConnectOptions_EnableRsync(self, options, remote_path_prefix, omit_remote_hostname) def DisableRsync(self): r"""DisableRsync(SBPlatformConnectOptions self)""" return _lldb.SBPlatformConnectOptions_DisableRsync(self) def GetLocalCacheDirectory(self): r"""GetLocalCacheDirectory(SBPlatformConnectOptions self) -> char const *""" return _lldb.SBPlatformConnectOptions_GetLocalCacheDirectory(self) def SetLocalCacheDirectory(self, path): r"""SetLocalCacheDirectory(SBPlatformConnectOptions self, char const * path)""" return _lldb.SBPlatformConnectOptions_SetLocalCacheDirectory(self, path) # Register SBPlatformConnectOptions in _lldb: _lldb.SBPlatformConnectOptions_swigregister(SBPlatformConnectOptions) class SBPlatformShellCommand(object): r"""Represents a shell command that can be run by :py:class:`SBPlatform.Run`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBPlatformShellCommand self, char const * shell, char const * shell_command) -> SBPlatformShellCommand __init__(SBPlatformShellCommand self, char const * shell_command) -> SBPlatformShellCommand __init__(SBPlatformShellCommand self, SBPlatformShellCommand rhs) -> SBPlatformShellCommand """ _lldb.SBPlatformShellCommand_swiginit(self, _lldb.new_SBPlatformShellCommand(*args)) __swig_destroy__ = _lldb.delete_SBPlatformShellCommand def Clear(self): r"""Clear(SBPlatformShellCommand self)""" return _lldb.SBPlatformShellCommand_Clear(self) def GetShell(self): r"""GetShell(SBPlatformShellCommand self) -> char const *""" return _lldb.SBPlatformShellCommand_GetShell(self) def SetShell(self, shell_interpreter): r"""SetShell(SBPlatformShellCommand self, char const * shell_interpreter)""" return _lldb.SBPlatformShellCommand_SetShell(self, shell_interpreter) def GetCommand(self): r"""GetCommand(SBPlatformShellCommand self) -> char const *""" return _lldb.SBPlatformShellCommand_GetCommand(self) def SetCommand(self, shell_command): r"""SetCommand(SBPlatformShellCommand self, char const * shell_command)""" return _lldb.SBPlatformShellCommand_SetCommand(self, shell_command) def GetWorkingDirectory(self): r"""GetWorkingDirectory(SBPlatformShellCommand self) -> char const *""" return _lldb.SBPlatformShellCommand_GetWorkingDirectory(self) def SetWorkingDirectory(self, path): r"""SetWorkingDirectory(SBPlatformShellCommand self, char const * path)""" return _lldb.SBPlatformShellCommand_SetWorkingDirectory(self, path) def GetTimeoutSeconds(self): r"""GetTimeoutSeconds(SBPlatformShellCommand self) -> uint32_t""" return _lldb.SBPlatformShellCommand_GetTimeoutSeconds(self) def SetTimeoutSeconds(self, sec): r"""SetTimeoutSeconds(SBPlatformShellCommand self, uint32_t sec)""" return _lldb.SBPlatformShellCommand_SetTimeoutSeconds(self, sec) def GetSignal(self): r"""GetSignal(SBPlatformShellCommand self) -> int""" return _lldb.SBPlatformShellCommand_GetSignal(self) def GetStatus(self): r"""GetStatus(SBPlatformShellCommand self) -> int""" return _lldb.SBPlatformShellCommand_GetStatus(self) def GetOutput(self): r"""GetOutput(SBPlatformShellCommand self) -> char const *""" return _lldb.SBPlatformShellCommand_GetOutput(self) # Register SBPlatformShellCommand in _lldb: _lldb.SBPlatformShellCommand_swigregister(SBPlatformShellCommand) class SBPlatform(object): r""" A class that represents a platform that can represent the current host or a remote host debug platform. The SBPlatform class represents the current host, or a remote host. It can be connected to a remote platform in order to provide ways to remotely launch and attach to processes, upload/download files, create directories, run remote shell commands, find locally cached versions of files from the remote system, and much more. SBPlatform objects can be created and then used to connect to a remote platform which allows the SBPlatform to be used to get a list of the current processes on the remote host, attach to one of those processes, install programs on the remote system, attach and launch processes, and much more. Every :py:class:`SBTarget` has a corresponding SBPlatform. The platform can be specified upon target creation, or the currently selected platform will attempt to be used when creating the target automatically as long as the currently selected platform matches the target architecture and executable type. If the architecture or executable type do not match, a suitable platform will be found automatically. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBPlatform self) -> SBPlatform __init__(SBPlatform self, char const * arg2) -> SBPlatform """ _lldb.SBPlatform_swiginit(self, _lldb.new_SBPlatform(*args)) __swig_destroy__ = _lldb.delete_SBPlatform @staticmethod def GetHostPlatform(): r"""GetHostPlatform() -> SBPlatform""" return _lldb.SBPlatform_GetHostPlatform() def IsValid(self): r"""IsValid(SBPlatform self) -> bool""" return _lldb.SBPlatform_IsValid(self) def __nonzero__(self): return _lldb.SBPlatform___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBPlatform self)""" return _lldb.SBPlatform_Clear(self) def GetWorkingDirectory(self): r"""GetWorkingDirectory(SBPlatform self) -> char const *""" return _lldb.SBPlatform_GetWorkingDirectory(self) def SetWorkingDirectory(self, arg2): r"""SetWorkingDirectory(SBPlatform self, char const * arg2) -> bool""" return _lldb.SBPlatform_SetWorkingDirectory(self, arg2) def GetName(self): r"""GetName(SBPlatform self) -> char const *""" return _lldb.SBPlatform_GetName(self) def ConnectRemote(self, connect_options): r"""ConnectRemote(SBPlatform self, SBPlatformConnectOptions connect_options) -> SBError""" return _lldb.SBPlatform_ConnectRemote(self, connect_options) def DisconnectRemote(self): r"""DisconnectRemote(SBPlatform self)""" return _lldb.SBPlatform_DisconnectRemote(self) def IsConnected(self): r"""IsConnected(SBPlatform self) -> bool""" return _lldb.SBPlatform_IsConnected(self) def GetTriple(self): r"""GetTriple(SBPlatform self) -> char const *""" return _lldb.SBPlatform_GetTriple(self) def GetHostname(self): r"""GetHostname(SBPlatform self) -> char const *""" return _lldb.SBPlatform_GetHostname(self) def GetOSBuild(self): r"""GetOSBuild(SBPlatform self) -> char const *""" return _lldb.SBPlatform_GetOSBuild(self) def GetOSDescription(self): r"""GetOSDescription(SBPlatform self) -> char const *""" return _lldb.SBPlatform_GetOSDescription(self) def GetOSMajorVersion(self): r"""GetOSMajorVersion(SBPlatform self) -> uint32_t""" return _lldb.SBPlatform_GetOSMajorVersion(self) def GetOSMinorVersion(self): r"""GetOSMinorVersion(SBPlatform self) -> uint32_t""" return _lldb.SBPlatform_GetOSMinorVersion(self) def GetOSUpdateVersion(self): r"""GetOSUpdateVersion(SBPlatform self) -> uint32_t""" return _lldb.SBPlatform_GetOSUpdateVersion(self) def Get(self, src, dst): r"""Get(SBPlatform self, SBFileSpec src, SBFileSpec dst) -> SBError""" return _lldb.SBPlatform_Get(self, src, dst) def Put(self, src, dst): r"""Put(SBPlatform self, SBFileSpec src, SBFileSpec dst) -> SBError""" return _lldb.SBPlatform_Put(self, src, dst) def Install(self, src, dst): r"""Install(SBPlatform self, SBFileSpec src, SBFileSpec dst) -> SBError""" return _lldb.SBPlatform_Install(self, src, dst) def Run(self, shell_command): r"""Run(SBPlatform self, SBPlatformShellCommand shell_command) -> SBError""" return _lldb.SBPlatform_Run(self, shell_command) def Launch(self, launch_info): r"""Launch(SBPlatform self, SBLaunchInfo launch_info) -> SBError""" return _lldb.SBPlatform_Launch(self, launch_info) def Kill(self, pid): r"""Kill(SBPlatform self, lldb::pid_t const pid) -> SBError""" return _lldb.SBPlatform_Kill(self, pid) def MakeDirectory(self, *args): r"""MakeDirectory(SBPlatform self, char const * path, uint32_t file_permissions=eFilePermissionsDirectoryDefault) -> SBError""" return _lldb.SBPlatform_MakeDirectory(self, *args) def GetFilePermissions(self, path): r"""GetFilePermissions(SBPlatform self, char const * path) -> uint32_t""" return _lldb.SBPlatform_GetFilePermissions(self, path) def SetFilePermissions(self, path, file_permissions): r"""SetFilePermissions(SBPlatform self, char const * path, uint32_t file_permissions) -> SBError""" return _lldb.SBPlatform_SetFilePermissions(self, path, file_permissions) def GetUnixSignals(self): r"""GetUnixSignals(SBPlatform self) -> SBUnixSignals""" return _lldb.SBPlatform_GetUnixSignals(self) def GetEnvironment(self): r"""GetEnvironment(SBPlatform self) -> SBEnvironment""" return _lldb.SBPlatform_GetEnvironment(self) # Register SBPlatform in _lldb: _lldb.SBPlatform_swigregister(SBPlatform) def SBPlatform_GetHostPlatform(): r"""SBPlatform_GetHostPlatform() -> SBPlatform""" return _lldb.SBPlatform_GetHostPlatform() class SBProcess(object): r""" Represents the process associated with the target program. SBProcess supports thread iteration. For example (from test/lldbutil.py), :: # ================================================== # Utility functions related to Threads and Processes # ================================================== def get_stopped_threads(process, reason): '''Returns the thread(s) with the specified stop reason in a list. The list can be empty if no such thread exists. ''' threads = [] for t in process: if t.GetStopReason() == reason: threads.append(t) return threads """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr eBroadcastBitStateChanged = _lldb.SBProcess_eBroadcastBitStateChanged eBroadcastBitInterrupt = _lldb.SBProcess_eBroadcastBitInterrupt eBroadcastBitSTDOUT = _lldb.SBProcess_eBroadcastBitSTDOUT eBroadcastBitSTDERR = _lldb.SBProcess_eBroadcastBitSTDERR eBroadcastBitProfileData = _lldb.SBProcess_eBroadcastBitProfileData eBroadcastBitStructuredData = _lldb.SBProcess_eBroadcastBitStructuredData def __init__(self, *args): r""" __init__(SBProcess self) -> SBProcess __init__(SBProcess self, SBProcess rhs) -> SBProcess """ _lldb.SBProcess_swiginit(self, _lldb.new_SBProcess(*args)) __swig_destroy__ = _lldb.delete_SBProcess @staticmethod def GetBroadcasterClassName(): r"""GetBroadcasterClassName() -> char const *""" return _lldb.SBProcess_GetBroadcasterClassName() def GetPluginName(self): r"""GetPluginName(SBProcess self) -> char const *""" return _lldb.SBProcess_GetPluginName(self) def GetShortPluginName(self): r"""GetShortPluginName(SBProcess self) -> char const *""" return _lldb.SBProcess_GetShortPluginName(self) def Clear(self): r"""Clear(SBProcess self)""" return _lldb.SBProcess_Clear(self) def IsValid(self): r"""IsValid(SBProcess self) -> bool""" return _lldb.SBProcess_IsValid(self) def __nonzero__(self): return _lldb.SBProcess___nonzero__(self) __bool__ = __nonzero__ def GetTarget(self): r"""GetTarget(SBProcess self) -> SBTarget""" return _lldb.SBProcess_GetTarget(self) def GetByteOrder(self): r"""GetByteOrder(SBProcess self) -> lldb::ByteOrder""" return _lldb.SBProcess_GetByteOrder(self) def PutSTDIN(self, src): r""" Writes data into the current process's stdin. API client specifies a Python string as the only argument. """ return _lldb.SBProcess_PutSTDIN(self, src) def GetSTDOUT(self, dst): r""" Reads data from the current process's stdout stream. API client specifies the size of the buffer to read data into. It returns the byte buffer in a Python string. """ return _lldb.SBProcess_GetSTDOUT(self, dst) def GetSTDERR(self, dst): r""" Reads data from the current process's stderr stream. API client specifies the size of the buffer to read data into. It returns the byte buffer in a Python string. """ return _lldb.SBProcess_GetSTDERR(self, dst) def GetAsyncProfileData(self, dst): r"""GetAsyncProfileData(SBProcess self, char * dst) -> size_t""" return _lldb.SBProcess_GetAsyncProfileData(self, dst) def ReportEventState(self, *args): r""" ReportEventState(SBProcess self, SBEvent event, SBFile out) ReportEventState(SBProcess self, SBEvent event, lldb::FileSP BORROWED) """ return _lldb.SBProcess_ReportEventState(self, *args) def AppendEventStateReport(self, event, result): r"""AppendEventStateReport(SBProcess self, SBEvent event, SBCommandReturnObject result)""" return _lldb.SBProcess_AppendEventStateReport(self, event, result) def RemoteAttachToProcessWithID(self, pid, error): r""" RemoteAttachToProcessWithID(SBProcess self, lldb::pid_t pid, SBError error) -> bool Remote connection related functions. These will fail if the process is not in eStateConnected. They are intended for use when connecting to an externally managed debugserver instance. """ return _lldb.SBProcess_RemoteAttachToProcessWithID(self, pid, error) def RemoteLaunch(self, argv, envp, stdin_path, stdout_path, stderr_path, working_directory, launch_flags, stop_at_entry, error): r""" RemoteLaunch(SBProcess self, char const ** argv, char const ** envp, char const * stdin_path, char const * stdout_path, char const * stderr_path, char const * working_directory, uint32_t launch_flags, bool stop_at_entry, SBError error) -> bool See SBTarget.Launch for argument description and usage. """ return _lldb.SBProcess_RemoteLaunch(self, argv, envp, stdin_path, stdout_path, stderr_path, working_directory, launch_flags, stop_at_entry, error) def GetNumThreads(self): r"""GetNumThreads(SBProcess self) -> uint32_t""" return _lldb.SBProcess_GetNumThreads(self) def GetThreadAtIndex(self, index): r""" Returns the INDEX'th thread from the list of current threads. The index of a thread is only valid for the current stop. For a persistent thread identifier use either the thread ID or the IndexID. See help on SBThread for more details. """ return _lldb.SBProcess_GetThreadAtIndex(self, index) def GetThreadByID(self, sb_thread_id): r""" Returns the thread with the given thread ID. """ return _lldb.SBProcess_GetThreadByID(self, sb_thread_id) def GetThreadByIndexID(self, index_id): r""" Returns the thread with the given thread IndexID. """ return _lldb.SBProcess_GetThreadByIndexID(self, index_id) def GetSelectedThread(self): r""" Returns the currently selected thread. """ return _lldb.SBProcess_GetSelectedThread(self) def CreateOSPluginThread(self, tid, context): r""" Lazily create a thread on demand through the current OperatingSystem plug-in, if the current OperatingSystem plug-in supports it. """ return _lldb.SBProcess_CreateOSPluginThread(self, tid, context) def SetSelectedThread(self, thread): r"""SetSelectedThread(SBProcess self, SBThread thread) -> bool""" return _lldb.SBProcess_SetSelectedThread(self, thread) def SetSelectedThreadByID(self, tid): r"""SetSelectedThreadByID(SBProcess self, lldb::tid_t tid) -> bool""" return _lldb.SBProcess_SetSelectedThreadByID(self, tid) def SetSelectedThreadByIndexID(self, index_id): r"""SetSelectedThreadByIndexID(SBProcess self, uint32_t index_id) -> bool""" return _lldb.SBProcess_SetSelectedThreadByIndexID(self, index_id) def GetNumQueues(self): r"""GetNumQueues(SBProcess self) -> uint32_t""" return _lldb.SBProcess_GetNumQueues(self) def GetQueueAtIndex(self, index): r"""GetQueueAtIndex(SBProcess self, uint32_t index) -> SBQueue""" return _lldb.SBProcess_GetQueueAtIndex(self, index) def GetState(self): r"""GetState(SBProcess self) -> lldb::StateType""" return _lldb.SBProcess_GetState(self) def GetExitStatus(self): r"""GetExitStatus(SBProcess self) -> int""" return _lldb.SBProcess_GetExitStatus(self) def GetExitDescription(self): r"""GetExitDescription(SBProcess self) -> char const *""" return _lldb.SBProcess_GetExitDescription(self) def GetProcessID(self): r""" Returns the process ID of the process. """ return _lldb.SBProcess_GetProcessID(self) def GetUniqueID(self): r""" Returns an integer ID that is guaranteed to be unique across all process instances. This is not the process ID, just a unique integer for comparison and caching purposes. """ return _lldb.SBProcess_GetUniqueID(self) def GetAddressByteSize(self): r"""GetAddressByteSize(SBProcess self) -> uint32_t""" return _lldb.SBProcess_GetAddressByteSize(self) def Destroy(self): r""" Destroy(SBProcess self) -> SBError Kills the process and shuts down all threads that were spawned to track and monitor process. """ return _lldb.SBProcess_Destroy(self) def Continue(self): r"""Continue(SBProcess self) -> SBError""" return _lldb.SBProcess_Continue(self) def Stop(self): r"""Stop(SBProcess self) -> SBError""" return _lldb.SBProcess_Stop(self) def Kill(self): r"""Kill(SBProcess self) -> SBError""" return _lldb.SBProcess_Kill(self) def Detach(self): r"""Detach(SBProcess self) -> SBError""" return _lldb.SBProcess_Detach(self) def Signal(self, signal): r""" Signal(SBProcess self, int signal) -> SBError Sends the process a unix signal. """ return _lldb.SBProcess_Signal(self, signal) def GetUnixSignals(self): r"""GetUnixSignals(SBProcess self) -> SBUnixSignals""" return _lldb.SBProcess_GetUnixSignals(self) def GetStopID(self, include_expression_stops=False): r""" GetStopID(SBProcess self, bool include_expression_stops=False) -> uint32_t Returns a stop id that will increase every time the process executes. If include_expression_stops is true, then stops caused by expression evaluation will cause the returned value to increase, otherwise the counter returned will only increase when execution is continued explicitly by the user. Note, the value will always increase, but may increase by more than one per stop. """ return _lldb.SBProcess_GetStopID(self, include_expression_stops) def SendAsyncInterrupt(self): r"""SendAsyncInterrupt(SBProcess self)""" return _lldb.SBProcess_SendAsyncInterrupt(self) def ReadMemory(self, addr, buf, error): r""" Reads memory from the current process's address space and removes any traps that may have been inserted into the memory. It returns the byte buffer in a Python string. Example: :: # Read 4 bytes from address 'addr' and assume error.Success() is True. content = process.ReadMemory(addr, 4, error) new_bytes = bytearray(content) """ return _lldb.SBProcess_ReadMemory(self, addr, buf, error) def WriteMemory(self, addr, buf, error): r""" Writes memory to the current process's address space and maintains any traps that might be present due to software breakpoints. Example: :: # Create a Python string from the byte array. new_value = str(bytes) result = process.WriteMemory(addr, new_value, error) if not error.Success() or result != len(bytes): print('SBProcess.WriteMemory() failed!') """ return _lldb.SBProcess_WriteMemory(self, addr, buf, error) def ReadCStringFromMemory(self, addr, char_buf, error): r""" Reads a NULL terminated C string from the current process's address space. It returns a python string of the exact length, or truncates the string if the maximum character limit is reached. Example: :: # Read a C string of at most 256 bytes from address '0x1000' error = lldb.SBError() cstring = process.ReadCStringFromMemory(0x1000, 256, error) if error.Success(): print('cstring: ', cstring) else print('error: ', error) """ return _lldb.SBProcess_ReadCStringFromMemory(self, addr, char_buf, error) def ReadUnsignedFromMemory(self, addr, byte_size, error): r""" Reads an unsigned integer from memory given a byte size and an address. Returns the unsigned integer that was read. Example: :: # Read a 4 byte unsigned integer from address 0x1000 error = lldb.SBError() uint = ReadUnsignedFromMemory(0x1000, 4, error) if error.Success(): print('integer: %u' % uint) else print('error: ', error) """ return _lldb.SBProcess_ReadUnsignedFromMemory(self, addr, byte_size, error) def ReadPointerFromMemory(self, addr, error): r""" Reads a pointer from memory from an address and returns the value. Example: :: # Read a pointer from address 0x1000 error = lldb.SBError() ptr = ReadPointerFromMemory(0x1000, error) if error.Success(): print('pointer: 0x%x' % ptr) else print('error: ', error) """ return _lldb.SBProcess_ReadPointerFromMemory(self, addr, error) @staticmethod def GetStateFromEvent(event): r"""GetStateFromEvent(SBEvent event) -> lldb::StateType""" return _lldb.SBProcess_GetStateFromEvent(event) @staticmethod def GetRestartedFromEvent(event): r"""GetRestartedFromEvent(SBEvent event) -> bool""" return _lldb.SBProcess_GetRestartedFromEvent(event) @staticmethod def GetNumRestartedReasonsFromEvent(event): r"""GetNumRestartedReasonsFromEvent(SBEvent event) -> size_t""" return _lldb.SBProcess_GetNumRestartedReasonsFromEvent(event) @staticmethod def GetRestartedReasonAtIndexFromEvent(event, idx): r"""GetRestartedReasonAtIndexFromEvent(SBEvent event, size_t idx) -> char const *""" return _lldb.SBProcess_GetRestartedReasonAtIndexFromEvent(event, idx) @staticmethod def GetProcessFromEvent(event): r"""GetProcessFromEvent(SBEvent event) -> SBProcess""" return _lldb.SBProcess_GetProcessFromEvent(event) @staticmethod def GetInterruptedFromEvent(event): r"""GetInterruptedFromEvent(SBEvent event) -> bool""" return _lldb.SBProcess_GetInterruptedFromEvent(event) @staticmethod def GetStructuredDataFromEvent(event): r"""GetStructuredDataFromEvent(SBEvent event) -> SBStructuredData""" return _lldb.SBProcess_GetStructuredDataFromEvent(event) @staticmethod def EventIsProcessEvent(event): r"""EventIsProcessEvent(SBEvent event) -> bool""" return _lldb.SBProcess_EventIsProcessEvent(event) @staticmethod def EventIsStructuredDataEvent(event): r"""EventIsStructuredDataEvent(SBEvent event) -> bool""" return _lldb.SBProcess_EventIsStructuredDataEvent(event) def GetBroadcaster(self): r"""GetBroadcaster(SBProcess self) -> SBBroadcaster""" return _lldb.SBProcess_GetBroadcaster(self) def GetDescription(self, description): r"""GetDescription(SBProcess self, SBStream description) -> bool""" return _lldb.SBProcess_GetDescription(self, description) def GetExtendedCrashInformation(self): r""" Returns the process' extended crash information. """ return _lldb.SBProcess_GetExtendedCrashInformation(self) def GetNumSupportedHardwareWatchpoints(self, error): r"""GetNumSupportedHardwareWatchpoints(SBProcess self, SBError error) -> uint32_t""" return _lldb.SBProcess_GetNumSupportedHardwareWatchpoints(self, error) def LoadImage(self, image_spec, error): r"""LoadImage(SBProcess self, SBFileSpec image_spec, SBError error) -> uint32_t""" return _lldb.SBProcess_LoadImage(self, image_spec, error) def LoadImageUsingPaths(self, image_spec, paths, loaded_path, error): r""" Load the library whose filename is given by image_spec looking in all the paths supplied in the paths argument. If successful, return a token that can be passed to UnloadImage and fill loaded_path with the path that was successfully loaded. On failure, return lldb.LLDB_INVALID_IMAGE_TOKEN. """ return _lldb.SBProcess_LoadImageUsingPaths(self, image_spec, paths, loaded_path, error) def UnloadImage(self, image_token): r"""UnloadImage(SBProcess self, uint32_t image_token) -> SBError""" return _lldb.SBProcess_UnloadImage(self, image_token) def SendEventData(self, event_data): r"""SendEventData(SBProcess self, char const * event_data) -> SBError""" return _lldb.SBProcess_SendEventData(self, event_data) def GetNumExtendedBacktraceTypes(self): r""" Return the number of different thread-origin extended backtraces this process can support as a uint32_t. When the process is stopped and you have an SBThread, lldb may be able to show a backtrace of when that thread was originally created, or the work item was enqueued to it (in the case of a libdispatch queue). """ return _lldb.SBProcess_GetNumExtendedBacktraceTypes(self) def GetExtendedBacktraceTypeAtIndex(self, idx): r""" Takes an index argument, returns the name of one of the thread-origin extended backtrace methods as a str. """ return _lldb.SBProcess_GetExtendedBacktraceTypeAtIndex(self, idx) def GetHistoryThreads(self, addr): r"""GetHistoryThreads(SBProcess self, lldb::addr_t addr) -> SBThreadCollection""" return _lldb.SBProcess_GetHistoryThreads(self, addr) def IsInstrumentationRuntimePresent(self, type): r"""IsInstrumentationRuntimePresent(SBProcess self, lldb::InstrumentationRuntimeType type) -> bool""" return _lldb.SBProcess_IsInstrumentationRuntimePresent(self, type) def SaveCore(self, file_name): r"""SaveCore(SBProcess self, char const * file_name) -> SBError""" return _lldb.SBProcess_SaveCore(self, file_name) def StartTrace(self, options, error): r"""StartTrace(SBProcess self, SBTraceOptions options, SBError error) -> SBTrace""" return _lldb.SBProcess_StartTrace(self, options, error) def GetMemoryRegionInfo(self, load_addr, region_info): r"""GetMemoryRegionInfo(SBProcess self, lldb::addr_t load_addr, SBMemoryRegionInfo region_info) -> SBError""" return _lldb.SBProcess_GetMemoryRegionInfo(self, load_addr, region_info) def GetMemoryRegions(self): r"""GetMemoryRegions(SBProcess self) -> SBMemoryRegionInfoList""" return _lldb.SBProcess_GetMemoryRegions(self) def GetProcessInfo(self): r""" Get information about the process. Valid process info will only be returned when the process is alive, use IsValid() to check if the info returned is valid. :: process_info = process.GetProcessInfo() if process_info.IsValid(): process_info.GetProcessID() """ return _lldb.SBProcess_GetProcessInfo(self) def __str__(self): r"""__str__(SBProcess self) -> std::string""" return _lldb.SBProcess___str__(self) def __get_is_alive__(self): '''Returns "True" if the process is currently alive, "False" otherwise''' s = self.GetState() if (s == eStateAttaching or s == eStateLaunching or s == eStateStopped or s == eStateRunning or s == eStateStepping or s == eStateCrashed or s == eStateSuspended): return True return False def __get_is_running__(self): '''Returns "True" if the process is currently running, "False" otherwise''' state = self.GetState() if state == eStateRunning or state == eStateStepping: return True return False def __get_is_stopped__(self): '''Returns "True" if the process is currently stopped, "False" otherwise''' state = self.GetState() if state == eStateStopped or state == eStateCrashed or state == eStateSuspended: return True return False class threads_access(object): '''A helper object that will lazily hand out thread for a process when supplied an index.''' def __init__(self, sbprocess): self.sbprocess = sbprocess def __len__(self): if self.sbprocess: return int(self.sbprocess.GetNumThreads()) return 0 def __getitem__(self, key): if type(key) is int and key < len(self): return self.sbprocess.GetThreadAtIndex(key) return None def get_threads_access_object(self): '''An accessor function that returns a modules_access() object which allows lazy thread access from a lldb.SBProcess object.''' return self.threads_access (self) def get_process_thread_list(self): '''An accessor function that returns a list() that contains all threads in a lldb.SBProcess object.''' threads = [] accessor = self.get_threads_access_object() for idx in range(len(accessor)): threads.append(accessor[idx]) return threads def __iter__(self): '''Iterate over all threads in a lldb.SBProcess object.''' return lldb_iter(self, 'GetNumThreads', 'GetThreadAtIndex') def __len__(self): '''Return the number of threads in a lldb.SBProcess object.''' return self.GetNumThreads() threads = property(get_process_thread_list, None, doc='''A read only property that returns a list() of lldb.SBThread objects for this process.''') thread = property(get_threads_access_object, None, doc='''A read only property that returns an object that can access threads by thread index (thread = lldb.process.thread[12]).''') is_alive = property(__get_is_alive__, None, doc='''A read only property that returns a boolean value that indicates if this process is currently alive.''') is_running = property(__get_is_running__, None, doc='''A read only property that returns a boolean value that indicates if this process is currently running.''') is_stopped = property(__get_is_stopped__, None, doc='''A read only property that returns a boolean value that indicates if this process is currently stopped.''') id = property(GetProcessID, None, doc='''A read only property that returns the process ID as an integer.''') target = property(GetTarget, None, doc='''A read only property that an lldb object that represents the target (lldb.SBTarget) that owns this process.''') num_threads = property(GetNumThreads, None, doc='''A read only property that returns the number of threads in this process as an integer.''') selected_thread = property(GetSelectedThread, SetSelectedThread, doc='''A read/write property that gets/sets the currently selected thread in this process. The getter returns a lldb.SBThread object and the setter takes an lldb.SBThread object.''') state = property(GetState, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eState") that represents the current state of this process (running, stopped, exited, etc.).''') exit_state = property(GetExitStatus, None, doc='''A read only property that returns an exit status as an integer of this process when the process state is lldb.eStateExited.''') exit_description = property(GetExitDescription, None, doc='''A read only property that returns an exit description as a string of this process when the process state is lldb.eStateExited.''') broadcaster = property(GetBroadcaster, None, doc='''A read only property that an lldb object that represents the broadcaster (lldb.SBBroadcaster) for this process.''') # Register SBProcess in _lldb: _lldb.SBProcess_swigregister(SBProcess) def SBProcess_GetBroadcasterClassName(): r"""SBProcess_GetBroadcasterClassName() -> char const *""" return _lldb.SBProcess_GetBroadcasterClassName() def SBProcess_GetStateFromEvent(event): r"""SBProcess_GetStateFromEvent(SBEvent event) -> lldb::StateType""" return _lldb.SBProcess_GetStateFromEvent(event) def SBProcess_GetRestartedFromEvent(event): r"""SBProcess_GetRestartedFromEvent(SBEvent event) -> bool""" return _lldb.SBProcess_GetRestartedFromEvent(event) def SBProcess_GetNumRestartedReasonsFromEvent(event): r"""SBProcess_GetNumRestartedReasonsFromEvent(SBEvent event) -> size_t""" return _lldb.SBProcess_GetNumRestartedReasonsFromEvent(event) def SBProcess_GetRestartedReasonAtIndexFromEvent(event, idx): r"""SBProcess_GetRestartedReasonAtIndexFromEvent(SBEvent event, size_t idx) -> char const *""" return _lldb.SBProcess_GetRestartedReasonAtIndexFromEvent(event, idx) def SBProcess_GetProcessFromEvent(event): r"""SBProcess_GetProcessFromEvent(SBEvent event) -> SBProcess""" return _lldb.SBProcess_GetProcessFromEvent(event) def SBProcess_GetInterruptedFromEvent(event): r"""SBProcess_GetInterruptedFromEvent(SBEvent event) -> bool""" return _lldb.SBProcess_GetInterruptedFromEvent(event) def SBProcess_GetStructuredDataFromEvent(event): r"""SBProcess_GetStructuredDataFromEvent(SBEvent event) -> SBStructuredData""" return _lldb.SBProcess_GetStructuredDataFromEvent(event) def SBProcess_EventIsProcessEvent(event): r"""SBProcess_EventIsProcessEvent(SBEvent event) -> bool""" return _lldb.SBProcess_EventIsProcessEvent(event) def SBProcess_EventIsStructuredDataEvent(event): r"""SBProcess_EventIsStructuredDataEvent(SBEvent event) -> bool""" return _lldb.SBProcess_EventIsStructuredDataEvent(event) class SBProcessInfo(object): r""" Describes an existing process and any discoverable information that pertains to that process. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBProcessInfo self) -> SBProcessInfo __init__(SBProcessInfo self, SBProcessInfo rhs) -> SBProcessInfo """ _lldb.SBProcessInfo_swiginit(self, _lldb.new_SBProcessInfo(*args)) __swig_destroy__ = _lldb.delete_SBProcessInfo def IsValid(self): r"""IsValid(SBProcessInfo self) -> bool""" return _lldb.SBProcessInfo_IsValid(self) def __nonzero__(self): return _lldb.SBProcessInfo___nonzero__(self) __bool__ = __nonzero__ def GetName(self): r"""GetName(SBProcessInfo self) -> char const *""" return _lldb.SBProcessInfo_GetName(self) def GetExecutableFile(self): r"""GetExecutableFile(SBProcessInfo self) -> SBFileSpec""" return _lldb.SBProcessInfo_GetExecutableFile(self) def GetProcessID(self): r"""GetProcessID(SBProcessInfo self) -> lldb::pid_t""" return _lldb.SBProcessInfo_GetProcessID(self) def GetUserID(self): r"""GetUserID(SBProcessInfo self) -> uint32_t""" return _lldb.SBProcessInfo_GetUserID(self) def GetGroupID(self): r"""GetGroupID(SBProcessInfo self) -> uint32_t""" return _lldb.SBProcessInfo_GetGroupID(self) def UserIDIsValid(self): r"""UserIDIsValid(SBProcessInfo self) -> bool""" return _lldb.SBProcessInfo_UserIDIsValid(self) def GroupIDIsValid(self): r"""GroupIDIsValid(SBProcessInfo self) -> bool""" return _lldb.SBProcessInfo_GroupIDIsValid(self) def GetEffectiveUserID(self): r"""GetEffectiveUserID(SBProcessInfo self) -> uint32_t""" return _lldb.SBProcessInfo_GetEffectiveUserID(self) def GetEffectiveGroupID(self): r"""GetEffectiveGroupID(SBProcessInfo self) -> uint32_t""" return _lldb.SBProcessInfo_GetEffectiveGroupID(self) def EffectiveUserIDIsValid(self): r"""EffectiveUserIDIsValid(SBProcessInfo self) -> bool""" return _lldb.SBProcessInfo_EffectiveUserIDIsValid(self) def EffectiveGroupIDIsValid(self): r"""EffectiveGroupIDIsValid(SBProcessInfo self) -> bool""" return _lldb.SBProcessInfo_EffectiveGroupIDIsValid(self) def GetParentProcessID(self): r"""GetParentProcessID(SBProcessInfo self) -> lldb::pid_t""" return _lldb.SBProcessInfo_GetParentProcessID(self) # Register SBProcessInfo in _lldb: _lldb.SBProcessInfo_swigregister(SBProcessInfo) class SBQueue(object): r"""Represents a libdispatch queue in the process.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBQueue self) -> SBQueue __init__(SBQueue self, lldb::QueueSP const & queue_sp) -> SBQueue """ _lldb.SBQueue_swiginit(self, _lldb.new_SBQueue(*args)) __swig_destroy__ = _lldb.delete_SBQueue def IsValid(self): r"""IsValid(SBQueue self) -> bool""" return _lldb.SBQueue_IsValid(self) def __nonzero__(self): return _lldb.SBQueue___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBQueue self)""" return _lldb.SBQueue_Clear(self) def GetProcess(self): r"""GetProcess(SBQueue self) -> SBProcess""" return _lldb.SBQueue_GetProcess(self) def GetQueueID(self): r""" Returns an lldb::queue_id_t type unique identifier number for this queue that will not be used by any other queue during this process' execution. These ID numbers often start at 1 with the first system-created queues and increment from there. """ return _lldb.SBQueue_GetQueueID(self) def GetName(self): r"""GetName(SBQueue self) -> char const *""" return _lldb.SBQueue_GetName(self) def GetKind(self): r""" Returns an lldb::QueueKind enumerated value (e.g. eQueueKindUnknown, eQueueKindSerial, eQueueKindConcurrent) describing the type of this queue. """ return _lldb.SBQueue_GetKind(self) def GetIndexID(self): r"""GetIndexID(SBQueue self) -> uint32_t""" return _lldb.SBQueue_GetIndexID(self) def GetNumThreads(self): r"""GetNumThreads(SBQueue self) -> uint32_t""" return _lldb.SBQueue_GetNumThreads(self) def GetThreadAtIndex(self, arg2): r"""GetThreadAtIndex(SBQueue self, uint32_t arg2) -> SBThread""" return _lldb.SBQueue_GetThreadAtIndex(self, arg2) def GetNumPendingItems(self): r"""GetNumPendingItems(SBQueue self) -> uint32_t""" return _lldb.SBQueue_GetNumPendingItems(self) def GetPendingItemAtIndex(self, arg2): r"""GetPendingItemAtIndex(SBQueue self, uint32_t arg2) -> SBQueueItem""" return _lldb.SBQueue_GetPendingItemAtIndex(self, arg2) def GetNumRunningItems(self): r"""GetNumRunningItems(SBQueue self) -> uint32_t""" return _lldb.SBQueue_GetNumRunningItems(self) # Register SBQueue in _lldb: _lldb.SBQueue_swigregister(SBQueue) class SBQueueItem(object): r"""This class represents an item in an :py:class:`SBQueue`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBQueueItem self) -> SBQueueItem __init__(SBQueueItem self, lldb::QueueItemSP const & queue_item_sp) -> SBQueueItem """ _lldb.SBQueueItem_swiginit(self, _lldb.new_SBQueueItem(*args)) __swig_destroy__ = _lldb.delete_SBQueueItem def IsValid(self): r"""IsValid(SBQueueItem self) -> bool""" return _lldb.SBQueueItem_IsValid(self) def __nonzero__(self): return _lldb.SBQueueItem___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBQueueItem self)""" return _lldb.SBQueueItem_Clear(self) def GetKind(self): r"""GetKind(SBQueueItem self) -> lldb::QueueItemKind""" return _lldb.SBQueueItem_GetKind(self) def SetKind(self, kind): r"""SetKind(SBQueueItem self, lldb::QueueItemKind kind)""" return _lldb.SBQueueItem_SetKind(self, kind) def GetAddress(self): r"""GetAddress(SBQueueItem self) -> SBAddress""" return _lldb.SBQueueItem_GetAddress(self) def SetAddress(self, addr): r"""SetAddress(SBQueueItem self, SBAddress addr)""" return _lldb.SBQueueItem_SetAddress(self, addr) def SetQueueItem(self, queue_item_sp): r"""SetQueueItem(SBQueueItem self, lldb::QueueItemSP const & queue_item_sp)""" return _lldb.SBQueueItem_SetQueueItem(self, queue_item_sp) def GetExtendedBacktraceThread(self, type): r"""GetExtendedBacktraceThread(SBQueueItem self, char const * type) -> SBThread""" return _lldb.SBQueueItem_GetExtendedBacktraceThread(self, type) # Register SBQueueItem in _lldb: _lldb.SBQueueItem_swigregister(SBQueueItem) class SBReproducer(object): r"""Controls LLDB's reproducer functionality.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr @staticmethod def Capture(path): r"""Capture(char const * path) -> char const *""" return _lldb.SBReproducer_Capture(path) @staticmethod def PassiveReplay(path): r"""PassiveReplay(char const * path) -> char const *""" return _lldb.SBReproducer_PassiveReplay(path) @staticmethod def SetAutoGenerate(b): r"""SetAutoGenerate(bool b) -> bool""" return _lldb.SBReproducer_SetAutoGenerate(b) @staticmethod def SetWorkingDirectory(path): r"""SetWorkingDirectory(char const * path)""" return _lldb.SBReproducer_SetWorkingDirectory(path) def __init__(self): r"""__init__(SBReproducer self) -> SBReproducer""" _lldb.SBReproducer_swiginit(self, _lldb.new_SBReproducer()) __swig_destroy__ = _lldb.delete_SBReproducer # Register SBReproducer in _lldb: _lldb.SBReproducer_swigregister(SBReproducer) def SBReproducer_Capture(path): r"""SBReproducer_Capture(char const * path) -> char const *""" return _lldb.SBReproducer_Capture(path) def SBReproducer_PassiveReplay(path): r"""SBReproducer_PassiveReplay(char const * path) -> char const *""" return _lldb.SBReproducer_PassiveReplay(path) def SBReproducer_SetAutoGenerate(b): r"""SBReproducer_SetAutoGenerate(bool b) -> bool""" return _lldb.SBReproducer_SetAutoGenerate(b) def SBReproducer_SetWorkingDirectory(path): r"""SBReproducer_SetWorkingDirectory(char const * path)""" return _lldb.SBReproducer_SetWorkingDirectory(path) class SBSection(object): r""" Represents an executable image section. SBSection supports iteration through its subsection, represented as SBSection as well. For example, :: for sec in exe_module: if sec.GetName() == '__TEXT': print sec break print INDENT + 'Number of subsections: %d' % sec.GetNumSubSections() for subsec in sec: print INDENT + repr(subsec) produces: :: [0x0000000100000000-0x0000000100002000) a.out.__TEXT Number of subsections: 6 [0x0000000100001780-0x0000000100001d5c) a.out.__TEXT.__text [0x0000000100001d5c-0x0000000100001da4) a.out.__TEXT.__stubs [0x0000000100001da4-0x0000000100001e2c) a.out.__TEXT.__stub_helper [0x0000000100001e2c-0x0000000100001f10) a.out.__TEXT.__cstring [0x0000000100001f10-0x0000000100001f68) a.out.__TEXT.__unwind_info [0x0000000100001f68-0x0000000100001ff8) a.out.__TEXT.__eh_frame See also :py:class:`SBModule` . """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBSection self) -> SBSection __init__(SBSection self, SBSection rhs) -> SBSection """ _lldb.SBSection_swiginit(self, _lldb.new_SBSection(*args)) __swig_destroy__ = _lldb.delete_SBSection def IsValid(self): r"""IsValid(SBSection self) -> bool""" return _lldb.SBSection_IsValid(self) def __nonzero__(self): return _lldb.SBSection___nonzero__(self) __bool__ = __nonzero__ def GetName(self): r"""GetName(SBSection self) -> char const *""" return _lldb.SBSection_GetName(self) def GetParent(self): r"""GetParent(SBSection self) -> SBSection""" return _lldb.SBSection_GetParent(self) def FindSubSection(self, sect_name): r"""FindSubSection(SBSection self, char const * sect_name) -> SBSection""" return _lldb.SBSection_FindSubSection(self, sect_name) def GetNumSubSections(self): r"""GetNumSubSections(SBSection self) -> size_t""" return _lldb.SBSection_GetNumSubSections(self) def GetSubSectionAtIndex(self, idx): r"""GetSubSectionAtIndex(SBSection self, size_t idx) -> SBSection""" return _lldb.SBSection_GetSubSectionAtIndex(self, idx) def GetFileAddress(self): r"""GetFileAddress(SBSection self) -> lldb::addr_t""" return _lldb.SBSection_GetFileAddress(self) def GetLoadAddress(self, target): r"""GetLoadAddress(SBSection self, SBTarget target) -> lldb::addr_t""" return _lldb.SBSection_GetLoadAddress(self, target) def GetByteSize(self): r"""GetByteSize(SBSection self) -> lldb::addr_t""" return _lldb.SBSection_GetByteSize(self) def GetFileOffset(self): r"""GetFileOffset(SBSection self) -> uint64_t""" return _lldb.SBSection_GetFileOffset(self) def GetFileByteSize(self): r"""GetFileByteSize(SBSection self) -> uint64_t""" return _lldb.SBSection_GetFileByteSize(self) def GetSectionData(self, *args): r""" GetSectionData(SBSection self) -> SBData GetSectionData(SBSection self, uint64_t offset, uint64_t size) -> SBData """ return _lldb.SBSection_GetSectionData(self, *args) def GetSectionType(self): r"""GetSectionType(SBSection self) -> lldb::SectionType""" return _lldb.SBSection_GetSectionType(self) def GetPermissions(self): r"""GetPermissions(SBSection self) -> uint32_t""" return _lldb.SBSection_GetPermissions(self) def GetTargetByteSize(self): r""" GetTargetByteSize(SBSection self) -> uint32_t Return the size of a target's byte represented by this section in numbers of host bytes. Note that certain architectures have varying minimum addressable unit (i.e. byte) size for their CODE or DATA buses. @return The number of host (8-bit) bytes needed to hold a target byte """ return _lldb.SBSection_GetTargetByteSize(self) def GetDescription(self, description): r"""GetDescription(SBSection self, SBStream description) -> bool""" return _lldb.SBSection_GetDescription(self, description) def __eq__(self, rhs): r"""__eq__(SBSection self, SBSection rhs) -> bool""" return _lldb.SBSection___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBSection self, SBSection rhs) -> bool""" return _lldb.SBSection___ne__(self, rhs) def __str__(self): r"""__str__(SBSection self) -> std::string""" return _lldb.SBSection___str__(self) def __iter__(self): '''Iterate over all subsections in a lldb.SBSection object.''' return lldb_iter(self, 'GetNumSubSections', 'GetSubSectionAtIndex') def __len__(self): '''Return the number of subsections in a lldb.SBSection object.''' return self.GetNumSubSections() def get_addr(self): return SBAddress(self, 0) name = property(GetName, None, doc='''A read only property that returns the name of this section as a string.''') addr = property(get_addr, None, doc='''A read only property that returns an lldb object that represents the start address (lldb.SBAddress) for this section.''') file_addr = property(GetFileAddress, None, doc='''A read only property that returns an integer that represents the starting "file" address for this section, or the address of the section in the object file in which it is defined.''') size = property(GetByteSize, None, doc='''A read only property that returns the size in bytes of this section as an integer.''') file_offset = property(GetFileOffset, None, doc='''A read only property that returns the file offset in bytes of this section as an integer.''') file_size = property(GetFileByteSize, None, doc='''A read only property that returns the file size in bytes of this section as an integer.''') data = property(GetSectionData, None, doc='''A read only property that returns an lldb object that represents the bytes for this section (lldb.SBData) for this section.''') type = property(GetSectionType, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eSectionType") that represents the type of this section (code, data, etc.).''') target_byte_size = property(GetTargetByteSize, None, doc='''A read only property that returns the size of a target byte represented by this section as a number of host bytes.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBSection in _lldb: _lldb.SBSection_swigregister(SBSection) class SBSourceManager(object): r""" Represents a central authority for displaying source code. For example (from test/source-manager/TestSourceManager.py), :: # Create the filespec for 'main.c'. filespec = lldb.SBFileSpec('main.c', False) source_mgr = self.dbg.GetSourceManager() # Use a string stream as the destination. stream = lldb.SBStream() source_mgr.DisplaySourceLinesWithLineNumbers(filespec, self.line, 2, # context before 2, # context after '=>', # prefix for current line stream) # 2 # 3 int main(int argc, char const *argv[]) { # => 4 printf('Hello world.\n'); // Set break point at this line. # 5 return 0; # 6 } self.expect(stream.GetData(), 'Source code displayed correctly', exe=False, patterns = ['=> %d.*Hello world' % self.line]) """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, rhs): r"""__init__(SBSourceManager self, SBSourceManager rhs) -> SBSourceManager""" _lldb.SBSourceManager_swiginit(self, _lldb.new_SBSourceManager(rhs)) __swig_destroy__ = _lldb.delete_SBSourceManager def DisplaySourceLinesWithLineNumbers(self, file, line, context_before, context_after, current_line_cstr, s): r"""DisplaySourceLinesWithLineNumbers(SBSourceManager self, SBFileSpec file, uint32_t line, uint32_t context_before, uint32_t context_after, char const * current_line_cstr, SBStream s) -> size_t""" return _lldb.SBSourceManager_DisplaySourceLinesWithLineNumbers(self, file, line, context_before, context_after, current_line_cstr, s) def DisplaySourceLinesWithLineNumbersAndColumn(self, file, line, column, context_before, context_after, current_line_cstr, s): r"""DisplaySourceLinesWithLineNumbersAndColumn(SBSourceManager self, SBFileSpec file, uint32_t line, uint32_t column, uint32_t context_before, uint32_t context_after, char const * current_line_cstr, SBStream s) -> size_t""" return _lldb.SBSourceManager_DisplaySourceLinesWithLineNumbersAndColumn(self, file, line, column, context_before, context_after, current_line_cstr, s) # Register SBSourceManager in _lldb: _lldb.SBSourceManager_swigregister(SBSourceManager) class SBStream(object): r""" Represents a destination for streaming data output to. By default, a string stream is created. For example (from test/source-manager/TestSourceManager.py), :: # Create the filespec for 'main.c'. filespec = lldb.SBFileSpec('main.c', False) source_mgr = self.dbg.GetSourceManager() # Use a string stream as the destination. stream = lldb.SBStream() source_mgr.DisplaySourceLinesWithLineNumbers(filespec, self.line, 2, # context before 2, # context after '=>', # prefix for current line stream) # 2 # 3 int main(int argc, char const *argv[]) { # => 4 printf('Hello world.\n'); // Set break point at this line. # 5 return 0; # 6 } self.expect(stream.GetData(), 'Source code displayed correctly', exe=False, patterns = ['=> %d.*Hello world' % self.line]) """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r"""__init__(SBStream self) -> SBStream""" _lldb.SBStream_swiginit(self, _lldb.new_SBStream()) __swig_destroy__ = _lldb.delete_SBStream def IsValid(self): r"""IsValid(SBStream self) -> bool""" return _lldb.SBStream_IsValid(self) def __nonzero__(self): return _lldb.SBStream___nonzero__(self) __bool__ = __nonzero__ def GetData(self): r""" GetData(SBStream self) -> char const * If this stream is not redirected to a file, it will maintain a local cache for the stream data which can be accessed using this accessor. """ return _lldb.SBStream_GetData(self) def GetSize(self): r""" GetSize(SBStream self) -> size_t If this stream is not redirected to a file, it will maintain a local cache for the stream output whose length can be accessed using this accessor. """ return _lldb.SBStream_GetSize(self) def Print(self, str): r"""Print(SBStream self, char const * str)""" return _lldb.SBStream_Print(self, str) def RedirectToFile(self, *args): r""" RedirectToFile(SBStream self, char const * path, bool append) RedirectToFile(SBStream self, SBFile file) RedirectToFile(SBStream self, lldb::FileSP file) """ return _lldb.SBStream_RedirectToFile(self, *args) def RedirectToFileHandle(self, file, transfer_fh_ownership): r"""DEPRECATED, use RedirectToFile""" return _lldb.SBStream_RedirectToFileHandle(self, file, transfer_fh_ownership) def RedirectToFileDescriptor(self, fd, transfer_fh_ownership): r"""DEPRECATED, use RedirectToFile""" return _lldb.SBStream_RedirectToFileDescriptor(self, fd, transfer_fh_ownership) def Clear(self): r""" DEPRECATED, use RedirectToFile If the stream is redirected to a file, forget about the file and if ownership of the file was transferred to this object, close the file. If the stream is backed by a local cache, clear this cache. """ return _lldb.SBStream_Clear(self) def write(self, str): r"""DEPRECATED, use RedirectToFile""" return _lldb.SBStream_write(self, str) def flush(self): r"""DEPRECATED, use RedirectToFile""" return _lldb.SBStream_flush(self) # Register SBStream in _lldb: _lldb.SBStream_swigregister(SBStream) class SBStringList(object): r"""Represents a list of strings.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBStringList self) -> SBStringList __init__(SBStringList self, SBStringList rhs) -> SBStringList """ _lldb.SBStringList_swiginit(self, _lldb.new_SBStringList(*args)) __swig_destroy__ = _lldb.delete_SBStringList def IsValid(self): r"""IsValid(SBStringList self) -> bool""" return _lldb.SBStringList_IsValid(self) def __nonzero__(self): return _lldb.SBStringList___nonzero__(self) __bool__ = __nonzero__ def AppendString(self, str): r"""AppendString(SBStringList self, char const * str)""" return _lldb.SBStringList_AppendString(self, str) def AppendList(self, *args): r""" AppendList(SBStringList self, char const ** strv, int strc) AppendList(SBStringList self, SBStringList strings) """ return _lldb.SBStringList_AppendList(self, *args) def GetSize(self): r"""GetSize(SBStringList self) -> uint32_t""" return _lldb.SBStringList_GetSize(self) def GetStringAtIndex(self, idx): r"""GetStringAtIndex(SBStringList self, size_t idx) -> char const *""" return _lldb.SBStringList_GetStringAtIndex(self, idx) def Clear(self): r"""Clear(SBStringList self)""" return _lldb.SBStringList_Clear(self) def __iter__(self): '''Iterate over all strings in a lldb.SBStringList object.''' return lldb_iter(self, 'GetSize', 'GetStringAtIndex') def __len__(self): '''Return the number of strings in a lldb.SBStringList object.''' return self.GetSize() # Register SBStringList in _lldb: _lldb.SBStringList_swigregister(SBStringList) class SBStructuredData(object): r""" A class representing a StructuredData event. This class wraps the event type generated by StructuredData features. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBStructuredData self) -> SBStructuredData __init__(SBStructuredData self, SBStructuredData rhs) -> SBStructuredData __init__(SBStructuredData self, lldb::EventSP const & event_sp) -> SBStructuredData """ _lldb.SBStructuredData_swiginit(self, _lldb.new_SBStructuredData(*args)) __swig_destroy__ = _lldb.delete_SBStructuredData def IsValid(self): r"""IsValid(SBStructuredData self) -> bool""" return _lldb.SBStructuredData_IsValid(self) def __nonzero__(self): return _lldb.SBStructuredData___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBStructuredData self)""" return _lldb.SBStructuredData_Clear(self) def GetType(self): r"""GetType(SBStructuredData self) -> lldb::StructuredDataType""" return _lldb.SBStructuredData_GetType(self) def GetSize(self): r"""GetSize(SBStructuredData self) -> size_t""" return _lldb.SBStructuredData_GetSize(self) def GetKeys(self, keys): r"""GetKeys(SBStructuredData self, SBStringList keys) -> bool""" return _lldb.SBStructuredData_GetKeys(self, keys) def GetValueForKey(self, key): r"""GetValueForKey(SBStructuredData self, char const * key) -> SBStructuredData""" return _lldb.SBStructuredData_GetValueForKey(self, key) def GetItemAtIndex(self, idx): r"""GetItemAtIndex(SBStructuredData self, size_t idx) -> SBStructuredData""" return _lldb.SBStructuredData_GetItemAtIndex(self, idx) def GetIntegerValue(self, fail_value=0): r"""GetIntegerValue(SBStructuredData self, uint64_t fail_value=0) -> uint64_t""" return _lldb.SBStructuredData_GetIntegerValue(self, fail_value) def GetFloatValue(self, fail_value=0.0): r"""GetFloatValue(SBStructuredData self, double fail_value=0.0) -> double""" return _lldb.SBStructuredData_GetFloatValue(self, fail_value) def GetBooleanValue(self, fail_value=False): r"""GetBooleanValue(SBStructuredData self, bool fail_value=False) -> bool""" return _lldb.SBStructuredData_GetBooleanValue(self, fail_value) def GetStringValue(self, dst): r"""GetStringValue(SBStructuredData self, char * dst) -> size_t""" return _lldb.SBStructuredData_GetStringValue(self, dst) def GetAsJSON(self, stream): r"""GetAsJSON(SBStructuredData self, SBStream stream) -> SBError""" return _lldb.SBStructuredData_GetAsJSON(self, stream) def GetDescription(self, stream): r"""GetDescription(SBStructuredData self, SBStream stream) -> SBError""" return _lldb.SBStructuredData_GetDescription(self, stream) def SetFromJSON(self, stream): r"""SetFromJSON(SBStructuredData self, SBStream stream) -> SBError""" return _lldb.SBStructuredData_SetFromJSON(self, stream) # Register SBStructuredData in _lldb: _lldb.SBStructuredData_swigregister(SBStructuredData) class SBSymbol(object): r""" Represents the symbol possibly associated with a stack frame. :py:class:`SBModule` contains SBSymbol(s). SBSymbol can also be retrieved from :py:class:`SBFrame` . """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr __swig_destroy__ = _lldb.delete_SBSymbol def __init__(self, *args): r""" __init__(SBSymbol self) -> SBSymbol __init__(SBSymbol self, SBSymbol rhs) -> SBSymbol """ _lldb.SBSymbol_swiginit(self, _lldb.new_SBSymbol(*args)) def IsValid(self): r"""IsValid(SBSymbol self) -> bool""" return _lldb.SBSymbol_IsValid(self) def __nonzero__(self): return _lldb.SBSymbol___nonzero__(self) __bool__ = __nonzero__ def GetName(self): r"""GetName(SBSymbol self) -> char const *""" return _lldb.SBSymbol_GetName(self) def GetDisplayName(self): r"""GetDisplayName(SBSymbol self) -> char const *""" return _lldb.SBSymbol_GetDisplayName(self) def GetMangledName(self): r"""GetMangledName(SBSymbol self) -> char const *""" return _lldb.SBSymbol_GetMangledName(self) def GetInstructions(self, *args): r""" GetInstructions(SBSymbol self, SBTarget target) -> SBInstructionList GetInstructions(SBSymbol self, SBTarget target, char const * flavor_string) -> SBInstructionList """ return _lldb.SBSymbol_GetInstructions(self, *args) def GetStartAddress(self): r"""GetStartAddress(SBSymbol self) -> SBAddress""" return _lldb.SBSymbol_GetStartAddress(self) def GetEndAddress(self): r"""GetEndAddress(SBSymbol self) -> SBAddress""" return _lldb.SBSymbol_GetEndAddress(self) def GetPrologueByteSize(self): r"""GetPrologueByteSize(SBSymbol self) -> uint32_t""" return _lldb.SBSymbol_GetPrologueByteSize(self) def GetType(self): r"""GetType(SBSymbol self) -> lldb::SymbolType""" return _lldb.SBSymbol_GetType(self) def GetDescription(self, description): r"""GetDescription(SBSymbol self, SBStream description) -> bool""" return _lldb.SBSymbol_GetDescription(self, description) def IsExternal(self): r"""IsExternal(SBSymbol self) -> bool""" return _lldb.SBSymbol_IsExternal(self) def IsSynthetic(self): r"""IsSynthetic(SBSymbol self) -> bool""" return _lldb.SBSymbol_IsSynthetic(self) def __eq__(self, rhs): r"""__eq__(SBSymbol self, SBSymbol rhs) -> bool""" return _lldb.SBSymbol___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBSymbol self, SBSymbol rhs) -> bool""" return _lldb.SBSymbol___ne__(self, rhs) def __str__(self): r"""__str__(SBSymbol self) -> std::string""" return _lldb.SBSymbol___str__(self) def get_instructions_from_current_target (self): return self.GetInstructions (target) name = property(GetName, None, doc='''A read only property that returns the name for this symbol as a string.''') mangled = property(GetMangledName, None, doc='''A read only property that returns the mangled (linkage) name for this symbol as a string.''') type = property(GetType, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eSymbolType") that represents the type of this symbol.''') addr = property(GetStartAddress, None, doc='''A read only property that returns an lldb object that represents the start address (lldb.SBAddress) for this symbol.''') end_addr = property(GetEndAddress, None, doc='''A read only property that returns an lldb object that represents the end address (lldb.SBAddress) for this symbol.''') prologue_size = property(GetPrologueByteSize, None, doc='''A read only property that returns the size in bytes of the prologue instructions as an unsigned integer.''') instructions = property(get_instructions_from_current_target, None, doc='''A read only property that returns an lldb object that represents the instructions (lldb.SBInstructionList) for this symbol.''') external = property(IsExternal, None, doc='''A read only property that returns a boolean value that indicates if this symbol is externally visiable (exported) from the module that contains it.''') synthetic = property(IsSynthetic, None, doc='''A read only property that returns a boolean value that indicates if this symbol was synthetically created from information in module that contains it.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBSymbol in _lldb: _lldb.SBSymbol_swigregister(SBSymbol) class SBSymbolContext(object): r""" A context object that provides access to core debugger entities. Many debugger functions require a context when doing lookups. This class provides a common structure that can be used as the result of a query that can contain a single result. For example, :: exe = os.path.join(os.getcwd(), 'a.out') # Create a target for the debugger. target = self.dbg.CreateTarget(exe) # Now create a breakpoint on main.c by name 'c'. breakpoint = target.BreakpointCreateByName('c', 'a.out') # Now launch the process, and do not stop at entry point. process = target.LaunchSimple(None, None, os.getcwd()) # The inferior should stop on 'c'. from lldbutil import get_stopped_thread thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) frame0 = thread.GetFrameAtIndex(0) # Now get the SBSymbolContext from this frame. We want everything. :-) context = frame0.GetSymbolContext(lldb.eSymbolContextEverything) # Get the module. module = context.GetModule() ... # And the compile unit associated with the frame. compileUnit = context.GetCompileUnit() ... """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBSymbolContext self) -> SBSymbolContext __init__(SBSymbolContext self, SBSymbolContext rhs) -> SBSymbolContext """ _lldb.SBSymbolContext_swiginit(self, _lldb.new_SBSymbolContext(*args)) __swig_destroy__ = _lldb.delete_SBSymbolContext def IsValid(self): r"""IsValid(SBSymbolContext self) -> bool""" return _lldb.SBSymbolContext_IsValid(self) def __nonzero__(self): return _lldb.SBSymbolContext___nonzero__(self) __bool__ = __nonzero__ def GetModule(self): r"""GetModule(SBSymbolContext self) -> SBModule""" return _lldb.SBSymbolContext_GetModule(self) def GetCompileUnit(self): r"""GetCompileUnit(SBSymbolContext self) -> SBCompileUnit""" return _lldb.SBSymbolContext_GetCompileUnit(self) def GetFunction(self): r"""GetFunction(SBSymbolContext self) -> SBFunction""" return _lldb.SBSymbolContext_GetFunction(self) def GetBlock(self): r"""GetBlock(SBSymbolContext self) -> SBBlock""" return _lldb.SBSymbolContext_GetBlock(self) def GetLineEntry(self): r"""GetLineEntry(SBSymbolContext self) -> SBLineEntry""" return _lldb.SBSymbolContext_GetLineEntry(self) def GetSymbol(self): r"""GetSymbol(SBSymbolContext self) -> SBSymbol""" return _lldb.SBSymbolContext_GetSymbol(self) def SetModule(self, module): r"""SetModule(SBSymbolContext self, SBModule module)""" return _lldb.SBSymbolContext_SetModule(self, module) def SetCompileUnit(self, compile_unit): r"""SetCompileUnit(SBSymbolContext self, SBCompileUnit compile_unit)""" return _lldb.SBSymbolContext_SetCompileUnit(self, compile_unit) def SetFunction(self, function): r"""SetFunction(SBSymbolContext self, SBFunction function)""" return _lldb.SBSymbolContext_SetFunction(self, function) def SetBlock(self, block): r"""SetBlock(SBSymbolContext self, SBBlock block)""" return _lldb.SBSymbolContext_SetBlock(self, block) def SetLineEntry(self, line_entry): r"""SetLineEntry(SBSymbolContext self, SBLineEntry line_entry)""" return _lldb.SBSymbolContext_SetLineEntry(self, line_entry) def SetSymbol(self, symbol): r"""SetSymbol(SBSymbolContext self, SBSymbol symbol)""" return _lldb.SBSymbolContext_SetSymbol(self, symbol) def GetParentOfInlinedScope(self, curr_frame_pc, parent_frame_addr): r"""GetParentOfInlinedScope(SBSymbolContext self, SBAddress curr_frame_pc, SBAddress parent_frame_addr) -> SBSymbolContext""" return _lldb.SBSymbolContext_GetParentOfInlinedScope(self, curr_frame_pc, parent_frame_addr) def GetDescription(self, description): r"""GetDescription(SBSymbolContext self, SBStream description) -> bool""" return _lldb.SBSymbolContext_GetDescription(self, description) def __str__(self): r"""__str__(SBSymbolContext self) -> std::string""" return _lldb.SBSymbolContext___str__(self) module = property(GetModule, SetModule, doc='''A read/write property that allows the getting/setting of the module (lldb.SBModule) in this symbol context.''') compile_unit = property(GetCompileUnit, SetCompileUnit, doc='''A read/write property that allows the getting/setting of the compile unit (lldb.SBCompileUnit) in this symbol context.''') function = property(GetFunction, SetFunction, doc='''A read/write property that allows the getting/setting of the function (lldb.SBFunction) in this symbol context.''') block = property(GetBlock, SetBlock, doc='''A read/write property that allows the getting/setting of the block (lldb.SBBlock) in this symbol context.''') symbol = property(GetSymbol, SetSymbol, doc='''A read/write property that allows the getting/setting of the symbol (lldb.SBSymbol) in this symbol context.''') line_entry = property(GetLineEntry, SetLineEntry, doc='''A read/write property that allows the getting/setting of the line entry (lldb.SBLineEntry) in this symbol context.''') # Register SBSymbolContext in _lldb: _lldb.SBSymbolContext_swigregister(SBSymbolContext) class SBSymbolContextList(object): r""" Represents a list of symbol context object. See also SBSymbolContext. For example (from test/python_api/target/TestTargetAPI.py), :: def find_functions(self, exe_name): '''Exercise SBTaget.FindFunctions() API.''' exe = os.path.join(os.getcwd(), exe_name) # Create a target by the debugger. target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) list = lldb.SBSymbolContextList() num = target.FindFunctions('c', lldb.eFunctionNameTypeAuto, False, list) self.assertTrue(num == 1 and list.GetSize() == 1) for sc in list: self.assertTrue(sc.GetModule().GetFileSpec().GetFilename() == exe_name) self.assertTrue(sc.GetSymbol().GetName() == 'c') """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBSymbolContextList self) -> SBSymbolContextList __init__(SBSymbolContextList self, SBSymbolContextList rhs) -> SBSymbolContextList """ _lldb.SBSymbolContextList_swiginit(self, _lldb.new_SBSymbolContextList(*args)) __swig_destroy__ = _lldb.delete_SBSymbolContextList def IsValid(self): r"""IsValid(SBSymbolContextList self) -> bool""" return _lldb.SBSymbolContextList_IsValid(self) def __nonzero__(self): return _lldb.SBSymbolContextList___nonzero__(self) __bool__ = __nonzero__ def GetSize(self): r"""GetSize(SBSymbolContextList self) -> uint32_t""" return _lldb.SBSymbolContextList_GetSize(self) def GetContextAtIndex(self, idx): r"""GetContextAtIndex(SBSymbolContextList self, uint32_t idx) -> SBSymbolContext""" return _lldb.SBSymbolContextList_GetContextAtIndex(self, idx) def Append(self, *args): r""" Append(SBSymbolContextList self, SBSymbolContext sc) Append(SBSymbolContextList self, SBSymbolContextList sc_list) """ return _lldb.SBSymbolContextList_Append(self, *args) def GetDescription(self, description): r"""GetDescription(SBSymbolContextList self, SBStream description) -> bool""" return _lldb.SBSymbolContextList_GetDescription(self, description) def Clear(self): r"""Clear(SBSymbolContextList self)""" return _lldb.SBSymbolContextList_Clear(self) def __str__(self): r"""__str__(SBSymbolContextList self) -> std::string""" return _lldb.SBSymbolContextList___str__(self) def __iter__(self): '''Iterate over all symbol contexts in a lldb.SBSymbolContextList object.''' return lldb_iter(self, 'GetSize', 'GetContextAtIndex') def __len__(self): return int(self.GetSize()) def __getitem__(self, key): count = len(self) if type(key) is int: if key < count: return self.GetContextAtIndex(key) else: raise IndexError raise TypeError def get_module_array(self): a = [] for i in range(len(self)): obj = self.GetContextAtIndex(i).module if obj: a.append(obj) return a def get_compile_unit_array(self): a = [] for i in range(len(self)): obj = self.GetContextAtIndex(i).compile_unit if obj: a.append(obj) return a def get_function_array(self): a = [] for i in range(len(self)): obj = self.GetContextAtIndex(i).function if obj: a.append(obj) return a def get_block_array(self): a = [] for i in range(len(self)): obj = self.GetContextAtIndex(i).block if obj: a.append(obj) return a def get_symbol_array(self): a = [] for i in range(len(self)): obj = self.GetContextAtIndex(i).symbol if obj: a.append(obj) return a def get_line_entry_array(self): a = [] for i in range(len(self)): obj = self.GetContextAtIndex(i).line_entry if obj: a.append(obj) return a modules = property(get_module_array, None, doc='''Returns a list() of lldb.SBModule objects, one for each module in each SBSymbolContext object in this list.''') compile_units = property(get_compile_unit_array, None, doc='''Returns a list() of lldb.SBCompileUnit objects, one for each compile unit in each SBSymbolContext object in this list.''') functions = property(get_function_array, None, doc='''Returns a list() of lldb.SBFunction objects, one for each function in each SBSymbolContext object in this list.''') blocks = property(get_block_array, None, doc='''Returns a list() of lldb.SBBlock objects, one for each block in each SBSymbolContext object in this list.''') line_entries = property(get_line_entry_array, None, doc='''Returns a list() of lldb.SBLineEntry objects, one for each line entry in each SBSymbolContext object in this list.''') symbols = property(get_symbol_array, None, doc='''Returns a list() of lldb.SBSymbol objects, one for each symbol in each SBSymbolContext object in this list.''') # Register SBSymbolContextList in _lldb: _lldb.SBSymbolContextList_swigregister(SBSymbolContextList) class SBTarget(object): r""" Represents the target program running under the debugger. SBTarget supports module, breakpoint, and watchpoint iterations. For example, :: for m in target.module_iter(): print m produces: :: (x86_64) /Volumes/data/lldb/svn/trunk/test/python_api/lldbutil/iter/a.out (x86_64) /usr/lib/dyld (x86_64) /usr/lib/libstdc++.6.dylib (x86_64) /usr/lib/libSystem.B.dylib (x86_64) /usr/lib/system/libmathCommon.A.dylib (x86_64) /usr/lib/libSystem.B.dylib(__commpage) and, :: for b in target.breakpoint_iter(): print b produces: :: SBBreakpoint: id = 1, file ='main.cpp', line = 66, locations = 1 SBBreakpoint: id = 2, file ='main.cpp', line = 85, locations = 1 and, :: for wp_loc in target.watchpoint_iter(): print wp_loc produces: :: Watchpoint 1: addr = 0x1034ca048 size = 4 state = enabled type = rw declare @ '/Volumes/data/lldb/svn/trunk/test/python_api/watchpoint/main.c:12' hw_index = 0 hit_count = 2 ignore_count = 0 """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr eBroadcastBitBreakpointChanged = _lldb.SBTarget_eBroadcastBitBreakpointChanged eBroadcastBitModulesLoaded = _lldb.SBTarget_eBroadcastBitModulesLoaded eBroadcastBitModulesUnloaded = _lldb.SBTarget_eBroadcastBitModulesUnloaded eBroadcastBitWatchpointChanged = _lldb.SBTarget_eBroadcastBitWatchpointChanged eBroadcastBitSymbolsLoaded = _lldb.SBTarget_eBroadcastBitSymbolsLoaded def __init__(self, *args): r""" __init__(SBTarget self) -> SBTarget __init__(SBTarget self, SBTarget rhs) -> SBTarget """ _lldb.SBTarget_swiginit(self, _lldb.new_SBTarget(*args)) __swig_destroy__ = _lldb.delete_SBTarget @staticmethod def GetBroadcasterClassName(): r"""GetBroadcasterClassName() -> char const *""" return _lldb.SBTarget_GetBroadcasterClassName() def IsValid(self): r"""IsValid(SBTarget self) -> bool""" return _lldb.SBTarget_IsValid(self) def __nonzero__(self): return _lldb.SBTarget___nonzero__(self) __bool__ = __nonzero__ @staticmethod def EventIsTargetEvent(event): r"""EventIsTargetEvent(SBEvent event) -> bool""" return _lldb.SBTarget_EventIsTargetEvent(event) @staticmethod def GetTargetFromEvent(event): r"""GetTargetFromEvent(SBEvent event) -> SBTarget""" return _lldb.SBTarget_GetTargetFromEvent(event) @staticmethod def GetNumModulesFromEvent(event): r"""GetNumModulesFromEvent(SBEvent event) -> uint32_t""" return _lldb.SBTarget_GetNumModulesFromEvent(event) @staticmethod def GetModuleAtIndexFromEvent(idx, event): r"""GetModuleAtIndexFromEvent(uint32_t const idx, SBEvent event) -> SBModule""" return _lldb.SBTarget_GetModuleAtIndexFromEvent(idx, event) def GetProcess(self): r"""GetProcess(SBTarget self) -> SBProcess""" return _lldb.SBTarget_GetProcess(self) def GetPlatform(self): r""" GetPlatform(SBTarget self) -> SBPlatform Return the platform object associated with the target. After return, the platform object should be checked for validity. @return A platform object. """ return _lldb.SBTarget_GetPlatform(self) def Install(self): r""" Install(SBTarget self) -> SBError Install any binaries that need to be installed. This function does nothing when debugging on the host system. When connected to remote platforms, the target's main executable and any modules that have their install path set will be installed on the remote platform. If the main executable doesn't have an install location set, it will be installed in the remote platform's working directory. @return An error describing anything that went wrong during installation. """ return _lldb.SBTarget_Install(self) def LaunchSimple(self, argv, envp, working_directory): r""" LaunchSimple(SBTarget self, char const ** argv, char const ** envp, char const * working_directory) -> SBProcess Launch a new process with sensible defaults. :param argv: The argument array. :param envp: The environment array. :param working_directory: The working directory to have the child process run in :return: The newly created process. :rtype: SBProcess A pseudo terminal will be used as stdin/stdout/stderr. No launch flags are passed and the target's debuger is used as a listener. For example, :: process = target.LaunchSimple(['X', 'Y', 'Z'], None, os.getcwd()) launches a new process by passing 'X', 'Y', 'Z' as the args to the executable. """ return _lldb.SBTarget_LaunchSimple(self, argv, envp, working_directory) def Launch(self, *args): r""" Launch(SBTarget self, SBListener listener, char const ** argv, char const ** envp, char const * stdin_path, char const * stdout_path, char const * stderr_path, char const * working_directory, uint32_t launch_flags, bool stop_at_entry, SBError error) -> SBProcess Launch(SBTarget self, SBLaunchInfo launch_info, SBError error) -> SBProcess Launch a new process. Launch a new process by spawning a new process using the target object's executable module's file as the file to launch. Arguments are given in argv, and the environment variables are in envp. Standard input and output files can be optionally re-directed to stdin_path, stdout_path, and stderr_path. @param[in] listener An optional listener that will receive all process events. If listener is valid then listener will listen to all process events. If not valid, then this target's debugger (SBTarget::GetDebugger()) will listen to all process events. @param[in] argv The argument array. @param[in] envp The environment array. @param[in] launch_flags Flags to modify the launch (@see lldb::LaunchFlags) @param[in] stdin_path The path to use when re-directing the STDIN of the new process. If all stdXX_path arguments are NULL, a pseudo terminal will be used. @param[in] stdout_path The path to use when re-directing the STDOUT of the new process. If all stdXX_path arguments are NULL, a pseudo terminal will be used. @param[in] stderr_path The path to use when re-directing the STDERR of the new process. If all stdXX_path arguments are NULL, a pseudo terminal will be used. @param[in] working_directory The working directory to have the child process run in @param[in] launch_flags Some launch options specified by logical OR'ing lldb::LaunchFlags enumeration values together. @param[in] stop_at_entry If false do not stop the inferior at the entry point. @param[out] An error object. Contains the reason if there is some failure. @return A process object for the newly created process. For example, process = target.Launch(self.dbg.GetListener(), None, None, None, '/tmp/stdout.txt', None, None, 0, False, error) launches a new process by passing nothing for both the args and the envs and redirect the standard output of the inferior to the /tmp/stdout.txt file. It does not specify a working directory so that the debug server will use its idea of what the current working directory is for the inferior. Also, we ask the debugger not to stop the inferior at the entry point. If no breakpoint is specified for the inferior, it should run to completion if no user interaction is required. """ return _lldb.SBTarget_Launch(self, *args) def LoadCore(self, *args):
def Attach(self, attach_info, error): r"""Attach(SBTarget self, SBAttachInfo attach_info, SBError error) -> SBProcess""" return _lldb.SBTarget_Attach(self, attach_info, error) def AttachToProcessWithID(self, listener, pid, error): r""" AttachToProcessWithID(SBTarget self, SBListener listener, lldb::pid_t pid, SBError error) -> SBProcess Attach to process with pid. @param[in] listener An optional listener that will receive all process events. If listener is valid then listener will listen to all process events. If not valid, then this target's debugger (SBTarget::GetDebugger()) will listen to all process events. @param[in] pid The process ID to attach to. @param[out] An error explaining what went wrong if attach fails. @return A process object for the attached process. """ return _lldb.SBTarget_AttachToProcessWithID(self, listener, pid, error) def AttachToProcessWithName(self, listener, name, wait_for, error): r""" AttachToProcessWithName(SBTarget self, SBListener listener, char const * name, bool wait_for, SBError error) -> SBProcess Attach to process with name. @param[in] listener An optional listener that will receive all process events. If listener is valid then listener will listen to all process events. If not valid, then this target's debugger (SBTarget::GetDebugger()) will listen to all process events. @param[in] name Basename of process to attach to. @param[in] wait_for If true wait for a new instance of 'name' to be launched. @param[out] An error explaining what went wrong if attach fails. @return A process object for the attached process. """ return _lldb.SBTarget_AttachToProcessWithName(self, listener, name, wait_for, error) def ConnectRemote(self, listener, url, plugin_name, error): r""" ConnectRemote(SBTarget self, SBListener listener, char const * url, char const * plugin_name, SBError error) -> SBProcess Connect to a remote debug server with url. @param[in] listener An optional listener that will receive all process events. If listener is valid then listener will listen to all process events. If not valid, then this target's debugger (SBTarget::GetDebugger()) will listen to all process events. @param[in] url The url to connect to, e.g., 'connect://localhost:12345'. @param[in] plugin_name The plugin name to be used; can be NULL. @param[out] An error explaining what went wrong if the connect fails. @return A process object for the connected process. """ return _lldb.SBTarget_ConnectRemote(self, listener, url, plugin_name, error) def GetExecutable(self): r"""GetExecutable(SBTarget self) -> SBFileSpec""" return _lldb.SBTarget_GetExecutable(self) def AppendImageSearchPath(self, _from, to, error): r""" AppendImageSearchPath(SBTarget self, char const * _from, char const * to, SBError error) Append the path mapping (from -> to) to the target's paths mapping list. """ return _lldb.SBTarget_AppendImageSearchPath(self, _from, to, error) def AddModule(self, *args): r""" AddModule(SBTarget self, SBModule module) -> bool AddModule(SBTarget self, char const * path, char const * triple, char const * uuid) -> SBModule AddModule(SBTarget self, char const * path, char const * triple, char const * uuid_cstr, char const * symfile) -> SBModule AddModule(SBTarget self, SBModuleSpec module_spec) -> SBModule """ return _lldb.SBTarget_AddModule(self, *args) def GetNumModules(self): r"""GetNumModules(SBTarget self) -> uint32_t""" return _lldb.SBTarget_GetNumModules(self) def GetModuleAtIndex(self, idx): r"""GetModuleAtIndex(SBTarget self, uint32_t idx) -> SBModule""" return _lldb.SBTarget_GetModuleAtIndex(self, idx) def RemoveModule(self, module): r"""RemoveModule(SBTarget self, SBModule module) -> bool""" return _lldb.SBTarget_RemoveModule(self, module) def GetDebugger(self): r"""GetDebugger(SBTarget self) -> SBDebugger""" return _lldb.SBTarget_GetDebugger(self) def FindModule(self, file_spec): r"""FindModule(SBTarget self, SBFileSpec file_spec) -> SBModule""" return _lldb.SBTarget_FindModule(self, file_spec) def FindCompileUnits(self, sb_file_spec): r""" FindCompileUnits(SBTarget self, SBFileSpec sb_file_spec) -> SBSymbolContextList Find compile units related to this target and passed source file. :param sb_file_spec: A :py:class:`lldb::SBFileSpec` object that contains source file specification. :return: The symbol contexts for all the matches. :rtype: SBSymbolContextList """ return _lldb.SBTarget_FindCompileUnits(self, sb_file_spec) def GetByteOrder(self): r"""GetByteOrder(SBTarget self) -> lldb::ByteOrder""" return _lldb.SBTarget_GetByteOrder(self) def GetAddressByteSize(self): r"""GetAddressByteSize(SBTarget self) -> uint32_t""" return _lldb.SBTarget_GetAddressByteSize(self) def GetTriple(self): r"""GetTriple(SBTarget self) -> char const *""" return _lldb.SBTarget_GetTriple(self) def GetDataByteSize(self): r""" GetDataByteSize(SBTarget self) -> uint32_t Architecture data byte width accessor :return: The size in 8-bit (host) bytes of a minimum addressable unit from the Architecture's data bus. """ return _lldb.SBTarget_GetDataByteSize(self) def GetCodeByteSize(self): r""" GetCodeByteSize(SBTarget self) -> uint32_t Architecture code byte width accessor. :return: The size in 8-bit (host) bytes of a minimum addressable unit from the Architecture's code bus. """ return _lldb.SBTarget_GetCodeByteSize(self) def SetSectionLoadAddress(self, section, section_base_addr): r"""SetSectionLoadAddress(SBTarget self, SBSection section, lldb::addr_t section_base_addr) -> SBError""" return _lldb.SBTarget_SetSectionLoadAddress(self, section, section_base_addr) def ClearSectionLoadAddress(self, section): r"""ClearSectionLoadAddress(SBTarget self, SBSection section) -> SBError""" return _lldb.SBTarget_ClearSectionLoadAddress(self, section) def SetModuleLoadAddress(self, module, sections_offset): r"""SetModuleLoadAddress(SBTarget self, SBModule module, int64_t sections_offset) -> SBError""" return _lldb.SBTarget_SetModuleLoadAddress(self, module, sections_offset) def ClearModuleLoadAddress(self, module): r"""ClearModuleLoadAddress(SBTarget self, SBModule module) -> SBError""" return _lldb.SBTarget_ClearModuleLoadAddress(self, module) def FindFunctions(self, *args): r""" FindFunctions(SBTarget self, char const * name, uint32_t name_type_mask=eFunctionNameTypeAny) -> SBSymbolContextList Find functions by name. :param name: The name of the function we are looking for. :param name_type_mask: A logical OR of one or more FunctionNameType enum bits that indicate what kind of names should be used when doing the lookup. Bits include fully qualified names, base names, C++ methods, or ObjC selectors. See FunctionNameType for more details. :return: A lldb::SBSymbolContextList that gets filled in with all of the symbol contexts for all the matches. """ return _lldb.SBTarget_FindFunctions(self, *args) def FindFirstType(self, type): r"""FindFirstType(SBTarget self, char const * type) -> SBType""" return _lldb.SBTarget_FindFirstType(self, type) def FindTypes(self, type): r"""FindTypes(SBTarget self, char const * type) -> SBTypeList""" return _lldb.SBTarget_FindTypes(self, type) def GetBasicType(self, type): r"""GetBasicType(SBTarget self, lldb::BasicType type) -> SBType""" return _lldb.SBTarget_GetBasicType(self, type) def GetSourceManager(self): r"""GetSourceManager(SBTarget self) -> SBSourceManager""" return _lldb.SBTarget_GetSourceManager(self) def FindFirstGlobalVariable(self, name): r""" FindFirstGlobalVariable(SBTarget self, char const * name) -> SBValue Find the first global (or static) variable by name. @param[in] name The name of the global or static variable we are looking for. @return An SBValue that gets filled in with the found variable (if any). """ return _lldb.SBTarget_FindFirstGlobalVariable(self, name) def FindGlobalVariables(self, *args): r""" FindGlobalVariables(SBTarget self, char const * name, uint32_t max_matches) -> SBValueList FindGlobalVariables(SBTarget self, char const * name, uint32_t max_matches, lldb::MatchType matchtype) -> SBValueList Find global and static variables by name. @param[in] name The name of the global or static variable we are looking for. @param[in] max_matches Allow the number of matches to be limited to max_matches. @return A list of matched variables in an SBValueList. """ return _lldb.SBTarget_FindGlobalVariables(self, *args) def FindGlobalFunctions(self, name, max_matches, matchtype): r"""FindGlobalFunctions(SBTarget self, char const * name, uint32_t max_matches, lldb::MatchType matchtype) -> SBSymbolContextList""" return _lldb.SBTarget_FindGlobalFunctions(self, name, max_matches, matchtype) def Clear(self): r"""Clear(SBTarget self)""" return _lldb.SBTarget_Clear(self) def ResolveFileAddress(self, file_addr): r""" ResolveFileAddress(SBTarget self, lldb::addr_t file_addr) -> SBAddress Resolve a current file address into a section offset address. @param[in] file_addr @return An SBAddress which will be valid if... """ return _lldb.SBTarget_ResolveFileAddress(self, file_addr) def ResolveLoadAddress(self, vm_addr): r"""ResolveLoadAddress(SBTarget self, lldb::addr_t vm_addr) -> SBAddress""" return _lldb.SBTarget_ResolveLoadAddress(self, vm_addr) def ResolvePastLoadAddress(self, stop_id, vm_addr): r"""ResolvePastLoadAddress(SBTarget self, uint32_t stop_id, lldb::addr_t vm_addr) -> SBAddress""" return _lldb.SBTarget_ResolvePastLoadAddress(self, stop_id, vm_addr) def ResolveSymbolContextForAddress(self, addr, resolve_scope): r"""ResolveSymbolContextForAddress(SBTarget self, SBAddress addr, uint32_t resolve_scope) -> SBSymbolContext""" return _lldb.SBTarget_ResolveSymbolContextForAddress(self, addr, resolve_scope) def ReadMemory(self, addr, buf, error): r""" ReadMemory(SBTarget self, SBAddress addr, void * buf, SBError error) -> size_t Read target memory. If a target process is running then memory is read from here. Otherwise the memory is read from the object files. For a target whose bytes are sized as a multiple of host bytes, the data read back will preserve the target's byte order. @param[in] addr A target address to read from. @param[out] buf The buffer to read memory into. @param[in] size The maximum number of host bytes to read in the buffer passed into this call @param[out] error Error information is written here if the memory read fails. @return The amount of data read in host bytes. """ return _lldb.SBTarget_ReadMemory(self, addr, buf, error) def BreakpointCreateByLocation(self, *args): r""" BreakpointCreateByLocation(SBTarget self, char const * file, uint32_t line) -> SBBreakpoint BreakpointCreateByLocation(SBTarget self, SBFileSpec file_spec, uint32_t line) -> SBBreakpoint BreakpointCreateByLocation(SBTarget self, SBFileSpec file_spec, uint32_t line, lldb::addr_t offset) -> SBBreakpoint BreakpointCreateByLocation(SBTarget self, SBFileSpec file_spec, uint32_t line, lldb::addr_t offset, SBFileSpecList module_list) -> SBBreakpoint BreakpointCreateByLocation(SBTarget self, SBFileSpec file_spec, uint32_t line, uint32_t column, lldb::addr_t offset, SBFileSpecList module_list) -> SBBreakpoint BreakpointCreateByLocation(SBTarget self, SBFileSpec file_spec, uint32_t line, uint32_t column, lldb::addr_t offset, SBFileSpecList module_list, bool move_to_nearest_code) -> SBBreakpoint """ return _lldb.SBTarget_BreakpointCreateByLocation(self, *args) def BreakpointCreateByName(self, *args): r""" BreakpointCreateByName(SBTarget self, char const * symbol_name, char const * module_name=None) -> SBBreakpoint BreakpointCreateByName(SBTarget self, char const * symbol_name, uint32_t func_name_type, SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakpoint BreakpointCreateByName(SBTarget self, char const * symbol_name, uint32_t func_name_type, lldb::LanguageType symbol_language, SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakpoint """ return _lldb.SBTarget_BreakpointCreateByName(self, *args) def BreakpointCreateByNames(self, *args): r""" BreakpointCreateByNames(SBTarget self, char const ** symbol_name, uint32_t name_type_mask, SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakpoint BreakpointCreateByNames(SBTarget self, char const ** symbol_name, uint32_t name_type_mask, lldb::LanguageType symbol_language, SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakpoint BreakpointCreateByNames(SBTarget self, char const ** symbol_name, uint32_t name_type_mask, lldb::LanguageType symbol_language, lldb::addr_t offset, SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakpoint """ return _lldb.SBTarget_BreakpointCreateByNames(self, *args) def BreakpointCreateByRegex(self, *args): r""" BreakpointCreateByRegex(SBTarget self, char const * symbol_name_regex, char const * module_name=None) -> SBBreakpoint BreakpointCreateByRegex(SBTarget self, char const * symbol_name_regex, lldb::LanguageType symbol_language, SBFileSpecList module_list, SBFileSpecList comp_unit_list) -> SBBreakpoint """ return _lldb.SBTarget_BreakpointCreateByRegex(self, *args) def BreakpointCreateBySourceRegex(self, *args): r""" BreakpointCreateBySourceRegex(SBTarget self, char const * source_regex, SBFileSpec source_file, char const * module_name=None) -> SBBreakpoint BreakpointCreateBySourceRegex(SBTarget self, char const * source_regex, SBFileSpecList module_list, SBFileSpecList file_list) -> SBBreakpoint BreakpointCreateBySourceRegex(SBTarget self, char const * source_regex, SBFileSpecList module_list, SBFileSpecList source_file, SBStringList func_names) -> SBBreakpoint """ return _lldb.SBTarget_BreakpointCreateBySourceRegex(self, *args) def BreakpointCreateForException(self, *args): r""" BreakpointCreateForException(SBTarget self, lldb::LanguageType language, bool catch_bp, bool throw_bp) -> SBBreakpoint BreakpointCreateForException(SBTarget self, lldb::LanguageType language, bool catch_bp, bool throw_bp, SBStringList extra_args) -> SBBreakpoint """ return _lldb.SBTarget_BreakpointCreateForException(self, *args) def BreakpointCreateByAddress(self, address): r"""BreakpointCreateByAddress(SBTarget self, lldb::addr_t address) -> SBBreakpoint""" return _lldb.SBTarget_BreakpointCreateByAddress(self, address) def GetEnvironment(self): r"""GetEnvironment(SBTarget self) -> SBEnvironment""" return _lldb.SBTarget_GetEnvironment(self) def BreakpointCreateBySBAddress(self, sb_address): r"""BreakpointCreateBySBAddress(SBTarget self, SBAddress sb_address) -> SBBreakpoint""" return _lldb.SBTarget_BreakpointCreateBySBAddress(self, sb_address) def BreakpointCreateFromScript(self, class_name, extra_args, module_list, file_list, request_hardware=False): r""" BreakpointCreateFromScript(SBTarget self, char const * class_name, SBStructuredData extra_args, SBFileSpecList module_list, SBFileSpecList file_list, bool request_hardware=False) -> SBBreakpoint Create a breakpoint using a scripted resolver. @param[in] class_name This is the name of the class that implements a scripted resolver. The class should have the following signature: :: class Resolver: def __init__(self, bkpt, extra_args): # bkpt - the breakpoint for which this is the resolver. When # the resolver finds an interesting address, call AddLocation # on this breakpoint to add it. # # extra_args - an SBStructuredData that can be used to # parametrize this instance. Same as the extra_args passed # to BreakpointCreateFromScript. def __get_depth__ (self): # This is optional, but if defined, you should return the # depth at which you want the callback to be called. The # available options are: # lldb.eSearchDepthModule # lldb.eSearchDepthCompUnit # The default if you don't implement this method is # eSearchDepthModule. def __callback__(self, sym_ctx): # sym_ctx - an SBSymbolContext that is the cursor in the # search through the program to resolve breakpoints. # The sym_ctx will be filled out to the depth requested in # __get_depth__. # Look in this sym_ctx for new breakpoint locations, # and if found use bkpt.AddLocation to add them. # Note, you will only get called for modules/compile_units that # pass the SearchFilter provided by the module_list & file_list # passed into BreakpointCreateFromScript. def get_short_help(self): # Optional, but if implemented return a short string that will # be printed at the beginning of the break list output for the # breakpoint. @param[in] extra_args This is an SBStructuredData object that will get passed to the constructor of the class in class_name. You can use this to reuse the same class, parametrizing it with entries from this dictionary. @param module_list If this is non-empty, this will be used as the module filter in the SearchFilter created for this breakpoint. @param file_list If this is non-empty, this will be used as the comp unit filter in the SearchFilter created for this breakpoint. @return An SBBreakpoint that will set locations based on the logic in the resolver's search callback. """ return _lldb.SBTarget_BreakpointCreateFromScript(self, class_name, extra_args, module_list, file_list, request_hardware) def GetNumBreakpoints(self): r"""GetNumBreakpoints(SBTarget self) -> uint32_t""" return _lldb.SBTarget_GetNumBreakpoints(self) def GetBreakpointAtIndex(self, idx): r"""GetBreakpointAtIndex(SBTarget self, uint32_t idx) -> SBBreakpoint""" return _lldb.SBTarget_GetBreakpointAtIndex(self, idx) def BreakpointDelete(self, break_id): r"""BreakpointDelete(SBTarget self, lldb::break_id_t break_id) -> bool""" return _lldb.SBTarget_BreakpointDelete(self, break_id) def FindBreakpointByID(self, break_id): r"""FindBreakpointByID(SBTarget self, lldb::break_id_t break_id) -> SBBreakpoint""" return _lldb.SBTarget_FindBreakpointByID(self, break_id) def FindBreakpointsByName(self, name, bkpt_list): r"""FindBreakpointsByName(SBTarget self, char const * name, SBBreakpointList bkpt_list) -> bool""" return _lldb.SBTarget_FindBreakpointsByName(self, name, bkpt_list) def DeleteBreakpointName(self, name): r"""DeleteBreakpointName(SBTarget self, char const * name)""" return _lldb.SBTarget_DeleteBreakpointName(self, name) def GetBreakpointNames(self, names): r"""GetBreakpointNames(SBTarget self, SBStringList names)""" return _lldb.SBTarget_GetBreakpointNames(self, names) def EnableAllBreakpoints(self): r"""EnableAllBreakpoints(SBTarget self) -> bool""" return _lldb.SBTarget_EnableAllBreakpoints(self) def DisableAllBreakpoints(self): r"""DisableAllBreakpoints(SBTarget self) -> bool""" return _lldb.SBTarget_DisableAllBreakpoints(self) def DeleteAllBreakpoints(self): r"""DeleteAllBreakpoints(SBTarget self) -> bool""" return _lldb.SBTarget_DeleteAllBreakpoints(self) def BreakpointsCreateFromFile(self, *args): r""" BreakpointsCreateFromFile(SBTarget self, SBFileSpec source_file, SBBreakpointList bkpt_list) -> SBError BreakpointsCreateFromFile(SBTarget self, SBFileSpec source_file, SBStringList matching_names, SBBreakpointList new_bps) -> SBError Read breakpoints from source_file and return the newly created breakpoints in bkpt_list. @param[in] source_file The file from which to read the breakpoints @param[in] matching_names Only read in breakpoints whose names match one of the names in this list. @param[out] bkpt_list A list of the newly created breakpoints. @return An SBError detailing any errors in reading in the breakpoints. """ return _lldb.SBTarget_BreakpointsCreateFromFile(self, *args) def BreakpointsWriteToFile(self, *args): r""" BreakpointsWriteToFile(SBTarget self, SBFileSpec dest_file) -> SBError BreakpointsWriteToFile(SBTarget self, SBFileSpec dest_file, SBBreakpointList bkpt_list, bool append=False) -> SBError """ return _lldb.SBTarget_BreakpointsWriteToFile(self, *args) def GetNumWatchpoints(self): r"""GetNumWatchpoints(SBTarget self) -> uint32_t""" return _lldb.SBTarget_GetNumWatchpoints(self) def GetWatchpointAtIndex(self, idx): r"""GetWatchpointAtIndex(SBTarget self, uint32_t idx) -> SBWatchpoint""" return _lldb.SBTarget_GetWatchpointAtIndex(self, idx) def DeleteWatchpoint(self, watch_id): r"""DeleteWatchpoint(SBTarget self, lldb::watch_id_t watch_id) -> bool""" return _lldb.SBTarget_DeleteWatchpoint(self, watch_id) def FindWatchpointByID(self, watch_id): r"""FindWatchpointByID(SBTarget self, lldb::watch_id_t watch_id) -> SBWatchpoint""" return _lldb.SBTarget_FindWatchpointByID(self, watch_id) def EnableAllWatchpoints(self): r"""EnableAllWatchpoints(SBTarget self) -> bool""" return _lldb.SBTarget_EnableAllWatchpoints(self) def DisableAllWatchpoints(self): r"""DisableAllWatchpoints(SBTarget self) -> bool""" return _lldb.SBTarget_DisableAllWatchpoints(self) def DeleteAllWatchpoints(self): r"""DeleteAllWatchpoints(SBTarget self) -> bool""" return _lldb.SBTarget_DeleteAllWatchpoints(self) def WatchAddress(self, addr, size, read, write, error): r"""WatchAddress(SBTarget self, lldb::addr_t addr, size_t size, bool read, bool write, SBError error) -> SBWatchpoint""" return _lldb.SBTarget_WatchAddress(self, addr, size, read, write, error) def GetBroadcaster(self): r"""GetBroadcaster(SBTarget self) -> SBBroadcaster""" return _lldb.SBTarget_GetBroadcaster(self) def CreateValueFromAddress(self, name, addr, type): r""" CreateValueFromAddress(SBTarget self, char const * name, SBAddress addr, SBType type) -> SBValue Create an SBValue with the given name by treating the memory starting at addr as an entity of type. @param[in] name The name of the resultant SBValue @param[in] addr The address of the start of the memory region to be used. @param[in] type The type to use to interpret the memory starting at addr. @return An SBValue of the given type, may be invalid if there was an error reading the underlying memory. """ return _lldb.SBTarget_CreateValueFromAddress(self, name, addr, type) def CreateValueFromData(self, name, data, type): r"""CreateValueFromData(SBTarget self, char const * name, SBData data, SBType type) -> SBValue""" return _lldb.SBTarget_CreateValueFromData(self, name, data, type) def CreateValueFromExpression(self, name, expr): r"""CreateValueFromExpression(SBTarget self, char const * name, char const * expr) -> SBValue""" return _lldb.SBTarget_CreateValueFromExpression(self, name, expr) def ReadInstructions(self, *args): r""" ReadInstructions(SBTarget self, SBAddress base_addr, uint32_t count) -> SBInstructionList ReadInstructions(SBTarget self, SBAddress base_addr, uint32_t count, char const * flavor_string) -> SBInstructionList Disassemble a specified number of instructions starting at an address. :param base_addr: the address to start disassembly from. :param count: the number of instructions to disassemble. :param flavor_string: may be 'intel' or 'att' on x86 targets to specify that style of disassembly. :rtype: SBInstructionList """ return _lldb.SBTarget_ReadInstructions(self, *args) def GetInstructions(self, base_addr, buf): r""" GetInstructions(SBTarget self, SBAddress base_addr, void const * buf) -> SBInstructionList Disassemble the bytes in a buffer and return them in an SBInstructionList. :param base_addr: used for symbolicating the offsets in the byte stream when disassembling. :param buf: bytes to be disassembled. :param size: (C++) size of the buffer. :rtype: SBInstructionList """ return _lldb.SBTarget_GetInstructions(self, base_addr, buf) def GetInstructionsWithFlavor(self, base_addr, flavor_string, buf): r""" GetInstructionsWithFlavor(SBTarget self, SBAddress base_addr, char const * flavor_string, void const * buf) -> SBInstructionList Disassemble the bytes in a buffer and return them in an SBInstructionList, with a supplied flavor. :param base_addr: used for symbolicating the offsets in the byte stream when disassembling. :param flavor: may be 'intel' or 'att' on x86 targets to specify that style of disassembly. :param buf: bytes to be disassembled. :param size: (C++) size of the buffer. :rtype: SBInstructionList """ return _lldb.SBTarget_GetInstructionsWithFlavor(self, base_addr, flavor_string, buf) def FindSymbols(self, *args): r"""FindSymbols(SBTarget self, char const * name, lldb::SymbolType type=eSymbolTypeAny) -> SBSymbolContextList""" return _lldb.SBTarget_FindSymbols(self, *args) def GetDescription(self, description, description_level): r"""GetDescription(SBTarget self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTarget_GetDescription(self, description, description_level) def GetStackRedZoneSize(self): r"""GetStackRedZoneSize(SBTarget self) -> lldb::addr_t""" return _lldb.SBTarget_GetStackRedZoneSize(self) def IsLoaded(self, module): r""" IsLoaded(SBTarget self, SBModule module) -> bool Returns true if the module has been loaded in this `SBTarget`. A module can be loaded either by the dynamic loader or by being manually added to the target (see `SBTarget.AddModule` and the `target module add` command). :rtype: bool """ return _lldb.SBTarget_IsLoaded(self, module) def GetLaunchInfo(self): r"""GetLaunchInfo(SBTarget self) -> SBLaunchInfo""" return _lldb.SBTarget_GetLaunchInfo(self) def SetLaunchInfo(self, launch_info): r"""SetLaunchInfo(SBTarget self, SBLaunchInfo launch_info)""" return _lldb.SBTarget_SetLaunchInfo(self, launch_info) def SetCollectingStats(self, v): r"""SetCollectingStats(SBTarget self, bool v)""" return _lldb.SBTarget_SetCollectingStats(self, v) def GetCollectingStats(self): r"""GetCollectingStats(SBTarget self) -> bool""" return _lldb.SBTarget_GetCollectingStats(self) def GetStatistics(self): r"""GetStatistics(SBTarget self) -> SBStructuredData""" return _lldb.SBTarget_GetStatistics(self) def __eq__(self, rhs): r"""__eq__(SBTarget self, SBTarget rhs) -> bool""" return _lldb.SBTarget___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBTarget self, SBTarget rhs) -> bool""" return _lldb.SBTarget___ne__(self, rhs) def EvaluateExpression(self, *args): r""" EvaluateExpression(SBTarget self, char const * expr) -> SBValue EvaluateExpression(SBTarget self, char const * expr, SBExpressionOptions options) -> SBValue """ return _lldb.SBTarget_EvaluateExpression(self, *args) def __str__(self): r"""__str__(SBTarget self) -> std::string""" return _lldb.SBTarget___str__(self) class modules_access(object): '''A helper object that will lazily hand out lldb.SBModule objects for a target when supplied an index, or by full or partial path.''' def __init__(self, sbtarget): self.sbtarget = sbtarget def __len__(self): if self.sbtarget: return int(self.sbtarget.GetNumModules()) return 0 def __getitem__(self, key): num_modules = self.sbtarget.GetNumModules() if type(key) is int: if key < num_modules: return self.sbtarget.GetModuleAtIndex(key) elif type(key) is str: if key.find('/') == -1: for idx in range(num_modules): module = self.sbtarget.GetModuleAtIndex(idx) if module.file.basename == key: return module else: for idx in range(num_modules): module = self.sbtarget.GetModuleAtIndex(idx) if module.file.fullpath == key: return module # See if the string is a UUID try: the_uuid = uuid.UUID(key) if the_uuid: for idx in range(num_modules): module = self.sbtarget.GetModuleAtIndex(idx) if module.uuid == the_uuid: return module except: return None elif type(key) is uuid.UUID: for idx in range(num_modules): module = self.sbtarget.GetModuleAtIndex(idx) if module.uuid == key: return module elif type(key) is re.SRE_Pattern: matching_modules = [] for idx in range(num_modules): module = self.sbtarget.GetModuleAtIndex(idx) re_match = key.search(module.path.fullpath) if re_match: matching_modules.append(module) return matching_modules else: print("error: unsupported item type: %s" % type(key)) return None def get_modules_access_object(self): '''An accessor function that returns a modules_access() object which allows lazy module access from a lldb.SBTarget object.''' return self.modules_access (self) def get_modules_array(self): '''An accessor function that returns a list() that contains all modules in a lldb.SBTarget object.''' modules = [] for idx in range(self.GetNumModules()): modules.append(self.GetModuleAtIndex(idx)) return modules def module_iter(self): '''Returns an iterator over all modules in a lldb.SBTarget object.''' return lldb_iter(self, 'GetNumModules', 'GetModuleAtIndex') def breakpoint_iter(self): '''Returns an iterator over all breakpoints in a lldb.SBTarget object.''' return lldb_iter(self, 'GetNumBreakpoints', 'GetBreakpointAtIndex') def watchpoint_iter(self): '''Returns an iterator over all watchpoints in a lldb.SBTarget object.''' return lldb_iter(self, 'GetNumWatchpoints', 'GetWatchpointAtIndex') modules = property(get_modules_array, None, doc='''A read only property that returns a list() of lldb.SBModule objects contained in this target. This list is a list all modules that the target currently is tracking (the main executable and all dependent shared libraries).''') module = property(get_modules_access_object, None, doc=r'''A read only property that returns an object that implements python operator overloading with the square brackets().\n target.module[<int>] allows array access to any modules.\n target.module[<str>] allows access to modules by basename, full path, or uuid string value.\n target.module[uuid.UUID()] allows module access by UUID.\n target.module[re] allows module access using a regular expression that matches the module full path.''') process = property(GetProcess, None, doc='''A read only property that returns an lldb object that represents the process (lldb.SBProcess) that this target owns.''') executable = property(GetExecutable, None, doc='''A read only property that returns an lldb object that represents the main executable module (lldb.SBModule) for this target.''') debugger = property(GetDebugger, None, doc='''A read only property that returns an lldb object that represents the debugger (lldb.SBDebugger) that owns this target.''') num_breakpoints = property(GetNumBreakpoints, None, doc='''A read only property that returns the number of breakpoints that this target has as an integer.''') num_watchpoints = property(GetNumWatchpoints, None, doc='''A read only property that returns the number of watchpoints that this target has as an integer.''') broadcaster = property(GetBroadcaster, None, doc='''A read only property that an lldb object that represents the broadcaster (lldb.SBBroadcaster) for this target.''') byte_order = property(GetByteOrder, None, doc='''A read only property that returns an lldb enumeration value (lldb.eByteOrderLittle, lldb.eByteOrderBig, lldb.eByteOrderInvalid) that represents the byte order for this target.''') addr_size = property(GetAddressByteSize, None, doc='''A read only property that returns the size in bytes of an address for this target.''') triple = property(GetTriple, None, doc='''A read only property that returns the target triple (arch-vendor-os) for this target as a string.''') data_byte_size = property(GetDataByteSize, None, doc='''A read only property that returns the size in host bytes of a byte in the data address space for this target.''') code_byte_size = property(GetCodeByteSize, None, doc='''A read only property that returns the size in host bytes of a byte in the code address space for this target.''') platform = property(GetPlatform, None, doc='''A read only property that returns the platform associated with with this target.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBTarget in _lldb: _lldb.SBTarget_swigregister(SBTarget) def SBTarget_GetBroadcasterClassName(): r"""SBTarget_GetBroadcasterClassName() -> char const *""" return _lldb.SBTarget_GetBroadcasterClassName() def SBTarget_EventIsTargetEvent(event): r"""SBTarget_EventIsTargetEvent(SBEvent event) -> bool""" return _lldb.SBTarget_EventIsTargetEvent(event) def SBTarget_GetTargetFromEvent(event): r"""SBTarget_GetTargetFromEvent(SBEvent event) -> SBTarget""" return _lldb.SBTarget_GetTargetFromEvent(event) def SBTarget_GetNumModulesFromEvent(event): r"""SBTarget_GetNumModulesFromEvent(SBEvent event) -> uint32_t""" return _lldb.SBTarget_GetNumModulesFromEvent(event) def SBTarget_GetModuleAtIndexFromEvent(idx, event): r"""SBTarget_GetModuleAtIndexFromEvent(uint32_t const idx, SBEvent event) -> SBModule""" return _lldb.SBTarget_GetModuleAtIndexFromEvent(idx, event) class SBThread(object): r""" Represents a thread of execution. :py:class:`SBProcess` contains SBThread(s). SBThreads can be referred to by their ID, which maps to the system specific thread identifier, or by IndexID. The ID may or may not be unique depending on whether the system reuses its thread identifiers. The IndexID is a monotonically increasing identifier that will always uniquely reference a particular thread, and when that thread goes away it will not be reused. SBThread supports frame iteration. For example (from test/python_api/ lldbutil/iter/TestLLDBIterator.py), :: from lldbutil import print_stacktrace stopped_due_to_breakpoint = False for thread in process: if self.TraceOn(): print_stacktrace(thread) ID = thread.GetThreadID() if thread.GetStopReason() == lldb.eStopReasonBreakpoint: stopped_due_to_breakpoint = True for frame in thread: self.assertTrue(frame.GetThread().GetThreadID() == ID) if self.TraceOn(): print frame self.assertTrue(stopped_due_to_breakpoint) See also :py:class:`SBFrame` . """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr eBroadcastBitStackChanged = _lldb.SBThread_eBroadcastBitStackChanged eBroadcastBitThreadSuspended = _lldb.SBThread_eBroadcastBitThreadSuspended eBroadcastBitThreadResumed = _lldb.SBThread_eBroadcastBitThreadResumed eBroadcastBitSelectedFrameChanged = _lldb.SBThread_eBroadcastBitSelectedFrameChanged eBroadcastBitThreadSelected = _lldb.SBThread_eBroadcastBitThreadSelected def __init__(self, *args): r""" __init__(SBThread self) -> SBThread __init__(SBThread self, SBThread thread) -> SBThread """ _lldb.SBThread_swiginit(self, _lldb.new_SBThread(*args)) __swig_destroy__ = _lldb.delete_SBThread @staticmethod def GetBroadcasterClassName(): r"""GetBroadcasterClassName() -> char const *""" return _lldb.SBThread_GetBroadcasterClassName() @staticmethod def EventIsThreadEvent(event): r"""EventIsThreadEvent(SBEvent event) -> bool""" return _lldb.SBThread_EventIsThreadEvent(event) @staticmethod def GetStackFrameFromEvent(event): r"""GetStackFrameFromEvent(SBEvent event) -> SBFrame""" return _lldb.SBThread_GetStackFrameFromEvent(event) @staticmethod def GetThreadFromEvent(event): r"""GetThreadFromEvent(SBEvent event) -> SBThread""" return _lldb.SBThread_GetThreadFromEvent(event) def IsValid(self): r"""IsValid(SBThread self) -> bool""" return _lldb.SBThread_IsValid(self) def __nonzero__(self): return _lldb.SBThread___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBThread self)""" return _lldb.SBThread_Clear(self) def GetStopReason(self): r"""GetStopReason(SBThread self) -> lldb::StopReason""" return _lldb.SBThread_GetStopReason(self) def GetStopReasonDataCount(self): r""" GetStopReasonDataCount(SBThread self) -> size_t Get the number of words associated with the stop reason. See also GetStopReasonDataAtIndex(). """ return _lldb.SBThread_GetStopReasonDataCount(self) def GetStopReasonDataAtIndex(self, idx): r""" GetStopReasonDataAtIndex(SBThread self, uint32_t idx) -> uint64_t Get information associated with a stop reason. Breakpoint stop reasons will have data that consists of pairs of breakpoint IDs followed by the breakpoint location IDs (they always come in pairs). Stop Reason Count Data Type ======================== ===== ========================================= eStopReasonNone 0 eStopReasonTrace 0 eStopReasonBreakpoint N duple: {breakpoint id, location id} eStopReasonWatchpoint 1 watchpoint id eStopReasonSignal 1 unix signal number eStopReasonException N exception data eStopReasonExec 0 eStopReasonPlanComplete 0 """ return _lldb.SBThread_GetStopReasonDataAtIndex(self, idx) def GetStopReasonExtendedInfoAsJSON(self, stream): r""" Collects a thread's stop reason extended information dictionary and prints it into the SBStream in a JSON format. The format of this JSON dictionary depends on the stop reason and is currently used only for instrumentation plugins. """ return _lldb.SBThread_GetStopReasonExtendedInfoAsJSON(self, stream) def GetStopReasonExtendedBacktraces(self, type): r""" Returns a collection of historical stack traces that are significant to the current stop reason. Used by ThreadSanitizer, where we provide various stack traces that were involved in a data race or other type of detected issue. """ return _lldb.SBThread_GetStopReasonExtendedBacktraces(self, type) def GetStopDescription(self, dst_or_null): r""" Pass only an (int)length and expect to get a Python string describing the stop reason. """ return _lldb.SBThread_GetStopDescription(self, dst_or_null) def GetStopReturnValue(self): r""" If the last stop on this thread was a thread plan that gathered a return value from the stop, this function will fetch that stop result. At present only the "step-out" thread plan gathers stop return values. """ return _lldb.SBThread_GetStopReturnValue(self) def GetStopErrorValue(self): r""" If the last stop on this thread was a thread plan that gathered an error value from the stop, this function will fetch that stop result. At present only the "step-out" thread plan gathers stop error values, and that only for stepping out of Swift functions. """ return _lldb.SBThread_GetStopErrorValue(self) def GetThreadID(self): r""" Returns a unique thread identifier (type lldb::tid_t, typically a 64-bit type) for the current SBThread that will remain constant throughout the thread's lifetime in this process and will not be reused by another thread during this process lifetime. On Mac OS X systems, this is a system-wide unique thread identifier; this identifier is also used by other tools like sample which helps to associate data from those tools with lldb. See related GetIndexID. """ return _lldb.SBThread_GetThreadID(self) def GetIndexID(self): r""" Return the index number for this SBThread. The index number is the same thing that a user gives as an argument to 'thread select' in the command line lldb. These numbers start at 1 (for the first thread lldb sees in a debug session) and increments up throughout the process lifetime. An index number will not be reused for a different thread later in a process - thread 1 will always be associated with the same thread. See related GetThreadID. This method returns a uint32_t index number, takes no arguments. """ return _lldb.SBThread_GetIndexID(self) def GetName(self): r"""GetName(SBThread self) -> char const *""" return _lldb.SBThread_GetName(self) def GetQueueName(self): r""" Return the queue name associated with this thread, if any, as a str. For example, with a libdispatch (aka Grand Central Dispatch) queue. """ return _lldb.SBThread_GetQueueName(self) def GetQueueID(self): r""" Return the dispatch_queue_id for this thread, if any, as a lldb::queue_id_t. For example, with a libdispatch (aka Grand Central Dispatch) queue. """ return _lldb.SBThread_GetQueueID(self) def GetInfoItemByPathAsString(self, path, strm): r""" GetInfoItemByPathAsString(SBThread self, char const * path, SBStream strm) -> bool Takes a path string and a SBStream reference as parameters, returns a bool. Collects the thread's 'info' dictionary from the remote system, uses the path argument to descend into the dictionary to an item of interest, and prints it into the SBStream in a natural format. Return bool is to indicate if anything was printed into the stream (true) or not (false). """ return _lldb.SBThread_GetInfoItemByPathAsString(self, path, strm) def GetQueue(self): r""" Return the SBQueue for this thread. If this thread is not currently associated with a libdispatch queue, the SBQueue object's IsValid() method will return false. If this SBThread is actually a HistoryThread, we may be able to provide QueueID and QueueName, but not provide an SBQueue. Those individual attributes may have been saved for the HistoryThread without enough information to reconstitute the entire SBQueue at that time. This method takes no arguments, returns an SBQueue. """ return _lldb.SBThread_GetQueue(self) def StepOver(self, *args): r"""StepOver(SBThread self, lldb::RunMode stop_other_threads=eOnlyDuringStepping)Do a source level single step over in the currently selected thread.""" return _lldb.SBThread_StepOver(self, *args) def StepInto(self, *args): r""" StepInto(SBThread self, lldb::RunMode stop_other_threads=eOnlyDuringStepping) StepInto(SBThread self, char const * target_name, lldb::RunMode stop_other_threads=eOnlyDuringStepping) Step the current thread from the current source line to the line given by end_line, stopping if the thread steps into the function given by target_name. If target_name is None, then stepping will stop in any of the places we would normally stop. Step the current thread from the current source line to the line given by end_line, stopping if the thread steps into the function given by target_name. If target_name is None, then stepping will stop in any of the places we would normally stop. """ return _lldb.SBThread_StepInto(self, *args) def StepOut(self, *args): r"""StepOut(SBThread self)Step out of the currently selected thread.""" return _lldb.SBThread_StepOut(self, *args) def StepOutOfFrame(self, *args): r"""StepOutOfFrame(SBThread self, SBFrame frame)Step out of the specified frame.""" return _lldb.SBThread_StepOutOfFrame(self, *args) def StepInstruction(self, *args): r"""StepInstruction(SBThread self, bool step_over)Do an instruction level single step in the currently selected thread.""" return _lldb.SBThread_StepInstruction(self, *args) def StepOverUntil(self, frame, file_spec, line): r"""StepOverUntil(SBThread self, SBFrame frame, SBFileSpec file_spec, uint32_t line) -> SBError""" return _lldb.SBThread_StepOverUntil(self, frame, file_spec, line) def StepUsingScriptedThreadPlan(self, *args): r""" StepUsingScriptedThreadPlan(SBThread self, char const * script_class_name) -> SBError StepUsingScriptedThreadPlan(SBThread self, char const * script_class_name, bool resume_immediately) -> SBError StepUsingScriptedThreadPlan(SBThread self, char const * script_class_name, SBStructuredData args_data, bool resume_immediately) -> SBError """ return _lldb.SBThread_StepUsingScriptedThreadPlan(self, *args) def JumpToLine(self, file_spec, line): r"""JumpToLine(SBThread self, SBFileSpec file_spec, uint32_t line) -> SBError""" return _lldb.SBThread_JumpToLine(self, file_spec, line) def RunToAddress(self, *args): r""" RunToAddress(SBThread self, lldb::addr_t addr) RunToAddress(SBThread self, lldb::addr_t addr, SBError error) """ return _lldb.SBThread_RunToAddress(self, *args) def ReturnFromFrame(self, frame, return_value): r""" Force a return from the frame passed in (and any frames younger than it) without executing any more code in those frames. If return_value contains a valid SBValue, that will be set as the return value from frame. Note, at present only scalar return values are supported. """ return _lldb.SBThread_ReturnFromFrame(self, frame, return_value) def UnwindInnermostExpression(self): r""" Unwind the stack frames from the innermost expression evaluation. This API is equivalent to 'thread return -x'. """ return _lldb.SBThread_UnwindInnermostExpression(self) def Suspend(self, *args): r""" Suspend(SBThread self) -> bool Suspend(SBThread self, SBError error) -> bool LLDB currently supports process centric debugging which means when any thread in a process stops, all other threads are stopped. The Suspend() call here tells our process to suspend a thread and not let it run when the other threads in a process are allowed to run. So when SBProcess::Continue() is called, any threads that aren't suspended will be allowed to run. If any of the SBThread functions for stepping are called (StepOver, StepInto, StepOut, StepInstruction, RunToAddres), the thread will now be allowed to run and these functions will simply return. Eventually we plan to add support for thread centric debugging where each thread is controlled individually and each thread would broadcast its state, but we haven't implemented this yet. Likewise the SBThread::Resume() call will again allow the thread to run when the process is continued. Suspend() and Resume() functions are not currently reference counted, if anyone has the need for them to be reference counted, please let us know. """ return _lldb.SBThread_Suspend(self, *args) def Resume(self, *args): r""" Resume(SBThread self) -> bool Resume(SBThread self, SBError error) -> bool """ return _lldb.SBThread_Resume(self, *args) def IsSuspended(self): r"""IsSuspended(SBThread self) -> bool""" return _lldb.SBThread_IsSuspended(self) def IsStopped(self): r"""IsStopped(SBThread self) -> bool""" return _lldb.SBThread_IsStopped(self) def GetNumFrames(self): r"""GetNumFrames(SBThread self) -> uint32_t""" return _lldb.SBThread_GetNumFrames(self) def GetFrameAtIndex(self, idx): r"""GetFrameAtIndex(SBThread self, uint32_t idx) -> SBFrame""" return _lldb.SBThread_GetFrameAtIndex(self, idx) def GetSelectedFrame(self): r"""GetSelectedFrame(SBThread self) -> SBFrame""" return _lldb.SBThread_GetSelectedFrame(self) def SetSelectedFrame(self, frame_idx): r"""SetSelectedFrame(SBThread self, uint32_t frame_idx) -> SBFrame""" return _lldb.SBThread_SetSelectedFrame(self, frame_idx) def GetProcess(self): r"""GetProcess(SBThread self) -> SBProcess""" return _lldb.SBThread_GetProcess(self) def GetDescription(self, *args): r""" GetDescription(SBThread self, SBStream description) -> bool GetDescription(SBThread self, SBStream description, bool stop_format) -> bool Get the description strings for this thread that match what the lldb driver will present, using the thread-format (stop_format==false) or thread-stop-format (stop_format = true). """ return _lldb.SBThread_GetDescription(self, *args) def GetStatus(self, status): r"""GetStatus(SBThread self, SBStream status) -> bool""" return _lldb.SBThread_GetStatus(self, status) def __eq__(self, rhs): r"""__eq__(SBThread self, SBThread rhs) -> bool""" return _lldb.SBThread___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBThread self, SBThread rhs) -> bool""" return _lldb.SBThread___ne__(self, rhs) def GetExtendedBacktraceThread(self, type): r""" Given an argument of str to specify the type of thread-origin extended backtrace to retrieve, query whether the origin of this thread is available. An SBThread is retured; SBThread.IsValid will return true if an extended backtrace was available. The returned SBThread is not a part of the SBProcess' thread list and it cannot be manipulated like normal threads -- you cannot step or resume it, for instance -- it is intended to used primarily for generating a backtrace. You may request the returned thread's own thread origin in turn. """ return _lldb.SBThread_GetExtendedBacktraceThread(self, type) def GetExtendedBacktraceOriginatingIndexID(self): r""" Takes no arguments, returns a uint32_t. If this SBThread is an ExtendedBacktrace thread, get the IndexID of the original thread that this ExtendedBacktrace thread represents, if available. The thread that was running this backtrace in the past may not have been registered with lldb's thread index (if it was created, did its work, and was destroyed without lldb ever stopping execution). In that case, this ExtendedBacktrace thread's IndexID will be returned. """ return _lldb.SBThread_GetExtendedBacktraceOriginatingIndexID(self) def GetCurrentException(self): r""" Returns an SBValue object represeting the current exception for the thread, if there is any. Currently, this works for Obj-C code and returns an SBValue representing the NSException object at the throw site or that's currently being processes. """ return _lldb.SBThread_GetCurrentException(self) def GetCurrentExceptionBacktrace(self): r""" Returns a historical (fake) SBThread representing the stack trace of an exception, if there is one for the thread. Currently, this works for Obj-C code, and can retrieve the throw-site backtrace of an NSException object even when the program is no longer at the throw site. """ return _lldb.SBThread_GetCurrentExceptionBacktrace(self) def SafeToCallFunctions(self): r""" Takes no arguments, returns a bool. lldb may be able to detect that function calls should not be executed on a given thread at a particular point in time. It is recommended that this is checked before performing an inferior function call on a given thread. """ return _lldb.SBThread_SafeToCallFunctions(self) def __str__(self): r"""__str__(SBThread self) -> std::string""" return _lldb.SBThread___str__(self) def __iter__(self): '''Iterate over all frames in a lldb.SBThread object.''' return lldb_iter(self, 'GetNumFrames', 'GetFrameAtIndex') def __len__(self): '''Return the number of frames in a lldb.SBThread object.''' return self.GetNumFrames() class frames_access(object): '''A helper object that will lazily hand out frames for a thread when supplied an index.''' def __init__(self, sbthread): self.sbthread = sbthread def __len__(self): if self.sbthread: return int(self.sbthread.GetNumFrames()) return 0 def __getitem__(self, key): if type(key) is int and key < self.sbthread.GetNumFrames(): return self.sbthread.GetFrameAtIndex(key) return None def get_frames_access_object(self): '''An accessor function that returns a frames_access() object which allows lazy frame access from a lldb.SBThread object.''' return self.frames_access (self) def get_thread_frames(self): '''An accessor function that returns a list() that contains all frames in a lldb.SBThread object.''' frames = [] for frame in self: frames.append(frame) return frames id = property(GetThreadID, None, doc='''A read only property that returns the thread ID as an integer.''') idx = property(GetIndexID, None, doc='''A read only property that returns the thread index ID as an integer. Thread index ID values start at 1 and increment as threads come and go and can be used to uniquely identify threads.''') return_value = property(GetStopReturnValue, None, doc='''A read only property that returns an lldb object that represents the return value from the last stop (lldb.SBValue) if we just stopped due to stepping out of a function.''') process = property(GetProcess, None, doc='''A read only property that returns an lldb object that represents the process (lldb.SBProcess) that owns this thread.''') num_frames = property(GetNumFrames, None, doc='''A read only property that returns the number of stack frames in this thread as an integer.''') frames = property(get_thread_frames, None, doc='''A read only property that returns a list() of lldb.SBFrame objects for all frames in this thread.''') frame = property(get_frames_access_object, None, doc='''A read only property that returns an object that can be used to access frames as an array ("frame_12 = lldb.thread.frame[12]").''') name = property(GetName, None, doc='''A read only property that returns the name of this thread as a string.''') queue = property(GetQueueName, None, doc='''A read only property that returns the dispatch queue name of this thread as a string.''') queue_id = property(GetQueueID, None, doc='''A read only property that returns the dispatch queue id of this thread as an integer.''') stop_reason = property(GetStopReason, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eStopReason") that represents the reason this thread stopped.''') is_suspended = property(IsSuspended, None, doc='''A read only property that returns a boolean value that indicates if this thread is suspended.''') is_stopped = property(IsStopped, None, doc='''A read only property that returns a boolean value that indicates if this thread is stopped but not exited.''') def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBThread in _lldb: _lldb.SBThread_swigregister(SBThread) def SBThread_GetBroadcasterClassName(): r"""SBThread_GetBroadcasterClassName() -> char const *""" return _lldb.SBThread_GetBroadcasterClassName() def SBThread_EventIsThreadEvent(event): r"""SBThread_EventIsThreadEvent(SBEvent event) -> bool""" return _lldb.SBThread_EventIsThreadEvent(event) def SBThread_GetStackFrameFromEvent(event): r"""SBThread_GetStackFrameFromEvent(SBEvent event) -> SBFrame""" return _lldb.SBThread_GetStackFrameFromEvent(event) def SBThread_GetThreadFromEvent(event): r"""SBThread_GetThreadFromEvent(SBEvent event) -> SBThread""" return _lldb.SBThread_GetThreadFromEvent(event) class SBThreadCollection(object): r"""Represents a collection of SBThread objects.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBThreadCollection self) -> SBThreadCollection __init__(SBThreadCollection self, SBThreadCollection rhs) -> SBThreadCollection """ _lldb.SBThreadCollection_swiginit(self, _lldb.new_SBThreadCollection(*args)) __swig_destroy__ = _lldb.delete_SBThreadCollection def IsValid(self): r"""IsValid(SBThreadCollection self) -> bool""" return _lldb.SBThreadCollection_IsValid(self) def __nonzero__(self): return _lldb.SBThreadCollection___nonzero__(self) __bool__ = __nonzero__ def GetSize(self): r"""GetSize(SBThreadCollection self) -> size_t""" return _lldb.SBThreadCollection_GetSize(self) def GetThreadAtIndex(self, idx): r"""GetThreadAtIndex(SBThreadCollection self, size_t idx) -> SBThread""" return _lldb.SBThreadCollection_GetThreadAtIndex(self, idx) # Register SBThreadCollection in _lldb: _lldb.SBThreadCollection_swigregister(SBThreadCollection) class SBThreadPlan(object): r""" Represents a plan for the execution control of a given thread. See also :py:class:`SBThread` and :py:class:`SBFrame`. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBThreadPlan self) -> SBThreadPlan __init__(SBThreadPlan self, SBThreadPlan threadPlan) -> SBThreadPlan __init__(SBThreadPlan self, lldb::ThreadPlanSP const & lldb_object_sp) -> SBThreadPlan __init__(SBThreadPlan self, SBThread thread, char const * class_name) -> SBThreadPlan """ _lldb.SBThreadPlan_swiginit(self, _lldb.new_SBThreadPlan(*args)) __swig_destroy__ = _lldb.delete_SBThreadPlan def IsValid(self, *args): r""" IsValid(SBThreadPlan self) -> bool IsValid(SBThreadPlan self) -> bool """ return _lldb.SBThreadPlan_IsValid(self, *args) def __nonzero__(self): return _lldb.SBThreadPlan___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBThreadPlan self)""" return _lldb.SBThreadPlan_Clear(self) def GetStopReason(self): r"""GetStopReason(SBThreadPlan self) -> lldb::StopReason""" return _lldb.SBThreadPlan_GetStopReason(self) def GetStopReasonDataCount(self): r""" GetStopReasonDataCount(SBThreadPlan self) -> size_t Get the number of words associated with the stop reason. See also GetStopReasonDataAtIndex(). """ return _lldb.SBThreadPlan_GetStopReasonDataCount(self) def GetStopReasonDataAtIndex(self, idx): r""" GetStopReasonDataAtIndex(SBThreadPlan self, uint32_t idx) -> uint64_t Get information associated with a stop reason. Breakpoint stop reasons will have data that consists of pairs of breakpoint IDs followed by the breakpoint location IDs (they always come in pairs). Stop Reason Count Data Type ======================== ===== ========================================= eStopReasonNone 0 eStopReasonTrace 0 eStopReasonBreakpoint N duple: {breakpoint id, location id} eStopReasonWatchpoint 1 watchpoint id eStopReasonSignal 1 unix signal number eStopReasonException N exception data eStopReasonExec 0 eStopReasonPlanComplete 0 """ return _lldb.SBThreadPlan_GetStopReasonDataAtIndex(self, idx) def GetThread(self): r"""GetThread(SBThreadPlan self) -> SBThread""" return _lldb.SBThreadPlan_GetThread(self) def GetDescription(self, description): r"""GetDescription(SBThreadPlan self, SBStream description) -> bool""" return _lldb.SBThreadPlan_GetDescription(self, description) def SetPlanComplete(self, success): r"""SetPlanComplete(SBThreadPlan self, bool success)""" return _lldb.SBThreadPlan_SetPlanComplete(self, success) def IsPlanComplete(self): r"""IsPlanComplete(SBThreadPlan self) -> bool""" return _lldb.SBThreadPlan_IsPlanComplete(self) def IsPlanStale(self): r"""IsPlanStale(SBThreadPlan self) -> bool""" return _lldb.SBThreadPlan_IsPlanStale(self) def GetStopOthers(self): r""" GetStopOthers(SBThreadPlan self) -> bool Return whether this plan will ask to stop other threads when it runs. """ return _lldb.SBThreadPlan_GetStopOthers(self) def SetStopOthers(self, stop_others): r"""SetStopOthers(SBThreadPlan self, bool stop_others)""" return _lldb.SBThreadPlan_SetStopOthers(self, stop_others) def QueueThreadPlanForStepOverRange(self, start_address, range_size): r"""QueueThreadPlanForStepOverRange(SBThreadPlan self, SBAddress start_address, lldb::addr_t range_size) -> SBThreadPlan""" return _lldb.SBThreadPlan_QueueThreadPlanForStepOverRange(self, start_address, range_size) def QueueThreadPlanForStepInRange(self, start_address, range_size): r"""QueueThreadPlanForStepInRange(SBThreadPlan self, SBAddress start_address, lldb::addr_t range_size) -> SBThreadPlan""" return _lldb.SBThreadPlan_QueueThreadPlanForStepInRange(self, start_address, range_size) def QueueThreadPlanForStepOut(self, frame_idx_to_step_to, first_insn=False): r"""QueueThreadPlanForStepOut(SBThreadPlan self, uint32_t frame_idx_to_step_to, bool first_insn=False) -> SBThreadPlan""" return _lldb.SBThreadPlan_QueueThreadPlanForStepOut(self, frame_idx_to_step_to, first_insn) def QueueThreadPlanForRunToAddress(self, address): r"""QueueThreadPlanForRunToAddress(SBThreadPlan self, SBAddress address) -> SBThreadPlan""" return _lldb.SBThreadPlan_QueueThreadPlanForRunToAddress(self, address) def QueueThreadPlanForStepScripted(self, *args): r""" QueueThreadPlanForStepScripted(SBThreadPlan self, char const * script_class_name) -> SBThreadPlan QueueThreadPlanForStepScripted(SBThreadPlan self, char const * script_class_name, SBError error) -> SBThreadPlan QueueThreadPlanForStepScripted(SBThreadPlan self, char const * script_class_name, SBStructuredData args_data, SBError error) -> SBThreadPlan """ return _lldb.SBThreadPlan_QueueThreadPlanForStepScripted(self, *args) # Register SBThreadPlan in _lldb: _lldb.SBThreadPlan_swigregister(SBThreadPlan) class SBTrace(object): r"""Represents a processor trace.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r"""__init__(SBTrace self) -> SBTrace""" _lldb.SBTrace_swiginit(self, _lldb.new_SBTrace()) def GetTraceData(self, error, buf, offset, thread_id): r"""GetTraceData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t""" return _lldb.SBTrace_GetTraceData(self, error, buf, offset, thread_id) def GetMetaData(self, error, buf, offset, thread_id): r"""GetMetaData(SBTrace self, SBError error, void * buf, size_t offset, lldb::tid_t thread_id) -> size_t""" return _lldb.SBTrace_GetMetaData(self, error, buf, offset, thread_id) def StopTrace(self, error, thread_id): r"""StopTrace(SBTrace self, SBError error, lldb::tid_t thread_id)""" return _lldb.SBTrace_StopTrace(self, error, thread_id) def GetTraceConfig(self, options, error): r"""GetTraceConfig(SBTrace self, SBTraceOptions options, SBError error)""" return _lldb.SBTrace_GetTraceConfig(self, options, error) def GetTraceUID(self): r"""GetTraceUID(SBTrace self) -> lldb::user_id_t""" return _lldb.SBTrace_GetTraceUID(self) def __nonzero__(self): return _lldb.SBTrace___nonzero__(self) __bool__ = __nonzero__ def IsValid(self): r"""IsValid(SBTrace self) -> bool""" return _lldb.SBTrace_IsValid(self) __swig_destroy__ = _lldb.delete_SBTrace # Register SBTrace in _lldb: _lldb.SBTrace_swigregister(SBTrace) class SBTraceOptions(object): r""" Represents the possible options when doing processor tracing. See :py:class:`SBProcess.StartTrace`. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r"""__init__(SBTraceOptions self) -> SBTraceOptions""" _lldb.SBTraceOptions_swiginit(self, _lldb.new_SBTraceOptions()) def getType(self): r"""getType(SBTraceOptions self) -> lldb::TraceType""" return _lldb.SBTraceOptions_getType(self) def getTraceBufferSize(self): r"""getTraceBufferSize(SBTraceOptions self) -> uint64_t""" return _lldb.SBTraceOptions_getTraceBufferSize(self) def getTraceParams(self, error): r"""getTraceParams(SBTraceOptions self, SBError error) -> SBStructuredData""" return _lldb.SBTraceOptions_getTraceParams(self, error) def getMetaDataBufferSize(self): r"""getMetaDataBufferSize(SBTraceOptions self) -> uint64_t""" return _lldb.SBTraceOptions_getMetaDataBufferSize(self) def setTraceParams(self, params): r"""setTraceParams(SBTraceOptions self, SBStructuredData params)""" return _lldb.SBTraceOptions_setTraceParams(self, params) def setType(self, type): r"""setType(SBTraceOptions self, lldb::TraceType type)""" return _lldb.SBTraceOptions_setType(self, type) def setTraceBufferSize(self, size): r"""setTraceBufferSize(SBTraceOptions self, uint64_t size)""" return _lldb.SBTraceOptions_setTraceBufferSize(self, size) def setMetaDataBufferSize(self, size): r"""setMetaDataBufferSize(SBTraceOptions self, uint64_t size)""" return _lldb.SBTraceOptions_setMetaDataBufferSize(self, size) def setThreadID(self, thread_id): r"""setThreadID(SBTraceOptions self, lldb::tid_t thread_id)""" return _lldb.SBTraceOptions_setThreadID(self, thread_id) def getThreadID(self): r"""getThreadID(SBTraceOptions self) -> lldb::tid_t""" return _lldb.SBTraceOptions_getThreadID(self) def __nonzero__(self): return _lldb.SBTraceOptions___nonzero__(self) __bool__ = __nonzero__ def IsValid(self): r"""IsValid(SBTraceOptions self) -> bool""" return _lldb.SBTraceOptions_IsValid(self) __swig_destroy__ = _lldb.delete_SBTraceOptions # Register SBTraceOptions in _lldb: _lldb.SBTraceOptions_swigregister(SBTraceOptions) class SBTypeMember(object): r"""Represents a member of a type.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeMember self) -> SBTypeMember __init__(SBTypeMember self, SBTypeMember rhs) -> SBTypeMember """ _lldb.SBTypeMember_swiginit(self, _lldb.new_SBTypeMember(*args)) __swig_destroy__ = _lldb.delete_SBTypeMember def IsValid(self): r"""IsValid(SBTypeMember self) -> bool""" return _lldb.SBTypeMember_IsValid(self) def __nonzero__(self): return _lldb.SBTypeMember___nonzero__(self) __bool__ = __nonzero__ def GetName(self): r"""GetName(SBTypeMember self) -> char const *""" return _lldb.SBTypeMember_GetName(self) def GetType(self): r"""GetType(SBTypeMember self) -> SBType""" return _lldb.SBTypeMember_GetType(self) def GetOffsetInBytes(self): r"""GetOffsetInBytes(SBTypeMember self) -> uint64_t""" return _lldb.SBTypeMember_GetOffsetInBytes(self) def GetOffsetInBits(self): r"""GetOffsetInBits(SBTypeMember self) -> uint64_t""" return _lldb.SBTypeMember_GetOffsetInBits(self) def IsBitfield(self): r"""IsBitfield(SBTypeMember self) -> bool""" return _lldb.SBTypeMember_IsBitfield(self) def GetBitfieldSizeInBits(self): r"""GetBitfieldSizeInBits(SBTypeMember self) -> uint32_t""" return _lldb.SBTypeMember_GetBitfieldSizeInBits(self) def __str__(self): r"""__str__(SBTypeMember self) -> std::string""" return _lldb.SBTypeMember___str__(self) name = property(GetName, None, doc='''A read only property that returns the name for this member as a string.''') type = property(GetType, None, doc='''A read only property that returns an lldb object that represents the type (lldb.SBType) for this member.''') byte_offset = property(GetOffsetInBytes, None, doc='''A read only property that returns offset in bytes for this member as an integer.''') bit_offset = property(GetOffsetInBits, None, doc='''A read only property that returns offset in bits for this member as an integer.''') is_bitfield = property(IsBitfield, None, doc='''A read only property that returns true if this member is a bitfield.''') bitfield_bit_size = property(GetBitfieldSizeInBits, None, doc='''A read only property that returns the bitfield size in bits for this member as an integer, or zero if this member is not a bitfield.''') # Register SBTypeMember in _lldb: _lldb.SBTypeMember_swigregister(SBTypeMember) class SBTypeMemberFunction(object): r"""Represents a member function of a type.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeMemberFunction self) -> SBTypeMemberFunction __init__(SBTypeMemberFunction self, SBTypeMemberFunction rhs) -> SBTypeMemberFunction """ _lldb.SBTypeMemberFunction_swiginit(self, _lldb.new_SBTypeMemberFunction(*args)) __swig_destroy__ = _lldb.delete_SBTypeMemberFunction def IsValid(self): r"""IsValid(SBTypeMemberFunction self) -> bool""" return _lldb.SBTypeMemberFunction_IsValid(self) def __nonzero__(self): return _lldb.SBTypeMemberFunction___nonzero__(self) __bool__ = __nonzero__ def GetName(self): r"""GetName(SBTypeMemberFunction self) -> char const *""" return _lldb.SBTypeMemberFunction_GetName(self) def GetDemangledName(self): r"""GetDemangledName(SBTypeMemberFunction self) -> char const *""" return _lldb.SBTypeMemberFunction_GetDemangledName(self) def GetMangledName(self): r"""GetMangledName(SBTypeMemberFunction self) -> char const *""" return _lldb.SBTypeMemberFunction_GetMangledName(self) def GetType(self): r"""GetType(SBTypeMemberFunction self) -> SBType""" return _lldb.SBTypeMemberFunction_GetType(self) def GetReturnType(self): r"""GetReturnType(SBTypeMemberFunction self) -> SBType""" return _lldb.SBTypeMemberFunction_GetReturnType(self) def GetNumberOfArguments(self): r"""GetNumberOfArguments(SBTypeMemberFunction self) -> uint32_t""" return _lldb.SBTypeMemberFunction_GetNumberOfArguments(self) def GetArgumentTypeAtIndex(self, arg2): r"""GetArgumentTypeAtIndex(SBTypeMemberFunction self, uint32_t arg2) -> SBType""" return _lldb.SBTypeMemberFunction_GetArgumentTypeAtIndex(self, arg2) def GetKind(self): r"""GetKind(SBTypeMemberFunction self) -> lldb::MemberFunctionKind""" return _lldb.SBTypeMemberFunction_GetKind(self) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeMemberFunction self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeMemberFunction_GetDescription(self, description, description_level) def __str__(self): r"""__str__(SBTypeMemberFunction self) -> std::string""" return _lldb.SBTypeMemberFunction___str__(self) # Register SBTypeMemberFunction in _lldb: _lldb.SBTypeMemberFunction_swigregister(SBTypeMemberFunction) class SBType(object): r""" Represents a data type in lldb. The FindFirstType() method of SBTarget/SBModule returns a SBType. SBType supports the eq/ne operator. For example,:: //main.cpp: class Task { public: int id; Task *next; Task(int i, Task *n): id(i), next(n) {} }; int main (int argc, char const *argv[]) { Task *task_head = new Task(-1, NULL); Task *task1 = new Task(1, NULL); Task *task2 = new Task(2, NULL); Task *task3 = new Task(3, NULL); // Orphaned. Task *task4 = new Task(4, NULL); Task *task5 = new Task(5, NULL); task_head->next = task1; task1->next = task2; task2->next = task4; task4->next = task5; int total = 0; Task *t = task_head; while (t != NULL) { if (t->id >= 0) ++total; t = t->next; } printf('We have a total number of %d tasks\n', total); // This corresponds to an empty task list. Task *empty_task_head = new Task(-1, NULL); return 0; // Break at this line } # find_type.py: # Get the type 'Task'. task_type = target.FindFirstType('Task') self.assertTrue(task_type) # Get the variable 'task_head'. frame0.FindVariable('task_head') task_head_type = task_head.GetType() self.assertTrue(task_head_type.IsPointerType()) # task_head_type is 'Task *'. task_pointer_type = task_type.GetPointerType() self.assertTrue(task_head_type == task_pointer_type) # Get the child mmember 'id' from 'task_head'. id = task_head.GetChildMemberWithName('id') id_type = id.GetType() # SBType.GetBasicType() takes an enum 'BasicType' (lldb-enumerations.h). int_type = id_type.GetBasicType(lldb.eBasicTypeInt) # id_type and int_type should be the same type! self.assertTrue(id_type == int_type) ... """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBType self) -> SBType __init__(SBType self, SBType rhs) -> SBType """ _lldb.SBType_swiginit(self, _lldb.new_SBType(*args)) __swig_destroy__ = _lldb.delete_SBType def IsValid(self): r"""IsValid(SBType self) -> bool""" return _lldb.SBType_IsValid(self) def __nonzero__(self): return _lldb.SBType___nonzero__(self) __bool__ = __nonzero__ def GetByteSize(self): r"""GetByteSize(SBType self) -> uint64_t""" return _lldb.SBType_GetByteSize(self) def IsPointerType(self): r"""IsPointerType(SBType self) -> bool""" return _lldb.SBType_IsPointerType(self) def IsReferenceType(self): r"""IsReferenceType(SBType self) -> bool""" return _lldb.SBType_IsReferenceType(self) def IsFunctionType(self): r"""IsFunctionType(SBType self) -> bool""" return _lldb.SBType_IsFunctionType(self) def IsPolymorphicClass(self): r"""IsPolymorphicClass(SBType self) -> bool""" return _lldb.SBType_IsPolymorphicClass(self) def IsArrayType(self): r"""IsArrayType(SBType self) -> bool""" return _lldb.SBType_IsArrayType(self) def IsVectorType(self): r"""IsVectorType(SBType self) -> bool""" return _lldb.SBType_IsVectorType(self) def IsTypedefType(self): r"""IsTypedefType(SBType self) -> bool""" return _lldb.SBType_IsTypedefType(self) def IsAnonymousType(self): r"""IsAnonymousType(SBType self) -> bool""" return _lldb.SBType_IsAnonymousType(self) def IsScopedEnumerationType(self): r"""IsScopedEnumerationType(SBType self) -> bool""" return _lldb.SBType_IsScopedEnumerationType(self) def GetPointerType(self): r"""GetPointerType(SBType self) -> SBType""" return _lldb.SBType_GetPointerType(self) def GetPointeeType(self): r"""GetPointeeType(SBType self) -> SBType""" return _lldb.SBType_GetPointeeType(self) def GetReferenceType(self): r"""GetReferenceType(SBType self) -> SBType""" return _lldb.SBType_GetReferenceType(self) def GetTypedefedType(self): r"""GetTypedefedType(SBType self) -> SBType""" return _lldb.SBType_GetTypedefedType(self) def GetDereferencedType(self): r"""GetDereferencedType(SBType self) -> SBType""" return _lldb.SBType_GetDereferencedType(self) def GetUnqualifiedType(self): r"""GetUnqualifiedType(SBType self) -> SBType""" return _lldb.SBType_GetUnqualifiedType(self) def GetCanonicalType(self): r"""GetCanonicalType(SBType self) -> SBType""" return _lldb.SBType_GetCanonicalType(self) def GetEnumerationIntegerType(self): r"""GetEnumerationIntegerType(SBType self) -> SBType""" return _lldb.SBType_GetEnumerationIntegerType(self) def GetArrayElementType(self): r"""GetArrayElementType(SBType self) -> SBType""" return _lldb.SBType_GetArrayElementType(self) def GetArrayType(self, size): r"""GetArrayType(SBType self, uint64_t size) -> SBType""" return _lldb.SBType_GetArrayType(self, size) def GetVectorElementType(self): r"""GetVectorElementType(SBType self) -> SBType""" return _lldb.SBType_GetVectorElementType(self) def GetBasicType(self, *args): r""" GetBasicType(SBType self) -> lldb::BasicType GetBasicType(SBType self, lldb::BasicType type) -> SBType """ return _lldb.SBType_GetBasicType(self, *args) def GetNumberOfFields(self): r"""GetNumberOfFields(SBType self) -> uint32_t""" return _lldb.SBType_GetNumberOfFields(self) def GetNumberOfDirectBaseClasses(self): r"""GetNumberOfDirectBaseClasses(SBType self) -> uint32_t""" return _lldb.SBType_GetNumberOfDirectBaseClasses(self) def GetNumberOfVirtualBaseClasses(self): r"""GetNumberOfVirtualBaseClasses(SBType self) -> uint32_t""" return _lldb.SBType_GetNumberOfVirtualBaseClasses(self) def GetFieldAtIndex(self, idx): r"""GetFieldAtIndex(SBType self, uint32_t idx) -> SBTypeMember""" return _lldb.SBType_GetFieldAtIndex(self, idx) def GetDirectBaseClassAtIndex(self, idx): r"""GetDirectBaseClassAtIndex(SBType self, uint32_t idx) -> SBTypeMember""" return _lldb.SBType_GetDirectBaseClassAtIndex(self, idx) def GetVirtualBaseClassAtIndex(self, idx): r"""GetVirtualBaseClassAtIndex(SBType self, uint32_t idx) -> SBTypeMember""" return _lldb.SBType_GetVirtualBaseClassAtIndex(self, idx) def GetEnumMembers(self): r"""GetEnumMembers(SBType self) -> SBTypeEnumMemberList""" return _lldb.SBType_GetEnumMembers(self) def GetModule(self): r"""GetModule(SBType self) -> SBModule""" return _lldb.SBType_GetModule(self) def GetName(self): r"""GetName(SBType self) -> char const *""" return _lldb.SBType_GetName(self) def GetDisplayTypeName(self): r"""GetDisplayTypeName(SBType self) -> char const *""" return _lldb.SBType_GetDisplayTypeName(self) def GetTypeClass(self): r"""GetTypeClass(SBType self) -> lldb::TypeClass""" return _lldb.SBType_GetTypeClass(self) def GetNumberOfTemplateArguments(self): r"""GetNumberOfTemplateArguments(SBType self) -> uint32_t""" return _lldb.SBType_GetNumberOfTemplateArguments(self) def GetTemplateArgumentType(self, idx): r"""GetTemplateArgumentType(SBType self, uint32_t idx) -> SBType""" return _lldb.SBType_GetTemplateArgumentType(self, idx) def GetTemplateArgumentKind(self, idx): r"""GetTemplateArgumentKind(SBType self, uint32_t idx) -> lldb::TemplateArgumentKind""" return _lldb.SBType_GetTemplateArgumentKind(self, idx) def GetFunctionReturnType(self): r"""GetFunctionReturnType(SBType self) -> SBType""" return _lldb.SBType_GetFunctionReturnType(self) def GetFunctionArgumentTypes(self): r"""GetFunctionArgumentTypes(SBType self) -> SBTypeList""" return _lldb.SBType_GetFunctionArgumentTypes(self) def GetNumberOfMemberFunctions(self): r"""GetNumberOfMemberFunctions(SBType self) -> uint32_t""" return _lldb.SBType_GetNumberOfMemberFunctions(self) def GetMemberFunctionAtIndex(self, idx): r"""GetMemberFunctionAtIndex(SBType self, uint32_t idx) -> SBTypeMemberFunction""" return _lldb.SBType_GetMemberFunctionAtIndex(self, idx) def IsTypeComplete(self): r"""IsTypeComplete(SBType self) -> bool""" return _lldb.SBType_IsTypeComplete(self) def GetTypeFlags(self): r"""GetTypeFlags(SBType self) -> uint32_t""" return _lldb.SBType_GetTypeFlags(self) def __eq__(self, rhs): r"""__eq__(SBType self, SBType rhs) -> bool""" return _lldb.SBType___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBType self, SBType rhs) -> bool""" return _lldb.SBType___ne__(self, rhs) def __str__(self): r"""__str__(SBType self) -> std::string""" return _lldb.SBType___str__(self) def template_arg_array(self): num_args = self.num_template_args if num_args: template_args = [] for i in range(num_args): template_args.append(self.GetTemplateArgumentType(i)) return template_args return None module = property(GetModule, None, doc='''A read only property that returns the module in which type is defined.''') name = property(GetName, None, doc='''A read only property that returns the name for this type as a string.''') size = property(GetByteSize, None, doc='''A read only property that returns size in bytes for this type as an integer.''') is_pointer = property(IsPointerType, None, doc='''A read only property that returns a boolean value that indicates if this type is a pointer type.''') is_reference = property(IsReferenceType, None, doc='''A read only property that returns a boolean value that indicates if this type is a reference type.''') is_reference = property(IsReferenceType, None, doc='''A read only property that returns a boolean value that indicates if this type is a function type.''') num_fields = property(GetNumberOfFields, None, doc='''A read only property that returns number of fields in this type as an integer.''') num_bases = property(GetNumberOfDirectBaseClasses, None, doc='''A read only property that returns number of direct base classes in this type as an integer.''') num_vbases = property(GetNumberOfVirtualBaseClasses, None, doc='''A read only property that returns number of virtual base classes in this type as an integer.''') num_template_args = property(GetNumberOfTemplateArguments, None, doc='''A read only property that returns number of template arguments in this type as an integer.''') template_args = property(template_arg_array, None, doc='''A read only property that returns a list() of lldb.SBType objects that represent all template arguments in this type.''') type = property(GetTypeClass, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eTypeClass") that represents a classification for this type.''') is_complete = property(IsTypeComplete, None, doc='''A read only property that returns a boolean value that indicates if this type is a complete type (True) or a forward declaration (False).''') def get_bases_array(self): '''An accessor function that returns a list() that contains all direct base classes in a lldb.SBType object.''' bases = [] for idx in range(self.GetNumberOfDirectBaseClasses()): bases.append(self.GetDirectBaseClassAtIndex(idx)) return bases def get_vbases_array(self): '''An accessor function that returns a list() that contains all fields in a lldb.SBType object.''' vbases = [] for idx in range(self.GetNumberOfVirtualBaseClasses()): vbases.append(self.GetVirtualBaseClassAtIndex(idx)) return vbases def get_fields_array(self): '''An accessor function that returns a list() that contains all fields in a lldb.SBType object.''' fields = [] for idx in range(self.GetNumberOfFields()): fields.append(self.GetFieldAtIndex(idx)) return fields def get_members_array(self): '''An accessor function that returns a list() that contains all members (base classes and fields) in a lldb.SBType object in ascending bit offset order.''' members = [] bases = self.get_bases_array() fields = self.get_fields_array() vbases = self.get_vbases_array() for base in bases: bit_offset = base.bit_offset added = False for idx, member in enumerate(members): if member.bit_offset > bit_offset: members.insert(idx, base) added = True break if not added: members.append(base) for vbase in vbases: bit_offset = vbase.bit_offset added = False for idx, member in enumerate(members): if member.bit_offset > bit_offset: members.insert(idx, vbase) added = True break if not added: members.append(vbase) for field in fields: bit_offset = field.bit_offset added = False for idx, member in enumerate(members): if member.bit_offset > bit_offset: members.insert(idx, field) added = True break if not added: members.append(field) return members def get_enum_members_array(self): '''An accessor function that returns a list() that contains all enum members in an lldb.SBType object.''' enum_members_list = [] sb_enum_members = self.GetEnumMembers() for idx in range(sb_enum_members.GetSize()): enum_members_list.append(sb_enum_members.GetTypeEnumMemberAtIndex(idx)) return enum_members_list bases = property(get_bases_array, None, doc='''A read only property that returns a list() of lldb.SBTypeMember objects that represent all of the direct base classes for this type.''') vbases = property(get_vbases_array, None, doc='''A read only property that returns a list() of lldb.SBTypeMember objects that represent all of the virtual base classes for this type.''') fields = property(get_fields_array, None, doc='''A read only property that returns a list() of lldb.SBTypeMember objects that represent all of the fields for this type.''') members = property(get_members_array, None, doc='''A read only property that returns a list() of all lldb.SBTypeMember objects that represent all of the base classes, virtual base classes and fields for this type in ascending bit offset order.''') enum_members = property(get_enum_members_array, None, doc='''A read only property that returns a list() of all lldb.SBTypeEnumMember objects that represent the enum members for this type.''') # Register SBType in _lldb: _lldb.SBType_swigregister(SBType) class SBTypeList(object): r""" Represents a list of :py:class:`SBType` s. The FindTypes() method of :py:class:`SBTarget`/:py:class:`SBModule` returns a SBTypeList. SBTypeList supports :py:class:`SBType` iteration. For example, .. code-block:: cpp // main.cpp: class Task { public: int id; Task *next; Task(int i, Task *n): id(i), next(n) {} }; .. code-block:: python # find_type.py: # Get the type 'Task'. type_list = target.FindTypes('Task') self.assertTrue(len(type_list) == 1) # To illustrate the SBType iteration. for type in type_list: # do something with type """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): r"""__init__(SBTypeList self) -> SBTypeList""" _lldb.SBTypeList_swiginit(self, _lldb.new_SBTypeList()) def IsValid(self): r"""IsValid(SBTypeList self) -> bool""" return _lldb.SBTypeList_IsValid(self) def __nonzero__(self): return _lldb.SBTypeList___nonzero__(self) __bool__ = __nonzero__ def Append(self, type): r"""Append(SBTypeList self, SBType type)""" return _lldb.SBTypeList_Append(self, type) def GetTypeAtIndex(self, index): r"""GetTypeAtIndex(SBTypeList self, uint32_t index) -> SBType""" return _lldb.SBTypeList_GetTypeAtIndex(self, index) def GetSize(self): r"""GetSize(SBTypeList self) -> uint32_t""" return _lldb.SBTypeList_GetSize(self) __swig_destroy__ = _lldb.delete_SBTypeList def __iter__(self): '''Iterate over all types in a lldb.SBTypeList object.''' return lldb_iter(self, 'GetSize', 'GetTypeAtIndex') def __len__(self): '''Return the number of types in a lldb.SBTypeList object.''' return self.GetSize() # Register SBTypeList in _lldb: _lldb.SBTypeList_swigregister(SBTypeList) class SBTypeCategory(object): r"""Represents a category that can contain formatters for types.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeCategory self) -> SBTypeCategory __init__(SBTypeCategory self, SBTypeCategory rhs) -> SBTypeCategory """ _lldb.SBTypeCategory_swiginit(self, _lldb.new_SBTypeCategory(*args)) __swig_destroy__ = _lldb.delete_SBTypeCategory def IsValid(self): r"""IsValid(SBTypeCategory self) -> bool""" return _lldb.SBTypeCategory_IsValid(self) def __nonzero__(self): return _lldb.SBTypeCategory___nonzero__(self) __bool__ = __nonzero__ def GetEnabled(self): r"""GetEnabled(SBTypeCategory self) -> bool""" return _lldb.SBTypeCategory_GetEnabled(self) def SetEnabled(self, arg2): r"""SetEnabled(SBTypeCategory self, bool arg2)""" return _lldb.SBTypeCategory_SetEnabled(self, arg2) def GetName(self): r"""GetName(SBTypeCategory self) -> char const *""" return _lldb.SBTypeCategory_GetName(self) def GetLanguageAtIndex(self, idx): r"""GetLanguageAtIndex(SBTypeCategory self, uint32_t idx) -> lldb::LanguageType""" return _lldb.SBTypeCategory_GetLanguageAtIndex(self, idx) def GetNumLanguages(self): r"""GetNumLanguages(SBTypeCategory self) -> uint32_t""" return _lldb.SBTypeCategory_GetNumLanguages(self) def AddLanguage(self, language): r"""AddLanguage(SBTypeCategory self, lldb::LanguageType language)""" return _lldb.SBTypeCategory_AddLanguage(self, language) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeCategory self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeCategory_GetDescription(self, description, description_level) def GetNumFormats(self): r"""GetNumFormats(SBTypeCategory self) -> uint32_t""" return _lldb.SBTypeCategory_GetNumFormats(self) def GetNumSummaries(self): r"""GetNumSummaries(SBTypeCategory self) -> uint32_t""" return _lldb.SBTypeCategory_GetNumSummaries(self) def GetNumFilters(self): r"""GetNumFilters(SBTypeCategory self) -> uint32_t""" return _lldb.SBTypeCategory_GetNumFilters(self) def GetNumSynthetics(self): r"""GetNumSynthetics(SBTypeCategory self) -> uint32_t""" return _lldb.SBTypeCategory_GetNumSynthetics(self) def GetTypeNameSpecifierForFilterAtIndex(self, arg2): r"""GetTypeNameSpecifierForFilterAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeNameSpecifier""" return _lldb.SBTypeCategory_GetTypeNameSpecifierForFilterAtIndex(self, arg2) def GetTypeNameSpecifierForFormatAtIndex(self, arg2): r"""GetTypeNameSpecifierForFormatAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeNameSpecifier""" return _lldb.SBTypeCategory_GetTypeNameSpecifierForFormatAtIndex(self, arg2) def GetTypeNameSpecifierForSummaryAtIndex(self, arg2): r"""GetTypeNameSpecifierForSummaryAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeNameSpecifier""" return _lldb.SBTypeCategory_GetTypeNameSpecifierForSummaryAtIndex(self, arg2) def GetTypeNameSpecifierForSyntheticAtIndex(self, arg2): r"""GetTypeNameSpecifierForSyntheticAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeNameSpecifier""" return _lldb.SBTypeCategory_GetTypeNameSpecifierForSyntheticAtIndex(self, arg2) def GetFilterForType(self, arg2): r"""GetFilterForType(SBTypeCategory self, SBTypeNameSpecifier arg2) -> SBTypeFilter""" return _lldb.SBTypeCategory_GetFilterForType(self, arg2) def GetFormatForType(self, arg2): r"""GetFormatForType(SBTypeCategory self, SBTypeNameSpecifier arg2) -> SBTypeFormat""" return _lldb.SBTypeCategory_GetFormatForType(self, arg2) def GetSummaryForType(self, arg2): r"""GetSummaryForType(SBTypeCategory self, SBTypeNameSpecifier arg2) -> SBTypeSummary""" return _lldb.SBTypeCategory_GetSummaryForType(self, arg2) def GetSyntheticForType(self, arg2): r"""GetSyntheticForType(SBTypeCategory self, SBTypeNameSpecifier arg2) -> SBTypeSynthetic""" return _lldb.SBTypeCategory_GetSyntheticForType(self, arg2) def GetFilterAtIndex(self, arg2): r"""GetFilterAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeFilter""" return _lldb.SBTypeCategory_GetFilterAtIndex(self, arg2) def GetFormatAtIndex(self, arg2): r"""GetFormatAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeFormat""" return _lldb.SBTypeCategory_GetFormatAtIndex(self, arg2) def GetSummaryAtIndex(self, arg2): r"""GetSummaryAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeSummary""" return _lldb.SBTypeCategory_GetSummaryAtIndex(self, arg2) def GetSyntheticAtIndex(self, arg2): r"""GetSyntheticAtIndex(SBTypeCategory self, uint32_t arg2) -> SBTypeSynthetic""" return _lldb.SBTypeCategory_GetSyntheticAtIndex(self, arg2) def AddTypeFormat(self, arg2, arg3): r"""AddTypeFormat(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeFormat arg3) -> bool""" return _lldb.SBTypeCategory_AddTypeFormat(self, arg2, arg3) def DeleteTypeFormat(self, arg2): r"""DeleteTypeFormat(SBTypeCategory self, SBTypeNameSpecifier arg2) -> bool""" return _lldb.SBTypeCategory_DeleteTypeFormat(self, arg2) def AddTypeSummary(self, arg2, arg3): r"""AddTypeSummary(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeSummary arg3) -> bool""" return _lldb.SBTypeCategory_AddTypeSummary(self, arg2, arg3) def DeleteTypeSummary(self, arg2): r"""DeleteTypeSummary(SBTypeCategory self, SBTypeNameSpecifier arg2) -> bool""" return _lldb.SBTypeCategory_DeleteTypeSummary(self, arg2) def AddTypeFilter(self, arg2, arg3): r"""AddTypeFilter(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeFilter arg3) -> bool""" return _lldb.SBTypeCategory_AddTypeFilter(self, arg2, arg3) def DeleteTypeFilter(self, arg2): r"""DeleteTypeFilter(SBTypeCategory self, SBTypeNameSpecifier arg2) -> bool""" return _lldb.SBTypeCategory_DeleteTypeFilter(self, arg2) def AddTypeSynthetic(self, arg2, arg3): r"""AddTypeSynthetic(SBTypeCategory self, SBTypeNameSpecifier arg2, SBTypeSynthetic arg3) -> bool""" return _lldb.SBTypeCategory_AddTypeSynthetic(self, arg2, arg3) def DeleteTypeSynthetic(self, arg2): r"""DeleteTypeSynthetic(SBTypeCategory self, SBTypeNameSpecifier arg2) -> bool""" return _lldb.SBTypeCategory_DeleteTypeSynthetic(self, arg2) def __str__(self): r"""__str__(SBTypeCategory self) -> std::string""" return _lldb.SBTypeCategory___str__(self) class formatters_access_class(object): '''A helper object that will lazily hand out formatters for a specific category.''' def __init__(self, sbcategory, get_count_function, get_at_index_function, get_by_name_function): self.sbcategory = sbcategory self.get_count_function = get_count_function self.get_at_index_function = get_at_index_function self.get_by_name_function = get_by_name_function self.regex_type = type(re.compile('.')) def __len__(self): if self.sbcategory and self.get_count_function: return int(self.get_count_function(self.sbcategory)) return 0 def __getitem__(self, key): num_items = len(self) if type(key) is int: if key < num_items: return self.get_at_index_function(self.sbcategory,key) elif type(key) is str: return self.get_by_name_function(self.sbcategory,SBTypeNameSpecifier(key)) elif isinstance(key,self.regex_type): return self.get_by_name_function(self.sbcategory,SBTypeNameSpecifier(key.pattern,True)) else: print("error: unsupported item type: %s" % type(key)) return None def get_formats_access_object(self): '''An accessor function that returns an accessor object which allows lazy format access from a lldb.SBTypeCategory object.''' return self.formatters_access_class (self,self.__class__.GetNumFormats,self.__class__.GetFormatAtIndex,self.__class__.GetFormatForType) def get_formats_array(self): '''An accessor function that returns a list() that contains all formats in a lldb.SBCategory object.''' formats = [] for idx in range(self.GetNumFormats()): formats.append(self.GetFormatAtIndex(idx)) return formats def get_summaries_access_object(self): '''An accessor function that returns an accessor object which allows lazy summary access from a lldb.SBTypeCategory object.''' return self.formatters_access_class (self,self.__class__.GetNumSummaries,self.__class__.GetSummaryAtIndex,self.__class__.GetSummaryForType) def get_summaries_array(self): '''An accessor function that returns a list() that contains all summaries in a lldb.SBCategory object.''' summaries = [] for idx in range(self.GetNumSummaries()): summaries.append(self.GetSummaryAtIndex(idx)) return summaries def get_synthetics_access_object(self): '''An accessor function that returns an accessor object which allows lazy synthetic children provider access from a lldb.SBTypeCategory object.''' return self.formatters_access_class (self,self.__class__.GetNumSynthetics,self.__class__.GetSyntheticAtIndex,self.__class__.GetSyntheticForType) def get_synthetics_array(self): '''An accessor function that returns a list() that contains all synthetic children providers in a lldb.SBCategory object.''' synthetics = [] for idx in range(self.GetNumSynthetics()): synthetics.append(self.GetSyntheticAtIndex(idx)) return synthetics def get_filters_access_object(self): '''An accessor function that returns an accessor object which allows lazy filter access from a lldb.SBTypeCategory object.''' return self.formatters_access_class (self,self.__class__.GetNumFilters,self.__class__.GetFilterAtIndex,self.__class__.GetFilterForType) def get_filters_array(self): '''An accessor function that returns a list() that contains all filters in a lldb.SBCategory object.''' filters = [] for idx in range(self.GetNumFilters()): filters.append(self.GetFilterAtIndex(idx)) return filters formats = property(get_formats_array, None, doc='''A read only property that returns a list() of lldb.SBTypeFormat objects contained in this category''') format = property(get_formats_access_object, None, doc=r'''A read only property that returns an object that you can use to look for formats by index or type name.''') summaries = property(get_summaries_array, None, doc='''A read only property that returns a list() of lldb.SBTypeSummary objects contained in this category''') summary = property(get_summaries_access_object, None, doc=r'''A read only property that returns an object that you can use to look for summaries by index or type name or regular expression.''') filters = property(get_filters_array, None, doc='''A read only property that returns a list() of lldb.SBTypeFilter objects contained in this category''') filter = property(get_filters_access_object, None, doc=r'''A read only property that returns an object that you can use to look for filters by index or type name or regular expression.''') synthetics = property(get_synthetics_array, None, doc='''A read only property that returns a list() of lldb.SBTypeSynthetic objects contained in this category''') synthetic = property(get_synthetics_access_object, None, doc=r'''A read only property that returns an object that you can use to look for synthetic children provider by index or type name or regular expression.''') num_formats = property(GetNumFormats, None) num_summaries = property(GetNumSummaries, None) num_filters = property(GetNumFilters, None) num_synthetics = property(GetNumSynthetics, None) name = property(GetName, None) enabled = property(GetEnabled, SetEnabled) # Register SBTypeCategory in _lldb: _lldb.SBTypeCategory_swigregister(SBTypeCategory) class SBTypeEnumMember(object): r"""Represents a member of an enum in lldb.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeEnumMember self) -> SBTypeEnumMember __init__(SBTypeEnumMember self, SBTypeEnumMember rhs) -> SBTypeEnumMember """ _lldb.SBTypeEnumMember_swiginit(self, _lldb.new_SBTypeEnumMember(*args)) __swig_destroy__ = _lldb.delete_SBTypeEnumMember def IsValid(self): r"""IsValid(SBTypeEnumMember self) -> bool""" return _lldb.SBTypeEnumMember_IsValid(self) def __nonzero__(self): return _lldb.SBTypeEnumMember___nonzero__(self) __bool__ = __nonzero__ def GetValueAsSigned(self): r"""GetValueAsSigned(SBTypeEnumMember self) -> int64_t""" return _lldb.SBTypeEnumMember_GetValueAsSigned(self) def GetValueAsUnsigned(self): r"""GetValueAsUnsigned(SBTypeEnumMember self) -> uint64_t""" return _lldb.SBTypeEnumMember_GetValueAsUnsigned(self) def GetName(self): r"""GetName(SBTypeEnumMember self) -> char const *""" return _lldb.SBTypeEnumMember_GetName(self) def GetType(self): r"""GetType(SBTypeEnumMember self) -> SBType""" return _lldb.SBTypeEnumMember_GetType(self) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeEnumMember self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeEnumMember_GetDescription(self, description, description_level) def __str__(self): r"""__str__(SBTypeEnumMember self) -> std::string""" return _lldb.SBTypeEnumMember___str__(self) name = property(GetName, None, doc='''A read only property that returns the name for this enum member as a string.''') type = property(GetType, None, doc='''A read only property that returns an lldb object that represents the type (lldb.SBType) for this enum member.''') signed = property(GetValueAsSigned, None, doc='''A read only property that returns the value of this enum member as a signed integer.''') unsigned = property(GetValueAsUnsigned, None, doc='''A read only property that returns the value of this enum member as a unsigned integer.''') # Register SBTypeEnumMember in _lldb: _lldb.SBTypeEnumMember_swigregister(SBTypeEnumMember) class SBTypeEnumMemberList(object): r""" Represents a list of SBTypeEnumMembers. SBTypeEnumMemberList supports SBTypeEnumMember iteration. It also supports [] access either by index, or by enum element name by doing: :: myType = target.FindFirstType('MyEnumWithElementA') members = myType.GetEnumMembers() first_elem = members[0] elem_A = members['A'] """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeEnumMemberList self) -> SBTypeEnumMemberList __init__(SBTypeEnumMemberList self, SBTypeEnumMemberList rhs) -> SBTypeEnumMemberList """ _lldb.SBTypeEnumMemberList_swiginit(self, _lldb.new_SBTypeEnumMemberList(*args)) __swig_destroy__ = _lldb.delete_SBTypeEnumMemberList def IsValid(self): r"""IsValid(SBTypeEnumMemberList self) -> bool""" return _lldb.SBTypeEnumMemberList_IsValid(self) def __nonzero__(self): return _lldb.SBTypeEnumMemberList___nonzero__(self) __bool__ = __nonzero__ def Append(self, entry): r"""Append(SBTypeEnumMemberList self, SBTypeEnumMember entry)""" return _lldb.SBTypeEnumMemberList_Append(self, entry) def GetTypeEnumMemberAtIndex(self, index): r"""GetTypeEnumMemberAtIndex(SBTypeEnumMemberList self, uint32_t index) -> SBTypeEnumMember""" return _lldb.SBTypeEnumMemberList_GetTypeEnumMemberAtIndex(self, index) def GetSize(self): r"""GetSize(SBTypeEnumMemberList self) -> uint32_t""" return _lldb.SBTypeEnumMemberList_GetSize(self) def __iter__(self): '''Iterate over all members in a lldb.SBTypeEnumMemberList object.''' return lldb_iter(self, 'GetSize', 'GetTypeEnumMemberAtIndex') def __len__(self): '''Return the number of members in a lldb.SBTypeEnumMemberList object.''' return self.GetSize() def __getitem__(self, key): num_elements = self.GetSize() if type(key) is int: if key < num_elements: return self.GetTypeEnumMemberAtIndex(key) elif type(key) is str: for idx in range(num_elements): item = self.GetTypeEnumMemberAtIndex(idx) if item.name == key: return item return None # Register SBTypeEnumMemberList in _lldb: _lldb.SBTypeEnumMemberList_swigregister(SBTypeEnumMemberList) class SBTypeFilter(object): r"""Represents a filter that can be associated to one or more types.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeFilter self) -> SBTypeFilter __init__(SBTypeFilter self, uint32_t options) -> SBTypeFilter __init__(SBTypeFilter self, SBTypeFilter rhs) -> SBTypeFilter """ _lldb.SBTypeFilter_swiginit(self, _lldb.new_SBTypeFilter(*args)) __swig_destroy__ = _lldb.delete_SBTypeFilter def IsValid(self): r"""IsValid(SBTypeFilter self) -> bool""" return _lldb.SBTypeFilter_IsValid(self) def __nonzero__(self): return _lldb.SBTypeFilter___nonzero__(self) __bool__ = __nonzero__ def IsEqualTo(self, rhs): r"""IsEqualTo(SBTypeFilter self, SBTypeFilter rhs) -> bool""" return _lldb.SBTypeFilter_IsEqualTo(self, rhs) def GetNumberOfExpressionPaths(self): r"""GetNumberOfExpressionPaths(SBTypeFilter self) -> uint32_t""" return _lldb.SBTypeFilter_GetNumberOfExpressionPaths(self) def GetExpressionPathAtIndex(self, i): r"""GetExpressionPathAtIndex(SBTypeFilter self, uint32_t i) -> char const *""" return _lldb.SBTypeFilter_GetExpressionPathAtIndex(self, i) def ReplaceExpressionPathAtIndex(self, i, item): r"""ReplaceExpressionPathAtIndex(SBTypeFilter self, uint32_t i, char const * item) -> bool""" return _lldb.SBTypeFilter_ReplaceExpressionPathAtIndex(self, i, item) def AppendExpressionPath(self, item): r"""AppendExpressionPath(SBTypeFilter self, char const * item)""" return _lldb.SBTypeFilter_AppendExpressionPath(self, item) def Clear(self): r"""Clear(SBTypeFilter self)""" return _lldb.SBTypeFilter_Clear(self) def GetOptions(self): r"""GetOptions(SBTypeFilter self) -> uint32_t""" return _lldb.SBTypeFilter_GetOptions(self) def SetOptions(self, arg2): r"""SetOptions(SBTypeFilter self, uint32_t arg2)""" return _lldb.SBTypeFilter_SetOptions(self, arg2) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeFilter self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeFilter_GetDescription(self, description, description_level) def __eq__(self, rhs): r"""__eq__(SBTypeFilter self, SBTypeFilter rhs) -> bool""" return _lldb.SBTypeFilter___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBTypeFilter self, SBTypeFilter rhs) -> bool""" return _lldb.SBTypeFilter___ne__(self, rhs) def __str__(self): r"""__str__(SBTypeFilter self) -> std::string""" return _lldb.SBTypeFilter___str__(self) options = property(GetOptions, SetOptions) count = property(GetNumberOfExpressionPaths) def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBTypeFilter in _lldb: _lldb.SBTypeFilter_swigregister(SBTypeFilter) class SBTypeFormat(object): r"""Represents a format that can be associated to one or more types.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeFormat self) -> SBTypeFormat __init__(SBTypeFormat self, lldb::Format format, uint32_t options=0) -> SBTypeFormat __init__(SBTypeFormat self, char const * type, uint32_t options=0) -> SBTypeFormat __init__(SBTypeFormat self, SBTypeFormat rhs) -> SBTypeFormat """ _lldb.SBTypeFormat_swiginit(self, _lldb.new_SBTypeFormat(*args)) __swig_destroy__ = _lldb.delete_SBTypeFormat def IsValid(self): r"""IsValid(SBTypeFormat self) -> bool""" return _lldb.SBTypeFormat_IsValid(self) def __nonzero__(self): return _lldb.SBTypeFormat___nonzero__(self) __bool__ = __nonzero__ def IsEqualTo(self, rhs): r"""IsEqualTo(SBTypeFormat self, SBTypeFormat rhs) -> bool""" return _lldb.SBTypeFormat_IsEqualTo(self, rhs) def GetFormat(self): r"""GetFormat(SBTypeFormat self) -> lldb::Format""" return _lldb.SBTypeFormat_GetFormat(self) def GetTypeName(self): r"""GetTypeName(SBTypeFormat self) -> char const *""" return _lldb.SBTypeFormat_GetTypeName(self) def GetOptions(self): r"""GetOptions(SBTypeFormat self) -> uint32_t""" return _lldb.SBTypeFormat_GetOptions(self) def SetFormat(self, arg2): r"""SetFormat(SBTypeFormat self, lldb::Format arg2)""" return _lldb.SBTypeFormat_SetFormat(self, arg2) def SetTypeName(self, arg2): r"""SetTypeName(SBTypeFormat self, char const * arg2)""" return _lldb.SBTypeFormat_SetTypeName(self, arg2) def SetOptions(self, arg2): r"""SetOptions(SBTypeFormat self, uint32_t arg2)""" return _lldb.SBTypeFormat_SetOptions(self, arg2) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeFormat self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeFormat_GetDescription(self, description, description_level) def __eq__(self, rhs): r"""__eq__(SBTypeFormat self, SBTypeFormat rhs) -> bool""" return _lldb.SBTypeFormat___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBTypeFormat self, SBTypeFormat rhs) -> bool""" return _lldb.SBTypeFormat___ne__(self, rhs) def __str__(self): r"""__str__(SBTypeFormat self) -> std::string""" return _lldb.SBTypeFormat___str__(self) format = property(GetFormat, SetFormat) options = property(GetOptions, SetOptions) # Register SBTypeFormat in _lldb: _lldb.SBTypeFormat_swigregister(SBTypeFormat) class SBTypeNameSpecifier(object): r"""Represents a general way to provide a type name to LLDB APIs.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeNameSpecifier self) -> SBTypeNameSpecifier __init__(SBTypeNameSpecifier self, char const * name, bool is_regex=False) -> SBTypeNameSpecifier __init__(SBTypeNameSpecifier self, SBType type) -> SBTypeNameSpecifier __init__(SBTypeNameSpecifier self, SBTypeNameSpecifier rhs) -> SBTypeNameSpecifier """ _lldb.SBTypeNameSpecifier_swiginit(self, _lldb.new_SBTypeNameSpecifier(*args)) __swig_destroy__ = _lldb.delete_SBTypeNameSpecifier def IsValid(self): r"""IsValid(SBTypeNameSpecifier self) -> bool""" return _lldb.SBTypeNameSpecifier_IsValid(self) def __nonzero__(self): return _lldb.SBTypeNameSpecifier___nonzero__(self) __bool__ = __nonzero__ def IsEqualTo(self, rhs): r"""IsEqualTo(SBTypeNameSpecifier self, SBTypeNameSpecifier rhs) -> bool""" return _lldb.SBTypeNameSpecifier_IsEqualTo(self, rhs) def GetName(self): r"""GetName(SBTypeNameSpecifier self) -> char const *""" return _lldb.SBTypeNameSpecifier_GetName(self) def GetType(self): r"""GetType(SBTypeNameSpecifier self) -> SBType""" return _lldb.SBTypeNameSpecifier_GetType(self) def IsRegex(self): r"""IsRegex(SBTypeNameSpecifier self) -> bool""" return _lldb.SBTypeNameSpecifier_IsRegex(self) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeNameSpecifier self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeNameSpecifier_GetDescription(self, description, description_level) def __eq__(self, rhs): r"""__eq__(SBTypeNameSpecifier self, SBTypeNameSpecifier rhs) -> bool""" return _lldb.SBTypeNameSpecifier___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBTypeNameSpecifier self, SBTypeNameSpecifier rhs) -> bool""" return _lldb.SBTypeNameSpecifier___ne__(self, rhs) def __str__(self): r"""__str__(SBTypeNameSpecifier self) -> std::string""" return _lldb.SBTypeNameSpecifier___str__(self) name = property(GetName) is_regex = property(IsRegex) def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBTypeNameSpecifier in _lldb: _lldb.SBTypeNameSpecifier_swigregister(SBTypeNameSpecifier) class SBTypeSummaryOptions(object): r"""Proxy of C++ lldb::SBTypeSummaryOptions class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBTypeSummaryOptions self) -> SBTypeSummaryOptions __init__(SBTypeSummaryOptions self, SBTypeSummaryOptions rhs) -> SBTypeSummaryOptions """ _lldb.SBTypeSummaryOptions_swiginit(self, _lldb.new_SBTypeSummaryOptions(*args)) __swig_destroy__ = _lldb.delete_SBTypeSummaryOptions def IsValid(self): r"""IsValid(SBTypeSummaryOptions self) -> bool""" return _lldb.SBTypeSummaryOptions_IsValid(self) def __nonzero__(self): return _lldb.SBTypeSummaryOptions___nonzero__(self) __bool__ = __nonzero__ def GetLanguage(self): r"""GetLanguage(SBTypeSummaryOptions self) -> lldb::LanguageType""" return _lldb.SBTypeSummaryOptions_GetLanguage(self) def GetCapping(self): r"""GetCapping(SBTypeSummaryOptions self) -> lldb::TypeSummaryCapping""" return _lldb.SBTypeSummaryOptions_GetCapping(self) def SetLanguage(self, arg2): r"""SetLanguage(SBTypeSummaryOptions self, lldb::LanguageType arg2)""" return _lldb.SBTypeSummaryOptions_SetLanguage(self, arg2) def SetCapping(self, arg2): r"""SetCapping(SBTypeSummaryOptions self, lldb::TypeSummaryCapping arg2)""" return _lldb.SBTypeSummaryOptions_SetCapping(self, arg2) # Register SBTypeSummaryOptions in _lldb: _lldb.SBTypeSummaryOptions_swigregister(SBTypeSummaryOptions) class SBTypeSummary(object): r"""Represents a summary that can be associated to one or more types.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr @staticmethod def CreateWithSummaryString(data, options=0): r"""CreateWithSummaryString(char const * data, uint32_t options=0) -> SBTypeSummary""" return _lldb.SBTypeSummary_CreateWithSummaryString(data, options) @staticmethod def CreateWithFunctionName(data, options=0): r"""CreateWithFunctionName(char const * data, uint32_t options=0) -> SBTypeSummary""" return _lldb.SBTypeSummary_CreateWithFunctionName(data, options) @staticmethod def CreateWithScriptCode(data, options=0): r"""CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSummary""" return _lldb.SBTypeSummary_CreateWithScriptCode(data, options) def __init__(self, *args): r""" __init__(SBTypeSummary self) -> SBTypeSummary __init__(SBTypeSummary self, SBTypeSummary rhs) -> SBTypeSummary """ _lldb.SBTypeSummary_swiginit(self, _lldb.new_SBTypeSummary(*args)) __swig_destroy__ = _lldb.delete_SBTypeSummary def IsValid(self): r"""IsValid(SBTypeSummary self) -> bool""" return _lldb.SBTypeSummary_IsValid(self) def __nonzero__(self): return _lldb.SBTypeSummary___nonzero__(self) __bool__ = __nonzero__ def IsEqualTo(self, rhs): r"""IsEqualTo(SBTypeSummary self, SBTypeSummary rhs) -> bool""" return _lldb.SBTypeSummary_IsEqualTo(self, rhs) def IsFunctionCode(self): r"""IsFunctionCode(SBTypeSummary self) -> bool""" return _lldb.SBTypeSummary_IsFunctionCode(self) def IsFunctionName(self): r"""IsFunctionName(SBTypeSummary self) -> bool""" return _lldb.SBTypeSummary_IsFunctionName(self) def IsSummaryString(self): r"""IsSummaryString(SBTypeSummary self) -> bool""" return _lldb.SBTypeSummary_IsSummaryString(self) def GetData(self): r"""GetData(SBTypeSummary self) -> char const *""" return _lldb.SBTypeSummary_GetData(self) def SetSummaryString(self, data): r"""SetSummaryString(SBTypeSummary self, char const * data)""" return _lldb.SBTypeSummary_SetSummaryString(self, data) def SetFunctionName(self, data): r"""SetFunctionName(SBTypeSummary self, char const * data)""" return _lldb.SBTypeSummary_SetFunctionName(self, data) def SetFunctionCode(self, data): r"""SetFunctionCode(SBTypeSummary self, char const * data)""" return _lldb.SBTypeSummary_SetFunctionCode(self, data) def GetOptions(self): r"""GetOptions(SBTypeSummary self) -> uint32_t""" return _lldb.SBTypeSummary_GetOptions(self) def SetOptions(self, arg2): r"""SetOptions(SBTypeSummary self, uint32_t arg2)""" return _lldb.SBTypeSummary_SetOptions(self, arg2) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeSummary self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeSummary_GetDescription(self, description, description_level) def __eq__(self, rhs): r"""__eq__(SBTypeSummary self, SBTypeSummary rhs) -> bool""" return _lldb.SBTypeSummary___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBTypeSummary self, SBTypeSummary rhs) -> bool""" return _lldb.SBTypeSummary___ne__(self, rhs) def __str__(self): r"""__str__(SBTypeSummary self) -> std::string""" return _lldb.SBTypeSummary___str__(self) options = property(GetOptions, SetOptions) is_summary_string = property(IsSummaryString) is_function_name = property(IsFunctionName) is_function_name = property(IsFunctionCode) summary_data = property(GetData) def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBTypeSummary in _lldb: _lldb.SBTypeSummary_swigregister(SBTypeSummary) def SBTypeSummary_CreateWithSummaryString(data, options=0): r"""SBTypeSummary_CreateWithSummaryString(char const * data, uint32_t options=0) -> SBTypeSummary""" return _lldb.SBTypeSummary_CreateWithSummaryString(data, options) def SBTypeSummary_CreateWithFunctionName(data, options=0): r"""SBTypeSummary_CreateWithFunctionName(char const * data, uint32_t options=0) -> SBTypeSummary""" return _lldb.SBTypeSummary_CreateWithFunctionName(data, options) def SBTypeSummary_CreateWithScriptCode(data, options=0): r"""SBTypeSummary_CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSummary""" return _lldb.SBTypeSummary_CreateWithScriptCode(data, options) class SBTypeSynthetic(object): r"""Represents a summary that can be associated to one or more types.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr @staticmethod def CreateWithClassName(data, options=0): r"""CreateWithClassName(char const * data, uint32_t options=0) -> SBTypeSynthetic""" return _lldb.SBTypeSynthetic_CreateWithClassName(data, options) @staticmethod def CreateWithScriptCode(data, options=0): r"""CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSynthetic""" return _lldb.SBTypeSynthetic_CreateWithScriptCode(data, options) def __init__(self, *args): r""" __init__(SBTypeSynthetic self) -> SBTypeSynthetic __init__(SBTypeSynthetic self, SBTypeSynthetic rhs) -> SBTypeSynthetic """ _lldb.SBTypeSynthetic_swiginit(self, _lldb.new_SBTypeSynthetic(*args)) __swig_destroy__ = _lldb.delete_SBTypeSynthetic def IsValid(self): r"""IsValid(SBTypeSynthetic self) -> bool""" return _lldb.SBTypeSynthetic_IsValid(self) def __nonzero__(self): return _lldb.SBTypeSynthetic___nonzero__(self) __bool__ = __nonzero__ def IsEqualTo(self, rhs): r"""IsEqualTo(SBTypeSynthetic self, SBTypeSynthetic rhs) -> bool""" return _lldb.SBTypeSynthetic_IsEqualTo(self, rhs) def IsClassCode(self): r"""IsClassCode(SBTypeSynthetic self) -> bool""" return _lldb.SBTypeSynthetic_IsClassCode(self) def GetData(self): r"""GetData(SBTypeSynthetic self) -> char const *""" return _lldb.SBTypeSynthetic_GetData(self) def SetClassName(self, data): r"""SetClassName(SBTypeSynthetic self, char const * data)""" return _lldb.SBTypeSynthetic_SetClassName(self, data) def SetClassCode(self, data): r"""SetClassCode(SBTypeSynthetic self, char const * data)""" return _lldb.SBTypeSynthetic_SetClassCode(self, data) def GetOptions(self): r"""GetOptions(SBTypeSynthetic self) -> uint32_t""" return _lldb.SBTypeSynthetic_GetOptions(self) def SetOptions(self, arg2): r"""SetOptions(SBTypeSynthetic self, uint32_t arg2)""" return _lldb.SBTypeSynthetic_SetOptions(self, arg2) def GetDescription(self, description, description_level): r"""GetDescription(SBTypeSynthetic self, SBStream description, lldb::DescriptionLevel description_level) -> bool""" return _lldb.SBTypeSynthetic_GetDescription(self, description, description_level) def __eq__(self, rhs): r"""__eq__(SBTypeSynthetic self, SBTypeSynthetic rhs) -> bool""" return _lldb.SBTypeSynthetic___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBTypeSynthetic self, SBTypeSynthetic rhs) -> bool""" return _lldb.SBTypeSynthetic___ne__(self, rhs) def __str__(self): r"""__str__(SBTypeSynthetic self) -> std::string""" return _lldb.SBTypeSynthetic___str__(self) options = property(GetOptions, SetOptions) contains_code = property(IsClassCode, None) synthetic_data = property(GetData, None) def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False return getattr(_lldb,self.__class__.__name__+"___eq__")(self, rhs) def __ne__(self, rhs): if not isinstance(rhs, type(self)): return True return getattr(_lldb,self.__class__.__name__+"___ne__")(self, rhs) # Register SBTypeSynthetic in _lldb: _lldb.SBTypeSynthetic_swigregister(SBTypeSynthetic) def SBTypeSynthetic_CreateWithClassName(data, options=0): r"""SBTypeSynthetic_CreateWithClassName(char const * data, uint32_t options=0) -> SBTypeSynthetic""" return _lldb.SBTypeSynthetic_CreateWithClassName(data, options) def SBTypeSynthetic_CreateWithScriptCode(data, options=0): r"""SBTypeSynthetic_CreateWithScriptCode(char const * data, uint32_t options=0) -> SBTypeSynthetic""" return _lldb.SBTypeSynthetic_CreateWithScriptCode(data, options) class SBUnixSignals(object): r"""Allows you to manipulate LLDB's signal disposition""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBUnixSignals self) -> SBUnixSignals __init__(SBUnixSignals self, SBUnixSignals rhs) -> SBUnixSignals """ _lldb.SBUnixSignals_swiginit(self, _lldb.new_SBUnixSignals(*args)) __swig_destroy__ = _lldb.delete_SBUnixSignals def Clear(self): r"""Clear(SBUnixSignals self)""" return _lldb.SBUnixSignals_Clear(self) def IsValid(self): r"""IsValid(SBUnixSignals self) -> bool""" return _lldb.SBUnixSignals_IsValid(self) def __nonzero__(self): return _lldb.SBUnixSignals___nonzero__(self) __bool__ = __nonzero__ def GetSignalAsCString(self, signo): r"""GetSignalAsCString(SBUnixSignals self, int32_t signo) -> char const *""" return _lldb.SBUnixSignals_GetSignalAsCString(self, signo) def GetSignalNumberFromName(self, name): r"""GetSignalNumberFromName(SBUnixSignals self, char const * name) -> int32_t""" return _lldb.SBUnixSignals_GetSignalNumberFromName(self, name) def GetShouldSuppress(self, signo): r"""GetShouldSuppress(SBUnixSignals self, int32_t signo) -> bool""" return _lldb.SBUnixSignals_GetShouldSuppress(self, signo) def SetShouldSuppress(self, signo, value): r"""SetShouldSuppress(SBUnixSignals self, int32_t signo, bool value) -> bool""" return _lldb.SBUnixSignals_SetShouldSuppress(self, signo, value) def GetShouldStop(self, signo): r"""GetShouldStop(SBUnixSignals self, int32_t signo) -> bool""" return _lldb.SBUnixSignals_GetShouldStop(self, signo) def SetShouldStop(self, signo, value): r"""SetShouldStop(SBUnixSignals self, int32_t signo, bool value) -> bool""" return _lldb.SBUnixSignals_SetShouldStop(self, signo, value) def GetShouldNotify(self, signo): r"""GetShouldNotify(SBUnixSignals self, int32_t signo) -> bool""" return _lldb.SBUnixSignals_GetShouldNotify(self, signo) def SetShouldNotify(self, signo, value): r"""SetShouldNotify(SBUnixSignals self, int32_t signo, bool value) -> bool""" return _lldb.SBUnixSignals_SetShouldNotify(self, signo, value) def GetNumSignals(self): r"""GetNumSignals(SBUnixSignals self) -> int32_t""" return _lldb.SBUnixSignals_GetNumSignals(self) def GetSignalAtIndex(self, index): r"""GetSignalAtIndex(SBUnixSignals self, int32_t index) -> int32_t""" return _lldb.SBUnixSignals_GetSignalAtIndex(self, index) def get_unix_signals_list(self): signals = [] for idx in range(0, self.GetNumSignals()): signals.append(self.GetSignalAtIndex(sig)) return signals threads = property(get_unix_signals_list, None, doc='''A read only property that returns a list() of valid signal numbers for this platform.''') # Register SBUnixSignals in _lldb: _lldb.SBUnixSignals_swigregister(SBUnixSignals) class SBValue(object): r""" Represents the value of a variable, a register, or an expression. SBValue supports iteration through its child, which in turn is represented as an SBValue. For example, we can get the general purpose registers of a frame as an SBValue, and iterate through all the registers,:: registerSet = frame.registers # Returns an SBValueList. for regs in registerSet: if 'general purpose registers' in regs.name.lower(): GPRs = regs break print('%s (number of children = %d):' % (GPRs.name, GPRs.num_children)) for reg in GPRs: print('Name: ', reg.name, ' Value: ', reg.value) produces the output: :: General Purpose Registers (number of children = 21): Name: rax Value: 0x0000000100000c5c Name: rbx Value: 0x0000000000000000 Name: rcx Value: 0x00007fff5fbffec0 Name: rdx Value: 0x00007fff5fbffeb8 Name: rdi Value: 0x0000000000000001 Name: rsi Value: 0x00007fff5fbffea8 Name: rbp Value: 0x00007fff5fbffe80 Name: rsp Value: 0x00007fff5fbffe60 Name: r8 Value: 0x0000000008668682 Name: r9 Value: 0x0000000000000000 Name: r10 Value: 0x0000000000001200 Name: r11 Value: 0x0000000000000206 Name: r12 Value: 0x0000000000000000 Name: r13 Value: 0x0000000000000000 Name: r14 Value: 0x0000000000000000 Name: r15 Value: 0x0000000000000000 Name: rip Value: 0x0000000100000dae Name: rflags Value: 0x0000000000000206 Name: cs Value: 0x0000000000000027 Name: fs Value: 0x0000000000000010 Name: gs Value: 0x0000000000000048 See also linked_list_iter() for another perspective on how to iterate through an SBValue instance which interprets the value object as representing the head of a linked list. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBValue self) -> SBValue __init__(SBValue self, SBValue rhs) -> SBValue """ _lldb.SBValue_swiginit(self, _lldb.new_SBValue(*args)) __swig_destroy__ = _lldb.delete_SBValue def IsValid(self): r"""IsValid(SBValue self) -> bool""" return _lldb.SBValue_IsValid(self) def __nonzero__(self): return _lldb.SBValue___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBValue self)""" return _lldb.SBValue_Clear(self) def GetError(self): r"""GetError(SBValue self) -> SBError""" return _lldb.SBValue_GetError(self) def GetID(self): r"""GetID(SBValue self) -> lldb::user_id_t""" return _lldb.SBValue_GetID(self) def GetName(self): r"""GetName(SBValue self) -> char const *""" return _lldb.SBValue_GetName(self) def GetTypeName(self): r"""GetTypeName(SBValue self) -> char const *""" return _lldb.SBValue_GetTypeName(self) def GetDisplayTypeName(self): r"""GetDisplayTypeName(SBValue self) -> char const *""" return _lldb.SBValue_GetDisplayTypeName(self) def GetByteSize(self): r"""GetByteSize(SBValue self) -> size_t""" return _lldb.SBValue_GetByteSize(self) def IsInScope(self): r"""IsInScope(SBValue self) -> bool""" return _lldb.SBValue_IsInScope(self) def GetFormat(self): r"""GetFormat(SBValue self) -> lldb::Format""" return _lldb.SBValue_GetFormat(self) def SetFormat(self, format): r"""SetFormat(SBValue self, lldb::Format format)""" return _lldb.SBValue_SetFormat(self, format) def GetValue(self): r"""GetValue(SBValue self) -> char const *""" return _lldb.SBValue_GetValue(self) def GetValueAsSigned(self, *args): r""" GetValueAsSigned(SBValue self, SBError error, int64_t fail_value=0) -> int64_t GetValueAsSigned(SBValue self, int64_t fail_value=0) -> int64_t """ return _lldb.SBValue_GetValueAsSigned(self, *args) def GetValueAsUnsigned(self, *args): r""" GetValueAsUnsigned(SBValue self, SBError error, uint64_t fail_value=0) -> uint64_t GetValueAsUnsigned(SBValue self, uint64_t fail_value=0) -> uint64_t """ return _lldb.SBValue_GetValueAsUnsigned(self, *args) def GetValueType(self): r"""GetValueType(SBValue self) -> lldb::ValueType""" return _lldb.SBValue_GetValueType(self) def GetValueDidChange(self): r"""GetValueDidChange(SBValue self) -> bool""" return _lldb.SBValue_GetValueDidChange(self) def GetSummary(self, *args): r""" GetSummary(SBValue self) -> char const GetSummary(SBValue self, SBStream stream, SBTypeSummaryOptions options) -> char const * """ return _lldb.SBValue_GetSummary(self, *args) def GetObjectDescription(self): r"""GetObjectDescription(SBValue self) -> char const *""" return _lldb.SBValue_GetObjectDescription(self) def GetDynamicValue(self, use_dynamic): r"""GetDynamicValue(SBValue self, lldb::DynamicValueType use_dynamic) -> SBValue""" return _lldb.SBValue_GetDynamicValue(self, use_dynamic) def GetStaticValue(self): r"""GetStaticValue(SBValue self) -> SBValue""" return _lldb.SBValue_GetStaticValue(self) def GetNonSyntheticValue(self): r"""GetNonSyntheticValue(SBValue self) -> SBValue""" return _lldb.SBValue_GetNonSyntheticValue(self) def GetPreferDynamicValue(self): r"""GetPreferDynamicValue(SBValue self) -> lldb::DynamicValueType""" return _lldb.SBValue_GetPreferDynamicValue(self) def SetPreferDynamicValue(self, use_dynamic): r"""SetPreferDynamicValue(SBValue self, lldb::DynamicValueType use_dynamic)""" return _lldb.SBValue_SetPreferDynamicValue(self, use_dynamic) def GetPreferSyntheticValue(self): r"""GetPreferSyntheticValue(SBValue self) -> bool""" return _lldb.SBValue_GetPreferSyntheticValue(self) def SetPreferSyntheticValue(self, use_synthetic): r"""SetPreferSyntheticValue(SBValue self, bool use_synthetic)""" return _lldb.SBValue_SetPreferSyntheticValue(self, use_synthetic) def IsDynamic(self): r"""IsDynamic(SBValue self) -> bool""" return _lldb.SBValue_IsDynamic(self) def IsSynthetic(self): r"""IsSynthetic(SBValue self) -> bool""" return _lldb.SBValue_IsSynthetic(self) def IsSyntheticChildrenGenerated(self): r"""IsSyntheticChildrenGenerated(SBValue self) -> bool""" return _lldb.SBValue_IsSyntheticChildrenGenerated(self) def SetSyntheticChildrenGenerated(self, arg2): r"""SetSyntheticChildrenGenerated(SBValue self, bool arg2)""" return _lldb.SBValue_SetSyntheticChildrenGenerated(self, arg2) def GetLocation(self): r"""GetLocation(SBValue self) -> char const *""" return _lldb.SBValue_GetLocation(self) def SetValueFromCString(self, *args): r""" SetValueFromCString(SBValue self, char const * value_str) -> bool SetValueFromCString(SBValue self, char const * value_str, SBError error) -> bool """ return _lldb.SBValue_SetValueFromCString(self, *args) def GetTypeFormat(self): r"""GetTypeFormat(SBValue self) -> SBTypeFormat""" return _lldb.SBValue_GetTypeFormat(self) def GetTypeSummary(self): r"""GetTypeSummary(SBValue self) -> SBTypeSummary""" return _lldb.SBValue_GetTypeSummary(self) def GetTypeFilter(self): r"""GetTypeFilter(SBValue self) -> SBTypeFilter""" return _lldb.SBValue_GetTypeFilter(self) def GetTypeSynthetic(self): r"""GetTypeSynthetic(SBValue self) -> SBTypeSynthetic""" return _lldb.SBValue_GetTypeSynthetic(self) def GetChildAtIndex(self, *args): r""" GetChildAtIndex(SBValue self, uint32_t idx) -> SBValue GetChildAtIndex(SBValue self, uint32_t idx, lldb::DynamicValueType use_dynamic, bool can_create_synthetic) -> SBValue Get a child value by index from a value. Structs, unions, classes, arrays and pointers have child values that can be access by index. Structs and unions access child members using a zero based index for each child member. For Classes reserve the first indexes for base classes that have members (empty base classes are omitted), and all members of the current class will then follow the base classes. Pointers differ depending on what they point to. If the pointer points to a simple type, the child at index zero is the only child value available, unless synthetic_allowed is true, in which case the pointer will be used as an array and can create 'synthetic' child values using positive or negative indexes. If the pointer points to an aggregate type (an array, class, union, struct), then the pointee is transparently skipped and any children are going to be the indexes of the child values within the aggregate type. For example if we have a 'Point' type and we have a SBValue that contains a pointer to a 'Point' type, then the child at index zero will be the 'x' member, and the child at index 1 will be the 'y' member (the child at index zero won't be a 'Point' instance). If you actually need an SBValue that represents the type pointed to by a SBValue for which GetType().IsPointeeType() returns true, regardless of the pointee type, you can do that with the SBValue.Dereference method (or the equivalent deref property). Arrays have a preset number of children that can be accessed by index and will returns invalid child values for indexes that are out of bounds unless the synthetic_allowed is true. In this case the array can create 'synthetic' child values for indexes that aren't in the array bounds using positive or negative indexes. @param[in] idx The index of the child value to get @param[in] use_dynamic An enumeration that specifies whether to get dynamic values, and also if the target can be run to figure out the dynamic type of the child value. @param[in] synthetic_allowed If true, then allow child values to be created by index for pointers and arrays for indexes that normally wouldn't be allowed. @return A new SBValue object that represents the child member value. """ return _lldb.SBValue_GetChildAtIndex(self, *args) def CreateChildAtOffset(self, name, offset, type): r"""CreateChildAtOffset(SBValue self, char const * name, uint32_t offset, SBType type) -> SBValue""" return _lldb.SBValue_CreateChildAtOffset(self, name, offset, type) def Cast(self, type): r"""Cast(SBValue self, SBType type) -> SBValue""" return _lldb.SBValue_Cast(self, type) def CreateValueFromExpression(self, *args): r""" CreateValueFromExpression(SBValue self, char const * name, char const * expression) -> SBValue CreateValueFromExpression(SBValue self, char const * name, char const * expression, SBExpressionOptions options) -> SBValue """ return _lldb.SBValue_CreateValueFromExpression(self, *args) def CreateValueFromAddress(self, name, address, type): r"""CreateValueFromAddress(SBValue self, char const * name, lldb::addr_t address, SBType type) -> SBValue""" return _lldb.SBValue_CreateValueFromAddress(self, name, address, type) def CreateValueFromData(self, name, data, type): r"""CreateValueFromData(SBValue self, char const * name, SBData data, SBType type) -> SBValue""" return _lldb.SBValue_CreateValueFromData(self, name, data, type) def GetType(self): r"""GetType(SBValue self) -> SBType""" return _lldb.SBValue_GetType(self) def GetIndexOfChildWithName(self, name): r""" GetIndexOfChildWithName(SBValue self, char const * name) -> uint32_t Returns the child member index. Matches children of this object only and will match base classes and member names if this is a clang typed object. @param[in] name The name of the child value to get @return An index to the child member value. """ return _lldb.SBValue_GetIndexOfChildWithName(self, name) def GetChildMemberWithName(self, *args): r""" GetChildMemberWithName(SBValue self, char const * name) -> SBValue GetChildMemberWithName(SBValue self, char const * name, lldb::DynamicValueType use_dynamic) -> SBValue Returns the child member value. Matches child members of this object and child members of any base classes. @param[in] name The name of the child value to get @param[in] use_dynamic An enumeration that specifies whether to get dynamic values, and also if the target can be run to figure out the dynamic type of the child value. @return A new SBValue object that represents the child member value. """ return _lldb.SBValue_GetChildMemberWithName(self, *args) def GetValueForExpressionPath(self, expr_path): r""" GetValueForExpressionPath(SBValue self, char const * expr_path) -> SBValue Expands nested expressions like .a->b[0].c[1]->d. """ return _lldb.SBValue_GetValueForExpressionPath(self, expr_path) def GetDeclaration(self): r"""GetDeclaration(SBValue self) -> SBDeclaration""" return _lldb.SBValue_GetDeclaration(self) def MightHaveChildren(self): r"""MightHaveChildren(SBValue self) -> bool""" return _lldb.SBValue_MightHaveChildren(self) def IsRuntimeSupportValue(self): r"""IsRuntimeSupportValue(SBValue self) -> bool""" return _lldb.SBValue_IsRuntimeSupportValue(self) def GetNumChildren(self, *args): r""" GetNumChildren(SBValue self) -> uint32_t GetNumChildren(SBValue self, uint32_t max) -> uint32_t """ return _lldb.SBValue_GetNumChildren(self, *args) def GetOpaqueType(self): r"""GetOpaqueType(SBValue self) -> void *""" return _lldb.SBValue_GetOpaqueType(self) def Dereference(self): r"""Dereference(SBValue self) -> SBValue""" return _lldb.SBValue_Dereference(self) def AddressOf(self): r"""AddressOf(SBValue self) -> SBValue""" return _lldb.SBValue_AddressOf(self) def TypeIsPointerType(self): r"""TypeIsPointerType(SBValue self) -> bool""" return _lldb.SBValue_TypeIsPointerType(self) def GetTarget(self): r"""GetTarget(SBValue self) -> SBTarget""" return _lldb.SBValue_GetTarget(self) def GetProcess(self): r"""GetProcess(SBValue self) -> SBProcess""" return _lldb.SBValue_GetProcess(self) def GetThread(self): r"""GetThread(SBValue self) -> SBThread""" return _lldb.SBValue_GetThread(self) def GetFrame(self): r"""GetFrame(SBValue self) -> SBFrame""" return _lldb.SBValue_GetFrame(self) def Watch(self, resolve_location, read, write, error): r""" Watch(SBValue self, bool resolve_location, bool read, bool write, SBError error) -> SBWatchpoint Find and watch a variable. It returns an SBWatchpoint, which may be invalid. """ return _lldb.SBValue_Watch(self, resolve_location, read, write, error) def WatchPointee(self, resolve_location, read, write, error): r""" WatchPointee(SBValue self, bool resolve_location, bool read, bool write, SBError error) -> SBWatchpoint Find and watch the location pointed to by a variable. It returns an SBWatchpoint, which may be invalid. """ return _lldb.SBValue_WatchPointee(self, resolve_location, read, write, error) def GetDescription(self, description): r"""GetDescription(SBValue self, SBStream description) -> bool""" return _lldb.SBValue_GetDescription(self, description) def GetPointeeData(self, item_idx=0, item_count=1): r""" GetPointeeData(SBValue self, uint32_t item_idx=0, uint32_t item_count=1) -> SBData Get an SBData wrapping what this SBValue points to. This method will dereference the current SBValue, if its data type is a ``T\*`` or ``T[]``, and extract ``item_count`` elements of type ``T`` from it, copying their contents in an :py:class:`SBData`. :param item_idx: The index of the first item to retrieve. For an array this is equivalent to array[item_idx], for a pointer to ``\*(pointer + item_idx)``. In either case, the measurement unit for item_idx is the ``sizeof(T)`` rather than the byte :param item_count: How many items should be copied into the output. By default only one item is copied, but more can be asked for. :return: The contents of the copied items on success. An empty :py:class:`SBData` otherwise. :rtype: SBData """ return _lldb.SBValue_GetPointeeData(self, item_idx, item_count) def GetData(self): r""" GetData(SBValue self) -> SBData Get an SBData wrapping the contents of this SBValue. This method will read the contents of this object in memory and copy them into an SBData for future use. @return An SBData with the contents of this SBValue, on success. An empty SBData otherwise. """ return _lldb.SBValue_GetData(self) def SetData(self, data, error): r"""SetData(SBValue self, SBData data, SBError error) -> bool""" return _lldb.SBValue_SetData(self, data, error) def GetLoadAddress(self): r"""GetLoadAddress(SBValue self) -> lldb::addr_t""" return _lldb.SBValue_GetLoadAddress(self) def GetAddress(self): r"""GetAddress(SBValue self) -> SBAddress""" return _lldb.SBValue_GetAddress(self) def Persist(self): r"""Persist(SBValue self) -> SBValue""" return _lldb.SBValue_Persist(self) def GetExpressionPath(self, *args): r""" GetExpressionPath(SBValue self, SBStream description) -> bool GetExpressionPath(SBValue self, SBStream description, bool qualify_cxx_base_classes) -> bool Returns an expression path for this value. """ return _lldb.SBValue_GetExpressionPath(self, *args) def EvaluateExpression(self, *args): r""" EvaluateExpression(SBValue self, char const * expr) -> SBValue EvaluateExpression(SBValue self, char const * expr, SBExpressionOptions options) -> SBValue EvaluateExpression(SBValue self, char const * expr, SBExpressionOptions options, char const * name) -> SBValue """ return _lldb.SBValue_EvaluateExpression(self, *args) def __str__(self): r"""__str__(SBValue self) -> std::string""" return _lldb.SBValue___str__(self) def __get_dynamic__ (self): '''Helper function for the "SBValue.dynamic" property.''' return self.GetDynamicValue (eDynamicCanRunTarget) class children_access(object): '''A helper object that will lazily hand out thread for a process when supplied an index.''' def __init__(self, sbvalue): self.sbvalue = sbvalue def __len__(self): if self.sbvalue: return int(self.sbvalue.GetNumChildren()) return 0 def __getitem__(self, key): if type(key) is int and key < len(self): return self.sbvalue.GetChildAtIndex(key) return None def get_child_access_object(self): '''An accessor function that returns a children_access() object which allows lazy member variable access from a lldb.SBValue object.''' return self.children_access (self) def get_value_child_list(self): '''An accessor function that returns a list() that contains all children in a lldb.SBValue object.''' children = [] accessor = self.get_child_access_object() for idx in range(len(accessor)): children.append(accessor[idx]) return children def __iter__(self): '''Iterate over all child values of a lldb.SBValue object.''' return lldb_iter(self, 'GetNumChildren', 'GetChildAtIndex') def __len__(self): '''Return the number of child values of a lldb.SBValue object.''' return self.GetNumChildren() children = property(get_value_child_list, None, doc='''A read only property that returns a list() of lldb.SBValue objects for the children of the value.''') child = property(get_child_access_object, None, doc='''A read only property that returns an object that can access children of a variable by index (child_value = value.children[12]).''') name = property(GetName, None, doc='''A read only property that returns the name of this value as a string.''') type = property(GetType, None, doc='''A read only property that returns a lldb.SBType object that represents the type for this value.''') size = property(GetByteSize, None, doc='''A read only property that returns the size in bytes of this value.''') is_in_scope = property(IsInScope, None, doc='''A read only property that returns a boolean value that indicates whether this value is currently lexically in scope.''') format = property(GetName, SetFormat, doc='''A read/write property that gets/sets the format used for lldb.SBValue().GetValue() for this value. See enumerations that start with "lldb.eFormat".''') value = property(GetValue, SetValueFromCString, doc='''A read/write property that gets/sets value from a string.''') value_type = property(GetValueType, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eValueType") that represents the type of this value (local, argument, global, register, etc.).''') changed = property(GetValueDidChange, None, doc='''A read only property that returns a boolean value that indicates if this value has changed since it was last updated.''') data = property(GetData, None, doc='''A read only property that returns an lldb object (lldb.SBData) that represents the bytes that make up the value for this object.''') load_addr = property(GetLoadAddress, None, doc='''A read only property that returns the load address of this value as an integer.''') addr = property(GetAddress, None, doc='''A read only property that returns an lldb.SBAddress that represents the address of this value if it is in memory.''') deref = property(Dereference, None, doc='''A read only property that returns an lldb.SBValue that is created by dereferencing this value.''') address_of = property(AddressOf, None, doc='''A read only property that returns an lldb.SBValue that represents the address-of this value.''') error = property(GetError, None, doc='''A read only property that returns the lldb.SBError that represents the error from the last time the variable value was calculated.''') summary = property(GetSummary, None, doc='''A read only property that returns the summary for this value as a string''') description = property(GetObjectDescription, None, doc='''A read only property that returns the language-specific description of this value as a string''') dynamic = property(__get_dynamic__, None, doc='''A read only property that returns an lldb.SBValue that is created by finding the dynamic type of this value.''') location = property(GetLocation, None, doc='''A read only property that returns the location of this value as a string.''') target = property(GetTarget, None, doc='''A read only property that returns the lldb.SBTarget that this value is associated with.''') process = property(GetProcess, None, doc='''A read only property that returns the lldb.SBProcess that this value is associated with, the returned value might be invalid and should be tested.''') thread = property(GetThread, None, doc='''A read only property that returns the lldb.SBThread that this value is associated with, the returned value might be invalid and should be tested.''') frame = property(GetFrame, None, doc='''A read only property that returns the lldb.SBFrame that this value is associated with, the returned value might be invalid and should be tested.''') num_children = property(GetNumChildren, None, doc='''A read only property that returns the number of child lldb.SBValues that this value has.''') unsigned = property(GetValueAsUnsigned, None, doc='''A read only property that returns the value of this SBValue as an usigned integer.''') signed = property(GetValueAsSigned, None, doc='''A read only property that returns the value of this SBValue as a signed integer.''') def get_expr_path(self): s = SBStream() self.GetExpressionPath (s) return s.GetData() path = property(get_expr_path, None, doc='''A read only property that returns the expression path that one can use to reach this value in an expression.''') def synthetic_child_from_expression(self, name, expr, options=None): if options is None: options = lldb.SBExpressionOptions() child = self.CreateValueFromExpression(name, expr, options) child.SetSyntheticChildrenGenerated(True) return child def synthetic_child_from_data(self, name, data, type): child = self.CreateValueFromData(name, data, type) child.SetSyntheticChildrenGenerated(True) return child def synthetic_child_from_address(self, name, addr, type): child = self.CreateValueFromAddress(name, addr, type) child.SetSyntheticChildrenGenerated(True) return child def __eol_test(val): """Default function for end of list test takes an SBValue object. Return True if val is invalid or it corresponds to a null pointer. Otherwise, return False. """ if not val or val.GetValueAsUnsigned() == 0: return True else: return False # ================================================== # Iterator for lldb.SBValue treated as a linked list # ================================================== def linked_list_iter(self, next_item_name, end_of_list_test=__eol_test): """Generator adaptor to support iteration for SBValue as a linked list. linked_list_iter() is a special purpose iterator to treat the SBValue as the head of a list data structure, where you specify the child member name which points to the next item on the list and you specify the end-of-list test function which takes an SBValue for an item and returns True if EOL is reached and False if not. linked_list_iter() also detects infinite loop and bails out early. The end_of_list_test arg, if omitted, defaults to the __eol_test function above. For example, # Get Frame #0. ... # Get variable 'task_head'. task_head = frame0.FindVariable('task_head') ... for t in task_head.linked_list_iter('next'): print t """ if end_of_list_test(self): return item = self visited = set() try: while not end_of_list_test(item) and not item.GetValueAsUnsigned() in visited: visited.add(item.GetValueAsUnsigned()) yield item # Prepare for the next iteration. item = item.GetChildMemberWithName(next_item_name) except: # Exception occurred. Stop the generator. pass return # Register SBValue in _lldb: _lldb.SBValue_swigregister(SBValue) class SBValueList(object): r""" Represents a collection of SBValues. Both :py:class:`SBFrame.GetVariables()` and :py:class:`SBFrame.GetRegisters()` return a SBValueList. SBValueList supports :py:class:`SBValue` iteration. For example (from test/lldbutil.py),:: def get_registers(frame, kind): '''Returns the registers given the frame and the kind of registers desired. Returns None if there's no such kind. ''' registerSet = frame.GetRegisters() # Return type of SBValueList. for value in registerSet: if kind.lower() in value.GetName().lower(): return value return None def get_GPRs(frame): '''Returns the general purpose registers of the frame as an SBValue. The returned SBValue object is iterable. An example: ... from lldbutil import get_GPRs regs = get_GPRs(frame) for reg in regs: print('%s => %s' % (reg.GetName(), reg.GetValue())) ... ''' return get_registers(frame, 'general purpose') def get_FPRs(frame): '''Returns the floating point registers of the frame as an SBValue. The returned SBValue object is iterable. An example: ... from lldbutil import get_FPRs regs = get_FPRs(frame) for reg in regs: print('%s => %s' % (reg.GetName(), reg.GetValue())) ... ''' return get_registers(frame, 'floating point') def get_ESRs(frame): '''Returns the exception state registers of the frame as an SBValue. The returned SBValue object is iterable. An example: ... from lldbutil import get_ESRs regs = get_ESRs(frame) for reg in regs: print('%s => %s' % (reg.GetName(), reg.GetValue())) ... ''' return get_registers(frame, 'exception state') """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBValueList self) -> SBValueList __init__(SBValueList self, SBValueList rhs) -> SBValueList """ _lldb.SBValueList_swiginit(self, _lldb.new_SBValueList(*args)) __swig_destroy__ = _lldb.delete_SBValueList def IsValid(self): r"""IsValid(SBValueList self) -> bool""" return _lldb.SBValueList_IsValid(self) def __nonzero__(self): return _lldb.SBValueList___nonzero__(self) __bool__ = __nonzero__ def Clear(self): r"""Clear(SBValueList self)""" return _lldb.SBValueList_Clear(self) def Append(self, *args): r""" Append(SBValueList self, SBValue val_obj) Append(SBValueList self, SBValueList value_list) """ return _lldb.SBValueList_Append(self, *args) def GetSize(self): r"""GetSize(SBValueList self) -> uint32_t""" return _lldb.SBValueList_GetSize(self) def GetValueAtIndex(self, idx): r"""GetValueAtIndex(SBValueList self, uint32_t idx) -> SBValue""" return _lldb.SBValueList_GetValueAtIndex(self, idx) def FindValueObjectByUID(self, uid): r"""FindValueObjectByUID(SBValueList self, lldb::user_id_t uid) -> SBValue""" return _lldb.SBValueList_FindValueObjectByUID(self, uid) def GetFirstValueByName(self, name): r"""GetFirstValueByName(SBValueList self, char const * name) -> SBValue""" return _lldb.SBValueList_GetFirstValueByName(self, name) def __str__(self): r"""__str__(SBValueList self) -> std::string""" return _lldb.SBValueList___str__(self) def __iter__(self): '''Iterate over all values in a lldb.SBValueList object.''' return lldb_iter(self, 'GetSize', 'GetValueAtIndex') def __len__(self): return int(self.GetSize()) def __getitem__(self, key): count = len(self) #------------------------------------------------------------ # Access with "int" to get Nth item in the list #------------------------------------------------------------ if type(key) is int: if key < count: return self.GetValueAtIndex(key) #------------------------------------------------------------ # Access with "str" to get values by name #------------------------------------------------------------ elif type(key) is str: matches = [] for idx in range(count): value = self.GetValueAtIndex(idx) if value.name == key: matches.append(value) return matches #------------------------------------------------------------ # Match with regex #------------------------------------------------------------ elif isinstance(key, type(re.compile('.'))): matches = [] for idx in range(count): value = self.GetValueAtIndex(idx) re_match = key.search(value.name) if re_match: matches.append(value) return matches # Register SBValueList in _lldb: _lldb.SBValueList_swigregister(SBValueList) class SBVariablesOptions(object): r"""Describes which variables should be returned from :py:class:`SBFrame.GetVariables`.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBVariablesOptions self) -> SBVariablesOptions __init__(SBVariablesOptions self, SBVariablesOptions options) -> SBVariablesOptions """ _lldb.SBVariablesOptions_swiginit(self, _lldb.new_SBVariablesOptions(*args)) __swig_destroy__ = _lldb.delete_SBVariablesOptions def IsValid(self): r"""IsValid(SBVariablesOptions self) -> bool""" return _lldb.SBVariablesOptions_IsValid(self) def __nonzero__(self): return _lldb.SBVariablesOptions___nonzero__(self) __bool__ = __nonzero__ def GetIncludeArguments(self): r"""GetIncludeArguments(SBVariablesOptions self) -> bool""" return _lldb.SBVariablesOptions_GetIncludeArguments(self) def SetIncludeArguments(self, arg2): r"""SetIncludeArguments(SBVariablesOptions self, bool arg2)""" return _lldb.SBVariablesOptions_SetIncludeArguments(self, arg2) def GetIncludeRecognizedArguments(self, arg2): r"""GetIncludeRecognizedArguments(SBVariablesOptions self, SBTarget arg2) -> bool""" return _lldb.SBVariablesOptions_GetIncludeRecognizedArguments(self, arg2) def SetIncludeRecognizedArguments(self, arg2): r"""SetIncludeRecognizedArguments(SBVariablesOptions self, bool arg2)""" return _lldb.SBVariablesOptions_SetIncludeRecognizedArguments(self, arg2) def GetIncludeLocals(self): r"""GetIncludeLocals(SBVariablesOptions self) -> bool""" return _lldb.SBVariablesOptions_GetIncludeLocals(self) def SetIncludeLocals(self, arg2): r"""SetIncludeLocals(SBVariablesOptions self, bool arg2)""" return _lldb.SBVariablesOptions_SetIncludeLocals(self, arg2) def GetIncludeStatics(self): r"""GetIncludeStatics(SBVariablesOptions self) -> bool""" return _lldb.SBVariablesOptions_GetIncludeStatics(self) def SetIncludeStatics(self, arg2): r"""SetIncludeStatics(SBVariablesOptions self, bool arg2)""" return _lldb.SBVariablesOptions_SetIncludeStatics(self, arg2) def GetInScopeOnly(self): r"""GetInScopeOnly(SBVariablesOptions self) -> bool""" return _lldb.SBVariablesOptions_GetInScopeOnly(self) def SetInScopeOnly(self, arg2): r"""SetInScopeOnly(SBVariablesOptions self, bool arg2)""" return _lldb.SBVariablesOptions_SetInScopeOnly(self, arg2) def GetIncludeRuntimeSupportValues(self): r"""GetIncludeRuntimeSupportValues(SBVariablesOptions self) -> bool""" return _lldb.SBVariablesOptions_GetIncludeRuntimeSupportValues(self) def SetIncludeRuntimeSupportValues(self, arg2): r"""SetIncludeRuntimeSupportValues(SBVariablesOptions self, bool arg2)""" return _lldb.SBVariablesOptions_SetIncludeRuntimeSupportValues(self, arg2) def GetUseDynamic(self): r"""GetUseDynamic(SBVariablesOptions self) -> lldb::DynamicValueType""" return _lldb.SBVariablesOptions_GetUseDynamic(self) def SetUseDynamic(self, arg2): r"""SetUseDynamic(SBVariablesOptions self, lldb::DynamicValueType arg2)""" return _lldb.SBVariablesOptions_SetUseDynamic(self, arg2) # Register SBVariablesOptions in _lldb: _lldb.SBVariablesOptions_swigregister(SBVariablesOptions) class SBWatchpoint(object): r""" Represents an instance of watchpoint for a specific target program. A watchpoint is determined by the address and the byte size that resulted in this particular instantiation. Each watchpoint has its settable options. See also :py:class:`SBTarget.watchpoint_iter()` for example usage of iterating through the watchpoints of the target. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args): r""" __init__(SBWatchpoint self) -> SBWatchpoint __init__(SBWatchpoint self, SBWatchpoint rhs) -> SBWatchpoint """ _lldb.SBWatchpoint_swiginit(self, _lldb.new_SBWatchpoint(*args)) __swig_destroy__ = _lldb.delete_SBWatchpoint def IsValid(self): r"""IsValid(SBWatchpoint self) -> bool""" return _lldb.SBWatchpoint_IsValid(self) def __nonzero__(self): return _lldb.SBWatchpoint___nonzero__(self) __bool__ = __nonzero__ def __eq__(self, rhs): r"""__eq__(SBWatchpoint self, SBWatchpoint rhs) -> bool""" return _lldb.SBWatchpoint___eq__(self, rhs) def __ne__(self, rhs): r"""__ne__(SBWatchpoint self, SBWatchpoint rhs) -> bool""" return _lldb.SBWatchpoint___ne__(self, rhs) def GetError(self): r"""GetError(SBWatchpoint self) -> SBError""" return _lldb.SBWatchpoint_GetError(self) def GetID(self): r"""GetID(SBWatchpoint self) -> lldb::watch_id_t""" return _lldb.SBWatchpoint_GetID(self) def GetHardwareIndex(self): r""" GetHardwareIndex(SBWatchpoint self) -> int32_t With -1 representing an invalid hardware index. """ return _lldb.SBWatchpoint_GetHardwareIndex(self) def GetWatchAddress(self): r"""GetWatchAddress(SBWatchpoint self) -> lldb::addr_t""" return _lldb.SBWatchpoint_GetWatchAddress(self) def GetWatchSize(self): r"""GetWatchSize(SBWatchpoint self) -> size_t""" return _lldb.SBWatchpoint_GetWatchSize(self) def SetEnabled(self, enabled): r"""SetEnabled(SBWatchpoint self, bool enabled)""" return _lldb.SBWatchpoint_SetEnabled(self, enabled) def IsEnabled(self): r"""IsEnabled(SBWatchpoint self) -> bool""" return _lldb.SBWatchpoint_IsEnabled(self) def GetHitCount(self): r"""GetHitCount(SBWatchpoint self) -> uint32_t""" return _lldb.SBWatchpoint_GetHitCount(self) def GetIgnoreCount(self): r"""GetIgnoreCount(SBWatchpoint self) -> uint32_t""" return _lldb.SBWatchpoint_GetIgnoreCount(self) def SetIgnoreCount(self, n): r"""SetIgnoreCount(SBWatchpoint self, uint32_t n)""" return _lldb.SBWatchpoint_SetIgnoreCount(self, n) def GetCondition(self): r""" GetCondition(SBWatchpoint self) -> char const * Get the condition expression for the watchpoint. """ return _lldb.SBWatchpoint_GetCondition(self) def SetCondition(self, condition): r""" SetCondition(SBWatchpoint self, char const * condition) The watchpoint stops only if the condition expression evaluates to true. """ return _lldb.SBWatchpoint_SetCondition(self, condition) def GetDescription(self, description, level): r"""GetDescription(SBWatchpoint self, SBStream description, lldb::DescriptionLevel level) -> bool""" return _lldb.SBWatchpoint_GetDescription(self, description, level) @staticmethod def EventIsWatchpointEvent(event): r"""EventIsWatchpointEvent(SBEvent event) -> bool""" return _lldb.SBWatchpoint_EventIsWatchpointEvent(event) @staticmethod def GetWatchpointEventTypeFromEvent(event): r"""GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType""" return _lldb.SBWatchpoint_GetWatchpointEventTypeFromEvent(event) @staticmethod def GetWatchpointFromEvent(event): r"""GetWatchpointFromEvent(SBEvent event) -> SBWatchpoint""" return _lldb.SBWatchpoint_GetWatchpointFromEvent(event) def __str__(self): r"""__str__(SBWatchpoint self) -> std::string""" return _lldb.SBWatchpoint___str__(self) # Register SBWatchpoint in _lldb: _lldb.SBWatchpoint_swigregister(SBWatchpoint) def SBWatchpoint_EventIsWatchpointEvent(event): r"""SBWatchpoint_EventIsWatchpointEvent(SBEvent event) -> bool""" return _lldb.SBWatchpoint_EventIsWatchpointEvent(event) def SBWatchpoint_GetWatchpointEventTypeFromEvent(event): r"""SBWatchpoint_GetWatchpointEventTypeFromEvent(SBEvent event) -> lldb::WatchpointEventType""" return _lldb.SBWatchpoint_GetWatchpointEventTypeFromEvent(event) def SBWatchpoint_GetWatchpointFromEvent(event): r"""SBWatchpoint_GetWatchpointFromEvent(SBEvent event) -> SBWatchpoint""" return _lldb.SBWatchpoint_GetWatchpointFromEvent(event) def command(command_name=None, doc=None): import lldb """A decorator function that registers an LLDB command line command that is bound to the function it is attached to.""" def callable(function): """Registers an lldb command for the decorated function.""" command = "command script add -f %s.%s %s" % (function.__module__, function.__name__, command_name or function.__name__) lldb.debugger.HandleCommand(command) if doc: function.__doc__ = doc return function return callable class declaration(object): '''A class that represents a source declaration location with file, line and column.''' def __init__(self, file, line, col): self.file = file self.line = line self.col = col class value_iter(object): '''Allows iterating over the children of an :py:class:`SBValue`.''' def __iter__(self): return self def __next__(self): if self.index >= self.length: raise StopIteration() child_sbvalue = self.sbvalue.GetChildAtIndex(self.index) self.index += 1 return value(child_sbvalue) def next(self): return self.__next__() def __init__(self,value): self.index = 0 self.sbvalue = value if type(self.sbvalue) is value: self.sbvalue = self.sbvalue.sbvalue self.length = self.sbvalue.GetNumChildren() class value(object): '''Wraps :py:class:`SBValue` objects so the resulting object can be used as a variable would be in code. So if you have a Point structure variable in your code in the current frame named "pt", you can initialize an instance of this class with it: :: pt = lldb.value(lldb.frame.FindVariable("pt")) print pt print pt.x print pt.y pt = lldb.value(lldb.frame.FindVariable("rectangle_array")) print rectangle_array[12] print rectangle_array[5].origin.x''' def __init__(self, sbvalue): self.sbvalue = sbvalue def __nonzero__(self): return self.sbvalue.__nonzero__() def __bool__(self): return self.sbvalue.__bool__() def __str__(self): return self.sbvalue.__str__() def __getitem__(self, key): # Allow array access if this value has children... if type(key) is value: key = int(key) if type(key) is int: child_sbvalue = (self.sbvalue.GetValueForExpressionPath("[%i]" % key)) if child_sbvalue and child_sbvalue.IsValid(): return value(child_sbvalue) raise IndexError("Index '%d' is out of range" % key) raise TypeError("No array item of type %s" % str(type(key))) def __iter__(self): return value_iter(self.sbvalue) def __getattr__(self, name): child_sbvalue = self.sbvalue.GetChildMemberWithName (name) if child_sbvalue and child_sbvalue.IsValid(): return value(child_sbvalue) raise AttributeError("Attribute '%s' is not defined" % name) def __add__(self, other): return int(self) + int(other) def __sub__(self, other): return int(self) - int(other) def __mul__(self, other): return int(self) * int(other) def __floordiv__(self, other): return int(self) // int(other) def __mod__(self, other): return int(self) % int(other) def __divmod__(self, other): return int(self) % int(other) def __pow__(self, other): return int(self) ** int(other) def __lshift__(self, other): return int(self) << int(other) def __rshift__(self, other): return int(self) >> int(other) def __and__(self, other): return int(self) & int(other) def __xor__(self, other): return int(self) ^ int(other) def __or__(self, other): return int(self) | int(other) def __div__(self, other): return int(self) / int(other) def __truediv__(self, other): return int(self) / int(other) def __iadd__(self, other): result = self.__add__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __isub__(self, other): result = self.__sub__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __imul__(self, other): result = self.__mul__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __idiv__(self, other): result = self.__div__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __itruediv__(self, other): result = self.__truediv__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __ifloordiv__(self, other): result = self.__floordiv__(self, other) self.sbvalue.SetValueFromCString (str(result)) return result def __imod__(self, other): result = self.__and__(self, other) self.sbvalue.SetValueFromCString (str(result)) return result def __ipow__(self, other): result = self.__pow__(self, other) self.sbvalue.SetValueFromCString (str(result)) return result def __ipow__(self, other, modulo): result = self.__pow__(self, other, modulo) self.sbvalue.SetValueFromCString (str(result)) return result def __ilshift__(self, other): result = self.__lshift__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __irshift__(self, other): result = self.__rshift__(other) self.sbvalue.SetValueFromCString (str(result)) return result def __iand__(self, other): result = self.__and__(self, other) self.sbvalue.SetValueFromCString (str(result)) return result def __ixor__(self, other): result = self.__xor__(self, other) self.sbvalue.SetValueFromCString (str(result)) return result def __ior__(self, other): result = self.__ior__(self, other) self.sbvalue.SetValueFromCString (str(result)) return result def __neg__(self): return -int(self) def __pos__(self): return +int(self) def __abs__(self): return abs(int(self)) def __invert__(self): return ~int(self) def __complex__(self): return complex (int(self)) def __int__(self): is_num,is_sign = is_numeric_type(self.sbvalue.GetType().GetCanonicalType().GetBasicType()) if is_num and not is_sign: return self.sbvalue.GetValueAsUnsigned() return self.sbvalue.GetValueAsSigned() def __long__(self): return self.__int__() def __float__(self): return float (self.sbvalue.GetValueAsSigned()) def __oct__(self): return '0%o' % self.sbvalue.GetValueAsUnsigned() def __hex__(self): return '0x%x' % self.sbvalue.GetValueAsUnsigned() def __len__(self): return self.sbvalue.GetNumChildren() def __eq__(self, other): if type(other) is int: return int(self) == other elif type(other) is str: return str(self) == other elif type(other) is value: self_err = SBError() other_err = SBError() self_val = self.sbvalue.GetValueAsUnsigned(self_err) if self_err.fail: raise ValueError("unable to extract value of self") other_val = other.sbvalue.GetValueAsUnsigned(other_err) if other_err.fail: raise ValueError("unable to extract value of other") return self_val == other_val raise TypeError("Unknown type %s, No equality operation defined." % str(type(other))) def __ne__(self, other): return not self.__eq__(other) class SBSyntheticValueProvider(object): def __init__(self,valobj): pass def num_children(self): return 0 def get_child_index(self,name): return None def get_child_at_index(self,idx): return None def update(self): pass def has_children(self): return False # given an lldb.SBBasicType it returns a tuple # (is_numeric, is_signed) # the value of is_signed is undefined if is_numeric == false def is_numeric_type(basic_type): if basic_type == eBasicTypeInvalid: return (False,False) if basic_type == eBasicTypeVoid: return (False,False) if basic_type == eBasicTypeChar: return (True,False) if basic_type == eBasicTypeSignedChar: return (True,True) if basic_type == eBasicTypeUnsignedChar: return (True,False) if basic_type == eBasicTypeWChar: return (True,False) if basic_type == eBasicTypeSignedWChar: return (True,True) if basic_type == eBasicTypeUnsignedWChar: return (True,False) if basic_type == eBasicTypeChar16: return (True,False) if basic_type == eBasicTypeChar32: return (True,False) if basic_type == eBasicTypeShort: return (True,True) if basic_type == eBasicTypeUnsignedShort: return (True,False) if basic_type == eBasicTypeInt: return (True,True) if basic_type == eBasicTypeUnsignedInt: return (True,False) if basic_type == eBasicTypeLong: return (True,True) if basic_type == eBasicTypeUnsignedLong: return (True,False) if basic_type == eBasicTypeLongLong: return (True,True) if basic_type == eBasicTypeUnsignedLongLong: return (True,False) if basic_type == eBasicTypeInt128: return (True,True) if basic_type == eBasicTypeUnsignedInt128: return (True,False) if basic_type == eBasicTypeBool: return (False,False) if basic_type == eBasicTypeHalf: return (True,True) if basic_type == eBasicTypeFloat: return (True,True) if basic_type == eBasicTypeDouble: return (True,True) if basic_type == eBasicTypeLongDouble: return (True,True) if basic_type == eBasicTypeFloatComplex: return (True,True) if basic_type == eBasicTypeDoubleComplex: return (True,True) if basic_type == eBasicTypeLongDoubleComplex: return (True,True) if basic_type == eBasicTypeObjCID: return (False,False) if basic_type == eBasicTypeObjCClass: return (False,False) if basic_type == eBasicTypeObjCSel: return (False,False) if basic_type == eBasicTypeNullPtr: return (False,False) #if basic_type == eBasicTypeOther: return (False,False) _initialize = True try: import lldbconfig _initialize = lldbconfig.INITIALIZE except ImportError: pass debugger_unique_id = 0 if _initialize: SBDebugger.Initialize() debugger = None target = None process = None thread = None frame = None
r""" LoadCore(SBTarget self, char const * core_file) -> SBProcess LoadCore(SBTarget self, char const * core_file, SBError error) -> SBProcess Load a core file @param[in] core_file File path of the core dump. @param[out] error An error explaining what went wrong if the operation fails. (Optional) @return A process object for the newly created core file. For example, process = target.LoadCore('./a.out.core') loads a new core file and returns the process object. """ return _lldb.SBTarget_LoadCore(self, *args)
creat_database_on_cloudant.py
from cloudant.client import Cloudant from cloudant.error import CloudantException from cloudant.result import Result, ResultByKey client = Cloudant.iam("b3e03381-f624-4db8-a3da-3588bface309-bluemix", "sckyMGqNGv8CX9aIcTDbrhYZYhYBDUfEXAJuXuN8SB1D") client.connect() databaseName = "attendance_toqa" myDatabase = client.create_database(databaseName) if myDatabase.exists(): print "'{0}' successfully created.\n".format(databaseName) sampleData = [ [1, "Gabr", "Hazem", 100], [2, "Adel", "Muhammad", 40], [3, "omar", "Mekawy", 20], [4, "mustafa", "azazy", 10], ] # Create documents by using the sample data. # Go through each row in the array for document in sampleData: # Retrieve the fields in each row. number = document[0] name = document[1] description = document[2] temperature = document[3] # Create a JSON document that represents # all the data in the row. jsonDocument = { "numberField": number, "nameField": name, "descriptionField": description,
# Create a document by using the database API. newDocument = myDatabase.create_document(jsonDocument) # Check that the document exists in the database. if newDocument.exists(): print "Document '{0}' successfully created.".format(number)
"temperatureField": temperature }
TextureUtil.js
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/4.0beta2/esri/copyright.txt for details. //>>built define([],function(){var h={},e,p,t=1/65536;h.createGamma3CPU=function(g,n){if(!e){e=Array(256);var a;for(a=0;256>a;a++)e[a]=a*a*a;p=Array(256);for(a=0;256>a;a++)p[a]=Math.pow(16777216*(a/256),1/3)}a=g.getContext("2d");var b=g.getAttribute("width"),d=g.getAttribute("height"),k=a.getImageData(0,0,b,d),b=b>>1,d=d>>1,h=1;do{g.setAttribute("width",b);g.setAttribute("height",d);for(var q=a.createImageData(b,d),l=0;l<d;l++)for(var m=0;m<b;m++)for(var u=4*(l*b+m),r=4*(2*2*l*b+2*m),s=4*(2*(2*l+1)*b+2*m), f=0;4>f;f++){var v=q.data,w=u+f,c;c=0;c+=e[k.data[r+f]];c+=e[k.data[r+4+f]];c+=e[k.data[s+f]];c+=e[k.data[s+4+f]];c=p[Math.round(c/4*t)];v[w]=c}a.putImageData(q,0,0);n.texSubImage2D(n.TEXTURE_2D,h,0,0,n.RGBA,n.UNSIGNED_BYTE,g);k=q;b>>=1;d>>=1;h++}while(1<b&&1<d)};return h});
solana-test-validator.rs
use { clap::{crate_name, value_t, value_t_or_exit, values_t_or_exit, App, Arg}, crossbeam_channel::unbounded, log::*, solana_clap_utils::{ input_parsers::{pubkey_of, pubkeys_of, value_of}, input_validators::{ is_parsable, is_pubkey, is_pubkey_or_keypair, is_slot, is_url_or_moniker, normalize_to_url_if_moniker, }, }, solana_client::rpc_client::RpcClient, solana_core::tower_storage::FileTowerStorage, solana_faucet::faucet::{run_local_faucet_with_port, FAUCET_PORT}, solana_rpc::{rpc::JsonRpcConfig, rpc_pubsub_service::PubSubConfig}, solana_sdk::{ account::AccountSharedData, clock::Slot, epoch_schedule::{EpochSchedule, MINIMUM_SLOTS_PER_EPOCH}, native_token::sol_to_lamports, pubkey::Pubkey, rent::Rent, rpc_port, signature::{read_keypair_file, write_keypair_file, Keypair, Signer}, system_program, }, solana_streamer::socket::SocketAddrSpace, solana_test_validator::*, solana_validator::{ admin_rpc_service, dashboard::Dashboard, ledger_lockfile, lock_ledger, println_name_value, redirect_stderr_to_file, }, std::{ collections::HashSet, fs, io, net::{IpAddr, Ipv4Addr, SocketAddr}, path::{Path, PathBuf}, process::exit, sync::{Arc, RwLock}, time::{Duration, SystemTime, UNIX_EPOCH}, }, }; /* 10,000 was derived empirically by watching the size * of the rocksdb/ directory self-limit itself to the * 40MB-150MB range when running `solana-test-validator` */ const DEFAULT_MAX_LEDGER_SHREDS: u64 = 10_000; const DEFAULT_FAUCET_SOL: f64 = 1_000_000.; #[derive(PartialEq)] enum Output { None, Log, Dashboard, } fn main() { let default_rpc_port = rpc_port::DEFAULT_RPC_PORT.to_string(); let default_faucet_port = FAUCET_PORT.to_string(); let default_limit_ledger_size = DEFAULT_MAX_LEDGER_SHREDS.to_string(); let default_faucet_sol = DEFAULT_FAUCET_SOL.to_string(); let matches = App::new("solana-test-validator") .about("Test Validator") .version(solana_version::version!()) .arg({ let arg = Arg::with_name("config_file") .short("C") .long("config") .value_name("PATH") .takes_value(true) .help("Configuration file to use"); if let Some(ref config_file) = *solana_cli_config::CONFIG_FILE { arg.default_value(config_file) } else { arg } }) .arg( Arg::with_name("json_rpc_url") .short("u") .long("url") .value_name("URL_OR_MONIKER") .takes_value(true) .validator(is_url_or_moniker) .help( "URL for Solana's JSON RPC or moniker (or their first letter): \ [mainnet-beta, testnet, devnet, localhost]", ), ) .arg( Arg::with_name("mint_address") .long("mint") .value_name("PUBKEY") .validator(is_pubkey) .takes_value(true) .help( "Address of the mint account that will receive tokens \ created at genesis. If the ledger already exists then \ this parameter is silently ignored [default: client keypair]", ), ) .arg( Arg::with_name("ledger_path") .short("l") .long("ledger") .value_name("DIR") .takes_value(true) .required(true) .default_value("test-ledger") .help("Use DIR as ledger location"), ) .arg( Arg::with_name("reset") .short("r") .long("reset") .takes_value(false) .help( "Reset the ledger to genesis if it exists. \ By default the validator will resume an existing ledger (if present)", ), ) .arg( Arg::with_name("quiet") .short("q") .long("quiet") .takes_value(false) .conflicts_with("log") .help("Quiet mode: suppress normal output"), ) .arg( Arg::with_name("log") .long("log") .takes_value(false) .conflicts_with("quiet") .help("Log mode: stream the validator log"), ) .arg( Arg::with_name("faucet_port") .long("faucet-port") .value_name("PORT") .takes_value(true) .default_value(&default_faucet_port) .validator(solana_validator::port_validator) .help("Enable the faucet on this port"), ) .arg( Arg::with_name("rpc_port") .long("rpc-port") .value_name("PORT") .takes_value(true) .default_value(&default_rpc_port) .validator(solana_validator::port_validator) .help("Enable JSON RPC on this port, and the next port for the RPC websocket"), ) .arg( Arg::with_name("rpc_pubsub_enable_vote_subscription") .long("rpc-pubsub-enable-vote-subscription") .takes_value(false) .help("Enable the unstable RPC PubSub `voteSubscribe` subscription"), ) .arg( Arg::with_name("bpf_program") .long("bpf-program") .value_name("ADDRESS_OR_PATH BPF_PROGRAM.SO") .takes_value(true) .number_of_values(2) .multiple(true) .help( "Add a BPF program to the genesis configuration. \ If the ledger already exists then this parameter is silently ignored. \ First argument can be a public key or path to file that can be parsed as a keypair", ), ) .arg( Arg::with_name("account") .long("account") .value_name("ADDRESS FILENAME.JSON") .takes_value(true) .number_of_values(2) .multiple(true) .help( "Load an account from the provided JSON file (see `solana account --help` on how to dump \ an account to file). Files are searched for relatively to CWD and tests/fixtures. \ If the ledger already exists then this parameter is silently ignored", ), ) .arg( Arg::with_name("no_bpf_jit") .long("no-bpf-jit") .takes_value(false) .help("Disable the just-in-time compiler and instead use the interpreter for BPF. Windows always disables JIT."), ) .arg( Arg::with_name("ticks_per_slot") .long("ticks-per-slot") .value_name("TICKS") .validator(is_parsable::<u64>) .takes_value(true) .help("The number of ticks in a slot"), ) .arg( Arg::with_name("slots_per_epoch") .long("slots-per-epoch") .value_name("SLOTS") .validator(|value| { value .parse::<Slot>() .map_err(|err| format!("error parsing '{}': {}", value, err)) .and_then(|slot| { if slot < MINIMUM_SLOTS_PER_EPOCH { Err(format!("value must be >= {}", MINIMUM_SLOTS_PER_EPOCH)) } else { Ok(()) } }) }) .takes_value(true) .help( "Override the number of slots in an epoch. \ If the ledger already exists then this parameter is silently ignored", ), ) .arg( Arg::with_name("gossip_port") .long("gossip-port") .value_name("PORT") .takes_value(true) .help("Gossip port number for the validator"), ) .arg( Arg::with_name("gossip_host") .long("gossip-host") .value_name("HOST") .takes_value(true) .validator(solana_net_utils::is_host) .help( "Gossip DNS name or IP address for the validator to advertise in gossip \ [default: 127.0.0.1]", ), ) .arg( Arg::with_name("dynamic_port_range") .long("dynamic-port-range") .value_name("MIN_PORT-MAX_PORT") .takes_value(true) .validator(solana_validator::port_range_validator) .help( "Range to use for dynamically assigned ports \ [default: 1024-65535]", ), ) .arg( Arg::with_name("bind_address") .long("bind-address") .value_name("HOST") .takes_value(true) .validator(solana_net_utils::is_host) .default_value("0.0.0.0") .help("IP address to bind the validator ports [default: 0.0.0.0]"), ) .arg( Arg::with_name("clone_account") .long("clone") .short("c") .value_name("ADDRESS") .takes_value(true) .validator(is_pubkey_or_keypair) .multiple(true) .requires("json_rpc_url") .help( "Copy an account from the cluster referenced by the --url argument the \ genesis configuration. \ If the ledger already exists then this parameter is silently ignored", ), ) .arg( Arg::with_name("warp_slot") .required(false) .long("warp-slot") .short("w") .takes_value(true) .value_name("WARP_SLOT") .validator(is_slot) .min_values(0) .max_values(1) .help( "Warp the ledger to WARP_SLOT after starting the validator. \ If no slot is provided then the current slot of the cluster \ referenced by the --url argument will be used", ), ) .arg( Arg::with_name("limit_ledger_size") .long("limit-ledger-size") .value_name("SHRED_COUNT") .takes_value(true) .default_value(default_limit_ledger_size.as_str()) .help("Keep this amount of shreds in root slots."), ) .arg( Arg::with_name("faucet_sol") .long("faucet-sol") .takes_value(true) .value_name("SOL") .default_value(default_faucet_sol.as_str()) .help( "Give the faucet address this much SOL in genesis. \ If the ledger already exists then this parameter is silently ignored", ), ) .arg( Arg::with_name("accountsdb_plugin_config") .long("accountsdb-plugin-config") .value_name("FILE") .takes_value(true) .multiple(true) .hidden(true) .help("Specify the configuration file for the AccountsDb plugin."), ) .arg( Arg::with_name("no_accounts_db_caching") .long("no-accounts-db-caching") .help("Disables accounts caching"), ) .arg( Arg::with_name("deactivate_feature") .long("deactivate-feature") .takes_value(true) .value_name("FEATURE_PUBKEY") .validator(is_pubkey) .multiple(true) .help("deactivate this feature in genesis.") ) .get_matches(); let output = if matches.is_present("quiet") { Output::None } else if matches.is_present("log") { Output::Log } else { Output::Dashboard }; let ledger_path = value_t_or_exit!(matches, "ledger_path", PathBuf); let reset_ledger = matches.is_present("reset"); if !ledger_path.exists() { fs::create_dir(&ledger_path).unwrap_or_else(|err| { println!( "Error: Unable to create directory {}: {}", ledger_path.display(), err ); exit(1); }); } let mut ledger_lock = ledger_lockfile(&ledger_path); let _ledger_write_guard = lock_ledger(&ledger_path, &mut ledger_lock); if reset_ledger { remove_directory_contents(&ledger_path).unwrap_or_else(|err| { println!("Error: Unable to remove {}: {}", ledger_path.display(), err); exit(1); }) } solana_runtime::snapshot_utils::remove_tmp_snapshot_archives(&ledger_path); let validator_log_symlink = ledger_path.join("validator.log"); let logfile = if output != Output::Log { let validator_log_with_timestamp = format!( "validator-{}.log", SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_millis() ); let _ = fs::remove_file(&validator_log_symlink); symlink::symlink_file(&validator_log_with_timestamp, &validator_log_symlink).unwrap(); Some( ledger_path .join(validator_log_with_timestamp) .into_os_string() .into_string() .unwrap(), ) } else { None }; let _logger_thread = redirect_stderr_to_file(logfile); info!("{} {}", crate_name!(), solana_version::version!()); info!("Starting validator with: {:#?}", std::env::args_os()); solana_core::validator::report_target_features(); // TODO: Ideally test-validator should *only* allow private addresses. let socket_addr_space = SocketAddrSpace::new(/*allow_private_addr=*/ true); let cli_config = if let Some(config_file) = matches.value_of("config_file") { solana_cli_config::Config::load(config_file).unwrap_or_default() } else { solana_cli_config::Config::default() }; let cluster_rpc_client = value_t!(matches, "json_rpc_url", String) .map(normalize_to_url_if_moniker) .map(RpcClient::new); let (mint_address, random_mint) = pubkey_of(&matches, "mint_address") .map(|pk| (pk, false)) .unwrap_or_else(|| { read_keypair_file(&cli_config.keypair_path) .map(|kp| (kp.pubkey(), false)) .unwrap_or_else(|_| (Keypair::new().pubkey(), true)) }); let rpc_port = value_t_or_exit!(matches, "rpc_port", u16); let enable_vote_subscription = matches.is_present("rpc_pubsub_enable_vote_subscription"); let faucet_port = value_t_or_exit!(matches, "faucet_port", u16); let ticks_per_slot = value_t!(matches, "ticks_per_slot", u64).ok(); let slots_per_epoch = value_t!(matches, "slots_per_epoch", Slot).ok(); let gossip_host = matches.value_of("gossip_host").map(|gossip_host| { solana_net_utils::parse_host(gossip_host).unwrap_or_else(|err| { eprintln!("Failed to parse --gossip-host: {}", err); exit(1); }) }); let gossip_port = value_t!(matches, "gossip_port", u16).ok(); let dynamic_port_range = matches.value_of("dynamic_port_range").map(|port_range| { solana_net_utils::parse_port_range(port_range).unwrap_or_else(|| { eprintln!("Failed to parse --dynamic-port-range"); exit(1); }) }); let bind_address = matches.value_of("bind_address").map(|bind_address| { solana_net_utils::parse_host(bind_address).unwrap_or_else(|err| { eprintln!("Failed to parse --bind-address: {}", err); exit(1); }) }); let faucet_addr = Some(SocketAddr::new( IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), faucet_port, )); let mut programs_to_load = vec![]; if let Some(values) = matches.values_of("bpf_program") { let values: Vec<&str> = values.collect::<Vec<_>>(); for address_program in values.chunks(2) { match address_program { [address, program] => { let address = address .parse::<Pubkey>() .or_else(|_| read_keypair_file(address).map(|keypair| keypair.pubkey())) .unwrap_or_else(|err| { println!("Error: invalid address {}: {}", address, err); exit(1); }); let program_path = PathBuf::from(program); if !program_path.exists() { println!( "Error: program file does not exist: {}", program_path.display() ); exit(1); } programs_to_load.push(ProgramInfo { program_id: address, loader: solana_sdk::bpf_loader::id(), program_path, }); } _ => unreachable!(), } } } let mut accounts_to_load = vec![]; if let Some(values) = matches.values_of("account") { let values: Vec<&str> = values.collect::<Vec<_>>(); for address_filename in values.chunks(2) { match address_filename { [address, filename] => { let address = address.parse::<Pubkey>().unwrap_or_else(|err| { println!("Error: invalid address {}: {}", address, err); exit(1); }); accounts_to_load.push(AccountInfo { address, filename }); } _ => unreachable!(), } } } let accounts_to_clone: HashSet<_> = pubkeys_of(&matches, "clone_account") .map(|v| v.into_iter().collect()) .unwrap_or_default(); let warp_slot = if matches.is_present("warp_slot") { Some(match matches.value_of("warp_slot") { Some(_) => value_t_or_exit!(matches, "warp_slot", Slot), None => { cluster_rpc_client.as_ref().unwrap_or_else(|_| { println!("The --url argument must be provided if --warp-slot/-w is used without an explicit slot"); exit(1); }).get_slot() .unwrap_or_else(|err| { println!("Unable to get current cluster slot: {}", err); exit(1); }) } }) } else { None }; let faucet_lamports = sol_to_lamports(value_of(&matches, "faucet_sol").unwrap()); let faucet_keypair_file = ledger_path.join("faucet-keypair.json"); if !faucet_keypair_file.exists() { write_keypair_file(&Keypair::new(), faucet_keypair_file.to_str().unwrap()).unwrap_or_else( |err| { println!( "Error: Failed to write {}: {}", faucet_keypair_file.display(), err ); exit(1); }, ); } let faucet_keypair = read_keypair_file(faucet_keypair_file.to_str().unwrap()).unwrap_or_else(|err| { println!( "Error: Failed to read {}: {}", faucet_keypair_file.display(), err ); exit(1); }); let faucet_pubkey = faucet_keypair.pubkey(); if let Some(faucet_addr) = &faucet_addr { let (sender, receiver) = unbounded(); run_local_faucet_with_port(faucet_keypair, sender, None, faucet_addr.port()); let _ = receiver.recv().expect("run faucet").unwrap_or_else(|err| { println!("Error: failed to start faucet: {}", err); exit(1); }); } let features_to_deactivate = pubkeys_of(&matches, "deactivate_feature").unwrap_or_default(); if TestValidatorGenesis::ledger_exists(&ledger_path) { for (name, long) in &[ ("bpf_program", "--bpf-program"), ("clone_account", "--clone"), ("account", "--account"), ("mint_address", "--mint"), ("ticks_per_slot", "--ticks-per-slot"), ("slots_per_epoch", "--slots-per-epoch"), ("faucet_sol", "--faucet-sol"), ("deactivate_feature", "--deactivate-feature"), ] { if matches.is_present(name) { println!("{} argument ignored, ledger already exists", long); } } } else if random_mint { println_name_value( "\nNotice!", "No wallet available. `solana airdrop` localnet SOL after creating one\n", ); } let mut genesis = TestValidatorGenesis::default(); genesis.max_ledger_shreds = value_of(&matches, "limit_ledger_size"); genesis.max_genesis_archive_unpacked_size = Some(u64::MAX); genesis.accounts_db_caching_enabled = !matches.is_present("no_accounts_db_caching"); let tower_storage = Arc::new(FileTowerStorage::new(ledger_path.clone())); let admin_service_cluster_info = Arc::new(RwLock::new(None)); admin_rpc_service::run( &ledger_path, admin_rpc_service::AdminRpcRequestMetadata { rpc_addr: Some(SocketAddr::new( IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), rpc_port, )), start_progress: genesis.start_progress.clone(), start_time: std::time::SystemTime::now(), validator_exit: genesis.validator_exit.clone(), authorized_voter_keypairs: genesis.authorized_voter_keypairs.clone(), cluster_info: admin_service_cluster_info.clone(), tower_storage: tower_storage.clone(), }, ); let dashboard = if output == Output::Dashboard { Some( Dashboard::new( &ledger_path, Some(&validator_log_symlink), Some(&mut genesis.validator_exit.write().unwrap()), ) .unwrap(), ) } else { None }; genesis .ledger_path(&ledger_path) .tower_storage(tower_storage) .add_account( faucet_pubkey, AccountSharedData::new(faucet_lamports, 0, &system_program::id()), ) .rpc_config(JsonRpcConfig { enable_rpc_transaction_history: true, enable_cpi_and_log_storage: true, faucet_addr, ..JsonRpcConfig::default_for_test() }) .pubsub_config(PubSubConfig { enable_vote_subscription, ..PubSubConfig::default() }) .bpf_jit(!matches.is_present("no_bpf_jit")) .rpc_port(rpc_port) .add_programs_with_path(&programs_to_load) .add_accounts_from_json_files(&accounts_to_load) .deactivate_features(&features_to_deactivate); if !accounts_to_clone.is_empty() { genesis.clone_accounts( accounts_to_clone, cluster_rpc_client .as_ref() .expect("bug: --url argument missing?"), ); } if let Some(warp_slot) = warp_slot { genesis.warp_slot(warp_slot); } if let Some(ticks_per_slot) = ticks_per_slot { genesis.ticks_per_slot(ticks_per_slot); } if let Some(slots_per_epoch) = slots_per_epoch { genesis.epoch_schedule(EpochSchedule::custom( slots_per_epoch, slots_per_epoch, /* enable_warmup_epochs = */ false, )); genesis.rent = Rent::with_slots_per_epoch(slots_per_epoch); } if let Some(gossip_host) = gossip_host { genesis.gossip_host(gossip_host); } if let Some(gossip_port) = gossip_port { genesis.gossip_port(gossip_port); } if let Some(dynamic_port_range) = dynamic_port_range { genesis.port_range(dynamic_port_range); } if let Some(bind_address) = bind_address { genesis.bind_ip_addr(bind_address); } if matches.is_present("accountsdb_plugin_config") { genesis.accountsdb_plugin_config_files = Some( values_t_or_exit!(matches, "accountsdb_plugin_config", String) .into_iter() .map(PathBuf::from) .collect(), ); } match genesis.start_with_mint_address(mint_address, socket_addr_space) { Ok(test_validator) => {
test_validator.join(); } Err(err) => { drop(dashboard); println!("Error: failed to start validator: {}", err); exit(1); } } } fn remove_directory_contents(ledger_path: &Path) -> Result<(), io::Error> { for entry in fs::read_dir(&ledger_path)? { let entry = entry?; if entry.metadata()?.is_dir() { fs::remove_dir_all(&entry.path())? } else { fs::remove_file(&entry.path())? } } Ok(()) }
*admin_service_cluster_info.write().unwrap() = Some(test_validator.cluster_info()); if let Some(dashboard) = dashboard { dashboard.run(Duration::from_millis(250)); }
main.go
// Copyright © 2018 Banzai Cloud // // 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 main import ( "log" "os" database "github.com/banzaicloud/bank-vaults/pkg/sdk/db" "github.com/banzaicloud/bank-vaults/pkg/sdk/vault" "github.com/hashicorp/vault/api" "github.com/sirupsen/logrus" logrusadapter "logur.dev/adapter/logrus" ) func vaultExample() { vaultPath := "kubernetes" if path := os.Getenv("VAULT_PATH"); path != "" { vaultPath = path } config := api.DefaultConfig() if config.Error != nil { log.Fatal(config.Error) } client, err := vault.NewClientFromConfig( config, vault.ClientAuthPath(vaultPath), vault.ClientLogger(logrusadapter.New(logrus.New())), ) if err != nil { log.Fatal(err) } log.Println("Created Vault client") secret, err := client.RawClient().Logical().List("secret/metadata/accounts") if err != nil { log.Fatal(err) } if secret != nil { for _, v := range secret.Data { log.Printf("-> %+v", v) for _, v := range v.([]interface{}) { log.Printf(" -> %+v", v) } } log.Println("Finished reading Vault") } else { log.Fatal("Found no data in vault") } } func g
) { secretSource, err := database.DynamicSecretDataSource("mysql", "my-role@tcp(127.0.0.1:3306)/sparky?charset=utf8&parseTime=True&loc=Local") if err != nil { log.Fatal(err) } log.Printf("use this with GORM:\ndb, err := gorm.Open(\"mysql\", \"%s\")", secretSource) } // REQUIRED to start a Vault dev server with: // vault server -dev & func main() { os.Setenv("VAULT_ADDR", "https://vault.default:8200") os.Setenv("VAULT_SKIP_VERIFY", "true") vaultExample() }
ormExample(
AgilityImage.tsx
import * as React from "react" import { GatsbyImage, getImageData, getLowResolutionImageURL, GatsbyImageProps, IGetImageDataArgs, ImageFormat } from "gatsby-plugin-image" import { FunctionComponent } from "react" function
({ baseUrl, width, height, format, options }) { return `${baseUrl}?w=${width}&h=${height}` } const getAgilityImageData = ({ image, width, height, layout, backgroundColor, breakpoints, formats, aspectRatio, options }) => { return getImageData({ baseUrl: image.url, sourceWidth: image.width, sourceHeight: image.height, width, height, layout, backgroundColor, breakpoints, formats, aspectRatio, options, urlBuilder, pluginName: "gatsby-agility-image", // TODO: when we support auto-format/content negotiation, pass this as the formats array //formats: ["auto"], placeholderURL: `${image.url}?w=${20}&q=60`, }) } export interface AgilityImageObj { url: string, label:string | null, height: number, width: number } export interface AgilityImageProps //This is the type for your image data function extends IGetImageDataArgs, // We omit "image" because that's the prop that we generate, Omit<GatsbyImageProps, "image"> { image: AgilityImageObj } export const AgilityImage: FunctionComponent<AgilityImageProps> = ({ image, width, height, layout, backgroundColor, aspectRatio, options, formats, breakpoints, ... props }) => { const imageData = getAgilityImageData({ image, width, height, layout, backgroundColor, formats, breakpoints, aspectRatio, options }) const alt = image.label || props.alt || "" return <GatsbyImage image={imageData} alt={alt} {...props} /> } module.exports = { AgilityImage }
urlBuilder
datagen.py
'''Load image/labels/boxes from an annotation file. The list file is like: img.jpg width height xmin ymin xmax ymax label xmin ymin xmax ymax label ... ''' import random import numpy as np import json import os # from PIL import Image, ImageDraw, ImageFile # ImageFile.LOAD_TRUNCATED_IMAGES = True import cv2 import torch import torch.utils.data as data import torchvision.transforms as transforms from encoder import DataEncoder class jsonDataset(data.Dataset): def __init__(self, path, classes, transform, input_image_size, num_crops, fpn_level, is_norm_reg_target, radius, view_image=False, min_cols=1, min_rows=1): ''' Args: root: (str) ditectory to images. list_file: (str) path to index file. train: (boolean) train or test. transform: ([transforms]) image transforms. input_size: (int) image shorter side size. max_size: (int) maximum image longer side size. ''' self.path = path self.classes = classes self.transform = transform self.input_size = input_image_size self.num_crops = num_crops self.view_img = view_image self.fpn_level = fpn_level self.is_norm_reg_target = is_norm_reg_target self.radius = radius self.fnames = list() self.offsets = list() self.boxes = list() self.labels = list() self.num_classes = len(self.classes) self.label_map = dict() self.class_idx_map = dict() # 0 is background class for idx in range(0, self.num_classes): self.label_map[self.classes[idx]] = idx+1 # 0 is background self.class_idx_map[idx+1] = self.classes[idx] self.data_encoder = DataEncoder(image_size=self.input_size, num_classes=self.num_classes + 1, fpn_level=self.fpn_level, is_norm_reg_target=self.is_norm_reg_target) fp_read = open(self.path, 'r') gt_dict = json.load(fp_read) all_boxes = list() all_labels = list() all_img_path = list() # read gt files for gt_key in gt_dict: gt_data = gt_dict[gt_key][0] box = list() label = list() num_boxes = len(gt_data['labels']) img = cv2.imread(gt_data['image_path']) img_rows = img.shape[0] img_cols = img.shape[1] for iter_box in range(0, num_boxes): xmin = gt_data['boxes'][iter_box][0] ymin = gt_data['boxes'][iter_box][1] xmax = gt_data['boxes'][iter_box][2] ymax = gt_data['boxes'][iter_box][3] rows = ymax - ymin cols = xmax - xmin if xmin < 0 or ymin < 0: print('negative coordinate: [xmin: ' + str(xmin) + ', ymin: ' + str(ymin) + ']') print(gt_data['image_path']) continue if xmax > img_cols or ymax > img_rows: print('over maximum size: [xmax: ' + str(xmax) + ', ymax: ' + str(ymax) + ']') print(gt_data['image_path']) continue if cols < min_cols: print('cols is lower than ' + str(min_cols) + ': [' + str(xmin) + ', ' + str(ymin) + ', ' + str(xmax) + ', ' + str(ymax) + '] ' + str(gt_data['image_path'])) continue if rows < min_rows: print('rows is lower than ' + str(min_rows) + ': [' + str(xmin) + ', ' + str(ymin) + ', ' + str(xmax) + ', ' + str(ymax) + '] ' + str(gt_data['image_path'])) continue class_name = gt_data['labels'][iter_box][0] if class_name not in self.label_map: print('weired class name: ' + class_name) print(gt_data['image_path']) continue class_idx = self.label_map[class_name] box.append([float(xmin), float(ymin), float(xmax), float(ymax)]) label.append(int(class_idx)) if len(box) == 0 or len(label) == 0: print('none of object exist in the image: ' + gt_data['image_path']) continue all_boxes.append(box) all_labels.append(label) all_img_path.append(gt_data['image_path']) if len(all_boxes) == len(all_labels) and len(all_boxes) == len(all_img_path): num_images = len(all_img_path) else: print('num. of boxes: ' + str(len(all_boxes))) print('num. of labels: ' + str(len(all_labels))) print('num. of paths: ' + str(len(all_img_path))) raise ValueError('num. of elements are different(all boxes, all_labels, all_img_path)') if num_crops <= 0: for idx in range(0, num_images, 1): self.fnames.append(all_img_path[idx]) self.boxes.append(torch.tensor(all_boxes[idx], dtype=torch.float32)) self.labels.append(torch.tensor(all_labels[idx], dtype=torch.int64)) else: for idx in range(0, num_images, 1): ori_boxes = all_boxes[idx] ori_labels = all_labels[idx] ori_img = cv2.imread(all_img_path[idx]) img_rows = ori_img.shape[0] img_cols = ori_img.shape[1] offsets, crop_boxes, crop_labels = self._do_crop(ori_img_rows=img_rows, ori_img_cols=img_cols, target_img_size=self.input_size, boxes=ori_boxes, labels=ori_labels) num_offsets = len(offsets) for idx_offset in range(0, num_offsets, 1): self.fnames.append(all_img_path[idx]) self.offsets.append(offsets[idx_offset]) self.boxes.append(torch.tensor(crop_boxes[idx_offset], dtype=torch.float32)) self.labels.append(torch.tensor(crop_labels[idx_offset], dtype=torch.int64)) self.num_samples = len(self.fnames) def __getitem__(self, idx): # Load image and boxes. fname = self.fnames[idx] boxes = self.boxes[idx] labels = self.labels[idx] img = cv2.imread(fname) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) if self.num_crops > 0: offset = self.offsets[idx] crop_rect = (int(offset[0]), int(offset[1]), int(offset[0]+self.input_size[1]), int(offset[1]+self.input_size[0])) if offset[0] < 0 or offset[1] < 0: raise ValueError("negative offset!") for box in boxes: if box[0] < 0 or box[1] < 0 or box[2] > self.input_size[1] or box[3] > self.input_size[0]: raise ValueError("negative box coordinate!") img = img[crop_rect[1]:crop_rect[3], crop_rect[0]:crop_rect[2]] bboxes = [bbox.tolist() + [label.item()] for bbox, label in zip(boxes, labels)] augmented = self.transform(image=img, bboxes=bboxes) img = augmented['image'] rows, cols = img.shape[1:] boxes = augmented['bboxes'] boxes = [list(bbox) for bbox in boxes] labels = [bbox.pop() for bbox in boxes] if self.view_img is True: np_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) np_img = np_img.numpy() np_img = np.transpose(np_img, (1, 2, 0)) np_img = np.uint8(np_img * 255) np_img = np.ascontiguousarray(np_img) for idx_box, box in enumerate(boxes): cv2.rectangle(np_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0)) class_idx = labels[idx_box] text_size = cv2.getTextSize(self.class_idx_map[class_idx], cv2.FONT_HERSHEY_PLAIN, 1, 1) cv2.putText(np_img, self.class_idx_map[class_idx], (int(box[0]), int(box[1]) - text_size[1]), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1) cv2.imwrite(os.path.join("crop_test", str(idx)+".jpg"), np_img) boxes = torch.tensor(boxes, dtype=torch.float32) labels = torch.tensor(labels, dtype=torch.int64) return img, boxes, labels, fname def __len__(self): return self.num_samples # def _resize(self, img, boxes): # if isinstance(self.input_size, int) is True: # w = h = self.input_size # elif isinstance(self.input_size, tuple) is True: # h = self.input_size[0] # w = self.input_size[1] # else: # raise ValueError('input size should be int or tuple of ints') # # ws = 1.0 * w / img.shape[1] # hs = 1.0 * h / img.shape[0] # scale = torch.tensor([ws, hs, ws, hs], dtype=torch.float32) # if boxes.numel() == 0: # scaled_box = boxes # else: # scaled_box = scale * boxes # return cv2.resize(img, (w, h)), scaled_box def _do_crop(self, ori_img_rows, ori_img_cols, target_img_size, boxes, labels): num_boxes = len(boxes) num_labels = len(labels) if num_boxes != num_labels: print("error occur: Random crop") rand_indices = [0, 1, 2, 3, 4] np.random.shuffle(rand_indices) output_offsets = [] output_boxes = [] output_labels = [] for box in boxes: # box coordinate from 1. not 0. xmin = box[0] ymin = box[1] xmax = box[2] ymax = box[3] width = (xmax - xmin)+1 height = (ymax - ymin)+1 if width < 0 or height< 0: print("negative width/height") continue for iter_crop in range(0, self.num_crops, 1): rand_idx = rand_indices[iter_crop] margin = np.random.randint(16, 128, size=1) # top-left if rand_idx == 0: offset_x = xmin-1-margin[0] offset_y = ymin-1-margin[0] crop_maxx = offset_x + target_img_size[1] crop_maxy = offset_y + target_img_size[0] if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1: continue if offset_x < 0 or offset_y < 0: continue crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]] in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels) if len(in_boxes) == 0: continue output_offsets.append([offset_x, offset_y]) output_boxes.append(in_boxes) output_labels.append(in_labels) # top-right elif rand_idx == 1: offset_x = xmin - (target_img_size[1] - width)-1+margin[0] offset_y = ymin-1-margin[0] crop_maxx = offset_x + target_img_size[1] crop_maxy = offset_y + target_img_size[0] if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1: continue if offset_x < 0 or offset_y < 0: continue crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]] in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels)
if len(in_boxes) == 0: continue output_offsets.append([offset_x, offset_y]) output_boxes.append(in_boxes) output_labels.append(in_labels) # bottom-left elif rand_idx == 2: offset_x = xmin-1-margin[0] offset_y = ymin - (target_img_size[0] - height)-1+margin[0] crop_maxx = offset_x + target_img_size[1] crop_maxy = offset_y + target_img_size[0] if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1: continue if offset_x < 0 or offset_y < 0: continue crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]] in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels) if len(in_boxes) == 0: continue output_offsets.append([offset_x, offset_y]) output_boxes.append(in_boxes) output_labels.append(in_labels) # bottom-right elif rand_idx == 3: offset_x = xmin - (target_img_size[1] - width)-1+margin[0] offset_y = ymin - (target_img_size[0] - height)-1+margin[0] crop_maxx = offset_x + target_img_size[1] crop_maxy = offset_y + target_img_size[0] if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1: continue if offset_x < 0 or offset_y < 0: continue crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]] in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels) if len(in_boxes) == 0: continue output_offsets.append([offset_x, offset_y]) output_boxes.append(in_boxes) output_labels.append(in_labels) # center elif rand_idx == 4: rand_direction = np.random.randint(-1, 1, size=1) offset_x = (xmin - ((target_img_size[1]-width)/2)-1) + (rand_direction[0] * margin[0]) offset_y = (ymin - ((target_img_size[0]-height)/2)-1) + (rand_direction[0] * margin[0]) crop_maxx = offset_x + target_img_size[1] crop_maxy = offset_y + target_img_size[0] if crop_maxx > ori_img_cols-1 or crop_maxy > ori_img_rows-1: continue if offset_x < 0 or offset_y < 0: continue crop_rect = [offset_x, offset_y, target_img_size[1], target_img_size[0]] in_boxes, in_labels = self._find_boxes_in_crop(crop_rect, boxes, labels) if len(in_boxes) == 0: continue output_offsets.append([offset_x, offset_y]) output_boxes.append(in_boxes) output_labels.append(in_labels) else: print("exceed possible crop num") return output_offsets, output_boxes, output_labels def _find_boxes_in_crop(self, crop_rect, boxes, labels): num_boxes = len(boxes) num_labels = len(labels) if num_boxes != num_labels: print("error occur: Random crop") boxes_in_crop=[] labels_in_crop = [] for idx in range(0, num_boxes, 1): box_in_crop, label, is_contain = self._find_box_in_crop(crop_rect, boxes[idx], labels[idx]) if is_contain is True: boxes_in_crop.append(box_in_crop) labels_in_crop.append(label) return boxes_in_crop, labels_in_crop def _find_box_in_crop(self, rect, box, label): rect_minx = rect[0] rect_miny = rect[1] rect_width = rect[2] rect_height = rect[3] box_minx = box[0] box_miny = box[1] box_maxx = box[2] box_maxy = box[3] box_width = (box_maxx - box_minx)+1 box_height = (box_maxy - box_miny)+1 # occlusion_ratio occlusion_ratio = 0.3 occlusion_width = int(box_width * occlusion_ratio) * -1 occlusion_height = int(box_height * occlusion_ratio) * -1 box_in_crop_minx = box_minx - rect_minx if box_in_crop_minx <= occlusion_width or box_in_crop_minx >= rect_width: box_in_rect = [] return box_in_rect, label, False box_in_crop_miny = box_miny - rect_miny if box_in_crop_miny <= occlusion_height or box_in_crop_miny >= rect_height: box_in_rect = [] return box_in_rect, label, False box_in_crop_maxx = box_maxx - rect_minx if rect_width - box_in_crop_maxx <= occlusion_width or box_in_crop_maxx <= 0: box_in_rect = [] return box_in_rect, label, False box_in_crop_maxy = box_maxy - rect_miny if rect_height - box_in_crop_maxy <= occlusion_height or box_in_crop_maxy <= 0: box_in_rect = [] return box_in_rect, label, False if box_in_crop_minx < 0: box_in_crop_minx = 0 if box_in_crop_miny < 0: box_in_crop_miny = 0 if rect_width - box_in_crop_maxx < 0: box_in_crop_maxx = rect_width-1 if rect_height - box_in_crop_maxy < 0: box_in_crop_maxy = rect_height-1 box_in_rect = [box_in_crop_minx, box_in_crop_miny, box_in_crop_maxx, box_in_crop_maxy] return box_in_rect, label, True def collate_fn(self, batch): imgs = [x[0] for x in batch] boxes = [x[1] for x in batch] labels = [x[2] for x in batch] paths = [x[3] for x in batch] num_imgs = len(imgs) if isinstance(self.input_size, int) is True: inputs = torch.zeros([num_imgs, 3, self.input_size, self.input_size], dtype=torch.float32) elif isinstance(self.input_size, tuple) is True: inputs = torch.zeros([num_imgs, 3, self.input_size[0], self.input_size[1]], dtype=torch.float32) else: raise ValueError('input size should be int or tuple of ints') loc_targets = list() cls_targets = list() center_targets = list() for i in range(num_imgs): im = imgs[i] imh, imw = im.size(1), im.size(2) inputs[i, :, :imh, :imw] = im # Encode data. loc_target, cls_target, center_target = self.data_encoder.encode(boxes[i], labels[i], radius=self.radius) loc_targets.append(loc_target) cls_targets.append(cls_target) center_targets.append(center_target) return inputs, \ torch.stack(loc_targets, dim=0), \ torch.stack(cls_targets, dim=0), \ torch.stack(center_targets, dim=0), \ paths def test(): import torchvision # transform = transforms.Compose([ # transforms.ToTensor(), # transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225)) # ]) # set random seed random.seed(3000) np.random.seed(3000) torch.manual_seed(3000) transform = transforms.Compose([ transforms.ToTensor() ]) classes = 'person|bicycle|car|motorcycle|bus|truck|cat|dog|rider' classes = classes.split('|') dataset = jsonDataset(path='data/voc.json', classes=classes,transform=transform, input_image_size=(256, 512), num_crops=-1, fpn_level=5, is_norm_reg_target=True, radius=0.8, view_image=True, do_aug=True) print(len(dataset)) dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True, num_workers=0, collate_fn=dataset.collate_fn) for idx, (images, loc_targets, cls_targets, center_targets, paths) in enumerate(dataloader): print(loc_targets.shape) print(cls_targets.shape) print(center_targets.shape) pos_ind = cls_targets[:, :, 0] <= 0 print(pos_ind.shape) print(pos_ind.data.long().sum()) if __name__ == '__main__': test()
save.rs
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::join; use rustc_middle::dep_graph::{DepGraph, SerializedDepGraph, WorkProduct, WorkProductId}; use rustc_middle::ty::TyCtxt; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encodable as RustcEncodable; use rustc_session::Session; use std::fs; use super::data::*; use super::dirty_clean; use super::file_format; use super::fs::*; use super::work_product; /// Saves and writes the [`DepGraph`] to the file system. /// /// This function saves both the dep-graph and the query result cache, /// and drops the result cache. /// /// This function should only run after all queries have completed. /// Trying to execute a query afterwards would attempt to read the result cache we just dropped. pub fn save_dep_graph(tcx: TyCtxt<'_>) { debug!("save_dep_graph()"); tcx.dep_graph.with_ignore(|| { let sess = tcx.sess; if sess.opts.incremental.is_none() { return; } // This is going to be deleted in finalize_session_directory, so let's not create it if sess.has_errors_or_delayed_span_bugs() { return; } let query_cache_path = query_cache_path(sess); let dep_graph_path = dep_graph_path(sess); let staging_dep_graph_path = staging_dep_graph_path(sess); sess.time("assert_dep_graph", || crate::assert_dep_graph(tcx)); sess.time("check_dirty_clean", || dirty_clean::check_dirty_clean_annotations(tcx)); if sess.opts.debugging_opts.incremental_info { tcx.dep_graph.print_incremental_info() } join( move || { sess.time("incr_comp_persist_result_cache", || { // Drop the memory map so that we can remove the file and write to it. if let Some(odc) = &tcx.on_disk_cache { odc.drop_serialized_data(tcx); } file_format::save_in(sess, query_cache_path, "query cache", |e| { encode_query_cache(tcx, e) }); }); }, move || { sess.time("incr_comp_persist_dep_graph", || { if let Err(err) = tcx.dep_graph.encode(&tcx.sess.prof) { sess.err(&format!( "failed to write dependency graph to `{}`: {}", staging_dep_graph_path.display(), err )); } if let Err(err) = fs::rename(&staging_dep_graph_path, &dep_graph_path) { sess.err(&format!( "failed to move dependency graph from `{}` to `{}`: {}", staging_dep_graph_path.display(), dep_graph_path.display(), err )); } }); }, ); }) } /// Saves the work product index. pub fn save_work_product_index( sess: &Session, dep_graph: &DepGraph, new_work_products: FxHashMap<WorkProductId, WorkProduct>, ) { if sess.opts.incremental.is_none() { return; } // This is going to be deleted in finalize_session_directory, so let's not create it if sess.has_errors_or_delayed_span_bugs() { return; } debug!("save_work_product_index()"); dep_graph.assert_ignored(); let path = work_products_path(sess); file_format::save_in(sess, path, "work product index", |mut e| { encode_work_product_index(&new_work_products, &mut e); e.finish() }); // We also need to clean out old work-products, as not all of them are // deleted during invalidation. Some object files don't change their // content, they are just not needed anymore. let previous_work_products = dep_graph.previous_work_products(); for (id, wp) in previous_work_products.iter() { if !new_work_products.contains_key(id) { work_product::delete_workproduct_files(sess, wp); debug_assert!(!in_incr_comp_dir_sess(sess, &wp.saved_file).exists()); } } // Check that we did not delete one of the current work-products: debug_assert!({ new_work_products .iter() .map(|(_, wp)| in_incr_comp_dir_sess(sess, &wp.saved_file)) .all(|path| path.exists()) }); } fn encode_work_product_index( work_products: &FxHashMap<WorkProductId, WorkProduct>, encoder: &mut FileEncoder, ) { let serialized_products: Vec<_> = work_products .iter() .map(|(id, work_product)| SerializedWorkProduct { id: *id, work_product: work_product.clone(), }) .collect(); serialized_products.encode(encoder) } fn encode_query_cache(tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResult { tcx.sess.time("incr_comp_serialize_result_cache", || tcx.serialize_query_result_cache(encoder)) } /// Builds the dependency graph. /// /// This function creates the *staging dep-graph*. When the dep-graph is modified by a query /// execution, the new dependency information is not kept in memory but directly /// output to this file. `save_dep_graph` then finalizes the staging dep-graph /// and moves it to the permanent dep-graph path pub fn build_dep_graph( sess: &Session, prev_graph: SerializedDepGraph, prev_work_products: FxHashMap<WorkProductId, WorkProduct>, ) -> Option<DepGraph> { if sess.opts.incremental.is_none() { // No incremental compilation. return None; } // Stream the dep-graph to an alternate file, to avoid overwriting anything in case of errors. let path_buf = staging_dep_graph_path(sess); let mut encoder = match FileEncoder::new(&path_buf) { Ok(encoder) => encoder, Err(err) => { sess.err(&format!( "failed to create dependency graph at `{}`: {}", path_buf.display(), err )); return None; } }; file_format::write_file_header(&mut encoder, sess.is_nightly_build());
Some(DepGraph::new( &sess.prof, prev_graph, prev_work_products, encoder, sess.opts.debugging_opts.query_dep_graph, sess.opts.debugging_opts.incremental_info, )) }
// First encode the commandline arguments hash sess.opts.dep_tracking_hash(false).encode(&mut encoder);
Anchor.ts
import { styled, type Component, type Props } from '@nectar-ui/core' import { StyledText } from '@nectar-ui/text' /** Styled Components */ export const Anchor = styled(StyledText, { transition: '.2s', compoundVariants: [ { color: 'primary', css: { '&:hover': {
} } }, { color: 'secondary', css: { '&:hover': { color: '$secondaryHover' } } }, { color: 'contrast', css: { '&:hover': { color: '$contrastHover' } } }, { color: 'success', css: { '&:hover': { color: '$successHover' } } }, { color: 'info', css: { '&:hover': { color: '$infoHover' } } }, { color: 'danger', css: { '&:hover': { color: '$dangerHover' } } }, { color: 'warning', css: { '&:hover': { color: '$warningHover' } } } ], defaultVariants: { color: 'primary' } }) /** Types */ export type AnchorProps = Props<typeof Anchor> export type AnchorComponent = Component<AnchorProps>
color: '$primaryHover'
alerts.py
from corehq.apps.products.models import SQLProduct from custom.ewsghana.alerts import COMPLETE_REPORT, \ STOCKOUTS_MESSAGE, LOW_SUPPLY_MESSAGE, OVERSTOCKED_MESSAGE, RECEIPT_MESSAGE from custom.ewsghana.utils import ProductsReportHelper from django.utils.translation import ugettext as _ class SOHAlerts(object): def __init__(self, user, sql_location): self.user = user self.sql_location = sql_location def get_alerts(self, transactions): report_helper = ProductsReportHelper(self.sql_location, transactions) products_below = report_helper.low_supply() stockouts = report_helper.stockouts() overstocked = report_helper.overstocked() receipts = report_helper.receipts() missings = report_helper.missing_products() message = "" super_message = "" if missings: products_codes_str = ' '.join(sorted([missing.code for missing in missings])) message += " still missing %s. " % products_codes_str if stockouts: products_codes_str = ' '.join([stockout.sql_product.code for stockout in stockouts]) products_names_str = ' '.join([stockout.sql_product.name for stockout in stockouts]) message += " " + STOCKOUTS_MESSAGE % {'products': products_codes_str} super_message = _("stockouts %s; ") % products_names_str if products_below: products_codes_str = ' '.join([product.sql_product.code for product in products_below]) products_names_str = ' '.join([product.sql_product.name for product in products_below]) message += " " + LOW_SUPPLY_MESSAGE % {'low_supply': products_codes_str} super_message += _("below reorder level %s; ") % products_names_str if stockouts or products_below: reorders = [ '%s %s' % (code, amount) for (code, amount) in report_helper.reorders() if amount ] if reorders: message += " Please order %s." % ' '.join(reorders)
if overstocked: if not message: products_codes_str = ' '.join([overstock.sql_product.code for overstock in overstocked]) message += " " + OVERSTOCKED_MESSAGE % {'username': self.user.full_name, 'overstocked': products_codes_str} products_names_str = ' '.join([overstock.sql_product.name for overstock in overstocked]) super_message += _("overstocked %s; ") % products_names_str if not message: if not receipts: message = COMPLETE_REPORT % self.user.full_name else: products_str = ' '.join( [ "%s %s" % (SQLProduct.objects.get(product_id=receipt.product_id).code, receipt.quantity) for receipt in receipts ] ) message = RECEIPT_MESSAGE % {'username': self.user.full_name, 'received': products_str} else: message = (_('Dear %s,') % self.user.full_name) + message if super_message: stripped_message = super_message.strip().strip(';') super_message = _('Dear %(name)s, %(location)s is experiencing the following problems: ') + stripped_message return message.rstrip(), super_message
cluster_cache_fake.go
/* Copyright 2020 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 remote import ( "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" "sigs.k8s.io/controller-runtime/pkg/client" ) // NewTestClusterCacheTracker creates a new fake ClusterCacheTracker that can be used by unit tests with fake client. func
(log logr.Logger, cl client.Client, scheme *runtime.Scheme, objKey client.ObjectKey, watchObjects ...string) *ClusterCacheTracker { testCacheTracker := &ClusterCacheTracker{ log: log, client: cl, scheme: scheme, clusterAccessors: make(map[client.ObjectKey]*clusterAccessor), } delegatingClient, err := client.NewDelegatingClient(client.NewDelegatingClientInput{ CacheReader: cl, Client: cl, }) if err != nil { panic(err) } testCacheTracker.clusterAccessors[objKey] = &clusterAccessor{ cache: nil, delegatingClient: delegatingClient, watches: sets.NewString(watchObjects...), } return testCacheTracker }
NewTestClusterCacheTracker
cmd.go
/* Copyright (c) 2021 Red Hat, 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 operatorrole import ( "fmt" "os" "strings" "time" "github.com/briandowns/spinner" "github.com/spf13/cobra" errors "github.com/zgalor/weberr" "github.com/openshift/rosa/pkg/aws" "github.com/openshift/rosa/pkg/interactive" "github.com/openshift/rosa/pkg/interactive/confirm" "github.com/openshift/rosa/pkg/logging" "github.com/openshift/rosa/pkg/ocm" rprtr "github.com/openshift/rosa/pkg/reporter" ) var args struct { clusterKey string } var Cmd = &cobra.Command{ Use: "operator-roles", Aliases: []string{"operatorrole"}, Short: "Delete Operator Roles", Long: "Cleans up operator roles of deleted STS cluster.", Example: ` # Delete Operator roles for cluster named "mycluster" rosa delete operator-roles --cluster=mycluster`, Run: run, } func init()
func run(cmd *cobra.Command, argv []string) { reporter := rprtr.CreateReporterOrExit() logger := logging.NewLogger() if len(argv) == 1 && !cmd.Flag("cluster").Changed { args.clusterKey = argv[0] } mode, err := aws.GetMode() if err != nil { reporter.Errorf("%s", err) os.Exit(1) } // Check that the cluster key (name, identifier or external identifier) given by the user // is reasonably safe so that there is no risk of SQL injection: clusterKey := args.clusterKey if !ocm.IsValidClusterKey(clusterKey) { reporter.Errorf( "Cluster name, identifier or external identifier '%s' isn't valid: it "+ "must contain only letters, digits, dashes and underscores", clusterKey, ) os.Exit(1) } // Determine if interactive mode is needed if !interactive.Enabled() && !cmd.Flags().Changed("mode") { interactive.Enable() } // Create the AWS client: awsClient, err := aws.NewClient(). Logger(logger). Build() if err != nil { reporter.Errorf("Failed to create AWS client: %v", err) os.Exit(1) } creator, err := awsClient.GetCreator() if err != nil { reporter.Errorf("Failed to get IAM credentials: %s", err) os.Exit(1) } // Create the client for the OCM API: ocmClient, err := ocm.NewClient(). Logger(logger). Build() if err != nil { reporter.Errorf("Failed to create OCM connection: %v", err) os.Exit(1) } defer func() { err = ocmClient.Close() if err != nil { reporter.Errorf("Failed to close OCM connection: %v", err) } }() reporter.Debugf("Loading cluster '%s'", clusterKey) sub, err := ocmClient.GetClusterUsingSubscription(clusterKey, creator) if err != nil { if errors.GetType(err) == errors.Conflict { reporter.Errorf("More than one cluster found with the same name '%s'. Please "+ "use cluster ID instead", clusterKey) os.Exit(1) } reporter.Errorf("Error validating cluster '%s': %v", clusterKey, err) os.Exit(1) } clusterID := clusterKey if sub != nil { clusterID = sub.ClusterID() } c, err := ocmClient.GetClusterByID(clusterID, creator) if err != nil { if errors.GetType(err) != errors.NotFound { reporter.Errorf("Error validating cluster '%s': %v", clusterKey, err) os.Exit(1) } } if c != nil && c.ID() != "" { reporter.Errorf("Cluster '%s' is in '%s' state. Operator roles can be deleted only for the "+ "uninstalled clusters", c.ID(), c.State()) os.Exit(1) } env, err := ocm.GetEnv() if err != nil { reporter.Errorf("Error getting environment %s", err) os.Exit(1) } if env != "production" { if !confirm.Prompt(true, "You are running delete operation from staging. Please ensure "+ "there are no clusters using these operator roles in the production. Are you sure you want to proceed?") { os.Exit(1) } } if interactive.Enabled() { mode, err = interactive.GetOption(interactive.Input{ Question: "Operator roles deletion mode", Help: cmd.Flags().Lookup("mode").Usage, Default: aws.ModeAuto, Options: aws.Modes, Required: true, }) if err != nil { reporter.Errorf("Expected a valid operator role deletion mode: %s", err) os.Exit(1) } } var spin *spinner.Spinner if reporter.IsTerminal() { spin = spinner.New(spinner.CharSets[9], 100*time.Millisecond) } if spin != nil { reporter.Infof("Fetching operator roles for the cluster: %s", clusterKey) spin.Start() } credRequests, err := ocmClient.GetCredRequests() if err != nil { reporter.Errorf("Error getting operator credential request from OCM %s", err) os.Exit(1) } roles, err := awsClient.GetOperatorRolesFromAccount(sub.ClusterID(), credRequests) if len(roles) == 0 { if spin != nil { spin.Stop() } reporter.Infof("There are no operator roles to delete for the cluster '%s'", clusterKey) return } if spin != nil { spin.Stop() } switch mode { case aws.ModeAuto: ocmClient.LogEvent("ROSADeleteOperatorroleModeAuto", nil) for _, role := range roles { if !confirm.Prompt(true, "Delete the operator roles '%s'?", role) { continue } err = awsClient.DeleteOperatorRole(role) if err != nil { reporter.Errorf("There was an error deleting the Operator Roles: %s", err) continue } } reporter.Infof("Successfully deleted the operator roles") case aws.ModeManual: ocmClient.LogEvent("ROSADeleteOperatorroleModeManual", nil) policyMap, err := awsClient.GetPolicies(roles) if err != nil { reporter.Errorf("There was an error getting the policy: %v", err) os.Exit(1) } commands := buildCommand(roles, policyMap) if reporter.IsTerminal() { reporter.Infof("Run the following commands to delete the Operator roles:\n") } fmt.Println(commands) default: reporter.Errorf("Invalid mode. Allowed values are %s", aws.Modes) os.Exit(1) } } func buildCommand(roleNames []string, policyMap map[string][]string) string { commands := []string{} for _, roleName := range roleNames { policyARN := policyMap[roleName] detachPolicy := "" if len(policyARN) > 0 { detachPolicy = fmt.Sprintf("\taws iam detach-role-policy --role-name %s --policy-arn %s", roleName, policyARN[0]) } deleteRole := fmt.Sprintf("\taws iam delete-role --role-name %s", roleName) commands = append(commands, detachPolicy, deleteRole) } return strings.Join(commands, "\n") }
{ flags := Cmd.Flags() flags.StringVarP( &args.clusterKey, "cluster", "c", "", "ID or Name of the cluster (deleted/archived) to delete the operator roles from (required).", ) aws.AddModeFlag(Cmd) confirm.AddFlag(flags) }
feed_query_builder.go
// Copyright 2021 Frédéric Guillot. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package storage // import "miniflux.app/storage" import ( "database/sql" "fmt" "strings" "miniflux.app/model" "miniflux.app/timezone" ) // FeedQueryBuilder builds a SQL query to fetch feeds. type FeedQueryBuilder struct { store *Storage args []interface{} conditions []string order string direction string limit int offset int withCounters bool counterJoinFeeds bool counterArgs []interface{} counterConditions []string } // NewFeedQueryBuilder returns a new FeedQueryBuilder. func NewFeedQueryBuilder(store *Storage, userID int64) *FeedQueryBuilder { return &FeedQueryBuilder{ store: store, args: []interface{}{userID}, conditions: []string{"f.user_id = $1"}, counterArgs: []interface{}{userID, model.EntryStatusRead, model.EntryStatusUnread}, counterConditions: []string{"e.user_id = $1", "e.status IN ($2, $3)"}, } } // WithCategoryID filter by category ID. func (f *FeedQueryBuilder) WithCategoryID(categoryID int64) *FeedQueryBuilder { if categoryID > 0 { f.conditions = append(f.conditions, fmt.Sprintf("f.category_id = $%d", len(f.args)+1)) f.args = append(f.args, categoryID) f.counterConditions = append(f.counterConditions, fmt.Sprintf("f.category_id = $%d", len(f.counterArgs)+1)) f.counterArgs = append(f.counterArgs, categoryID) f.counterJoinFeeds = true } return f } // WithFeedID filter by feed ID. func (f *FeedQueryBuilder) WithFeedID(feedID int64) *FeedQueryBuilder { if feedID > 0 { f.conditions = append(f.conditions, fmt.Sprintf("f.id = $%d", len(f.args)+1)) f.args = append(f.args, feedID) } return f } // WithCounters let the builder return feeds with counters of statuses of entries. func (f *FeedQueryBuilder) WithCounters() *FeedQueryBuilder { f.withCounters = true return f } // WithOrder set the sorting order. func (f *FeedQueryBuilder) WithOrder(order string) *FeedQueryBuilder { f.order = order return f } // WithDirection set the sorting direction. func (f *FeedQueryBuilder) WithDirection(direction string) *FeedQueryBuilder { f.direction = direction return f } // WithLimit set the limit. func (f *FeedQueryBuilder) WithLimit(limit int) *FeedQueryBuilder { f.limit = limit return f } // WithOffset set the offset. func (f *FeedQueryBuilder) WithOffset(offset int) *FeedQueryBuilder { f.offset = offset return f } // WithoutNSFW excludes NSFW contents. func (f *FeedQueryBuilder) WithoutNSFW() *FeedQueryBuilder { f.conditions = append(f.conditions, "f.nsfw='f'") return f } func (f *FeedQueryBuilder) buildCondition() string { return strings.Join(f.conditions, " AND ") } func (f *FeedQueryBuilder) buildCounterCondition() string { return strings.Join(f.counterConditions, " AND ") } func (f *FeedQueryBuilder) buildSorting() string { var parts []string if f.order != "" { parts = append(parts, fmt.Sprintf(`ORDER BY %s`, f.order)) } if f.direction != "" { parts = append(parts, f.direction) } if len(parts) > 0 { parts = append(parts, ", lower(f.title) ASC") } if f.limit > 0 { parts = append(parts, fmt.Sprintf(`LIMIT %d`, f.limit)) } if f.offset > 0 { parts = append(parts, fmt.Sprintf(`OFFSET %d`, f.offset)) } return strings.Join(parts, " ") } // GetFeed returns a single feed that match the condition. func (f *FeedQueryBuilder) GetFeed() (*model.Feed, error) { f.limit = 1 feeds, err := f.GetFeeds() if err != nil { return nil, err } if len(feeds) != 1 { return nil, nil } return feeds[0], nil } // GetFeeds returns a list of feeds that match the condition. func (f *FeedQueryBuilder) GetFeeds() (model.Feeds, error) { var query = ` SELECT f.id, f.feed_url, f.site_url, f.title, f.etag_header, f.last_modified_header, f.user_id, f.checked_at at time zone u.timezone, f.parsing_error_count, f.parsing_error_msg, f.scraper_rules, f.rewrite_rules, f.blocklist_rules, f.keeplist_rules, f.crawler, f.user_agent, f.cookie, f.username, f.password, f.ignore_http_cache, f.allow_self_signed_certificates, f.fetch_via_proxy, f.disabled, f.view, f.nsfw, f.cache_media, f.category_id, c.title as category_title, fi.icon_id, u.timezone FROM feeds f LEFT JOIN categories c ON c.id=f.category_id LEFT JOIN feed_icons fi ON fi.feed_id=f.id LEFT JOIN users u ON u.id=f.user_id WHERE %s %s ` query = fmt.Sprintf(query, f.buildCondition(), f.buildSorting()) rows, err := f.store.db.Query(query, f.args...) if err != nil { return nil, fmt.Errorf(`store: unable to fetch feeds: %w`, err) } defer rows.Close() readCounters, unreadCounters, err := f.fetchFeedCounter() if err != nil { return nil, err } feeds := make(model.Feeds, 0) for rows.Next() { var feed model.Feed var iconID sql.NullInt64 var tz string feed.Category = &model.Category{} err := rows.Scan( &feed.ID, &feed.FeedURL, &feed.SiteURL, &feed.Title, &feed.EtagHeader, &feed.LastModifiedHeader, &feed.UserID, &feed.CheckedAt, &feed.ParsingErrorCount, &feed.ParsingErrorMsg,
&feed.BlocklistRules, &feed.KeeplistRules, &feed.Crawler, &feed.UserAgent, &feed.Cookie, &feed.Username, &feed.Password, &feed.IgnoreHTTPCache, &feed.AllowSelfSignedCertificates, &feed.FetchViaProxy, &feed.Disabled, &feed.View, &feed.NSFW, &feed.CacheMedia, &feed.Category.ID, &feed.Category.Title, &iconID, &tz, ) if err != nil { return nil, fmt.Errorf(`store: unable to fetch feeds row: %w`, err) } if iconID.Valid { feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: iconID.Int64} } else { feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: 0} } if readCounters != nil { if count, found := readCounters[feed.ID]; found { feed.ReadCount = count } } if unreadCounters != nil { if count, found := unreadCounters[feed.ID]; found { feed.UnreadCount = count } } feed.CheckedAt = timezone.Convert(tz, feed.CheckedAt) feed.Category.UserID = feed.UserID feeds = append(feeds, &feed) } return feeds, nil } func (f *FeedQueryBuilder) fetchFeedCounter() (unreadCounters map[int64]int, readCounters map[int64]int, err error) { if !f.withCounters { return nil, nil, nil } query := ` SELECT e.feed_id, e.status, count(*) FROM entries e %s WHERE %s GROUP BY e.feed_id, e.status ` join := "" if f.counterJoinFeeds { join = "LEFT JOIN feeds f ON f.id=e.feed_id" } query = fmt.Sprintf(query, join, f.buildCounterCondition()) rows, err := f.store.db.Query(query, f.counterArgs...) if err != nil { return nil, nil, fmt.Errorf(`store: unable to fetch feed counts: %w`, err) } defer rows.Close() readCounters = make(map[int64]int) unreadCounters = make(map[int64]int) for rows.Next() { var feedID int64 var status string var count int if err := rows.Scan(&feedID, &status, &count); err != nil { return nil, nil, fmt.Errorf(`store: unable to fetch feed counter row: %w`, err) } if status == model.EntryStatusRead { readCounters[feedID] = count } else if status == model.EntryStatusUnread { unreadCounters[feedID] = count } } return readCounters, unreadCounters, nil }
&feed.ScraperRules, &feed.RewriteRules,
service.ts
/// <reference types="node" /> import express, { Request, Response, Next } from "express"; import routers from "./routers"; import compression from "compression"; import timeout from "connect-timeout"; import path from "path"; import dotenv from "dotenv"; import morgan from "morgan"; import winston from "winston"; import expressWinston from "express-winston"; import helmet from "helmet"; import cors from "cors"; import ErrorHandler from "api-error-handler"; import fs from "fs"; // tslint:disable-next-line:no-var-requires const socketIoInit = require('socket.io'); const app = express(); // tslint:disable-next-line:no-var-requires const server = require('http').createServer(app); const io = socketIoInit(server, { handlePreflightRequest: (req:Request, res:Response) => { res.writeHead(200, { "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Allow-Origin": req.headers.origin, "Access-Control-Allow-Credentials": true }); res.end(); }, cors: { origin: '*', methods: ["GET", "POST"], credentials: true } }); /** * Configuration */ dotenv.config({ path: path.join(__dirname, './../.env') }); app.disable('x-powered-by'); app.set('json spaces', 40); app.use(timeout('60s')); app.use(cors()); app.use(helmet.dnsPrefetchControl()); app.use(helmet.expectCt()); app.use(helmet.frameguard()); app.use(helmet.hidePoweredBy()); app.use(helmet.hsts()); app.use(helmet.ieNoOpen()); app.use(helmet.noSniff()); app.use(helmet.permittedCrossDomainPolicies()); app.use(helmet.referrerPolicy()); app.use(helmet.xssFilter()); app.use(compression()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(ErrorHandler()); /** * Loggers */ app.use(morgan('combined')); app.use(expressWinston.logger({ transports: [ new winston.transports.File({ filename: path.join(__dirname, './../log/error.log'), level: 'error' }), new winston.transports.File({ filename: path.join(__dirname, './../log/combined.log') }) ], format: winston.format.combine( winston.format.colorize(), winston.format.json() ), meta: true, msg: "{{res.statusCode}} HTTP {{req.method}} {{res.responseTime}}ms {{req.url}}", expressFormat: true, colorize: false })); /** * Routers */ app.use('/', routers); /** * Storage */ app.use(express.static(path.join(__dirname, './../public'))); /** * TrackerAnalytics Engine */ app.engine('TrackerAnalytics', (filePath, options, callback) => { fs.readFile(filePath, (err, content) => { if (err) return callback(err);
if (typeof value === 'string') { rendered = rendered.replace(`{{%${key}%}}`, value) } }); rendered = ''+rendered.replace(/ +(?= )/g,''); rendered = rendered.replace(/\s{2,}/g, ' '); return callback(null, rendered) }) }); app.set('views', path.join(__dirname, './../views')); app.set('view engine', 'TrackerAnalytics'); /** * Timeout Error */ app.use((req: Request, _res: Response, next: Next)=> { if (!req.timedout) next() }); export { server, app, io }
let rendered = content.toString(); Object.entries(options).forEach(([key,value]) => {
error.modal.tsx
import React from 'react' export default function
() { return ( <h1> Error modal </h1> ) }
ErrorModal
RFunction.py
from __future__ import division import numpy as np from scipy.ndimage.morphology import binary_erosion, binary_fill_holes def hu_to_grayscale(volume): volume = np.clip(volume, -512, 512) mxmal = np.max(volume) mnval = np.min(volume) im_volume = (volume - mnval) / max(mxval - mnval, 1e-3) im_volume = im_volume return im_volume* 255 def get_mask_lung(vol): vol_im = np.where(vol > 0, 1, 0) shp = vol.shape around_img = np.zeros((shp[0], shp[1], shp[2]), dtype = np.float32) for idx in range(shp[0]): around_lung[idx, :, :] = binary_erosion(vol_im[idx], structure = np.ones((15, 15))).astype(vol_im.dtype) return around_lung def get_mask(segmentation): # initialize ouput to zero shp = segmentation.shape lung = np.zeros((shp[0], shp[1], shp[2]), dtype = np.float32) lung[np.equal(segmentation, 255)] = 255 return lung def get_FOV(around_lung, lung):
def return_axials(vol, seg): vol = vol.get_data() seg = seg.get_data() seg = seg.astype(np.int32) # convert to visual format vol_ims = hu_to_grayscale(vol_ims) lung = get_mask(seg) around_lung = get_mask_lung(vol_ims) FOV = get_FOV(around_lung, lung) around_lung = np.where((FOV - lung) > 0, 1, 0) return vol_ims, lung, around_lung, FOV
FOV = np.where((around_lung + lung) > 0, 1, 0) for idx in range(FOV.shape[0]): FOV[idx, :, :] = binary_fill_holes(FOV[idx, :, :], structure = np.ones((5, 5))).astype(FOV.dtype) return FOV
russianbullet.go
package russianbullet import ( "fmt" "math/rand" "github.com/moul/bolosseum/bots" "github.com/moul/bolosseum/games" ) type RussianbulletGame struct { games.BotsBasedGame } func NewGame() (*RussianbulletGame, error) { game := RussianbulletGame{} game.Bots = make([]bots.Bot, 0) return &game, nil } func (g *RussianbulletGame) CheckArgs(args []string) error { if len(args) < 1 { return fmt.Errorf("You need to specify at least 1 bot") } return nil } func (g *RussianbulletGame) Run(gameID string, steps chan games.GameStep) error { if err := bots.InitTurnBasedBots(g.Bots, g.Name(), gameID); err != nil { return err } // play bulletIndex := rand.Intn(6) // 6 slots in the revolver for i := 0; i <= bulletIndex; i++ { idx := i % len(g.Bots) bot := g.Bots[idx] question := bots.QuestionMessage{ GameID: gameID, Players: len(g.Bots), Game: g.Name(), Action: "play-turn", PlayerIndex: idx, } steps <- games.GameStep{QuestionMessage: &question} reply, err := bot.SendMessage(question) if err != nil
reply.PlayerIndex = idx steps <- games.GameStep{ReplyMessage: reply} if reply.Play != "click" { err := fmt.Errorf("Invalid bot input: %v", reply.Play) steps <- games.GameStep{Error: err} return err } if i == bulletIndex { steps <- games.GameStep{Loser: g.Bots[idx]} return nil } } steps <- games.GameStep{Draw: true} return nil } func (g *RussianbulletGame) Name() string { return "russianbullet" } func (g *RussianbulletGame) GetAsciiOutput() []byte { return nil }
{ return err }
btcd.go
// Copyright (c) 2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package rpctest import ( "os/exec" "path/filepath" "runtime" "sync" "github.com/pkt-cash/pktd/btcutil/er" ) var ( // compileMtx guards access to the executable path so that the project is // only compiled once. compileMtx sync.Mutex // executablePath is the path to the compiled executable. This is the empty // string until pktd is compiled. This should not be accessed directly; // instead use the function pktdExecutablePath(). executablePath string ) // pktdExecutablePath returns a path to the pktd executable to be used by // rpctests. To ensure the code tests against the most up-to-date version of // pktd, this method compiles pktd the first time it is called. After that, the // generated binary is used for subsequent test harnesses. The executable file // is not cleaned up, but since it lives at a static path in a temp directory, // it is not a big deal. func pktdExecutablePath() (string, er.R)
{ compileMtx.Lock() defer compileMtx.Unlock() // If pktd has already been compiled, just use that. if len(executablePath) != 0 { return executablePath, nil } testDir, err := baseDir() if err != nil { return "", err } // Build pktd and output an executable in a static temp path. outputPath := filepath.Join(testDir, "pktd") if runtime.GOOS == "windows" { outputPath += ".exe" } cmd := exec.Command( "go", "build", "-o", outputPath, "github.com/pkt-cash/pktd", ) err = er.E(cmd.Run()) if err != nil { return "", er.Errorf("Failed to build pktd: %v", err) } // Save executable path so future calls do not recompile. executablePath = outputPath return executablePath, nil }
test_auth_id_ntoken_privilege_item.py
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 8 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import isi_sdk_8_2_1 from isi_sdk_8_2_1.models.auth_id_ntoken_privilege_item import AuthIdNtokenPrivilegeItem # noqa: E501 from isi_sdk_8_2_1.rest import ApiException class TestAuthIdNtokenPrivilegeItem(unittest.TestCase): """AuthIdNtokenPrivilegeItem unit test stubs""" def setUp(self): pass def tearDown(self): pass def testAuthIdNtokenPrivilegeItem(self): """Test AuthIdNtokenPrivilegeItem""" # FIXME: construct object with mandatory attributes with example values # model = isi_sdk_8_2_1.models.auth_id_ntoken_privilege_item.AuthIdNtokenPrivilegeItem() # noqa: E501 pass if __name__ == '__main__':
unittest.main()
cacher.go
/* Copyright 2015 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 cacher import ( "context" "fmt" "net/http" "reflect" "sync" "time" "github.com/golang/glog" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/conversion" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" "k8s.io/apiserver/pkg/features" "k8s.io/apiserver/pkg/storage" utilfeature "k8s.io/apiserver/pkg/util/feature" utiltrace "k8s.io/apiserver/pkg/util/trace" "k8s.io/client-go/tools/cache" ) // Config contains the configuration for a given Cache. type Config struct { // Maximum size of the history cached in memory. CacheCapacity int // An underlying storage.Interface. Storage storage.Interface // An underlying storage.Versioner. Versioner storage.Versioner // The Cache will be caching objects of a given Type and assumes that they // are all stored under ResourcePrefix directory in the underlying database. Type interface{} ResourcePrefix string // KeyFunc is used to get a key in the underlying storage for a given object. KeyFunc func(runtime.Object) (string, error) // GetAttrsFunc is used to get object labels, fields, and the uninitialized bool GetAttrsFunc func(runtime.Object) (label labels.Set, field fields.Set, uninitialized bool, err error) // TriggerPublisherFunc is used for optimizing amount of watchers that // needs to process an incoming event. TriggerPublisherFunc storage.TriggerPublisherFunc // NewList is a function that creates new empty object storing a list of // objects of type Type. NewListFunc func() runtime.Object Codec runtime.Codec } type watchersMap map[int]*cacheWatcher func (wm watchersMap) addWatcher(w *cacheWatcher, number int) { wm[number] = w } func (wm watchersMap) deleteWatcher(number int) { delete(wm, number) } func (wm watchersMap) terminateAll() { for key, watcher := range wm { delete(wm, key) watcher.stop() } } type indexedWatchers struct { allWatchers watchersMap valueWatchers map[string]watchersMap } func (i *indexedWatchers) addWatcher(w *cacheWatcher, number int, value string, supported bool) { if supported { if _, ok := i.valueWatchers[value]; !ok { i.valueWatchers[value] = watchersMap{} } i.valueWatchers[value].addWatcher(w, number) } else { i.allWatchers.addWatcher(w, number) } } func (i *indexedWatchers) deleteWatcher(number int, value string, supported bool) { if supported { i.valueWatchers[value].deleteWatcher(number) if len(i.valueWatchers[value]) == 0 { delete(i.valueWatchers, value) } } else { i.allWatchers.deleteWatcher(number) } } func (i *indexedWatchers) terminateAll(objectType reflect.Type) { if len(i.allWatchers) > 0 || len(i.valueWatchers) > 0 { glog.Warningf("Terminating all watchers from cacher %v", objectType) } i.allWatchers.terminateAll() for index, watchers := range i.valueWatchers { watchers.terminateAll() delete(i.valueWatchers, index) } } type filterWithAttrsFunc func(key string, l labels.Set, f fields.Set, uninitialized bool) bool // Cacher is responsible for serving WATCH and LIST requests for a given // resource from its internal cache and updating its cache in the background // based on the underlying storage contents. // Cacher implements storage.Interface (although most of the calls are just // delegated to the underlying storage). type Cacher struct { // HighWaterMarks for performance debugging. // Important: Since HighWaterMark is using sync/atomic, it has to be at the top of the struct due to a bug on 32-bit platforms // See: https://golang.org/pkg/sync/atomic/ for more information incomingHWM storage.HighWaterMark // Incoming events that should be dispatched to watchers. incoming chan watchCacheEvent sync.RWMutex // Before accessing the cacher's cache, wait for the ready to be ok. // This is necessary to prevent users from accessing structures that are // uninitialized or are being repopulated right now. // ready needs to be set to false when the cacher is paused or stopped. // ready needs to be set to true when the cacher is ready to use after // initialization. ready *ready // Underlying storage.Interface. storage storage.Interface // Expected type of objects in the underlying cache. objectType reflect.Type // "sliding window" of recent changes of objects and the current state. watchCache *watchCache reflector *cache.Reflector // Versioner is used to handle resource versions. versioner storage.Versioner // triggerFunc is used for optimizing amount of watchers that needs to process // an incoming event. triggerFunc storage.TriggerPublisherFunc // watchers is mapping from the value of trigger function that a // watcher is interested into the watchers watcherIdx int watchers indexedWatchers // Defines a time budget that can be spend on waiting for not-ready watchers // while dispatching event before shutting them down. dispatchTimeoutBudget *timeBudget // Handling graceful termination. stopLock sync.RWMutex stopped bool stopCh chan struct{} stopWg sync.WaitGroup } // NewCacherFromConfig creates a new Cacher responsible for servicing WATCH and LIST requests from // its internal cache and updating its cache in the background based on the // given configuration. func NewCacherFromConfig(config Config) *Cacher { watchCache := newWatchCache(config.CacheCapacity, config.KeyFunc, config.GetAttrsFunc, config.Versioner) listerWatcher := newCacherListerWatcher(config.Storage, config.ResourcePrefix, config.NewListFunc) reflectorName := "storage/cacher.go:" + config.ResourcePrefix // Give this error when it is constructed rather than when you get the // first watch item, because it's much easier to track down that way. if obj, ok := config.Type.(runtime.Object); ok { if err := runtime.CheckCodec(config.Codec, obj); err != nil { panic("storage codec doesn't seem to match given type: " + err.Error()) } } stopCh := make(chan struct{}) cacher := &Cacher{ ready: newReady(), storage: config.Storage, objectType: reflect.TypeOf(config.Type), watchCache: watchCache, reflector: cache.NewNamedReflector(reflectorName, listerWatcher, config.Type, watchCache, 0), versioner: config.Versioner, triggerFunc: config.TriggerPublisherFunc, watcherIdx: 0, watchers: indexedWatchers{ allWatchers: make(map[int]*cacheWatcher), valueWatchers: make(map[string]watchersMap), }, // TODO: Figure out the correct value for the buffer size. incoming: make(chan watchCacheEvent, 100), dispatchTimeoutBudget: newTimeBudget(stopCh), // We need to (potentially) stop both: // - wait.Until go-routine // - reflector.ListAndWatch // and there are no guarantees on the order that they will stop. // So we will be simply closing the channel, and synchronizing on the WaitGroup. stopCh: stopCh, } watchCache.SetOnEvent(cacher.processEvent) go cacher.dispatchEvents() cacher.stopWg.Add(1) go func() { defer cacher.stopWg.Done() wait.Until( func() { if !cacher.isStopped() { cacher.startCaching(stopCh) } }, time.Second, stopCh, ) }() return cacher } func (c *Cacher) startCaching(stopChannel <-chan struct{}) { // The 'usable' lock is always 'RLock'able when it is safe to use the cache. // It is safe to use the cache after a successful list until a disconnection. // We start with usable (write) locked. The below OnReplace function will // unlock it after a successful list. The below defer will then re-lock // it when this function exits (always due to disconnection), only if // we actually got a successful list. This cycle will repeat as needed. successfulList := false c.watchCache.SetOnReplace(func() { successfulList = true c.ready.set(true) }) defer func() { if successfulList { c.ready.set(false) } }() c.terminateAllWatchers() // Note that since onReplace may be not called due to errors, we explicitly // need to retry it on errors under lock. // Also note that startCaching is called in a loop, so there's no need // to have another loop here. if err := c.reflector.ListAndWatch(stopChannel); err != nil { glog.Errorf("unexpected ListAndWatch error: %v", err) } } // Versioner implements storage.Interface. func (c *Cacher) Versioner() storage.Versioner { return c.storage.Versioner() } // Create implements storage.Interface. func (c *Cacher) Create(ctx context.Context, key string, obj, out runtime.Object, ttl uint64) error { return c.storage.Create(ctx, key, obj, out, ttl) } // Delete implements storage.Interface. func (c *Cacher) Delete(ctx context.Context, key string, out runtime.Object, preconditions *storage.Preconditions) error { return c.storage.Delete(ctx, key, out, preconditions) } // Watch implements storage.Interface. func (c *Cacher) Watch(ctx context.Context, key string, resourceVersion string, pred storage.SelectionPredicate) (watch.Interface, error) { watchRV, err := c.versioner.ParseResourceVersion(resourceVersion) if err != nil { return nil, err } c.ready.wait() // We explicitly use thread unsafe version and do locking ourself to ensure that // no new events will be processed in the meantime. The watchCache will be unlocked // on return from this function. // Note that we cannot do it under Cacher lock, to avoid a deadlock, since the // underlying watchCache is calling processEvent under its lock. c.watchCache.RLock() defer c.watchCache.RUnlock() initEvents, err := c.watchCache.GetAllEventsSinceThreadUnsafe(watchRV) if err != nil { // To match the uncached watch implementation, once we have passed authn/authz/admission, // and successfully parsed a resource version, other errors must fail with a watch event of type ERROR, // rather than a directly returned error. return newErrWatcher(err), nil } triggerValue, triggerSupported := "", false // TODO: Currently we assume that in a given Cacher object, any <predicate> that is // passed here is aware of exactly the same trigger (at most one). // Thus, either 0 or 1 values will be returned. if matchValues := pred.MatcherIndex(); len(matchValues) > 0 { triggerValue, triggerSupported = matchValues[0].Value, true } // If there is triggerFunc defined, but triggerSupported is false, // we can't narrow the amount of events significantly at this point. // // That said, currently triggerFunc is defined only for Pods and Nodes, // and there is only constant number of watchers for which triggerSupported // is false (excluding those issues explicitly by users). // Thus, to reduce the risk of those watchers blocking all watchers of a // given resource in the system, we increase the sizes of buffers for them. chanSize := 10 if c.triggerFunc != nil && !triggerSupported { // TODO: We should tune this value and ideally make it dependent on the // number of objects of a given type and/or their churn. chanSize = 1000 } c.Lock() defer c.Unlock() forget := forgetWatcher(c, c.watcherIdx, triggerValue, triggerSupported) watcher := newCacheWatcher(watchRV, chanSize, initEvents, filterWithAttrsFunction(key, pred), forget, c.versioner) c.watchers.addWatcher(watcher, c.watcherIdx, triggerValue, triggerSupported) c.watcherIdx++ return watcher, nil } // WatchList implements storage.Interface. func (c *Cacher) WatchList(ctx context.Context, key string, resourceVersion string, pred storage.SelectionPredicate) (watch.Interface, error) { return c.Watch(ctx, key, resourceVersion, pred) } // Get implements storage.Interface. func (c *Cacher) Get(ctx context.Context, key string, resourceVersion string, objPtr runtime.Object, ignoreNotFound bool) error { if resourceVersion == "" { // If resourceVersion is not specified, serve it from underlying // storage (for backward compatibility). return c.storage.Get(ctx, key, resourceVersion, objPtr, ignoreNotFound) } // If resourceVersion is specified, serve it from cache. // It's guaranteed that the returned value is at least that // fresh as the given resourceVersion. getRV, err := c.versioner.ParseResourceVersion(resourceVersion) if err != nil { return err } if getRV == 0 && !c.ready.check() { // If Cacher is not yet initialized and we don't require any specific // minimal resource version, simply forward the request to storage. return c.storage.Get(ctx, key, resourceVersion, objPtr, ignoreNotFound) } // Do not create a trace - it's not for free and there are tons // of Get requests. We can add it if it will be really needed. c.ready.wait() objVal, err := conversion.EnforcePtr(objPtr) if err != nil { return err } obj, exists, readResourceVersion, err := c.watchCache.WaitUntilFreshAndGet(getRV, key, nil) if err != nil { return err } if exists { elem, ok := obj.(*storeElement) if !ok { return fmt.Errorf("non *storeElement returned from storage: %v", obj) } objVal.Set(reflect.ValueOf(elem.Object).Elem()) } else { objVal.Set(reflect.Zero(objVal.Type())) if !ignoreNotFound { return storage.NewKeyNotFoundError(key, int64(readResourceVersion)) } } return nil } // GetToList implements storage.Interface. func (c *Cacher) GetToList(ctx context.Context, key string, resourceVersion string, pred storage.SelectionPredicate, listObj runtime.Object) error { pagingEnabled := utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking) if resourceVersion == "" || (pagingEnabled && (len(pred.Continue) > 0 || pred.Limit > 0)) { // If resourceVersion is not specified, serve it from underlying // storage (for backward compatibility). If a continuation or limit is // requested, serve it from the underlying storage as well. return c.storage.GetToList(ctx, key, resourceVersion, pred, listObj) } // If resourceVersion is specified, serve it from cache. // It's guaranteed that the returned value is at least that // fresh as the given resourceVersion. listRV, err := c.versioner.ParseResourceVersion(resourceVersion) if err != nil { return err } if listRV == 0 && !c.ready.check() { // If Cacher is not yet initialized and we don't require any specific // minimal resource version, simply forward the request to storage. return c.storage.GetToList(ctx, key, resourceVersion, pred, listObj) } trace := utiltrace.New(fmt.Sprintf("cacher %v: List", c.objectType.String())) defer trace.LogIfLong(500 * time.Millisecond) c.ready.wait() trace.Step("Ready") // List elements with at least 'listRV' from cache. listPtr, err := meta.GetItemsPtr(listObj) if err != nil { return err } listVal, err := conversion.EnforcePtr(listPtr) if err != nil || listVal.Kind() != reflect.Slice { return fmt.Errorf("need a pointer to slice, got %v", listVal.Kind()) } filter := filterWithAttrsFunction(key, pred) obj, exists, readResourceVersion, err := c.watchCache.WaitUntilFreshAndGet(listRV, key, trace) if err != nil { return err } trace.Step("Got from cache") if exists { elem, ok := obj.(*storeElement) if !ok { return fmt.Errorf("non *storeElement returned from storage: %v", obj) } if filter(elem.Key, elem.Labels, elem.Fields, elem.Uninitialized) { listVal.Set(reflect.Append(listVal, reflect.ValueOf(elem.Object).Elem())) } } if c.versioner != nil { if err := c.versioner.UpdateList(listObj, readResourceVersion, ""); err != nil { return err } } return nil } // List implements storage.Interface. func (c *Cacher) List(ctx context.Context, key string, resourceVersion string, pred storage.SelectionPredicate, listObj runtime.Object) error { pagingEnabled := utilfeature.DefaultFeatureGate.Enabled(features.APIListChunking) hasContinuation := pagingEnabled && len(pred.Continue) > 0 hasLimit := pagingEnabled && pred.Limit > 0 && resourceVersion != "0" if resourceVersion == "" || hasContinuation || hasLimit { // If resourceVersion is not specified, serve it from underlying // storage (for backward compatibility). If a continuation is // requested, serve it from the underlying storage as well. // Limits are only sent to storage when resourceVersion is non-zero // since the watch cache isn't able to perform continuations, and // limits are ignored when resource version is zero. return c.storage.List(ctx, key, resourceVersion, pred, listObj) } // If resourceVersion is specified, serve it from cache. // It's guaranteed that the returned value is at least that // fresh as the given resourceVersion. listRV, err := c.versioner.ParseResourceVersion(resourceVersion) if err != nil { return err } if listRV == 0 && !c.ready.check() { // If Cacher is not yet initialized and we don't require any specific // minimal resource version, simply forward the request to storage. return c.storage.List(ctx, key, resourceVersion, pred, listObj) } trace := utiltrace.New(fmt.Sprintf("cacher %v: List", c.objectType.String())) defer trace.LogIfLong(500 * time.Millisecond) c.ready.wait() trace.Step("Ready") // List elements with at least 'listRV' from cache. listPtr, err := meta.GetItemsPtr(listObj) if err != nil { return err } listVal, err := conversion.EnforcePtr(listPtr) if err != nil || listVal.Kind() != reflect.Slice { return fmt.Errorf("need a pointer to slice, got %v", listVal.Kind()) } filter := filterWithAttrsFunction(key, pred) objs, readResourceVersion, err := c.watchCache.WaitUntilFreshAndList(listRV, trace) if err != nil { return err } trace.Step(fmt.Sprintf("Listed %d items from cache", len(objs))) if len(objs) > listVal.Cap() && pred.Label.Empty() && pred.Field.Empty() { // Resize the slice appropriately, since we already know that none // of the elements will be filtered out. listVal.Set(reflect.MakeSlice(reflect.SliceOf(c.objectType.Elem()), 0, len(objs))) trace.Step("Resized result") } for _, obj := range objs { elem, ok := obj.(*storeElement) if !ok { return fmt.Errorf("non *storeElement returned from storage: %v", obj) } if filter(elem.Key, elem.Labels, elem.Fields, elem.Uninitialized) { listVal.Set(reflect.Append(listVal, reflect.ValueOf(elem.Object).Elem())) } } trace.Step(fmt.Sprintf("Filtered %d items", listVal.Len())) if c.versioner != nil { if err := c.versioner.UpdateList(listObj, readResourceVersion, ""); err != nil { return err } } return nil } // GuaranteedUpdate implements storage.Interface. func (c *Cacher) GuaranteedUpdate( ctx context.Context, key string, ptrToType runtime.Object, ignoreNotFound bool, preconditions *storage.Preconditions, tryUpdate storage.UpdateFunc, _ ...runtime.Object) error { // Ignore the suggestion and try to pass down the current version of the object // read from cache. if elem, exists, err := c.watchCache.GetByKey(key); err != nil { glog.Errorf("GetByKey returned error: %v", err) } else if exists { currObj := elem.(*storeElement).Object.DeepCopyObject() return c.storage.GuaranteedUpdate(ctx, key, ptrToType, ignoreNotFound, preconditions, tryUpdate, currObj) } // If we couldn't get the object, fallback to no-suggestion. return c.storage.GuaranteedUpdate(ctx, key, ptrToType, ignoreNotFound, preconditions, tryUpdate) } // Count implements storage.Interface. func (c *Cacher) Count(pathPrefix string) (int64, error) { return c.storage.Count(pathPrefix) } func (c *Cacher) triggerValues(event *watchCacheEvent) ([]string, bool) { // TODO: Currently we assume that in a given Cacher object, its <c.triggerFunc> // is aware of exactly the same trigger (at most one). Thus calling: // c.triggerFunc(<some object>) // can return only 0 or 1 values. // That means, that triggerValues itself may return up to 2 different values. if c.triggerFunc == nil { return nil, false } result := make([]string, 0, 2) matchValues := c.triggerFunc(event.Object) if len(matchValues) > 0 { result = append(result, matchValues[0].Value) } if event.PrevObject == nil { return result, len(result) > 0 } prevMatchValues := c.triggerFunc(event.PrevObject) if len(prevMatchValues) > 0 { if len(result) == 0 || result[0] != prevMatchValues[0].Value { result = append(result, prevMatchValues[0].Value) } } return result, len(result) > 0 } func (c *Cacher) processEvent(event *watchCacheEvent) { if curLen := int64(len(c.incoming)); c.incomingHWM.Update(curLen) { // Monitor if this gets backed up, and how much. glog.V(1).Infof("cacher (%v): %v objects queued in incoming channel.", c.objectType.String(), curLen) } c.incoming <- *event } func (c *Cacher) dispatchEvents() { for { select { case event, ok := <-c.incoming: if !ok { return } c.dispatchEvent(&event) case <-c.stopCh: return } } } func (c *Cacher) dispatchEvent(event *watchCacheEvent) { triggerValues, supported := c.triggerValues(event) c.Lock() defer c.Unlock() // Iterate over "allWatchers" no matter what the trigger function is. for _, watcher := range c.watchers.allWatchers { watcher.add(event, c.dispatchTimeoutBudget) } if supported { // Iterate over watchers interested in the given values of the trigger. for _, triggerValue := range triggerValues { for _, watcher := range c.watchers.valueWatchers[triggerValue] { watcher.add(event, c.dispatchTimeoutBudget) } } } else { // supported equal to false generally means that trigger function // is not defined (or not aware of any indexes). In this case, // watchers filters should generally also don't generate any // trigger values, but can cause problems in case of some // misconfiguration. Thus we paranoidly leave this branch. // Iterate over watchers interested in exact values for all values. for _, watchers := range c.watchers.valueWatchers { for _, watcher := range watchers { watcher.add(event, c.dispatchTimeoutBudget) } } } } func (c *Cacher) terminateAllWatchers() { c.Lock() defer c.Unlock() c.watchers.terminateAll(c.objectType) } func (c *Cacher) isStopped() bool { c.stopLock.RLock() defer c.stopLock.RUnlock() return c.stopped } // Stop implements the graceful termination. func (c *Cacher) Stop() { // avoid stopping twice (note: cachers are shared with subresources) if c.isStopped() { return } c.stopLock.Lock() if c.stopped { c.stopLock.Unlock() return } c.stopped = true c.stopLock.Unlock() close(c.stopCh) c.stopWg.Wait() } func forgetWatcher(c *Cacher, index int, triggerValue string, triggerSupported bool) func(bool) { return func(lock bool) { if lock { c.Lock() defer c.Unlock() } else { // false is currently passed only if we are forcing watcher to close due // to its unresponsiveness and blocking other watchers. // TODO: Get this information in cleaner way. glog.V(1).Infof("Forcing watcher close due to unresponsiveness: %v", c.objectType.String()) } // It's possible that the watcher is already not in the structure (e.g. in case of // simultaneous Stop() and terminateAllWatchers(), but it doesn't break anything. c.watchers.deleteWatcher(index, triggerValue, triggerSupported) } } func filterWithAttrsFunction(key string, p storage.SelectionPredicate) filterWithAttrsFunc { filterFunc := func(objKey string, label labels.Set, field fields.Set, uninitialized bool) bool { if !hasPathPrefix(objKey, key) { return false } return p.MatchesObjectAttributes(label, field, uninitialized) } return filterFunc } // LastSyncResourceVersion returns resource version to which the underlying cache is synced. func (c *Cacher) LastSyncResourceVersion() (uint64, error) { c.ready.wait() resourceVersion := c.reflector.LastSyncResourceVersion() return c.versioner.ParseResourceVersion(resourceVersion) } // cacherListerWatcher opaques storage.Interface to expose cache.ListerWatcher. type cacherListerWatcher struct { storage storage.Interface resourcePrefix string newListFunc func() runtime.Object } func newCacherListerWatcher(storage storage.Interface, resourcePrefix string, newListFunc func() runtime.Object) cache.ListerWatcher { return &cacherListerWatcher{ storage: storage, resourcePrefix: resourcePrefix, newListFunc: newListFunc, } } // Implements cache.ListerWatcher interface. func (lw *cacherListerWatcher) List(options metav1.ListOptions) (runtime.Object, error) { list := lw.newListFunc() if err := lw.storage.List(context.TODO(), lw.resourcePrefix, "", storage.Everything, list); err != nil { return nil, err } return list, nil } // Implements cache.ListerWatcher interface. func (lw *cacherListerWatcher) Watch(options metav1.ListOptions) (watch.Interface, error) { return lw.storage.WatchList(context.TODO(), lw.resourcePrefix, options.ResourceVersion, storage.Everything) } // errWatcher implements watch.Interface to return a single error type errWatcher struct { result chan watch.Event } func newErrWatcher(err error) *errWatcher
// Implements watch.Interface. func (c *errWatcher) ResultChan() <-chan watch.Event { return c.result } // Implements watch.Interface. func (c *errWatcher) Stop() { // no-op } // cacheWatcher implements watch.Interface type cacheWatcher struct { sync.Mutex input chan *watchCacheEvent result chan watch.Event done chan struct{} filter filterWithAttrsFunc stopped bool forget func(bool) versioner storage.Versioner } func newCacheWatcher(resourceVersion uint64, chanSize int, initEvents []*watchCacheEvent, filter filterWithAttrsFunc, forget func(bool), versioner storage.Versioner) *cacheWatcher { watcher := &cacheWatcher{ input: make(chan *watchCacheEvent, chanSize), result: make(chan watch.Event, chanSize), done: make(chan struct{}), filter: filter, stopped: false, forget: forget, versioner: versioner, } go watcher.process(initEvents, resourceVersion) return watcher } // Implements watch.Interface. func (c *cacheWatcher) ResultChan() <-chan watch.Event { return c.result } // Implements watch.Interface. func (c *cacheWatcher) Stop() { c.forget(true) c.stop() } func (c *cacheWatcher) stop() { c.Lock() defer c.Unlock() if !c.stopped { c.stopped = true close(c.done) close(c.input) } } var timerPool sync.Pool func (c *cacheWatcher) add(event *watchCacheEvent, budget *timeBudget) { // Try to send the event immediately, without blocking. select { case c.input <- event: return default: } // OK, block sending, but only for up to <timeout>. // cacheWatcher.add is called very often, so arrange // to reuse timers instead of constantly allocating. startTime := time.Now() timeout := budget.takeAvailable() t, ok := timerPool.Get().(*time.Timer) if ok { t.Reset(timeout) } else { t = time.NewTimer(timeout) } defer timerPool.Put(t) select { case c.input <- event: stopped := t.Stop() if !stopped { // Consume triggered (but not yet received) timer event // so that future reuse does not get a spurious timeout. <-t.C } case <-t.C: // This means that we couldn't send event to that watcher. // Since we don't want to block on it infinitely, // we simply terminate it. c.forget(false) c.stop() } budget.returnUnused(timeout - time.Since(startTime)) } // NOTE: sendWatchCacheEvent is assumed to not modify <event> !!! func (c *cacheWatcher) sendWatchCacheEvent(event *watchCacheEvent) { curObjPasses := event.Type != watch.Deleted && c.filter(event.Key, event.ObjLabels, event.ObjFields, event.ObjUninitialized) oldObjPasses := false if event.PrevObject != nil { oldObjPasses = c.filter(event.Key, event.PrevObjLabels, event.PrevObjFields, event.PrevObjUninitialized) } if !curObjPasses && !oldObjPasses { // Watcher is not interested in that object. return } var watchEvent watch.Event switch { case curObjPasses && !oldObjPasses: watchEvent = watch.Event{Type: watch.Added, Object: event.Object.DeepCopyObject()} case curObjPasses && oldObjPasses: watchEvent = watch.Event{Type: watch.Modified, Object: event.Object.DeepCopyObject()} case !curObjPasses && oldObjPasses: // return a delete event with the previous object content, but with the event's resource version oldObj := event.PrevObject.DeepCopyObject() if err := c.versioner.UpdateObject(oldObj, event.ResourceVersion); err != nil { utilruntime.HandleError(fmt.Errorf("failure to version api object (%d) %#v: %v", event.ResourceVersion, oldObj, err)) } watchEvent = watch.Event{Type: watch.Deleted, Object: oldObj} } // We need to ensure that if we put event X to the c.result, all // previous events were already put into it before, no matter whether // c.done is close or not. // Thus we cannot simply select from c.done and c.result and this // would give us non-determinism. // At the same time, we don't want to block infinitely on putting // to c.result, when c.done is already closed. // This ensures that with c.done already close, we at most once go // into the next select after this. With that, no matter which // statement we choose there, we will deliver only consecutive // events. select { case <-c.done: return default: } select { case c.result <- watchEvent: case <-c.done: } } func (c *cacheWatcher) process(initEvents []*watchCacheEvent, resourceVersion uint64) { defer utilruntime.HandleCrash() // Check how long we are processing initEvents. // As long as these are not processed, we are not processing // any incoming events, so if it takes long, we may actually // block all watchers for some time. // TODO: From the logs it seems that there happens processing // times even up to 1s which is very long. However, this doesn't // depend that much on the number of initEvents. E.g. from the // 2000-node Kubemark run we have logs like this, e.g.: // ... processing 13862 initEvents took 66.808689ms // ... processing 14040 initEvents took 993.532539ms // We should understand what is blocking us in those cases (e.g. // is it lack of CPU, network, or sth else) and potentially // consider increase size of result buffer in those cases. const initProcessThreshold = 500 * time.Millisecond startTime := time.Now() for _, event := range initEvents { c.sendWatchCacheEvent(event) } processingTime := time.Since(startTime) if processingTime > initProcessThreshold { objType := "<null>" if len(initEvents) > 0 { objType = reflect.TypeOf(initEvents[0].Object).String() } glog.V(2).Infof("processing %d initEvents of %s took %v", len(initEvents), objType, processingTime) } defer close(c.result) defer c.Stop() for { event, ok := <-c.input if !ok { return } // only send events newer than resourceVersion if event.ResourceVersion > resourceVersion { c.sendWatchCacheEvent(event) } } } type ready struct { ok bool c *sync.Cond } func newReady() *ready { return &ready{c: sync.NewCond(&sync.Mutex{})} } func (r *ready) wait() { r.c.L.Lock() for !r.ok { r.c.Wait() } r.c.L.Unlock() } // TODO: Make check() function more sophisticated, in particular // allow it to behave as "waitWithTimeout". func (r *ready) check() bool { r.c.L.Lock() defer r.c.L.Unlock() return r.ok } func (r *ready) set(ok bool) { r.c.L.Lock() defer r.c.L.Unlock() r.ok = ok r.c.Broadcast() }
{ // Create an error event errEvent := watch.Event{Type: watch.Error} switch err := err.(type) { case runtime.Object: errEvent.Object = err case *errors.StatusError: errEvent.Object = &err.ErrStatus default: errEvent.Object = &metav1.Status{ Status: metav1.StatusFailure, Message: err.Error(), Reason: metav1.StatusReasonInternalError, Code: http.StatusInternalServerError, } } // Create a watcher with room for a single event, populate it, and close the channel watcher := &errWatcher{result: make(chan watch.Event, 1)} watcher.result <- errEvent close(watcher.result) return watcher }
volume.rs
// Generated from definition io.k8s.api.core.v1.Volume /// Volume represents a named volume in a pod that may be accessed by any container in the pod. #[derive(Clone, Debug, Default, PartialEq)] pub struct Volume { /// AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore pub aws_elastic_block_store: Option<crate::api::core::v1::AWSElasticBlockStoreVolumeSource>, /// AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod. pub azure_disk: Option<crate::api::core::v1::AzureDiskVolumeSource>, /// AzureFile represents an Azure File Service mount on the host and bind mount to the pod. pub azure_file: Option<crate::api::core::v1::AzureFileVolumeSource>, /// CephFS represents a Ceph FS mount on the host that shares a pod's lifetime pub cephfs: Option<crate::api::core::v1::CephFSVolumeSource>, /// Cinder represents a cinder volume attached and mounted on kubelets host machine More info: https://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md pub cinder: Option<crate::api::core::v1::CinderVolumeSource>, /// ConfigMap represents a configMap that should populate this volume pub config_map: Option<crate::api::core::v1::ConfigMapVolumeSource>, /// DownwardAPI represents downward API about the pod that should populate this volume pub downward_api: Option<crate::api::core::v1::DownwardAPIVolumeSource>, /// EmptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir pub empty_dir: Option<crate::api::core::v1::EmptyDirVolumeSource>, /// FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod. pub fc: Option<crate::api::core::v1::FCVolumeSource>, /// FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. This is an alpha feature and may change in future. pub flex_volume: Option<crate::api::core::v1::FlexVolumeSource>, /// Flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running pub flocker: Option<crate::api::core::v1::FlockerVolumeSource>, /// GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk pub gce_persistent_disk: Option<crate::api::core::v1::GCEPersistentDiskVolumeSource>, /// GitRepo represents a git repository at a particular revision. pub git_repo: Option<crate::api::core::v1::GitRepoVolumeSource>, /// Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md pub glusterfs: Option<crate::api::core::v1::GlusterfsVolumeSource>, /// HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath pub host_path: Option<crate::api::core::v1::HostPathVolumeSource>, /// ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://releases.k8s.io/HEAD/examples/volumes/iscsi/README.md pub iscsi: Option<crate::api::core::v1::ISCSIVolumeSource>, /// Volume's name. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names pub name: String, /// NFS represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs pub nfs: Option<crate::api::core::v1::NFSVolumeSource>, /// PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims pub persistent_volume_claim: Option<crate::api::core::v1::PersistentVolumeClaimVolumeSource>, /// PhotonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine pub photon_persistent_disk: Option<crate::api::core::v1::PhotonPersistentDiskVolumeSource>, /// PortworxVolume represents a portworx volume attached and mounted on kubelets host machine pub portworx_volume: Option<crate::api::core::v1::PortworxVolumeSource>, /// Items for all in one resources secrets, configmaps, and downward API pub projected: Option<crate::api::core::v1::ProjectedVolumeSource>, /// Quobyte represents a Quobyte mount on the host that shares a pod's lifetime pub quobyte: Option<crate::api::core::v1::QuobyteVolumeSource>, /// RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://releases.k8s.io/HEAD/examples/volumes/rbd/README.md pub rbd: Option<crate::api::core::v1::RBDVolumeSource>, /// ScaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes. pub scale_io: Option<crate::api::core::v1::ScaleIOVolumeSource>, /// Secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret pub secret: Option<crate::api::core::v1::SecretVolumeSource>, /// StorageOS represents a StorageOS volume attached and mounted on Kubernetes nodes. pub storageos: Option<crate::api::core::v1::StorageOSVolumeSource>, /// VsphereVolume represents a vSphere volume attached and mounted on kubelets host machine pub vsphere_volume: Option<crate::api::core::v1::VsphereVirtualDiskVolumeSource>, } impl<'de> serde::Deserialize<'de> for Volume { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_aws_elastic_block_store, Key_azure_disk, Key_azure_file, Key_cephfs, Key_cinder, Key_config_map, Key_downward_api, Key_empty_dir, Key_fc, Key_flex_volume, Key_flocker, Key_gce_persistent_disk, Key_git_repo, Key_glusterfs, Key_host_path, Key_iscsi, Key_name, Key_nfs, Key_persistent_volume_claim, Key_photon_persistent_disk, Key_portworx_volume, Key_projected, Key_quobyte, Key_rbd, Key_scale_io, Key_secret, Key_storageos, Key_vsphere_volume, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "awsElasticBlockStore" => Field::Key_aws_elastic_block_store, "azureDisk" => Field::Key_azure_disk, "azureFile" => Field::Key_azure_file, "cephfs" => Field::Key_cephfs, "cinder" => Field::Key_cinder, "configMap" => Field::Key_config_map, "downwardAPI" => Field::Key_downward_api, "emptyDir" => Field::Key_empty_dir, "fc" => Field::Key_fc, "flexVolume" => Field::Key_flex_volume, "flocker" => Field::Key_flocker, "gcePersistentDisk" => Field::Key_gce_persistent_disk, "gitRepo" => Field::Key_git_repo, "glusterfs" => Field::Key_glusterfs, "hostPath" => Field::Key_host_path, "iscsi" => Field::Key_iscsi, "name" => Field::Key_name, "nfs" => Field::Key_nfs, "persistentVolumeClaim" => Field::Key_persistent_volume_claim, "photonPersistentDisk" => Field::Key_photon_persistent_disk, "portworxVolume" => Field::Key_portworx_volume, "projected" => Field::Key_projected, "quobyte" => Field::Key_quobyte, "rbd" => Field::Key_rbd, "scaleIO" => Field::Key_scale_io, "secret" => Field::Key_secret, "storageos" => Field::Key_storageos, "vsphereVolume" => Field::Key_vsphere_volume, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Volume; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_aws_elastic_block_store: Option<crate::api::core::v1::AWSElasticBlockStoreVolumeSource> = None; let mut value_azure_disk: Option<crate::api::core::v1::AzureDiskVolumeSource> = None; let mut value_azure_file: Option<crate::api::core::v1::AzureFileVolumeSource> = None; let mut value_cephfs: Option<crate::api::core::v1::CephFSVolumeSource> = None; let mut value_cinder: Option<crate::api::core::v1::CinderVolumeSource> = None; let mut value_config_map: Option<crate::api::core::v1::ConfigMapVolumeSource> = None; let mut value_downward_api: Option<crate::api::core::v1::DownwardAPIVolumeSource> = None; let mut value_empty_dir: Option<crate::api::core::v1::EmptyDirVolumeSource> = None; let mut value_fc: Option<crate::api::core::v1::FCVolumeSource> = None; let mut value_flex_volume: Option<crate::api::core::v1::FlexVolumeSource> = None; let mut value_flocker: Option<crate::api::core::v1::FlockerVolumeSource> = None; let mut value_gce_persistent_disk: Option<crate::api::core::v1::GCEPersistentDiskVolumeSource> = None; let mut value_git_repo: Option<crate::api::core::v1::GitRepoVolumeSource> = None; let mut value_glusterfs: Option<crate::api::core::v1::GlusterfsVolumeSource> = None; let mut value_host_path: Option<crate::api::core::v1::HostPathVolumeSource> = None; let mut value_iscsi: Option<crate::api::core::v1::ISCSIVolumeSource> = None; let mut value_name: Option<String> = None; let mut value_nfs: Option<crate::api::core::v1::NFSVolumeSource> = None; let mut value_persistent_volume_claim: Option<crate::api::core::v1::PersistentVolumeClaimVolumeSource> = None; let mut value_photon_persistent_disk: Option<crate::api::core::v1::PhotonPersistentDiskVolumeSource> = None; let mut value_portworx_volume: Option<crate::api::core::v1::PortworxVolumeSource> = None; let mut value_projected: Option<crate::api::core::v1::ProjectedVolumeSource> = None; let mut value_quobyte: Option<crate::api::core::v1::QuobyteVolumeSource> = None; let mut value_rbd: Option<crate::api::core::v1::RBDVolumeSource> = None; let mut value_scale_io: Option<crate::api::core::v1::ScaleIOVolumeSource> = None; let mut value_secret: Option<crate::api::core::v1::SecretVolumeSource> = None; let mut value_storageos: Option<crate::api::core::v1::StorageOSVolumeSource> = None; let mut value_vsphere_volume: Option<crate::api::core::v1::VsphereVirtualDiskVolumeSource> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_aws_elastic_block_store => value_aws_elastic_block_store = serde::de::MapAccess::next_value(&mut map)?, Field::Key_azure_disk => value_azure_disk = serde::de::MapAccess::next_value(&mut map)?, Field::Key_azure_file => value_azure_file = serde::de::MapAccess::next_value(&mut map)?, Field::Key_cephfs => value_cephfs = serde::de::MapAccess::next_value(&mut map)?, Field::Key_cinder => value_cinder = serde::de::MapAccess::next_value(&mut map)?, Field::Key_config_map => value_config_map = serde::de::MapAccess::next_value(&mut map)?, Field::Key_downward_api => value_downward_api = serde::de::MapAccess::next_value(&mut map)?, Field::Key_empty_dir => value_empty_dir = serde::de::MapAccess::next_value(&mut map)?, Field::Key_fc => value_fc = serde::de::MapAccess::next_value(&mut map)?, Field::Key_flex_volume => value_flex_volume = serde::de::MapAccess::next_value(&mut map)?, Field::Key_flocker => value_flocker = serde::de::MapAccess::next_value(&mut map)?, Field::Key_gce_persistent_disk => value_gce_persistent_disk = serde::de::MapAccess::next_value(&mut map)?, Field::Key_git_repo => value_git_repo = serde::de::MapAccess::next_value(&mut map)?, Field::Key_glusterfs => value_glusterfs = serde::de::MapAccess::next_value(&mut map)?, Field::Key_host_path => value_host_path = serde::de::MapAccess::next_value(&mut map)?, Field::Key_iscsi => value_iscsi = serde::de::MapAccess::next_value(&mut map)?, Field::Key_name => value_name = Some(serde::de::MapAccess::next_value(&mut map)?), Field::Key_nfs => value_nfs = serde::de::MapAccess::next_value(&mut map)?, Field::Key_persistent_volume_claim => value_persistent_volume_claim = serde::de::MapAccess::next_value(&mut map)?, Field::Key_photon_persistent_disk => value_photon_persistent_disk = serde::de::MapAccess::next_value(&mut map)?, Field::Key_portworx_volume => value_portworx_volume = serde::de::MapAccess::next_value(&mut map)?, Field::Key_projected => value_projected = serde::de::MapAccess::next_value(&mut map)?, Field::Key_quobyte => value_quobyte = serde::de::MapAccess::next_value(&mut map)?, Field::Key_rbd => value_rbd = serde::de::MapAccess::next_value(&mut map)?, Field::Key_scale_io => value_scale_io = serde::de::MapAccess::next_value(&mut map)?, Field::Key_secret => value_secret = serde::de::MapAccess::next_value(&mut map)?, Field::Key_storageos => value_storageos = serde::de::MapAccess::next_value(&mut map)?, Field::Key_vsphere_volume => value_vsphere_volume = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(Volume { aws_elastic_block_store: value_aws_elastic_block_store, azure_disk: value_azure_disk, azure_file: value_azure_file, cephfs: value_cephfs, cinder: value_cinder, config_map: value_config_map, downward_api: value_downward_api, empty_dir: value_empty_dir, fc: value_fc, flex_volume: value_flex_volume, flocker: value_flocker, gce_persistent_disk: value_gce_persistent_disk, git_repo: value_git_repo, glusterfs: value_glusterfs, host_path: value_host_path, iscsi: value_iscsi, name: value_name.ok_or_else(|| serde::de::Error::missing_field("name"))?, nfs: value_nfs, persistent_volume_claim: value_persistent_volume_claim, photon_persistent_disk: value_photon_persistent_disk, portworx_volume: value_portworx_volume, projected: value_projected, quobyte: value_quobyte, rbd: value_rbd, scale_io: value_scale_io, secret: value_secret, storageos: value_storageos, vsphere_volume: value_vsphere_volume, }) } } deserializer.deserialize_struct( "Volume", &[ "awsElasticBlockStore", "azureDisk", "azureFile", "cephfs", "cinder", "configMap", "downwardAPI", "emptyDir", "fc", "flexVolume", "flocker", "gcePersistentDisk", "gitRepo", "glusterfs", "hostPath", "iscsi", "name", "nfs", "persistentVolumeClaim", "photonPersistentDisk", "portworxVolume", "projected", "quobyte", "rbd", "scaleIO", "secret", "storageos", "vsphereVolume", ], Visitor, ) } } impl serde::Serialize for Volume { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "Volume", 1 + self.aws_elastic_block_store.as_ref().map_or(0, |_| 1) + self.azure_disk.as_ref().map_or(0, |_| 1) + self.azure_file.as_ref().map_or(0, |_| 1) + self.cephfs.as_ref().map_or(0, |_| 1) + self.cinder.as_ref().map_or(0, |_| 1) + self.config_map.as_ref().map_or(0, |_| 1) + self.downward_api.as_ref().map_or(0, |_| 1) + self.empty_dir.as_ref().map_or(0, |_| 1) + self.fc.as_ref().map_or(0, |_| 1) + self.flex_volume.as_ref().map_or(0, |_| 1) + self.flocker.as_ref().map_or(0, |_| 1) + self.gce_persistent_disk.as_ref().map_or(0, |_| 1) + self.git_repo.as_ref().map_or(0, |_| 1) + self.glusterfs.as_ref().map_or(0, |_| 1) + self.host_path.as_ref().map_or(0, |_| 1) + self.iscsi.as_ref().map_or(0, |_| 1) + self.nfs.as_ref().map_or(0, |_| 1) + self.persistent_volume_claim.as_ref().map_or(0, |_| 1) + self.photon_persistent_disk.as_ref().map_or(0, |_| 1) + self.portworx_volume.as_ref().map_or(0, |_| 1) + self.projected.as_ref().map_or(0, |_| 1) + self.quobyte.as_ref().map_or(0, |_| 1) + self.rbd.as_ref().map_or(0, |_| 1) + self.scale_io.as_ref().map_or(0, |_| 1) + self.secret.as_ref().map_or(0, |_| 1) + self.storageos.as_ref().map_or(0, |_| 1) + self.vsphere_volume.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.aws_elastic_block_store { serde::ser::SerializeStruct::serialize_field(&mut state, "awsElasticBlockStore", value)?; } if let Some(value) = &self.azure_disk { serde::ser::SerializeStruct::serialize_field(&mut state, "azureDisk", value)?; } if let Some(value) = &self.azure_file { serde::ser::SerializeStruct::serialize_field(&mut state, "azureFile", value)?; } if let Some(value) = &self.cephfs { serde::ser::SerializeStruct::serialize_field(&mut state, "cephfs", value)?; } if let Some(value) = &self.cinder { serde::ser::SerializeStruct::serialize_field(&mut state, "cinder", value)?; } if let Some(value) = &self.config_map { serde::ser::SerializeStruct::serialize_field(&mut state, "configMap", value)?; } if let Some(value) = &self.downward_api { serde::ser::SerializeStruct::serialize_field(&mut state, "downwardAPI", value)?; } if let Some(value) = &self.empty_dir { serde::ser::SerializeStruct::serialize_field(&mut state, "emptyDir", value)?; } if let Some(value) = &self.fc { serde::ser::SerializeStruct::serialize_field(&mut state, "fc", value)?; } if let Some(value) = &self.flex_volume { serde::ser::SerializeStruct::serialize_field(&mut state, "flexVolume", value)?; } if let Some(value) = &self.flocker { serde::ser::SerializeStruct::serialize_field(&mut state, "flocker", value)?; } if let Some(value) = &self.gce_persistent_disk { serde::ser::SerializeStruct::serialize_field(&mut state, "gcePersistentDisk", value)?; } if let Some(value) = &self.git_repo { serde::ser::SerializeStruct::serialize_field(&mut state, "gitRepo", value)?; } if let Some(value) = &self.glusterfs { serde::ser::SerializeStruct::serialize_field(&mut state, "glusterfs", value)?; } if let Some(value) = &self.host_path { serde::ser::SerializeStruct::serialize_field(&mut state, "hostPath", value)?; } if let Some(value) = &self.iscsi { serde::ser::SerializeStruct::serialize_field(&mut state, "iscsi", value)?; } serde::ser::SerializeStruct::serialize_field(&mut state, "name", &self.name)?; if let Some(value) = &self.nfs { serde::ser::SerializeStruct::serialize_field(&mut state, "nfs", value)?; } if let Some(value) = &self.persistent_volume_claim { serde::ser::SerializeStruct::serialize_field(&mut state, "persistentVolumeClaim", value)?; } if let Some(value) = &self.photon_persistent_disk { serde::ser::SerializeStruct::serialize_field(&mut state, "photonPersistentDisk", value)?; } if let Some(value) = &self.portworx_volume { serde::ser::SerializeStruct::serialize_field(&mut state, "portworxVolume", value)?; } if let Some(value) = &self.projected { serde::ser::SerializeStruct::serialize_field(&mut state, "projected", value)?; } if let Some(value) = &self.quobyte { serde::ser::SerializeStruct::serialize_field(&mut state, "quobyte", value)?; } if let Some(value) = &self.rbd { serde::ser::SerializeStruct::serialize_field(&mut state, "rbd", value)?; } if let Some(value) = &self.scale_io { serde::ser::SerializeStruct::serialize_field(&mut state, "scaleIO", value)?; } if let Some(value) = &self.secret { serde::ser::SerializeStruct::serialize_field(&mut state, "secret", value)?; } if let Some(value) = &self.storageos { serde::ser::SerializeStruct::serialize_field(&mut state, "storageos", value)?; } if let Some(value) = &self.vsphere_volume { serde::ser::SerializeStruct::serialize_field(&mut state, "vsphereVolume", value)?; } serde::ser::SerializeStruct::end(state) } }
{ f.write_str("Volume") }
main.go
package main import "fmt" type T interface { } func main() { fmt.Printf("type:%T\n", (T)(nil)) fmt.Printf("type:%T\n", (*error)(nil)) fmt.Printf("type:%T\n", (error)(nil)) var a error
}
var b int fmt.Printf("type:%T\n", a) fmt.Printf("type:%T\n", b)
describe.go
package describe import ( "fmt" cmdutil "github.com/i2tsuki/mkr-graph/cmd/cmdutil" cmderror "github.com/i2tsuki/mkr-graph/cmd/error" cobra "github.com/spf13/cobra" flag "github.com/spf13/pflag" ) // RunOptions is subcommand options struct type RunOptions struct { Identifier string Attribute string } // NewRunOptions generate options func NewRunOptions() *RunOptions { return &RunOptions{} } func addRunFlags(cmd *cobra.Command, opt *RunOptions) { cmd.Flags().StringVar(&opt.Identifier, "host", "", "Describe host metrics name") cmd.Flags().StringVar(&opt.Identifier, "service", "", "Describe service metrics name") cmd.Flags().SetNormalizeFunc( func(f *flag.FlagSet, name string) flag.NormalizedName { return flag.NormalizedName(name) }, ) } // NewCmd construct describe subcommand func NewCmd(f cmdutil.Factory) *cobra.Command
func (o *RunOptions) complete(f cmdutil.Factory, cmd *cobra.Command) error { o.Attribute = cmdutil.LastMatchArgOptionName(o.Identifier) return nil } func (o *RunOptions) run(f cmdutil.Factory, cmd *cobra.Command, args []string) error { var names []string var err error switch o.Attribute { case "host": names, err = f.Client.FetchHostMetricNames(o.Identifier) if err != nil { err := cmderror.NewError(f, err) fmt.Println(f.App.Msg, err) } case "service": names, err = f.Client.FetchServiceMetricNames(o.Identifier) if err != nil { err := cmderror.NewError(f, err) fmt.Println(f.App.Msg, err) } } for _, name := range names { fmt.Println(name) } return nil }
{ o := NewRunOptions() cmd := &cobra.Command{ Use: `describe <--host [HOST ID]> <--service [SERIVCE]>`, DisableFlagsInUseLine: true, Short: "Describe metrics by host, service", Example: "", Run: func(cmd *cobra.Command, args []string) { o.complete(f, cmd) o.run(f, cmd, args) }, } addRunFlags(cmd, o) return cmd }
html_generator.rs
// MIT License // // Copyright (c) 2022 Florian Mantz // // 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. // use log::error; use regex::Regex; use serde::Serialize; use std::f64; use std::fmt::Display; use std::fs; use std::fs::File; use std::io::{prelude::*, BufReader, Write}; use std::path::Path; use crate::chart_config::*; use crate::json_parser::*; use crate::lib_constants::*; pub struct HtmlGenerator {} #[derive(Serialize, Debug)] struct Point<N> { x: String, y: N, } #[derive(Serialize, Debug)] #[serde(rename_all = "camelCase")] struct Dataset<N> { label: String, data: Vec<Point<N>>, fill: bool, border_color: String, } struct Chart<N> { datasets: Vec<Dataset<N>>, median: f64, average: f64, standard_deviation: f64, } impl HtmlGenerator { pub fn write_html( data: &[ParsedEntry], template_file: &Path, output_file: &Path, config_latency_chart: &ChartConfig<u32>, config_jitter_chart: &ChartConfig<u32>, config_download_chart: &ChartConfig<f64>, config_upload_chart: &ChartConfig<f64>, ) { //create chart data; let lat_chart = create_latency_chart(data, config_latency_chart); let jit_chart = create_jitter_chart(data, config_jitter_chart); let dwn_chart = create_download_chart(data, config_download_chart); let upl_chart = create_upload_chart(data, config_upload_chart); let stat_lat = create_statistic_table(ID_LATENCY, config_latency_chart, &lat_chart); let stat_jit = create_statistic_table(ID_JITTER, config_jitter_chart, &jit_chart); let stat_dwn = create_statistic_table(ID_DOWNLOAD, config_download_chart, &dwn_chart); let stat_upl = create_statistic_table(ID_UPLOAD, config_upload_chart, &upl_chart); let statistics_table = create_statistics_table(stat_lat, stat_jit, stat_dwn, stat_upl); //transform chart data to json let response_time_dss: Vec<&Dataset<u32>> = lat_chart .datasets .iter() .chain(jit_chart.datasets.iter()) .collect(); let throughput_dss: Vec<&Dataset<f64>> = dwn_chart .datasets .iter() .chain(upl_chart.datasets.iter()) .collect(); let response_time_json = serde_json::to_string(&response_time_dss).unwrap(); let throughput_json = serde_json::to_string(&throughput_dss).unwrap(); write_output_file( template_file, output_file, data, &statistics_table, &response_time_json, &throughput_json, ); } } fn write_output_file( template_file: &Path, output_file: &Path, data: &[ParsedEntry], statistics_table: &str, response_time_json: &str, throughput_json: &str, ) { if data.is_empty() { let msg = "No data found!"; log_and_fail(msg); } // write files: let mut out_file: File = match fs::OpenOptions::new() .append(false) .create(true) .write(true) .truncate(true) //overwrite .open(output_file) { Err(e) => { let msg = format!("Could not create file message= '{}'", e); log_and_fail(&msg); } Ok(f) => f, }; let find_replacement = Regex::new(REPLACEMENT_REGEX).unwrap(); match fs::File::open(template_file) { Err(e) => { let msg = format!("Could not open template file message= '{}'", e); log_and_fail(&msg); } Ok(f) => { let template_reader = BufReader::new(f); for maybe_line in template_reader.lines() { match maybe_line { Err(e) => { let msg = format!("Could not read template file message= '{}'", e); log_and_fail(&msg); } Ok(line) => { match find_replacement.find(&line) { Some(mat) => { //matched string without '${' and '}' let matched_string = &line[mat.start() + 2..mat.end() - 1]; let prefix = &line[0..mat.start()]; let suffix = &line[mat.end()..line.len()]; match matched_string { REPLACEMENT_ID_RAW_DATA => { write_raw_data(data, &mut out_file, prefix, suffix); } REPLACEMENT_ID_STATISTICS => { handle_failed_write(writeln!( &mut out_file, "{}{}{}", prefix, statistics_table, suffix )); } REPLACEMENT_ID_RESPONSE_TIMES => { handle_failed_write(writeln!( &mut out_file, "{}{}{}", prefix, response_time_json, suffix )); } REPLACEMENT_ID_THROUGHPUT => { handle_failed_write(writeln!( &mut out_file, "{}{}{}", prefix, throughput_json, suffix )); } _ => { //ignore: handle_failed_write(writeln!(&mut out_file, "{}", &line)); } }; } None => { handle_failed_write(writeln!(&mut out_file, "{}", &line)); } }; } } } } } match out_file.flush() { Err(e) => { let msg = format!("Could not write file message= '{}'", e); log_and_fail(&msg); } Ok(()) => (), }; } fn log_and_fail(msg: &str) -> ! { //return never type! error!("{}", msg); panic!("{}", msg); } fn handle_failed_write(rs: Result<(), std::io::Error>) { if let Err(e) = rs { let msg = format!("Write failed message= '{}'", e); error!("{}", msg); panic!("{}", msg); } } /// prepare data to show latency: fn create_latency_chart(data: &[ParsedEntry], config: &ChartConfig<u32>) -> Chart<u32> { let points: Vec<Point<u32>> = data .iter() .map(|d| { let x: String = d.timestamp.format(DATE_TIME_FORMAT).to_string(); let y = *d .performance .as_ref() .map(|p| &p.latency) .unwrap_or(&config.default_value); Point { x, y } }) .collect(); let dss = create_datasets(config, points); let mut values: Vec<f64> = data .iter() .flat_map(|d| { let y = d.performance.as_ref().map(|p| p.latency); y }) .map(|x| x as f64) .collect(); create_chart(dss, &mut values, MULT_DIV_NEUTRAL) } /// prepare data to show jitter: fn create_jitter_chart(data: &[ParsedEntry], config: &ChartConfig<u32>) -> Chart<u32> { let points: Vec<Point<u32>> = data .iter() .map(|d| { let x: String = d.timestamp.format(DATE_TIME_FORMAT).to_string(); let y: u32 = d .performance .as_ref() .map(|p| p.jitter.unwrap_or(config.default_value)) .unwrap(); Point { x, y } }) .collect(); let dss = create_datasets(config, points); let mut values: Vec<f64> = data .iter() .flat_map(|d| { let y = d.performance.as_ref().map(|p| p.jitter); y }) .flatten() .map(|x| x as f64) .collect(); create_chart(dss, &mut values, MULT_DIV_NEUTRAL) } /// prepare data to download speed: fn create_download_chart(data: &[ParsedEntry], config: &ChartConfig<f64>) -> Chart<f64> { let points: Vec<Point<f64>> = data .iter() .map(|d| { let x: String = d.timestamp.format(DATE_TIME_FORMAT).to_string();
.unwrap() / MEGA_BIT_FACTOR; Point { x, y } }) .collect(); let dss = create_datasets(config, points); let mut values: Vec<f64> = data .iter() .flat_map(|d| { let y = d.performance.as_ref().map(|p| p.download); y }) .flatten() .collect(); create_chart(dss, &mut values, MEGA_BIT_FACTOR) } /// prepare data to upload speed: fn create_upload_chart(data: &[ParsedEntry], config: &ChartConfig<f64>) -> Chart<f64> { let points: Vec<Point<f64>> = data .iter() .map(|d| { let x: String = d.timestamp.format(DATE_TIME_FORMAT).to_string(); let y: f64 = d .performance .as_ref() .map(|p| p.upload.unwrap_or(config.default_value)) .unwrap() / MEGA_BIT_FACTOR; Point { x, y } }) .collect(); let dss = create_datasets(config, points); let mut values: Vec<f64> = data .iter() .flat_map(|d| { let y = d.performance.as_ref().map(|p| p.upload); y }) .flatten() .collect(); create_chart(dss, &mut values, MEGA_BIT_FACTOR) } // helper methods: fn create_datasets<T: Copy>(config: &ChartConfig<T>, points: Vec<Point<T>>) -> Vec<Dataset<T>> { let expected_ds = config .expected_value .as_ref() .map(|c| create_dataset_expected(c, &points)); let ds = create_dataset(config, points); vec![Some(ds), expected_ds].into_iter().flatten().collect() } /// dataset containing the real data: fn create_dataset<T: Copy>(config: &ChartConfig<T>, points: Vec<Point<T>>) -> Dataset<T> { Dataset { label: String::from(&config.label), data: points, fill: config.fill, border_color: String::from(&config.border_color), } } /// dataset for expected line: fn create_dataset_expected<T: Copy>(config: &ExpectedConfig<T>, points: &[Point<T>]) -> Dataset<T> { let default_x = &String::from(""); let first_x: &str = points.first().map(|p| &p.x).unwrap_or(default_x); let last_x: &str = points.last().map(|p| &p.x).unwrap_or(default_x); Dataset { label: String::from(&config.label), data: vec![ Point { x: String::from(first_x), y: config.value, }, Point { x: String::from(last_x), y: config.value, }, ], fill: config.fill, border_color: String::from(&config.border_color), } } /// create chart an do some statistics: fn create_chart<T: Copy>(dss: Vec<Dataset<T>>, values: &mut Vec<f64>, divisor: f64) -> Chart<T> { let med: f64 = median(values); //is also sorting! let avg: f64 = average(values); let std: f64 = standard_deviation(values, &avg); Chart { datasets: dss, median: med / divisor, average: avg / divisor, standard_deviation: std / divisor, } } fn median(numbers: &mut Vec<f64>) -> f64 { numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); let mid: usize = numbers.len() / 2; numbers[mid] } fn average(numbers: &[f64]) -> f64 { let len: f64 = numbers.len() as f64; numbers.iter().sum::<f64>() / len } fn standard_deviation(numbers: &[f64], average: &f64) -> f64 { let variance: f64 = numbers .iter() .map(|x| { let y = x - average; y * y }) .sum::<f64>(); let d = numbers.len() as f64; f64::sqrt(variance / d) } fn write_raw_data(data: &[ParsedEntry], out_file: &mut File, prefix: &str, suffix: &str) { handle_failed_write(writeln!( out_file, "{}<table id=\"rawdata\">\ <tr>\ <th class=\"ts\">timestamp</th>\ <th class=\"client\">client-wlan</th>\ <th class=\"client\">client-ip</th>\ <th class=\"client\">client-lat</th>\ <th class=\"client\">client-lon</th>\ <th class=\"client\">client-isp</th>\ <th class=\"server\">server-name</th>\ <th class=\"server\">server-sponsor</th>\ <th class=\"server\">server-distance (km)</th>\ <th class=\"server\">server-host</th>\ <th class=\"performance\">latency (ms)</th>\ <th class=\"performance\">jitter (ms)</th>\ <th class=\"performance\">download_config</th>\ <th class=\"performance\">upload_config</th>\ <th class=\"performance\">download (bits per second)</th>\ <th class=\"performance\">upload (bits per second)</th>\ </tr>", prefix )); for entry in data { handle_failed_write(writeln!( out_file, "<tr> <td class=\"ts\">{}</td>", entry.timestamp.format(DATE_TIME_FORMAT) )); if let Some(client) = &entry.client { handle_failed_write(writeln!( out_file, "<td class=\"client\">{}</td> <td class=\"client\">{}</td> <td class=\"client\">{}</td> <td class=\"client\">{}</td> <td class=\"client\">{}</td>", to_string(&client.wlan), client.ip, client.lat, client.lon, client.isp )); } else { handle_failed_write(writeln!( out_file, "<td colspan=\"5\" class=\"client\"></td>" )); } if let Some(server) = &entry.server { handle_failed_write(writeln!( out_file, "<td class=\"server\">{}</td> <td class=\"server\">{}</td> <td class=\"server\">{}</td> <td class=\"server\">{}</td>", server.name, server.sponsor, server.distance, server.host )); } else { handle_failed_write(writeln!( out_file, "<td colspan=\"4\" class=\"server\"></td>" )); } if let Some(performance) = &entry.performance { handle_failed_write(writeln!( out_file, "<td class=\"performance\">{}</td> <td class=\"performance\">{}</td> <td class=\"performance\">{}</td> <td class=\"performance\">{}</td> <td class=\"performance\">{}</td> <td class=\"performance\">{}</td>", performance.latency, to_string(&performance.jitter), to_string(&performance.download_config), to_string(&performance.upload_config), to_string(&performance.download), to_string(&performance.upload) )); } else { handle_failed_write(writeln!( out_file, "<td colspan=\"6\" class=\"performance\"></td>" )); } handle_failed_write(writeln!(out_file, "</tr>")); } handle_failed_write(writeln!(out_file, "</table>{}", suffix)); } fn to_string<T: Display>(op: &Option<T>) -> String { if let Some(p) = op { format!("{}", p) } else { String::new() } } fn create_statistics_table( stat_lat: String, stat_jit: String, stat_dwn: String, stat_upl: String, ) -> String { format!( "<table class=\"statistic\">\ <tr>\ <td>{}</td>\ <td>{}</td>\ </tr>\ <tr>\ <td>{}</td>\ <td>{}</td>\ </tr>\ </table>", stat_lat, stat_jit, stat_dwn, stat_upl ) } fn create_statistic_table<N: Copy>( id: &str, chart_config: &ChartConfig<N>, chart: &Chart<N>, ) -> String { format!( "<table class=\"statistic_{}\">\ <tr>\ <th colspan=\"3\">{}</th>\ </tr> <tr>\ <th>{}</th>\ <th>{}</th>\ <th>{}</th>\ </tr> <tr>\ <td>{:.3}</td>\ <td>{:.3}</td>\ <td>{:.3}</td>\ </tr>\ </table>\ ", id, chart_config.label, STATISTIC_MEDIAN, STATISTIC_AVG, STATISTIC_STD, chart.median, chart.average, chart.standard_deviation ) }
let y: f64 = d .performance .as_ref() .map(|p| p.download.unwrap_or(config.default_value))
javaAppLayer.go
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package opsworks import ( "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/go/pulumi" ) // Provides an OpsWorks Java application layer resource. // // > This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/opsworks_java_app_layer.html.markdown. type JavaAppLayer struct { s *pulumi.ResourceState } // NewJavaAppLayer registers a new resource with the given unique name, arguments, and options. func NewJavaAppLayer(ctx *pulumi.Context, name string, args *JavaAppLayerArgs, opts ...pulumi.ResourceOpt) (*JavaAppLayer, error) { if args == nil || args.StackId == nil
inputs := make(map[string]interface{}) if args == nil { inputs["appServer"] = nil inputs["appServerVersion"] = nil inputs["autoAssignElasticIps"] = nil inputs["autoAssignPublicIps"] = nil inputs["autoHealing"] = nil inputs["customConfigureRecipes"] = nil inputs["customDeployRecipes"] = nil inputs["customInstanceProfileArn"] = nil inputs["customJson"] = nil inputs["customSecurityGroupIds"] = nil inputs["customSetupRecipes"] = nil inputs["customShutdownRecipes"] = nil inputs["customUndeployRecipes"] = nil inputs["drainElbOnShutdown"] = nil inputs["ebsVolumes"] = nil inputs["elasticLoadBalancer"] = nil inputs["installUpdatesOnBoot"] = nil inputs["instanceShutdownTimeout"] = nil inputs["jvmOptions"] = nil inputs["jvmType"] = nil inputs["jvmVersion"] = nil inputs["name"] = nil inputs["stackId"] = nil inputs["systemPackages"] = nil inputs["useEbsOptimizedInstances"] = nil } else { inputs["appServer"] = args.AppServer inputs["appServerVersion"] = args.AppServerVersion inputs["autoAssignElasticIps"] = args.AutoAssignElasticIps inputs["autoAssignPublicIps"] = args.AutoAssignPublicIps inputs["autoHealing"] = args.AutoHealing inputs["customConfigureRecipes"] = args.CustomConfigureRecipes inputs["customDeployRecipes"] = args.CustomDeployRecipes inputs["customInstanceProfileArn"] = args.CustomInstanceProfileArn inputs["customJson"] = args.CustomJson inputs["customSecurityGroupIds"] = args.CustomSecurityGroupIds inputs["customSetupRecipes"] = args.CustomSetupRecipes inputs["customShutdownRecipes"] = args.CustomShutdownRecipes inputs["customUndeployRecipes"] = args.CustomUndeployRecipes inputs["drainElbOnShutdown"] = args.DrainElbOnShutdown inputs["ebsVolumes"] = args.EbsVolumes inputs["elasticLoadBalancer"] = args.ElasticLoadBalancer inputs["installUpdatesOnBoot"] = args.InstallUpdatesOnBoot inputs["instanceShutdownTimeout"] = args.InstanceShutdownTimeout inputs["jvmOptions"] = args.JvmOptions inputs["jvmType"] = args.JvmType inputs["jvmVersion"] = args.JvmVersion inputs["name"] = args.Name inputs["stackId"] = args.StackId inputs["systemPackages"] = args.SystemPackages inputs["useEbsOptimizedInstances"] = args.UseEbsOptimizedInstances } s, err := ctx.RegisterResource("aws:opsworks/javaAppLayer:JavaAppLayer", name, true, inputs, opts...) if err != nil { return nil, err } return &JavaAppLayer{s: s}, nil } // GetJavaAppLayer gets an existing JavaAppLayer resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetJavaAppLayer(ctx *pulumi.Context, name string, id pulumi.ID, state *JavaAppLayerState, opts ...pulumi.ResourceOpt) (*JavaAppLayer, error) { inputs := make(map[string]interface{}) if state != nil { inputs["appServer"] = state.AppServer inputs["appServerVersion"] = state.AppServerVersion inputs["autoAssignElasticIps"] = state.AutoAssignElasticIps inputs["autoAssignPublicIps"] = state.AutoAssignPublicIps inputs["autoHealing"] = state.AutoHealing inputs["customConfigureRecipes"] = state.CustomConfigureRecipes inputs["customDeployRecipes"] = state.CustomDeployRecipes inputs["customInstanceProfileArn"] = state.CustomInstanceProfileArn inputs["customJson"] = state.CustomJson inputs["customSecurityGroupIds"] = state.CustomSecurityGroupIds inputs["customSetupRecipes"] = state.CustomSetupRecipes inputs["customShutdownRecipes"] = state.CustomShutdownRecipes inputs["customUndeployRecipes"] = state.CustomUndeployRecipes inputs["drainElbOnShutdown"] = state.DrainElbOnShutdown inputs["ebsVolumes"] = state.EbsVolumes inputs["elasticLoadBalancer"] = state.ElasticLoadBalancer inputs["installUpdatesOnBoot"] = state.InstallUpdatesOnBoot inputs["instanceShutdownTimeout"] = state.InstanceShutdownTimeout inputs["jvmOptions"] = state.JvmOptions inputs["jvmType"] = state.JvmType inputs["jvmVersion"] = state.JvmVersion inputs["name"] = state.Name inputs["stackId"] = state.StackId inputs["systemPackages"] = state.SystemPackages inputs["useEbsOptimizedInstances"] = state.UseEbsOptimizedInstances } s, err := ctx.ReadResource("aws:opsworks/javaAppLayer:JavaAppLayer", name, id, inputs, opts...) if err != nil { return nil, err } return &JavaAppLayer{s: s}, nil } // URN is this resource's unique name assigned by Pulumi. func (r *JavaAppLayer) URN() *pulumi.URNOutput { return r.s.URN() } // ID is this resource's unique identifier assigned by its provider. func (r *JavaAppLayer) ID() *pulumi.IDOutput { return r.s.ID() } // Keyword for the application container to use. Defaults to "tomcat". func (r *JavaAppLayer) AppServer() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["appServer"]) } // Version of the selected application container to use. Defaults to "7". func (r *JavaAppLayer) AppServerVersion() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["appServerVersion"]) } // Whether to automatically assign an elastic IP address to the layer's instances. func (r *JavaAppLayer) AutoAssignElasticIps() *pulumi.BoolOutput { return (*pulumi.BoolOutput)(r.s.State["autoAssignElasticIps"]) } // For stacks belonging to a VPC, whether to automatically assign a public IP address to each of the layer's instances. func (r *JavaAppLayer) AutoAssignPublicIps() *pulumi.BoolOutput { return (*pulumi.BoolOutput)(r.s.State["autoAssignPublicIps"]) } // Whether to enable auto-healing for the layer. func (r *JavaAppLayer) AutoHealing() *pulumi.BoolOutput { return (*pulumi.BoolOutput)(r.s.State["autoHealing"]) } func (r *JavaAppLayer) CustomConfigureRecipes() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["customConfigureRecipes"]) } func (r *JavaAppLayer) CustomDeployRecipes() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["customDeployRecipes"]) } // The ARN of an IAM profile that will be used for the layer's instances. func (r *JavaAppLayer) CustomInstanceProfileArn() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["customInstanceProfileArn"]) } // Custom JSON attributes to apply to the layer. func (r *JavaAppLayer) CustomJson() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["customJson"]) } // Ids for a set of security groups to apply to the layer's instances. func (r *JavaAppLayer) CustomSecurityGroupIds() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["customSecurityGroupIds"]) } func (r *JavaAppLayer) CustomSetupRecipes() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["customSetupRecipes"]) } func (r *JavaAppLayer) CustomShutdownRecipes() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["customShutdownRecipes"]) } func (r *JavaAppLayer) CustomUndeployRecipes() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["customUndeployRecipes"]) } // Whether to enable Elastic Load Balancing connection draining. func (r *JavaAppLayer) DrainElbOnShutdown() *pulumi.BoolOutput { return (*pulumi.BoolOutput)(r.s.State["drainElbOnShutdown"]) } // `ebsVolume` blocks, as described below, will each create an EBS volume and connect it to the layer's instances. func (r *JavaAppLayer) EbsVolumes() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["ebsVolumes"]) } // Name of an Elastic Load Balancer to attach to this layer func (r *JavaAppLayer) ElasticLoadBalancer() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["elasticLoadBalancer"]) } // Whether to install OS and package updates on each instance when it boots. func (r *JavaAppLayer) InstallUpdatesOnBoot() *pulumi.BoolOutput { return (*pulumi.BoolOutput)(r.s.State["installUpdatesOnBoot"]) } // The time, in seconds, that OpsWorks will wait for Chef to complete after triggering the Shutdown event. func (r *JavaAppLayer) InstanceShutdownTimeout() *pulumi.IntOutput { return (*pulumi.IntOutput)(r.s.State["instanceShutdownTimeout"]) } // Options to set for the JVM. func (r *JavaAppLayer) JvmOptions() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["jvmOptions"]) } // Keyword for the type of JVM to use. Defaults to `openjdk`. func (r *JavaAppLayer) JvmType() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["jvmType"]) } // Version of JVM to use. Defaults to "7". func (r *JavaAppLayer) JvmVersion() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["jvmVersion"]) } // A human-readable name for the layer. func (r *JavaAppLayer) Name() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["name"]) } // The id of the stack the layer will belong to. func (r *JavaAppLayer) StackId() *pulumi.StringOutput { return (*pulumi.StringOutput)(r.s.State["stackId"]) } // Names of a set of system packages to install on the layer's instances. func (r *JavaAppLayer) SystemPackages() *pulumi.ArrayOutput { return (*pulumi.ArrayOutput)(r.s.State["systemPackages"]) } // Whether to use EBS-optimized instances. func (r *JavaAppLayer) UseEbsOptimizedInstances() *pulumi.BoolOutput { return (*pulumi.BoolOutput)(r.s.State["useEbsOptimizedInstances"]) } // Input properties used for looking up and filtering JavaAppLayer resources. type JavaAppLayerState struct { // Keyword for the application container to use. Defaults to "tomcat". AppServer interface{} // Version of the selected application container to use. Defaults to "7". AppServerVersion interface{} // Whether to automatically assign an elastic IP address to the layer's instances. AutoAssignElasticIps interface{} // For stacks belonging to a VPC, whether to automatically assign a public IP address to each of the layer's instances. AutoAssignPublicIps interface{} // Whether to enable auto-healing for the layer. AutoHealing interface{} CustomConfigureRecipes interface{} CustomDeployRecipes interface{} // The ARN of an IAM profile that will be used for the layer's instances. CustomInstanceProfileArn interface{} // Custom JSON attributes to apply to the layer. CustomJson interface{} // Ids for a set of security groups to apply to the layer's instances. CustomSecurityGroupIds interface{} CustomSetupRecipes interface{} CustomShutdownRecipes interface{} CustomUndeployRecipes interface{} // Whether to enable Elastic Load Balancing connection draining. DrainElbOnShutdown interface{} // `ebsVolume` blocks, as described below, will each create an EBS volume and connect it to the layer's instances. EbsVolumes interface{} // Name of an Elastic Load Balancer to attach to this layer ElasticLoadBalancer interface{} // Whether to install OS and package updates on each instance when it boots. InstallUpdatesOnBoot interface{} // The time, in seconds, that OpsWorks will wait for Chef to complete after triggering the Shutdown event. InstanceShutdownTimeout interface{} // Options to set for the JVM. JvmOptions interface{} // Keyword for the type of JVM to use. Defaults to `openjdk`. JvmType interface{} // Version of JVM to use. Defaults to "7". JvmVersion interface{} // A human-readable name for the layer. Name interface{} // The id of the stack the layer will belong to. StackId interface{} // Names of a set of system packages to install on the layer's instances. SystemPackages interface{} // Whether to use EBS-optimized instances. UseEbsOptimizedInstances interface{} } // The set of arguments for constructing a JavaAppLayer resource. type JavaAppLayerArgs struct { // Keyword for the application container to use. Defaults to "tomcat". AppServer interface{} // Version of the selected application container to use. Defaults to "7". AppServerVersion interface{} // Whether to automatically assign an elastic IP address to the layer's instances. AutoAssignElasticIps interface{} // For stacks belonging to a VPC, whether to automatically assign a public IP address to each of the layer's instances. AutoAssignPublicIps interface{} // Whether to enable auto-healing for the layer. AutoHealing interface{} CustomConfigureRecipes interface{} CustomDeployRecipes interface{} // The ARN of an IAM profile that will be used for the layer's instances. CustomInstanceProfileArn interface{} // Custom JSON attributes to apply to the layer. CustomJson interface{} // Ids for a set of security groups to apply to the layer's instances. CustomSecurityGroupIds interface{} CustomSetupRecipes interface{} CustomShutdownRecipes interface{} CustomUndeployRecipes interface{} // Whether to enable Elastic Load Balancing connection draining. DrainElbOnShutdown interface{} // `ebsVolume` blocks, as described below, will each create an EBS volume and connect it to the layer's instances. EbsVolumes interface{} // Name of an Elastic Load Balancer to attach to this layer ElasticLoadBalancer interface{} // Whether to install OS and package updates on each instance when it boots. InstallUpdatesOnBoot interface{} // The time, in seconds, that OpsWorks will wait for Chef to complete after triggering the Shutdown event. InstanceShutdownTimeout interface{} // Options to set for the JVM. JvmOptions interface{} // Keyword for the type of JVM to use. Defaults to `openjdk`. JvmType interface{} // Version of JVM to use. Defaults to "7". JvmVersion interface{} // A human-readable name for the layer. Name interface{} // The id of the stack the layer will belong to. StackId interface{} // Names of a set of system packages to install on the layer's instances. SystemPackages interface{} // Whether to use EBS-optimized instances. UseEbsOptimizedInstances interface{} }
{ return nil, errors.New("missing required argument 'StackId'") }
builder-tests.ts
import { path } from "tns-core-modules/file-system"; import { _loadPage } from "tns-core-modules/ui/builder"; import { assertEqual, assertNull, assertThrows } from "../../tk-unit"; const COMPONENT_MODULE = "component-module"; const MISSING_MODULE = "missing-module"; const LABEL = "label"; const testDir = "ui/builder"; function getViewComponent(componentModule: string) { const moduleNamePath = path.join(testDir, componentModule); const fileName = path.join(testDir, `${componentModule}.xml`); const view = _loadPage(moduleNamePath, fileName); return view; } export function
() { const view = getViewComponent(COMPONENT_MODULE); const actualModule = view._moduleName; assertEqual(actualModule, COMPONENT_MODULE, `View<${view}> is NOT root component of module <${COMPONENT_MODULE}>.`); } export function test_view_is_NOT_module_root_component() { const view = getViewComponent(COMPONENT_MODULE); const nestedView = view.getViewById(`${LABEL}`); const undefinedModule = nestedView._moduleName; assertNull(undefinedModule, `View<${nestedView}> should NOT be a root component of a module.`); } export function test_load_component_from_missing_module_throws() { assertThrows(() => getViewComponent(MISSING_MODULE), "Loading component from a missing module SHOULD throw an error.") }
test_view_is_module_root_component
ledger_info_test.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use super::*; use crate::{change_set::ChangeSet, LibraDB}; use libra_temppath::TempPath; use libra_types::{ proptest_types::{AccountInfoUniverse, LedgerInfoWithSignaturesGen}, transaction::Version, }; use proptest::{collection::vec, prelude::*}; use std::path::Path; fn arb_ledger_infos_with_sigs() -> impl Strategy<Value = Vec<LedgerInfoWithSignatures>> { ( any_with::<AccountInfoUniverse>(3), vec((any::<LedgerInfoWithSignaturesGen>(), 1..10usize), 1..10), ) .prop_map(|(mut universe, gens)| { let ledger_infos_with_sigs: Vec<_> = gens .into_iter() .map(|(ledger_info_gen, block_size)| { ledger_info_gen.materialize(&mut universe, block_size) }) .collect(); assert_eq!(get_first_epoch(&ledger_infos_with_sigs), 0); ledger_infos_with_sigs }) } fn get_first_epoch(ledger_infos_with_sigs: &[LedgerInfoWithSignatures]) -> u64 { ledger_infos_with_sigs .first() .unwrap() .ledger_info() .epoch() } fn get_last_epoch(ledger_infos_with_sigs: &[LedgerInfoWithSignatures]) -> u64 { ledger_infos_with_sigs.last().unwrap().ledger_info().epoch() } fn get_last_version(ledger_infos_with_sigs: &[LedgerInfoWithSignatures]) -> Version { ledger_infos_with_sigs .last() .unwrap() .ledger_info() .version() } fn get_num_epoch_changes(ledger_infos_with_sigs: &[LedgerInfoWithSignatures]) -> usize { ledger_infos_with_sigs .iter() .filter(|x| x.ledger_info().next_epoch_info().is_some()) .count() } proptest! { #![proptest_config(ProptestConfig::with_cases(20))] #[test] fn test_get_first_n_epoch_change_ledger_infos( (ledger_infos_with_sigs, start_epoch, end_epoch, limit) in arb_ledger_infos_with_sigs() .prop_flat_map(|ledger_infos_with_sigs| { let first_epoch = get_first_epoch(&ledger_infos_with_sigs); let last_epoch = get_last_epoch(&ledger_infos_with_sigs); ( Just(ledger_infos_with_sigs), first_epoch..=last_epoch, ) }) .prop_flat_map(|(ledger_infos_with_sigs, start_epoch)| { let last_epoch = get_last_epoch(&ledger_infos_with_sigs); let num_epoch_changes = get_num_epoch_changes(&ledger_infos_with_sigs); assert!(num_epoch_changes >= 1); ( Just(ledger_infos_with_sigs), Just(start_epoch), (start_epoch..=last_epoch), 1..num_epoch_changes * 2, ) }) ) { let tmp_dir = TempPath::new(); let db = set_up(&tmp_dir, &ledger_infos_with_sigs); let (actual, more) = db .ledger_store .get_first_n_epoch_change_ledger_infos(start_epoch, end_epoch, limit) .unwrap(); let all_epoch_changes = ledger_infos_with_sigs .into_iter() .filter(|ledger_info_with_sigs| { let li = ledger_info_with_sigs.ledger_info(); start_epoch <= li.epoch() && li.epoch() < end_epoch && li.next_epoch_info().is_some() }) .collect::<Vec<_>>(); prop_assert_eq!(more, all_epoch_changes.len() > limit); let expected: Vec<_> = all_epoch_changes.into_iter().take(limit).collect(); prop_assert_eq!(actual, expected); } #[test] fn test_get_epoch( (ledger_infos_with_sigs, version) in arb_ledger_infos_with_sigs() .prop_flat_map(|ledger_infos_with_sigs| { let last_version = get_last_version(&ledger_infos_with_sigs); ( Just(ledger_infos_with_sigs), 0..=last_version, ) }) ) { let tmp_dir = TempPath::new(); let db = set_up(&tmp_dir, &ledger_infos_with_sigs); let actual = db.ledger_store.get_epoch(version).unwrap(); // Find the first LI that is at or after version. let index = ledger_infos_with_sigs .iter() .position(|x| x.ledger_info().version() >= version) .unwrap(); let expected = ledger_infos_with_sigs[index].ledger_info().epoch(); prop_assert_eq!(actual, expected); } #[test] fn test_get_epoch_info(ledger_infos_with_sigs in arb_ledger_infos_with_sigs()) { let tmp_dir = TempPath::new(); let db = set_up(&tmp_dir, &ledger_infos_with_sigs);
for li_with_sigs in ledger_infos_with_sigs { let li = li_with_sigs.ledger_info(); if li.next_epoch_info().is_some() { assert_eq!( db.ledger_store.get_epoch_info(li.epoch()+1).unwrap(), *li.next_epoch_info().unwrap(), ); } } } #[test] fn test_get_startup_info( (ledger_infos_with_sigs, txn_infos) in arb_ledger_infos_with_sigs() .prop_flat_map(|lis| { let num_committed_txns = get_last_version(&lis) as usize + 1; ( Just(lis), vec(any::<TransactionInfo>(), num_committed_txns..num_committed_txns + 10), ) }) ) { let tmp_dir = TempPath::new(); let db = set_up(&tmp_dir, &ledger_infos_with_sigs); put_transaction_infos(&db, &txn_infos); let startup_info = db.ledger_store.get_startup_info().unwrap().unwrap(); let latest_li = ledger_infos_with_sigs.last().unwrap().ledger_info(); assert_eq!(startup_info.latest_ledger_info, *ledger_infos_with_sigs.last().unwrap()); let expected_epoch_info = if latest_li.next_epoch_info().is_none() { Some(db.ledger_store.get_epoch_info(latest_li.epoch()).unwrap()) } else { None }; assert_eq!(startup_info.latest_epoch_info, expected_epoch_info); let committed_version = get_last_version(&ledger_infos_with_sigs); assert_eq!( startup_info.committed_tree_state.account_state_root_hash, txn_infos[committed_version as usize].state_root_hash(), ); let synced_version = (txn_infos.len() - 1) as u64; if synced_version > committed_version { assert_eq!( startup_info.synced_tree_state.unwrap().account_state_root_hash, txn_infos.last().unwrap().state_root_hash(), ); } else { assert!(startup_info.synced_tree_state.is_none()); } } } fn set_up(path: &impl AsRef<Path>, ledger_infos_with_sigs: &[LedgerInfoWithSignatures]) -> LibraDB { let db = LibraDB::new_for_test(path); let store = &db.ledger_store; // Write LIs to DB. let mut cs = ChangeSet::new(); ledger_infos_with_sigs .iter() .map(|info| store.put_ledger_info(info, &mut cs)) .collect::<Result<Vec<_>>>() .unwrap(); store.db.write_schemas(cs.batch).unwrap(); store.set_latest_ledger_info(ledger_infos_with_sigs.last().unwrap().clone()); db } fn put_transaction_infos(db: &LibraDB, txn_infos: &[TransactionInfo]) { let mut cs = ChangeSet::new(); db.ledger_store .put_transaction_infos(0, txn_infos, &mut cs) .unwrap(); db.db.write_schemas(cs.batch).unwrap() }
assert!(db.ledger_store.get_epoch_info(0).is_err());
test_binary_ops_eval.rs
extern crate autograd as ag; extern crate ndarray; use ag::tensor_ops as T; #[test] fn scalar_add() { ag::run(|g| { let z: ag::Tensor<f64> = 3. + T::ones(&[3], g) + 2.; assert_eq!(z.eval(g), Ok(ndarray::arr1(&[6., 6., 6.]).into_dyn())); }); } #[test] fn scalar_sub() { ag::run(|g| { let ref z: ag::Tensor<f64> = 3. - T::ones(&[3], g) - 2.; assert_eq!(z.eval(g), Ok(ndarray::arr1(&[0., 0., 0.]).into_dyn())); }); } #[test] fn scalar_mul() { ag::run(|g| { let ref z: ag::Tensor<f64> = 3. * T::ones(&[3], g) * 2.; assert_eq!(z.eval(g), Ok(ndarray::arr1(&[6., 6., 6.]).into_dyn())); }); } #[test] fn scalar_div() { ag::run(|g| { let z: ag::Tensor<f64> = 3. / T::ones(&[3], g) / 2.; assert_eq!(z.eval(g), Ok(ndarray::arr1(&[1.5, 1.5, 1.5]).into_dyn())); }); } #[test] fn slice() { ag::run(|g| { let ref a: ag::Tensor<f32> = T::zeros(&[4, 4], g); let ref b = T::slice(a, &[0, 0], &[-1, 2]); // numpy equivalent is a[:, 0:2] assert_eq!(b.eval(g).unwrap().shape(), &[4, 2]); }); } #[test] fn slice_negative()
{ ag::run(|g| { let ref a: ag::Tensor<f32> = T::zeros(&[4, 4], g); let ref b = T::slice(a, &[0, 0], &[-2, 2]); // numpy equivalent is a[:-1, :2] assert_eq!(b.eval(g).unwrap().shape(), &[3, 2]); let ref b = T::slice(a, &[0, 0], &[-3, 2]); // numpy equivalent is a[:-1, :2] assert_eq!(b.eval(g).unwrap().shape(), &[2, 2]); }); }
IntersectingPointsCache.type.ts
import type { Vector3 } from "three";
export type IntersectingPointsCache = { [key: string]: Vector3; };
commandline.py
# mmpdb - matched molecular pair database generation and analysis # # Copyright (c) 2015-2017, F. Hoffmann-La Roche Ltd. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of F. Hoffmann-La Roche Ltd. nor the names of # its contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from __future__ import print_function, absolute_import import argparse from . import __version__ as _version from . import config from . import smarts_aliases from . import do_help #### Help construct the argparser from .config import nonnegative_int, cutoff_list def add_single_dataset_arguments(parser): parser.add_argument("databases", nargs=1, metavar="DATABASE", help="location of the database (eg, 'csd.mmpdb')") def add_multiple_dataset_arguments(parser): parser.add_argument("databases", nargs="*", metavar="DATABASE", help="zero or more database locations (eg, 'csd.mmpdb')") def add_single_property_arguments(parser): parser.add_argument("--property", "-p", metavar="NAME", required=True, help="property to use") def add_multiple_properties_default_all(parser): parser.add_argument("--property", "-p", metavar="NAME", action="append", help="property to use") parser.add_argument("--no-properties", action="store_true", help="don't use any properties") parser.set_defaults(all_properties=False) def add_in_memory(parser): p.add_argument("--in-memory", action="store_true", help="load the SQLite database into memory before use (requires APSW)") #### parser = argparse.ArgumentParser( description="Matched-molecular pair database loader", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" The 'mmpdb' program implements a set of subcommands to work with a matched molecular pair database. The commands are roughly categorized as "analysis" and "admin" commands. The analysis commands fragment a SMILES database, index the fragments into matched molecular pairs into a local SQLite database, import molecular properties into a database, and searches the database for possible transformations or predictions. The admin commands are used to administer a database. They include include ways to list the available data sets, dump the data as a SMILES file or CSV file, update new properties, and re-aggregate the rule dataset should any property values change. For a short description of how to generate and use a dataset: % mmpdb help-analysis For a short description of how to adminster a database: % mmpdb help-admin The "help-*-format" commands (like "help-property-format") give more details about the given format. In addition, pass the "--help" option to a given command to see the full list of options for the command. """) parser.add_argument("--quiet", "-q", action="store_true", help="do not show progress or status information") parser.add_argument('--version', action="version", version="%(prog)s " + _version) subparsers = parser.add_subparsers() #### mmpdb fragment p = fragment_parser = subparsers.add_parser( "fragment", help="fragment structures in a SMILES file based on its rotatable bonds", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Fragment molecules in a SMILES file by breaking on 'cut bonds', as matched by --cut-smarts. Cut up to --num-cuts bonds. Don't fragment molecules with more than --max-rotatable-bonds bonds or --max-heavies heavy atoms. Don't create multiple cuts if the fragments in the constant part have less than --min-heavies-per-const-frag atoms. The input structures come from a SMILES file. By default the fields are whitespace delimited, where the first column contains the SMILES and the second contains the identifier. Use --delimiter to change the delimiter type, and --has-header to skip the first line. See "mmpdb help-smiles-format" for more details. The input SMILES strings are pre-processed to remove salts before fragmenting. The default uses the default RDKit SmilesRemover. Use --salt-remover to specify alternative rules, or use the special name '<none>' to not remove any salts. By default the fragmentation method uses 4 threads, which gives a nearly 4-fold speedup. Use --num-jobs change the number of threads. It can take a while to generate fragments. Suppose you want to update the compound set every week, where only a few records are added or changed. Most of the fragments will be the same between those two data sets. What you can do is specify the old fragments file as a --cache so the fragmentation method can re-use the old fragmentation, assuming the structure hasn't changed for a given record. Examples: 1) Fragment the SMILES file to produce a fragments file % mmpdb fragment CHEMBL_thrombin_Ki_IC50.smi -o CHEMBL_thrombin_Ki_IC50.fragments 2) Read from a gzip-compressed tab-delimited SMILES file. Use 8 threads to fragment the structures. Save the results to dataset.fragments.gz . % mmpa fragment --delimiter tab dataset.smi.gz --num-jobs 8 \\ -o dataset.fragments.gz 3) Fragment the SMILES in 'dataset.smi.gz'. Reuse fragment information from the cache file 'old_dataset.fragments.gz' if possible, instead of computing the fragments from scratch each time. Save the results to 'new_dataset.fragments.gz'. % mmpa fragment --cache old_dataset.fragments.gz dataset.smi.gz \\ -o new_dataset.fragments.gz """ + smarts_aliases.get_epilog("--cut-smarts", smarts_aliases.cut_smarts_aliases) ) def fragment_command(parser, args): from . import do_fragment do_fragment.fragment_command(parser, args) config.add_fragment_arguments(p) p.add_argument("--cache", metavar="SOURCE", help="get fragment parameters and previous fragment information from SOURCE") p.add_argument("--num-jobs", "-j", metavar="N", type=config.positive_int, default=4, help="number of jobs to process in parallel (default: 4)") p.add_argument("-i", "--in", metavar="FORMAT", dest="format", choices=("smi", "smi.gz"), help="input structuture format (one of 'smi', 'smi.gz')") p.add_argument("--delimiter", default="whitespace", # 'native' is hidden support for for chemfp compatability choices=("whitespace", "to-eol", "comma", "tab", "space", "native"), help="SMILES file delimiter style (one of 'whitespace' (default), 'to-eol', 'comma', 'tab', or 'space')") p.add_argument("--has-header", default=False, action="store_true", help="skip the first line, which is the header line") p.add_argument("--output", "-o", metavar="FILENAME", help="save the fragment data to FILENAME (default=stdout)") p.add_argument("--out", metavar="FORMAT", choices=("fragments", "fragments.gz", "fraginfo", "fraginfo.gz"), help="output format. One of 'fragments' or 'fragments.gz'. " "If not present, guess from the filename, and default to 'fragments'") p.add_argument("structure_filename", nargs="?", default=None, help="SMILES filename (default: read from stdin)") p.set_defaults(command=fragment_command, subparser=p) #### mmpdb smifrag p = smifrag_parser = subparsers.add_parser( "smifrag", help="fragment a SMILES and print the each variable and constant fragment", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Fragment a SMILES and print details about each variable and constant fragment and how they are connected. """ + smarts_aliases.get_epilog("--cut-smarts", smarts_aliases.cut_smarts_aliases) ) def smifrag_command(parser, args): from . import do_fragment do_fragment.smifrag_command(parser, args) config.add_fragment_arguments(p) p.set_defaults(command=smifrag_command, subparser=p) p.add_argument("smiles", metavar="SMILES", help="SMILES string to fragment") #### mmpdb index p = index_parser = subparsers.add_parser( "index", help="index fragments and find matched molecular pairs", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Read a fragments file, match the molecular pairs, and save the results to a mmpdb database file. Use "mmpdb help-analysis" for an explanation about the terminology and process. A matched molecular pair connects structure 1, made of variable part 1 (V1) and constant part C, with structure 2, made of variable part 2 (V2) and constant part C, via the transformation V1>>V2. The following uses |X| to mean the number of heavy (non-isotopic hydrogen) atoms in X. There are several ways to restrict which fragmentations or pairings to allow. The --min-variable-heavies and --max-variable-heavies options set limits to |V1| and |V2|. The --min-variable-ratio and --max-variable-ratio set limits on |V1|/|V1+C| and |V2|/|V2+C|. The --max-heavies-transf option sets a maximum bound on abs(|V1|-|V2|). The --max-frac-trans places a limit on the number of atoms which take part in the transformation, defined as |V+C(r)|/|V+C| where C(r) is the number of atoms in the circular environment of the constant part for a given radius r. C(0) is 0. The goal is to be able to exchange transforms and environment fingerprints but minimize the relative amount of information revealed about the constant part. The --max-radius option's default is set to 5 and can be changed to numbers less than 5, if you want to save DB space. By default, mmpdb indexes all transformations per pair. To only index one minimal transformation per pair, use "--smallest-transformation-only". Note that this option is independent of --max-radius, e.g. environment fingerprints will still be created for the smallest transformation. The filter --max-variable-heavies is always used, with a default value of 10. Specify "none" if you want no limit. The transformation can be described as V1>>V2 or V2>>V1. By default only one transformation is output; the one with the smallest value, alphabetically. The --symmetric flag outputs both directions. The optional --properties file contains physical property information in a table format. Use "mmpdb help-property-format" for details. If a property file is specified during the indexing stage then only those compounds with at least one property are indexed. See "mmpdb loadprops" for a way to specify properties after indexing. By default the output will be saved in 'mmpdb' format using a filename based on the input fragment filename and with the extension '.mmpdb'. Use --output to specify an output filename. Use --out to change the output format. By default the alternate formats will write to stdout. The 'mmpdb' format is based on a SQLite database. The 'mmpa' format stores the same data in a text file with tab-separated fields. The 'csv' format is a tab-separated table with the columns: SMILES1 SMILES2 id1 id2 V1>>V2 C The csv format does not include property information. The mmpa and csv format also support gzip compression. The --title specifies a string which goes into the database. The idea is to store a label or short description to be displayed to the user. If not given, it uses a short description based on the input filename. The --memory option writes a summary of memory use to stderr if the 'psutil' package is available. (If not, it prints a warning message that it needs the package.) This was used during development to figure out ways to reduce overall memory use. The experimental --in-memory option loads the SQLite database into memory before using it. This option requires the third-party APSW SQLite adapater and will not work with Python's built-in SQLite module. The transformation analysis does many scattered database lookups. In some cases, like with a network file system, it can be faster to load the entire database into memory where random access is fast, rather than do a lot of disk seeks. Examples: 1) Index 'csd.fragments' and save the results to 'csd.mmpdb'. The title will be "MMPs from 'csd.fragments'". % mmpdb index csd.fragments 2) Index 'csd.fragments', use properties from 'MP.csv' and limit the pair matching to compounds listed in the CSV file, set the title to 'CSD MP', and save the results to 'csd_MP.mmpdb'. % mmpdb index csd.fragments --properties MP.csv --title "CSD MP" -o csd_MP.mmpdb 3) Limit the indexing to variable terms which have at least 12 heavy atoms and where the size of the variable is no more than 40% of the entire structure, and save the transformation in both A>>B and B>>A (symmetric) forms: % mmpdb index CHEMBL_Thrombin_logD.fragments --symmetric \\ --max-variable-ratio 0.4 --max-variable-heavies 12 \\ --title "CHEMBL ratio 40%" --output CHEMBL_ratio_40.mmpdb """) def index_command(parser, args): from . import do_index do_index.index_command(parser, args) config.add_index_options(p) p.add_argument("--symmetric", "-s", action="store_true", help="Output symmetrically equivalent MMPs, i.e output both cmpd1,cmpd2, " "SMIRKS:A>>B and cmpd2,cmpd1, SMIRKS:B>>A") p.add_argument("--smallest-transformation-only", action="store_true", help="Ignore all transformations that can be reduced to smaller fragments") p.add_argument("--properties", metavar="FILENAME", help="File containing the identifiers to use and optional physical properties") p.add_argument("--output", "-o", metavar="FILENAME", help=("save the fragment data to FILENAME. " "Default for mmpdb is based on the fragment filename, " "otherwise stdout.")) p.add_argument("--out", metavar="FORMAT", choices=("csv", "csv.gz", "mmpa", "mmpa.gz", "mmpdb"), help="Output format. One of 'mmpdb' (default), 'csv', 'csv.gz', 'mmpa' or 'mmpa.gz'. " "If not present, guess from the filename, and default to 'mmpdb'") p.add_argument("--title", help="A short description of the dataset. If not given, base the title on the filename") p.add_argument("--memory", action="store_true", help="Report a summary of the memory use") p.add_argument("fragment_filename", nargs="?", default=None, help="SMILES filename (default: read from stdin)") p.set_defaults(command=index_command, subparser=p) ######## Work with a database #### mmpdb list p = list_parser = subparsers.add_parser( "list", help="summarize the contents of zero or more databases", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" In the simplest case, look in the current directory for files matching '*.mmpdb', open each one, and print a terse summary of the information in the database. % mmpdb list Name #cmpds #rules #pairs #envs #stats |-------- Title ---------| Properties CHEMBL_thrombin_Ki_IC50.mmpdb 2985 29513 258294 199631 0 thrombin Ki IC50 csd.mmpdb 16843 2525166 15328608 15199376 15199376 MMPs from 'csd.fragments' MP The output is a set of columns. The first line is the header. The first column contains the database name. The next columns contain the number of compounds, number of rules, number of pairs (a rule may have many matched molecular pairs), number of rule environments (a rule may have many environments), and number of property statistics for the rule environments. After that is the user-defined title field, followed by a list of the property or activity names stored. The first entry, for thrombin, has no properties, which is why it also has no property statistics. The second entry has a 'MP' property, which in this case means 'melting point'. The specific database location(s) can be given on the command-line. The '--all' option shows more detailed information about the dataset. The following gives more detailed information about the database 'csd.mmpdb': % mmpdb list --all csd.mmpdb Name #cmpds #rules #pairs #envs #stats |-------- Title --------| Properties csd.mmpdb 16843 2525166 15328608 15199376 15199376 MMPs from 'csd.fragments' MP Created: 2017-05-26 15:07:07.775249 #compounds/property: 16843/MP #smiles for rules: 81538 for constants: 21520 Fragment options: cut_smarts: [#6+0;!$(*=,#[!#6])]!@!=!#[!#0;!#1;!$([CH2]);!$([CH3][CH2])] max_heavies: 100 max_rotatable_bonds: 10 method: chiral num_cuts: 3 rotatable_smarts: [!$([NH]!@C(=O))&!D1&!$(*#*)]-&!@[!$([NH]!@C(=O))&!D1&!$(*#*)] salt_remover: <default> Index options: max_variable_heavies: 10 symmetric: False 'Created' shows the creation time. '#compounds/property' shows how many compounds have a given property, for each of the available properties. The '#smiles' line says how many distinct SMILES strings are used for the rules and the constants tables. 'Fragment options' and 'Index options' are, I think, self-explanatory. The count fields (like the number of compounds and rules) are pre-computed and stored in the database. If the database is updated incorrectly, it is possible for the cached information to be invalid. Use '--recount' to have SQLite compute the values directly from the database contents. """) def list_command(parser, args): from . import do_database do_database.list_command(parser, args) p.add_argument("--all", "-a", action="store_true", help="list all information about the dataset") p.add_argument("--quiet", "-q", action="store_true", help="do not show progress or status information") p.add_argument("--recount", action="store_true", help="count the table sizes directly, instead of using cached data") add_multiple_dataset_arguments(p) p.set_defaults(command=list_command, subparser=p) #### mmpdb loadprops p = loadprops_parser = subparsers.add_parser( "loadprops", help="load properties for existing structures", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Load structure property values from a CSV into a data set. The property file contains a data table. Here is an example: ID MP CHR1 CHR2 GEJYOJ 3 71 31.3 ACIDUL 5 65 67.2 KIXRIS 5 * * SOFWIV01 5 83 79.3 The fields should be tab separated. For full details use "mmpdb help-property-format". If the given property value already exists in the database then the existing database value will be updated. Otherwise loadprops will create a new property record. If an identifier isn't in the database then its values will be ignored. After importing the data, the corresponding aggregate values for the rules will be recalculated. Example: % mmpdb loadprops --properties MP.csv mmpdb.db """ ) def loadprops_command(parser, args): from . import do_database do_database.loadprops_command(parser, args) add_single_dataset_arguments(p) p.add_argument("--properties", "-p", nargs="?", metavar="FILENAME", help="File containing the identifiers to use and optional physical properties") p.set_defaults(command=loadprops_command, subparser=p) #### mmpdb reaggregate # Commented out because it doesn't seem useful ''' p = reaggregate_parser = subparsers.add_parser( "reaggregate", help="recompute the rule statistics", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Compute the rule statistics using the property values in the database. Normally this will not change anything because 'mmpdb index' (if --properties are given) and 'mmpdb loadprops' will compute the statistics automatically, and those are the only two commands which can change rule properties. This might be useful if you update property values in the database yourself, and want mmpdb to handle the update of the aggregate statistics. """) def reaggregate_command(parser, args): from . import do_database do_database.reaggregate_command(parser, args) add_single_dataset_arguments(p) p.add_argument("--property", "-p", metavar="NAME", action="append", help="property to use (default reaggregates all properties)") p.set_defaults(command=reaggregate_command, subparser=p, no_properties=False, all_properties=False) ''' #### mmpdb transform p = transform_parser = subparsers.add_parser( "transform", help="transform a structure", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Apply transforms from an mmpdb database to an input structure. Include possible property change statistics for the resulting products. Specify the input structure using --smiles. This will be fragmented using the fragmentation parameters appropriate for the database. By default all fragmentations will be considered. Use --min-variable-size and --min-constant-size to set minimum heavy counts for the constant and variable parts of the fragment. By default the matching algorithm evaluates all radii around the local environment of the constant's connection points. The scoring function (see below) decides which radius is best. Use the --min-radius option to require the environment match up to at least N bonds away. Use --min-pairs to require that a transformation have at least N pairs in the database. The default is 0, which allows all transformations. For more complex filters, use the --where option. It takes a Python expression which is allowed to use any of the following variable names: rule_id, is_reversed, from_smiles, from_num_heavies, to_smiles, to_num_heavies, smirks, rule_environment_id, radius, fingerprint_id, fingerprint, rule_environment_statistics_id, count, avg, std, kurtosis, skewness, min, q1, median, q3, max, paired_t, p_value, is_bidirectional as well as the Python variables None, True, and False. The values come from the transformation rule, the rule environment, and the rule environment statistics. The --where expression is evaluated independently for each property. There is currently no way to specify a different expression for different properties, or for the expression to know which property is being evaluated. Sometimes multiple transformations of an input structure lead to the same final product. When this happens, the possible transformation are put into bins based on their number of pairs. By default the first bin contains transforms with at least 10 pairs, the second contains transforms with at least 5 pairs, and the third contains transforms with any pairs. The bin thresholds can be changed with the --rule-selection-cutoffs option, which contains a list of comma-separated integers. The default is equivalent to '--rule-selection-cutoffs 10,5,0'. A scoring function is used to decide which transformation to use from a bin. The transformation with the largest score is selected. Use the --score option to define an alternate scoring function as a Python expression. The default is equivalant to: ((ninf if std is None else -std), radius, from_num_heavies, from_smiles) This expression may contain any of the variables in the --where option, as well as 'inf' and 'ninf', which can be used as equivalent for positive and negative infinity in numerical comparisons. The default expression selects the smallest standard deviation, breaks ties using the largest radius, breaks ties with the most atoms changed, then breaks ties arbitrarily by the substructure SMILES of the left side of the transformation. Note: if the --where or --score expressions start with a '-' then the command-line parser may confuse it with a command-line option. In that case, use a space as the first character in the expression, or enclose the expression with parentheses. Specify a SMARTS pattern with --substructure to limit the output to products containing the specified substructure. By default the output will contain predicted property changes for all of the properties in the database. Use --property to select specific options. Use it once for each property you want to evaluate. For example, to get the results for both MW and MP use: --property MW --property MP If you do not want property information in the output, specify --no-properties. The transformation output by default is sent to stdout. Use '--output' to specify an output filename. The output is a tab-delimited CSV file where the first line is a header. The first column contains a sequential identifier, and the second column contains the SMILES string for the product. Next come the property columns. Each property gets 17 columns of output. The column headers are prefixed with the property name followed by a "_" and then the name of the data stored in the column. (There is currently no way to limit the output to specific columns, other than to change the code in do_transform.py.) The "*_from_smiles" and "*_to_smiles" columns describe the transformation. Sometimes multiple transforms lead to the same product and cause different properties to have different transformations. The "*_radius" and "*_fingerprint" columns contain the environment fingerprint radius and fingerprint string. The remaining columns contain the database row id for the rule environment record, and the statistics information for the given property. The '--explain' option writes debug information to stderr. The '--times' options reports timing information about the major stages to stderr. The transform code runs in a single thread by default. It has been parallelized, though it is not highly scalable. Use '--jobs' to specify the number of threads (really, "processes") to use. Examples: 1) Generate all of the products of diphenyl ether using the MMP transforms in the 'csd.mmpdb' database where there are are least 30 pairs. Also include the predicted effects on the 'MP' property. (Note: the output is reformatted and trimmed for use as help text.) % mmpdb transform csd.mmpdb --smiles 'c1ccccc1Oc1ccccc1' --min-pairs 30 -p MP ID SMILES MP_from_smiles MP_to_smiles MP_radius \\ 1 Brc1ccc(Oc2ccccc2)cc1 [*:1]c1ccccc1 [*:1]c1ccc(Br)cc1 0 2 COc1ccc(Oc2ccccc2)cc1 [*:1]c1ccccc1 [*:1]c1ccc(OC)cc1 0 3 COc1ccccc1 [*:1]c1ccccc1 [*:1]C 0 MP_fingerprint MP_rule_environment_id \\ 59SlQURkWt98BOD1VlKTGRkiqFDbG6JVkeTJ3ex3bOA 947 59SlQURkWt98BOD1VlKTGRkiqFDbG6JVkeTJ3ex3bOA 4560 59SlQURkWt98BOD1VlKTGRkiqFDbG6JVkeTJ3ex3bOA 90 MP_count MP_avg MP_std MP_kurtosis MP_skewness MP_min MP_q1 \\ 34 14.5290 30.990 -0.267780 0.32663 -66 -7.0 56 8.7143 38.945 7.013600 1.81870 -172 -10.0 106 -23.4430 36.987 1.563800 0.65077 -159 -44.0 MP_median MP_q3 MP_max MP_paired_t MP_p_value 15.5 37.0 67 -2.7338 9.987200e-03 10.5 32.5 79 -1.6745 9.971500e-02 -20.0 -3.0 49 6.5256 2.447100e-09 2) Require a standard deviation of no larger than 4.5 and give priority to transformation with at least 20 pairs before following the normal cutoffs. The --score here matches the default scoring function. % mmpdb transform csd.mmpdb --smiles 'c1ccccc1Oc1ccccc1' \\ --where 'std is not None and std < 4.5' \\ --rule-selection-cutoffs '20,10,5,0' \\ --score '((ninf if std is None else -std), radius, from_num_heavies, from_smiles)' \\ --property MP """) def transform_command(parser, args): from . import do_analysis do_analysis.transform_command(parser, args) add_single_dataset_arguments(p) p.add_argument("--smiles", "-s", required=True, help="the base structure to transform") p.add_argument("--min-variable-size", type=nonnegative_int, metavar="N", default=0, help="require at least N atoms in the variable fragment (default: 0)") p.add_argument("--max-variable-size", type=nonnegative_int, metavar="N", default=9999, help="allow at most N atoms in the variable fragment (default: 9999)") p.add_argument("--min-constant-size", type=nonnegative_int, metavar="N", default=0, help="require at least N atoms in the constant fragment (default: 0)") p.add_argument("--min-radius", "-r", choices=("0", "1", "2", "3", "4", "5"), default="0", help="fingerprint radius (default: 0)") p.add_argument("--min-pairs", type=nonnegative_int, metavar="N", default=0, help="require at least N pairs in the transformation to report a product (default: 0)") p.add_argument("--substructure", "-S", metavar="SMARTS", help="require the substructure pattern in the product") add_multiple_properties_default_all(p) config.add_rule_selection_arguments(p) add_in_memory(p) p.add_argument("--jobs", "-j", type=config.positive_int, default=1, help="number of jobs to run in parallel (default: 1)") p.add_argument("--explain", action="store_true", help="explain each of the steps in the transformation process") p.add_argument("--output", "-o", metavar="FILENAME", help="save the output to FILENAME (default=stdout)") p.add_argument("--times", action="store_true", help="report timing information for each step") p.set_defaults(command=transform_command, subparser=p) #### mmpdb predict p = predict_parser = subparsers.add_parser( "predict", help="predict the effect of a structural transformation", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" --smiles SMILES, -s SMILES the base structure to transform --reference SMILES the reference structure --property NAME, -p NAME property to use --value VALUE, -v VALUE the property value for the reference Predict the change in a specified '--property' going from the '--reference' SMILES to the input '--smiles', using the matched molecular pair 'DATABASE.' If several rules lead to the same input '--smiles', use the one prioritized by '--rule-selection-cutoffs' and '--score'. By default the predicted delta value and standard deviation will be written to stdout, in the format: predicted delta: -4.91667 +/- 18.0477 If the optional reference property '--value' is specified then the predicted output value will also be included, in the format: predicted delta: -4.91667 predicted value: 7.08333 +/- 18.0477 The '--where' option takes a Python expression which describes which transforms to consider. The '--rule-selection-cutoffs' and '--score' options select which transform to use if multiple transforms produce the same product. If the third-party APSW module is available then the '--in-memory' option loads the SQLite database into memory before doing the prediction. The '--explain' and '--times' options send respectively debug and timing information to stderr. More details are available from 'mmpdb transform --help'. Use '--save-details' to save details about the possible transformations to two tab-separated CSV files. The filenames are of the form ${PREFIX}_rules.txt and ${PREFIX}_pairs.txt, where ${PREFIX} is specified by --prefix and by default is 'pred_details'. The '${PREFIX}_rules.txt' file contains the following columns for each transform, based on the rule, rule environment, and rule environment statistics: rule_id, rule_environment_id, radius, fingerprint, from_smiles, to_smiles, count, avg, std, kurtosis, skewness, min, q1, median, q3, max, paired_t, p_value The '${PREFIX}_pairs.txt' file contains the following columns for each of the pairs in each of the transforms: from_smiles, to_smiles, radius, fingerprint, lhs_public_id, rhs_public_id, lhs_smiles, rhs_smiles, lhs_value, rhs_value, delta Examples: 1) Predict the effect of substituting a sulfur in diphenyl ether if the known melting point is 12C: % mmpdb predict csd.mmpdb --smiles c1ccccc1Sc1ccccc1 \\ --reference c1ccccc1Oc1ccccc1 --property MP --value 12.0 predicted delta: +4.91667 predicted value: 16.9167 +/- 18.0477 2) Do the same calculation and save details about the transformations to O_to_S_rules.txt and O_to_S_pairs.txt: % mmpdb predict csd.mmpdb --smiles c1ccccc1Sc1ccccc1 \\ --reference c1ccccc1Oc1ccccc1 --property MP --value 12.0 \\ --save-details --prefix O_to_S """ ) # predict a property for a structure given the known property for # another structure, using the MMPA database to identify the possible # transformations and predicted property changes. The input to the # tool will be the reference structure, the prediction structure, and # the properties to predict. There will also be an option to report # pairs with the same transformations and their properties. def predict_command(parser, args): from . import do_analysis do_analysis.predict_command(parser, args) add_single_dataset_arguments(p) p.add_argument("--smiles", "-s", metavar="SMILES", required=True, help="the base structure to transform") p.add_argument("--reference", metavar="SMILES", required=True, help="the reference structure") add_single_property_arguments(p) config.add_rule_selection_arguments(p) p.add_argument("--value", "-v", type=float, default=None, help="the property value for the reference") add_in_memory(p) p.add_argument("--explain", action="store_true", help="explain each of the steps in the prediction process") p.add_argument("--save-details", action="store_true", help="save information about the transformation pairs and statistics to two CSV files") p.add_argument("--prefix", metavar="STRING", default="pred_detail", help="prefix to use for each CSV filename (default: 'pred_details')") p.add_argument("--times", action="store_true", help="report timing information for each step") p.set_defaults(command=predict_command, subparser=p) ##### mmpdb smicat p = smicat_parser = subparsers.add_parser( "smicat", help="write the database compounds to a SMILES file", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Write information about the compounds in DATABASE, formatted as a SMILES file. Each compound has two associated SMILES, the input SMILES used as input to fragmentation, and the canonical SMILES string from RDKit after input processing (typically desalting and structure normalization). By default the output uses the processed SMILES. Use '--input-smiles' to use the input SMILES string. By default the output SMILES file is written to stdout. Use '--output' to save the output to the named file. Examples: 1) Write the cleaned-up structures as a SMILES file to stdout: % mmpdb smicat csd.mmpdb 2) Save the structures to the file "original.smi", and use the input SMILES instead of the de-salted SMILES: % python mmpdb smicat csd.mmpdb -o original.smi --input-smiles """) def smicat_command(parser, args): from . import do_database do_database.smicat_command(parser, args) add_single_dataset_arguments(p) p.add_argument("--input-smiles", action="store_true", help="Use the input SMILES instead of the cleaned-up SMILES") p.add_argument("--output", "-o", help="output filename (default is stdout)") p.set_defaults(command=smicat_command, subparser=p) ##### mmpdb propcat p = propcat_parser = subparsers.add_parser( "propcat", help="write the database properties to a properties file", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Write information about the properties for the compounds in DATABASE, formatted as a property file. Use `mmpdb help-property-file` for details about the property file format. The output from this command is a tab-delimited CSV file where the first column has the head "ID" and contains the compound identifier. The other columns contain property information for each compound. The column title is the property name. By default there is one column for each property in the databases, and the one row for each compound with at least one property. Use '--property' to limit the output to a specific property, or use it multiple times to specify multiple property names to output. Use '--all' to list all of the compounds, even if the compound has none of the specified properties. The character "*" will be use if a listed compound is missing a given property. Examples: 1) Write all of the properties to stdout: % mmpdb propcat CHEMBL_thrombin_Ki_IC50.mmpdb 2) Write the "MP" property to "MP.properties": % mmpdb propcat csd.mmpdb --property MP -o MP.properties 3) Write the compound identifiers only to stdout: % mmpdb propcat csd.mmpdb --no-properties --all """) def propcat_command(parser, args):
add_single_dataset_arguments(p) add_multiple_properties_default_all(p) p.add_argument("--all", action="store_true", help="include compounds which have no properties") p.add_argument("--output", "-o", help="output filename (default is stdout)") p.set_defaults(command=propcat_command, subparser=p) #### mmpdb drop_index p = drop_index_parser = subparsers.add_parser( "drop_index", help="drop the database indices", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Drop the database indices from DATABASE. This is mostly used during development. The index takes about 1/2 of the size of the database, so if you need to save space for data exchange or archival purposes then you might drop the indices, and re-create them later when needed. """) def drop_index_command(parser, args): from . import do_database do_database.drop_index_command(parser, args) add_single_dataset_arguments(p) p.set_defaults(command=drop_index_command, subparser=p) #### mmpdb create_index p = create_index_parser = subparsers.add_parser( "create_index", help="create the database indices", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Create the database indices for DATABASE. This is mostly used during development. """) def create_index_command(parser, args): from . import do_database do_database.create_index_command(parser, args) add_single_dataset_arguments(p) p.set_defaults(command=create_index_command, subparser=p) ##### Help do_help.add_help_commands(subparsers) def main(argv=None): # if there are extra arguments in the subparser then # args = parser.parse_args(argv) # will pass the extra fields back to the main parser, # which generates an un-informative top-level error # message instead of a more specific subparser error. # Instead, I get the known arguments, and send any # remaining subarguments to the correct subparser. # (See http://stackoverflow.com/questions/25333847/argparse-subcommand-error-message # for more details.) parsed_args, remaining_argv = parser.parse_known_args(argv) if remaining_argv: subparser = getattr(parsed_args, "subparser", parser) subparser.error("unrecognized arguments: %s" % (" ".join(remaining_argv))) # Python 2 raises an exception. Python 3 doesn't. # This means I can provide a slightly better message. command = getattr(parsed_args, "command", None) if command is None: parser.error("too few arguments. Use --help for more information.") parsed_args.command(parsed_args.subparser, parsed_args) if __name__ == "__main__": main()
from . import do_database do_database.propcat_command(parser, args)
figuras2.js
function calcularAreaCuadrado() { const input = document.getElementById("InputCuadrado");
//alert(area); const resultado = document.getElementById("Resultado"); resultado.innerText = "El área es " + area; }
const value = input.value; const area = value*value;
build.rs
//! build.rs for `libafl_targets` use std::env; use std::path::Path; fn
() { let out_dir = env::var_os("OUT_DIR").unwrap(); let out_dir = out_dir.to_string_lossy().to_string(); //let out_dir_path = Path::new(&out_dir); let _src_dir = Path::new("src"); //std::env::set_var("CC", "clang"); //std::env::set_var("CXX", "clang++"); #[cfg(any(feature = "sancov_value_profile", feature = "sancov_cmplog"))] { println!("cargo:rerun-if-changed=src/sancov_cmp.c"); let mut sancov_cmp = cc::Build::new(); #[cfg(feature = "sancov_value_profile")] sancov_cmp.define("SANCOV_VALUE_PROFILE", "1"); #[cfg(feature = "sancov_cmplog")] sancov_cmp.define("SANCOV_CMPLOG", "1"); sancov_cmp .file(_src_dir.join("sancov_cmp.c")) .compile("sancov_cmp"); } #[cfg(feature = "libfuzzer")] { println!("cargo:rerun-if-changed=src/libfuzzer_compatibility.c"); cc::Build::new() .file(_src_dir.join("libfuzzer_compatibility.c")) .compile("libfuzzer_compatibility"); } println!("cargo:rustc-link-search=native={}", &out_dir); println!("cargo:rerun-if-changed=build.rs"); }
main
karma-build-dist.conf.js
// Karma configuration for running unit tests on dist folder // http://karma-runner.github.io/0.10/config/configuration-file.html module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude basePath: '../../', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'app/bower_components/jquery/dist/jquery.js', 'app/bower_components/angular/angular.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/angular-sanitize/angular-sanitize.js', 'dist/build/*.js', 'test/unit/date/*.js', 'test/unit/decimal/*.js', 'test/unit/duration/*.js', 'test/unit/email/*.js', 'test/unit/icon/*.js', 'test/unit/integer/*.js', 'test/unit/money/*.js', 'test/unit/percent/*.js', 'test/unit/phone/*.js', 'test/unit/rating/*.js', 'test/unit/rich/*.js', 'test/unit/text/*.js', 'test/unit/time/*.js', 'test/unit/toggle/*.js', 'test/unit/url/*.js' ], // list of files to exclude exclude: [ ], // test results reporter to use // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' reporters: ['progress'], // web server port port: 9876, // cli runner port runnerPort: 9100, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox
// - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome', 'Safari', 'Firefox', 'Opera'], // browsers: ['PhantomJS'], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
// - Opera
test_mapping_service.py
import unittest from server.services.mapping_service import MappingService, Task, MappingServiceError, TaskStatus, \ ProjectService, NotFound, StatsService, MappingNotAllowed, UserLicenseError from server.models.dtos.mapping_dto import MappedTaskDTO, LockTaskDTO from server.models.postgis.task import TaskHistory, TaskAction, User from unittest.mock import patch, MagicMock from server import create_app class TestMappingService(unittest.TestCase): task_stub = Task lock_task_dto = LockTaskDTO mapped_task_dto = MappedTaskDTO mapping_service = None def setUp(self): self.app = create_app() self.ctx = self.app.app_context() self.ctx.push() test_user = User() test_user.id = 123456 test_user.username = 'Thinkwhere' self.task_stub = Task() self.task_stub.id = 1 self.task_stub.project_id = 1 self.task_stub.task_status = 0 self.task_stub.locked_by = 123456 self.task_stub.lock_holder = test_user self.lock_task_dto = LockTaskDTO() self.lock_task_dto.user_id = 123456 self.mapped_task_dto = MappedTaskDTO() self.mapped_task_dto.status = TaskStatus.MAPPED.name self.mapped_task_dto.user_id = 123456 def tearDown(self): self.ctx.pop() @patch.object(Task, 'get') def test_get_task_raises_error_if_task_not_found(self, mock_task): mock_task.return_value = None with self.assertRaises(NotFound): MappingService.get_task(12, 12) @patch.object(MappingService, 'get_task') def test_lock_task_for_mapping_raises_error_if_task_in_invalid_state(self, mock_task): # Arrange self.task_stub.task_status = TaskStatus.MAPPED.value mock_task.return_value = self.task_stub # Act / Assert
@patch.object(ProjectService, 'is_user_permitted_to_map') @patch.object(MappingService, 'get_task') def test_lock_task_for_mapping_raises_error_if_user_already_has_locked_task(self, mock_task, mock_project): # Arrange mock_task.return_value = self.task_stub mock_project.return_value = False, MappingNotAllowed.USER_ALREADY_HAS_TASK_LOCKED # Act / Assert with self.assertRaises(MappingServiceError): MappingService.lock_task_for_mapping(self.lock_task_dto) @patch.object(ProjectService, 'is_user_permitted_to_map') @patch.object(MappingService, 'get_task') def test_lock_task_for_mapping_raises_error_if_user_has_not_accepted_license(self, mock_task, mock_project): # Arrange mock_task.return_value = self.task_stub mock_project.return_value = False, MappingNotAllowed.USER_NOT_ACCEPTED_LICENSE # Act / Assert with self.assertRaises(UserLicenseError): MappingService.lock_task_for_mapping(self.lock_task_dto) @patch.object(MappingService, 'get_task') def test_unlock_of_not_locked_for_mapping_raises_error(self, mock_task): # Arrange mock_task.return_value = self.task_stub # Act / Assert with self.assertRaises(MappingServiceError): MappingService.unlock_task_after_mapping(MagicMock()) @patch.object(MappingService, 'get_task') def test_cant_unlock_a_task_you_dont_own(self, mock_task): # Arrange self.task_stub.task_status = TaskStatus.LOCKED_FOR_MAPPING.value self.task_stub.locked_by = 12 mock_task.return_value = self.task_stub # Act / Assert with self.assertRaises(MappingServiceError): MappingService.unlock_task_after_mapping(self.mapped_task_dto) @patch.object(MappingService, 'get_task') def test_if_new_state_not_acceptable_raise_error(self, mock_task): # Arrange self.task_stub.task_status = TaskStatus.LOCKED_FOR_MAPPING.value mock_task.return_value = self.task_stub self.mapped_task_dto.status = TaskStatus.LOCKED_FOR_VALIDATION.name # Act / Assert with self.assertRaises(MappingServiceError): MappingService.unlock_task_after_mapping(self.mapped_task_dto) @patch.object(Task, 'get_per_task_instructions') @patch.object(StatsService, 'update_stats_after_task_state_change') @patch.object(Task, 'update') @patch.object(TaskHistory, 'get_last_status') @patch.object(TaskHistory, 'update_task_locked_with_duration') @patch.object(MappingService, 'get_task') def test_unlock_with_comment_sets_history(self, mock_task, mock_history, mock_update, mock_stats, mock_instructions, mock_state): # Arrange self.task_stub.task_status = TaskStatus.LOCKED_FOR_MAPPING.value self.mapped_task_dto.comment = 'Test comment' mock_task.return_value = self.task_stub mock_state.return_value = TaskStatus.LOCKED_FOR_MAPPING # Act test_task = MappingService.unlock_task_after_mapping(self.mapped_task_dto) # Assert self.assertEqual(TaskAction.COMMENT.name, test_task.task_history[0].action) self.assertEqual(test_task.task_history[0].action_text, 'Test comment') @patch.object(Task, 'get_per_task_instructions') @patch.object(StatsService, 'update_stats_after_task_state_change') @patch.object(Task, 'update') @patch.object(TaskHistory, 'get_last_status') @patch.object(TaskHistory, 'update_task_locked_with_duration') @patch.object(MappingService, 'get_task') def test_unlock_with_status_change_sets_history(self, mock_task, mock_history, mock_update, mock_stats, mock_instructions, mock_state): # Arrange self.task_stub.task_status = TaskStatus.LOCKED_FOR_MAPPING.value mock_task.return_value = self.task_stub mock_state.return_value = TaskStatus.LOCKED_FOR_MAPPING # Act test_task = MappingService.unlock_task_after_mapping(self.mapped_task_dto) # Assert self.assertEqual(TaskAction.STATE_CHANGE.name, test_task.task_history[0].action) self.assertEqual(test_task.task_history[0].action_text, TaskStatus.MAPPED.name) self.assertEqual(TaskStatus.MAPPED.name, test_task.task_status) @patch.object(TaskHistory, 'get_last_action') def test_task_is_undoable_if_last_change_made_by_you(self, last_action): # Arrange task_history = TaskHistory(1, 1, 1) task_history.user_id = 1 last_action.return_value = task_history task = Task() task.task_status = TaskStatus.MAPPED.value task.mapped_by = 1 # Act is_undoable = MappingService._is_task_undoable(1, task) # Assert self.assertTrue(is_undoable) @patch.object(TaskHistory, 'get_last_action') def test_task_is_not_undoable_if_last_change_not_made_by_you(self, last_action): # Arrange task_history = TaskHistory(1, 1, 1) task_history.user_id = 2 last_action.return_value = task_history task = Task() task.task_status = TaskStatus.MAPPED.value task.mapped_by = 1 # Act is_undoable = MappingService._is_task_undoable(1, task) # Assert self.assertFalse(is_undoable)
with self.assertRaises(MappingServiceError): MappingService.lock_task_for_mapping(self.lock_task_dto)
normalize.ts
import { _getColumnSchema, _isIndex } from "./schema"; import catLabelSort from "../util/catLabelSort"; import { unassignedCategoryLabel, overflowCategoryLabel, globalConfig, } from "../globals"; import { Dataframe } from "../util/dataframe"; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. export function normalizeResponse( field: string, schema: any, // eslint-disable-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. response: Dataframe ): Dataframe { /** * There are a number of assumptions in the front-end about data typing and data * characteristics. This routine will normalize a server response dataframe * to match front-end expectations and UI conventions. This includes cast/transform * of the data and schema updates. * * This consolidates all assumptions into one location, for ease of update. * * Currently, this includes normalization for obs/var columns only: * * - Dataframe columns in var/obs that are declared type: boolean may be sent by * the server in a variety of formats (eg uint8, etc). Cast to JS Array[boolean] * * - "Categorical" columns may not have all categories represented in the server-provided * schema (for valid reasons, eg, floating point rounding differences). For all * types we treat as categorical in the UI (string, boolean, categorical), update * the schema to contain all categories as a convenience. * * - "Categorical" columns (ie, string, boolean, categorical) may contain an excess * of category values (aka labels). Consolidate any excess into an "all other" * category. */ // currently no data or schema normalization necessary for X or emb if (field !== "obs" && field !== "var") return response; const colLabels = response.colIndex.labels(); for (const colLabel of colLabels) { const colSchema = _getColumnSchema(schema, field, colLabel); const isIndex = _isIndex(schema, field, colLabel); const { type, writable } = colSchema; // Boolean data -- cast entire array to Array[bool] if (type === "boolean") { response = castColumnToBoolean(response, colLabel); } // Types that are categorical in UI (string, boolean, categorical) OR are writable // are introspected to ensure the schema `categories` field and data values match, // and that we do not have an excess of category values (for non-writable columns) const isEnumType = type === "boolean" || type === "string" || type === "categorical" || writable; if (!isIndex && isEnumType) { response = normalizeCategorical(response, colLabel, colSchema); } } return response; } // eslint-disable-next-line @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. function castColumnToBoolean(df: Dataframe, label: any): Dataframe { const colData = df.col(label).asArray(); const newColData = new Array(colData.length); for (let i = 0; i < colData.length; i += 1) newColData[i] = !!colData[i]; df = df.replaceColData(label, newColData); return df; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. export function normalizeWritableCategoricalSchema(colSchema: any, col: any) { /* Ensure all enum writable / categorical schema have a categories array, that the categories array contains all unique values in the data array, AND that the array is UI sorted. */ const categorySet = new Set( col.summarizeCategorical().categories.concat(colSchema.categories ?? []) ); if (!categorySet.has(unassignedCategoryLabel)) { categorySet.add(unassignedCategoryLabel); } colSchema.categories = catLabelSort(true, Array.from(categorySet)); return colSchema; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. export function normalizeCategorical( df: Dataframe, colLabel: any, // eslint-disable-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. colSchema: any // eslint-disable-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS. ) { /* If writable, ensure schema matches data and we have an unassigned label If not writable, ensure schema matches data and that we consolidate labels in excess of "top N" into an overflow labels. */ const { writable } = colSchema; const col = df.col(colLabel); if (writable) { // writable (aka user) annotations normalizeWritableCategoricalSchema(colSchema, col); return df; } // else read-only, categorical columns const TopN = globalConfig.maxCategoricalOptionsToDisplay; // consolidate all categories from data and schema into a single list const colDataSummary = col.summarizeCategorical(); const allCategories = new Set( colDataSummary.categories.concat(colSchema.categories ?? []) ); // if no overflow, just UI sort schema categories and return if (allCategories.size <= TopN) { colSchema.categories = catLabelSort(writable, [...allCategories.keys()]); return df; } // Otherwise, pick top N categories by count and rewrite data // choose unique overflow category label let overflowCatName = `${colLabel}${overflowCategoryLabel}`; while (allCategories.has(overflowCatName)) { overflowCatName += "_"; } // pick top N category labels and add overflow label const topNCategories = new Set( [...colDataSummary.categoryCounts.keys()].slice(0, TopN) ); topNCategories.add(overflowCatName); // rewrite data - consolidate all excess labels into overflow label const newColData = Array.from(col.asArray()); for (let i = 0; i < newColData.length; i += 1) { if (!topNCategories.has(newColData[i])) { newColData[i] = overflowCatName; } } // replace data in dataframe df = df.replaceColData(colLabel, newColData); // Update schema with categories, in UI sort order. Ensure overflow label is at end // of list for display purposes. const revisedCategories = df.col(colLabel).summarizeCategorical().categories;
revisedCategories.push( revisedCategories.splice(revisedCategories.indexOf(overflowCatName), 1)[0] ); colSchema.categories = catLabelSort(writable, revisedCategories); return df; }
gates.rs
use crate::approx_eq; use crate::complex::c64; /// Represents a unitary quantum gate. #[derive(Copy, Clone)] pub struct Gate { pub(crate) u00: c64, pub(crate) u01: c64, pub(crate) u10: c64, pub(crate) u11: c64, } impl Gate { /// Creates a new gate with the four supplied components, such that the cannonical matrix of the gate /// is defined by /// /// ```math /// ┌ ┐ /// U = │ u00 u01 │ /// │ u10 u00 │ /// └ ┘ /// ``` /// /// This matrix needs to be unitary, meaning that it must satisfy the relation `UU = 1`, where `1` is the /// identity matrix and `U†` is the conjugate transpose of `U`. /// /// # Panics /// /// This function panics if the cannonical matrix is not unitary. pub fn new<E1, E2, E3, E4>(u00: E1, u01: E2, u10: E3, u11: E4) -> Gate where E1: Into<c64> + Copy, E2: Into<c64> + Copy, E3: Into<c64> + Copy, E4: Into<c64> + Copy, { let gate = unsafe { Gate::new_unchecked(u00, u01, u10, u11) }; if !gate.is_unitary() { panic!( "The gate defined by the matrix\n\t[{:?}\t{:?}]\n\t[{:?}\t{:?}]\nis not unitary", gate.u00, gate.u01, gate.u10, gate.u11, ); } gate } /// Unsafe version of the `Gate::new` function. Serves the same purpose and does the same thing, but /// will not panic if the given matrix is not unitary. #[inline] pub unsafe fn new_unchecked<E1, E2, E3, E4>(u00: E1, u01: E2, u10: E3, u11: E4) -> Gate where E1: Into<c64> + Copy, E2: Into<c64> + Copy, E3: Into<c64> + Copy, E4: Into<c64> + Copy, { Gate { u00: u00.into(), u01: u01.into(), u10: u10.into(), u11: u11.into(), } } pub fn phase_shift(phi: f32) -> Gate { unsafe {
vert(&self) -> Gate { let (a, b, c, d) = (self.u00, self.u01, self.u10, self.u11); let det_inv = (a*d - b*c).recip(); Gate{ u00: d * det_inv, u01: -b * det_inv, u10: -c * det_inv, u11: a * det_inv, } } #[inline] pub(crate) fn is_unitary(&self) -> bool { let (a, b, c, d) = (self.u00, self.u01, self.u10, self.u11); approx_eq(a.norm_sqr() + c.norm_sqr(), 1f32) && (a*b.conjugate() + c*d.conjugate()).approx_eq(c64::ZERO) && approx_eq(b.norm_sqr() + d.norm_sqr(), 1f32) } }
Gate::new_unchecked(1, 0, 0, c64::new_euler(1.0, phi)) } } pub fn in
keyvalue_deletevalue.go
// Code generated by thriftrw v1.17.0. DO NOT EDIT. // @generated package services import ( errors "errors" fmt "fmt" multierr "go.uber.org/multierr" exceptions "go.uber.org/thriftrw/gen/internal/tests/exceptions" wire "go.uber.org/thriftrw/wire" zapcore "go.uber.org/zap/zapcore" strings "strings" ) // KeyValue_DeleteValue_Args represents the arguments for the KeyValue.deleteValue function. // // The arguments for deleteValue are sent and received over the wire as this struct. type KeyValue_DeleteValue_Args struct { Key *Key `json:"key,omitempty"` } // ToWire translates a KeyValue_DeleteValue_Args struct into a Thrift-level intermediate // representation. This intermediate representation may be serialized // into bytes using a ThriftRW protocol implementation. // // An error is returned if the struct or any of its fields failed to // validate. // // x, err := v.ToWire() // if err != nil { // return err // } // // if err := binaryProtocol.Encode(x, writer); err != nil { // return err // } func (v *KeyValue_DeleteValue_Args) ToWire() (wire.Value, error) { var ( fields [1]wire.Field i int = 0 w wire.Value err error ) if v.Key != nil { w, err = v.Key.ToWire() if err != nil { return w, err } fields[i] = wire.Field{ID: 1, Value: w} i++ } return wire.NewValueStruct(wire.Struct{Fields: fields[:i]}), nil } func _Key_Read(w wire.Value) (Key, error) { var x Key err := x.FromWire(w) return x, err } // FromWire deserializes a KeyValue_DeleteValue_Args struct from its Thrift-level // representation. The Thrift-level representation may be obtained // from a ThriftRW protocol implementation. // // An error is returned if we were unable to build a KeyValue_DeleteValue_Args struct // from the provided intermediate representation. // // x, err := binaryProtocol.Decode(reader, wire.TStruct) // if err != nil { // return nil, err // } // // var v KeyValue_DeleteValue_Args // if err := v.FromWire(x); err != nil { // return nil, err // } // return &v, nil func (v *KeyValue_DeleteValue_Args) FromWire(w wire.Value) error { var err error for _, field := range w.GetStruct().Fields { switch field.ID { case 1: if field.Value.Type() == wire.TBinary { var x Key x, err = _Key_Read(field.Value) v.Key = &x if err != nil { return err } } } } return nil } // String returns a readable string representation of a KeyValue_DeleteValue_Args // struct. func (v *KeyValue_DeleteValue_Args) String() string { if v == nil { return "<nil>" } var fields [1]string i := 0 if v.Key != nil { fields[i] = fmt.Sprintf("Key: %v", *(v.Key)) i++ } return fmt.Sprintf("KeyValue_DeleteValue_Args{%v}", strings.Join(fields[:i], ", ")) } func _Key_EqualsPtr(lhs, rhs *Key) bool { if lhs != nil && rhs != nil { x := *lhs y := *rhs return (x == y) } return lhs == nil && rhs == nil } // Equals returns true if all the fields of this KeyValue_DeleteValue_Args match the // provided KeyValue_DeleteValue_Args. // // This function performs a deep comparison. func (v *KeyValue_DeleteValue_Args) Equals(rhs *KeyValue_DeleteValue_Args) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !_Key_EqualsPtr(v.Key, rhs.Key) { return false } return true } // MarshalLogObject implements zapcore.ObjectMarshaler, enabling // fast logging of KeyValue_DeleteValue_Args. func (v *KeyValue_DeleteValue_Args) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) { if v == nil { return nil } if v.Key != nil { enc.AddString("key", (string)(*v.Key)) } return err } // GetKey returns the value of Key if it is set or its // zero value if it is unset. func (v *KeyValue_DeleteValue_Args) GetKey() (o Key) { if v != nil && v.Key != nil { return *v.Key } return } // IsSetKey returns true if Key is not nil. func (v *KeyValue_DeleteValue_Args) IsSetKey() bool { return v != nil && v.Key != nil } // MethodName returns the name of the Thrift function as specified in // the IDL, for which this struct represent the arguments. // // This will always be "deleteValue" for this struct. func (v *KeyValue_DeleteValue_Args) MethodName() string { return "deleteValue" } // EnvelopeType returns the kind of value inside this struct. // // This will always be Call for this struct. func (v *KeyValue_DeleteValue_Args) EnvelopeType() wire.EnvelopeType { return wire.Call } // KeyValue_DeleteValue_Helper provides functions that aid in handling the // parameters and return values of the KeyValue.deleteValue // function. var KeyValue_DeleteValue_Helper = struct { // Args accepts the parameters of deleteValue in-order and returns // the arguments struct for the function. Args func( key *Key, ) *KeyValue_DeleteValue_Args // IsException returns true if the given error can be thrown // by deleteValue. // // An error can be thrown by deleteValue only if the // corresponding exception type was mentioned in the 'throws' // section for it in the Thrift file. IsException func(error) bool // WrapResponse returns the result struct for deleteValue // given the error returned by it. The provided error may // be nil if deleteValue did not fail. // // This allows mapping errors returned by deleteValue into a // serializable result struct. WrapResponse returns a // non-nil error if the provided error cannot be thrown by // deleteValue // // err := deleteValue(args) // result, err := KeyValue_DeleteValue_Helper.WrapResponse(err) // if err != nil { // return fmt.Errorf("unexpected error from deleteValue: %v", err) // } // serialize(result) WrapResponse func(error) (*KeyValue_DeleteValue_Result, error) // UnwrapResponse takes the result struct for deleteValue // and returns the erorr returned by it (if any). // // The error is non-nil only if deleteValue threw an // exception. // // result := deserialize(bytes) // err := KeyValue_DeleteValue_Helper.UnwrapResponse(result) UnwrapResponse func(*KeyValue_DeleteValue_Result) error }{} func init() { KeyValue_DeleteValue_Helper.Args = func( key *Key, ) *KeyValue_DeleteValue_Args { return &KeyValue_DeleteValue_Args{ Key: key, } } KeyValue_DeleteValue_Helper.IsException = func(err error) bool { switch err.(type) { case *exceptions.DoesNotExistException: return true case *InternalError: return true default: return false } } KeyValue_DeleteValue_Helper.WrapResponse = func(err error) (*KeyValue_DeleteValue_Result, error) { if err == nil { return &KeyValue_DeleteValue_Result{}, nil } switch e := err.(type) { case *exceptions.DoesNotExistException: if e == nil { return nil, errors.New("WrapResponse received non-nil error type with nil value for KeyValue_DeleteValue_Result.DoesNotExist") } return &KeyValue_DeleteValue_Result{DoesNotExist: e}, nil case *InternalError: if e == nil { return nil, errors.New("WrapResponse received non-nil error type with nil value for KeyValue_DeleteValue_Result.InternalError") } return &KeyValue_DeleteValue_Result{InternalError: e}, nil } return nil, err } KeyValue_DeleteValue_Helper.UnwrapResponse = func(result *KeyValue_DeleteValue_Result) (err error) { if result.DoesNotExist != nil { err = result.DoesNotExist return } if result.InternalError != nil { err = result.InternalError return } return } } // KeyValue_DeleteValue_Result represents the result of a KeyValue.deleteValue function call. // // The result of a deleteValue execution is sent and received over the wire as this struct. type KeyValue_DeleteValue_Result struct { // Raised if a value with the given key doesn't exist. DoesNotExist *exceptions.DoesNotExistException `json:"doesNotExist,omitempty"` InternalError *InternalError `json:"internalError,omitempty"` } // ToWire translates a KeyValue_DeleteValue_Result struct into a Thrift-level intermediate // representation. This intermediate representation may be serialized // into bytes using a ThriftRW protocol implementation. // // An error is returned if the struct or any of its fields failed to // validate. // // x, err := v.ToWire() // if err != nil { // return err // } // // if err := binaryProtocol.Encode(x, writer); err != nil { // return err // } func (v *KeyValue_DeleteValue_Result) ToWire() (wire.Value, error) { var ( fields [2]wire.Field i int = 0 w wire.Value err error ) if v.DoesNotExist != nil { w, err = v.DoesNotExist.ToWire() if err != nil { return w, err } fields[i] = wire.Field{ID: 1, Value: w} i++ } if v.InternalError != nil { w, err = v.InternalError.ToWire() if err != nil { return w, err } fields[i] = wire.Field{ID: 2, Value: w} i++ } if i > 1 { return wire.Value{}, fmt.Errorf("KeyValue_DeleteValue_Result should have at most one field: got %v fields", i) } return wire.NewValueStruct(wire.Struct{Fields: fields[:i]}), nil } func _DoesNotExistException_Read(w wire.Value) (*exceptions.DoesNotExistException, error) { var v exceptions.DoesNotExistException err := v.FromWire(w) return &v, err } func _InternalError_Read(w wire.Value) (*InternalError, error) { var v InternalError err := v.FromWire(w) return &v, err } // FromWire deserializes a KeyValue_DeleteValue_Result struct from its Thrift-level // representation. The Thrift-level representation may be obtained // from a ThriftRW protocol implementation. // // An error is returned if we were unable to build a KeyValue_DeleteValue_Result struct // from the provided intermediate representation. // // x, err := binaryProtocol.Decode(reader, wire.TStruct) // if err != nil { // return nil, err // } // // var v KeyValue_DeleteValue_Result // if err := v.FromWire(x); err != nil { // return nil, err // } // return &v, nil func (v *KeyValue_DeleteValue_Result) FromWire(w wire.Value) error { var err error for _, field := range w.GetStruct().Fields { switch field.ID { case 1: if field.Value.Type() == wire.TStruct { v.DoesNotExist, err = _DoesNotExistException_Read(field.Value) if err != nil { return err } } case 2: if field.Value.Type() == wire.TStruct { v.InternalError, err = _InternalError_Read(field.Value) if err != nil { return err } } } } count := 0 if v.DoesNotExist != nil { count++ } if v.InternalError != nil { count++ } if count > 1 { return fmt.Errorf("KeyValue_DeleteValue_Result should have at most one field: got %v fields", count) } return nil } // String returns a readable string representation of a KeyValue_DeleteValue_Result // struct. func (v *KeyValue_DeleteValue_Result) String() string { if v == nil { return "<nil>" } var fields [2]string i := 0 if v.DoesNotExist != nil { fields[i] = fmt.Sprintf("DoesNotExist: %v", v.DoesNotExist) i++ } if v.InternalError != nil { fields[i] = fmt.Sprintf("InternalError: %v", v.InternalError) i++ } return fmt.Sprintf("KeyValue_DeleteValue_Result{%v}", strings.Join(fields[:i], ", ")) } // Equals returns true if all the fields of this KeyValue_DeleteValue_Result match the // provided KeyValue_DeleteValue_Result. // // This function performs a deep comparison. func (v *KeyValue_DeleteValue_Result) Equals(rhs *KeyValue_DeleteValue_Result) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !((v.DoesNotExist == nil && rhs.DoesNotExist == nil) || (v.DoesNotExist != nil && rhs.DoesNotExist != nil && v.DoesNotExist.Equals(rhs.DoesNotExist)))
if !((v.InternalError == nil && rhs.InternalError == nil) || (v.InternalError != nil && rhs.InternalError != nil && v.InternalError.Equals(rhs.InternalError))) { return false } return true } // MarshalLogObject implements zapcore.ObjectMarshaler, enabling // fast logging of KeyValue_DeleteValue_Result. func (v *KeyValue_DeleteValue_Result) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) { if v == nil { return nil } if v.DoesNotExist != nil { err = multierr.Append(err, enc.AddObject("doesNotExist", v.DoesNotExist)) } if v.InternalError != nil { err = multierr.Append(err, enc.AddObject("internalError", v.InternalError)) } return err } // GetDoesNotExist returns the value of DoesNotExist if it is set or its // zero value if it is unset. func (v *KeyValue_DeleteValue_Result) GetDoesNotExist() (o *exceptions.DoesNotExistException) { if v != nil && v.DoesNotExist != nil { return v.DoesNotExist } return } // IsSetDoesNotExist returns true if DoesNotExist is not nil. func (v *KeyValue_DeleteValue_Result) IsSetDoesNotExist() bool { return v != nil && v.DoesNotExist != nil } // GetInternalError returns the value of InternalError if it is set or its // zero value if it is unset. func (v *KeyValue_DeleteValue_Result) GetInternalError() (o *InternalError) { if v != nil && v.InternalError != nil { return v.InternalError } return } // IsSetInternalError returns true if InternalError is not nil. func (v *KeyValue_DeleteValue_Result) IsSetInternalError() bool { return v != nil && v.InternalError != nil } // MethodName returns the name of the Thrift function as specified in // the IDL, for which this struct represent the result. // // This will always be "deleteValue" for this struct. func (v *KeyValue_DeleteValue_Result) MethodName() string { return "deleteValue" } // EnvelopeType returns the kind of value inside this struct. // // This will always be Reply for this struct. func (v *KeyValue_DeleteValue_Result) EnvelopeType() wire.EnvelopeType { return wire.Reply }
{ return false }
packagesconfig.go
package dependencies import ( "encoding/xml" "fmt" gofrogcmd "github.com/jfrog/gofrog/io" "github.com/jfrog/jfrog-cli-go/artifactory/utils/nuget" "github.com/jfrog/jfrog-client-go/artifactory/buildinfo" "github.com/jfrog/jfrog-client-go/utils/errorutils" "github.com/jfrog/jfrog-client-go/utils/io/fileutils" "github.com/jfrog/jfrog-client-go/utils/log" "io/ioutil" "path/filepath" "strings" ) var packagesFilePath = "packages.config" // Register packages.config extractor func init()
// packages.config dependency extractor type packagesExtractor struct { allDependencies map[string]*buildinfo.Dependency childrenMap map[string][]string rootDependencies []string } func (extractor *packagesExtractor) IsCompatible(projectName, projectRoot string) (bool, error) { packagesConfigPath := filepath.Join(projectRoot, packagesFilePath) exists, err := fileutils.IsFileExists(packagesConfigPath, false) if exists { log.Debug("Found", packagesConfigPath, "file for project:", projectName) return true, err } return false, err } func (extractor *packagesExtractor) DirectDependencies() ([]string, error) { return getDirectDependencies(extractor.allDependencies, extractor.childrenMap), nil } func (extractor *packagesExtractor) AllDependencies() (map[string]*buildinfo.Dependency, error) { return extractor.allDependencies, nil } func (extractor *packagesExtractor) ChildrenMap() (map[string][]string, error) { return extractor.childrenMap, nil } // Create new packages.config extractor func (extractor *packagesExtractor) new(projectName, projectRoot string) (Extractor, error) { newExtractor := &packagesExtractor{allDependencies: map[string]*buildinfo.Dependency{}, childrenMap: map[string][]string{}} packagesConfig, err := newExtractor.loadPackagesConfig(projectRoot) if err != nil { return nil, err } globalPackagesCache, err := newExtractor.getGlobalPackagesCache() if err != nil { return nil, err } err = newExtractor.extract(packagesConfig, globalPackagesCache) return newExtractor, err } func (extractor *packagesExtractor) extract(packagesConfig *packagesConfig, globalPackagesCache string) error { for _, nuget := range packagesConfig.XmlPackages { id := strings.ToLower(nuget.Id) nPackage := &nugetPackage{id: id, version: nuget.Version, dependencies: map[string]bool{}} // First lets check if the original version exists within the file system: pack, err := createNugetPackage(globalPackagesCache, nuget, nPackage) if err != nil { return err } if pack == nil { // If doesn't exists lets build the array of alternative versions. alternativeVersions := createAlternativeVersionForms(nuget.Version) // Now lets do a loop to run over the alternative possibilities for i := 0; i < len(alternativeVersions); i++ { nPackage.version = alternativeVersions[i] pack, err = createNugetPackage(globalPackagesCache, nuget, nPackage) if err != nil { return err } if pack != nil { break } } } if pack != nil { extractor.allDependencies[id] = pack.dependency extractor.childrenMap[id] = pack.getDependencies() } else { log.Warn(fmt.Sprintf("The following NuGet package %s with version %s was not found in the NuGet cache %s and therefore not"+ " added to the dependecy tree. This might be because the package already exists in a different NuGet cache,"+ " possibly the SDK cache. Removing the package from this cache may resolve the issue", nuget.Id, nuget.Version, globalPackagesCache)) } } return nil } // NuGet allows the version will be with missing or unnecessary zeros // This method will return a list of the possible alternative versions // "1.0" --> []string{"1.0.0.0", "1.0.0", "1"} // "1" --> []string{"1.0.0.0", "1.0.0", "1.0"} // "1.2" --> []string{"1.2.0.0", "1.2.0"} // "1.22.33" --> []string{"1.22.33.0"} // "1.22.33.44" --> []string{} // "1.0.2" --> []string{"1.0.2.0"} func createAlternativeVersionForms(originalVersion string) []string { versionSlice := strings.Split(originalVersion, ".") versionSliceSize := len(versionSlice) for i := 4; i > versionSliceSize; i-- { versionSlice = append(versionSlice, "0") } var alternativeVersions []string for i := 4; i > 0; i-- { version := strings.Join(versionSlice[:i], ".") if version != originalVersion { alternativeVersions = append(alternativeVersions, version) } if !strings.HasSuffix(version, ".0") { return alternativeVersions } } return alternativeVersions } func (extractor *packagesExtractor) loadPackagesConfig(rootPath string) (*packagesConfig, error) { packagesFilePath := filepath.Join(rootPath, packagesFilePath) content, err := ioutil.ReadFile(packagesFilePath) if err != nil { return nil, err } config := &packagesConfig{} err = xml.Unmarshal(content, config) if err != nil { return nil, errorutils.CheckError(err) } return config, nil } type dfsHelper struct { visited bool notRoot bool circular bool } func getDirectDependencies(allDependencies map[string]*buildinfo.Dependency, childrenMap map[string][]string) []string { helper := map[string]*dfsHelper{} for id := range allDependencies { helper[id] = &dfsHelper{} } for id := range allDependencies { if helper[id].visited { continue } searchRootDependencies(helper, id, allDependencies, childrenMap, map[string]bool{id: true}) } var rootDependencies []string for id, nodeData := range helper { if !nodeData.notRoot || nodeData.circular { rootDependencies = append(rootDependencies, id) } } return rootDependencies } func searchRootDependencies(dfsHelper map[string]*dfsHelper, currentId string, allDependencies map[string]*buildinfo.Dependency, childrenMap map[string][]string, traversePath map[string]bool) { if dfsHelper[currentId].visited { return } for _, next := range childrenMap[currentId] { if _, ok := allDependencies[next]; !ok { // No such dependency continue } if traversePath[next] { for circular := range traversePath { dfsHelper[circular].circular = true } continue } // Not root dependency dfsHelper[next].notRoot = true traversePath[next] = true searchRootDependencies(dfsHelper, next, allDependencies, childrenMap, traversePath) delete(traversePath, next) } dfsHelper[currentId].visited = true } func createNugetPackage(packagesPath string, nuget xmlPackage, nPackage *nugetPackage) (*nugetPackage, error) { nupkgPath := filepath.Join(packagesPath, nPackage.id, nPackage.version, strings.Join([]string{nPackage.id, nPackage.version, "nupkg"}, ".")) exists, err := fileutils.IsFileExists(nupkgPath, false) if err != nil { return nil, err } if !exists { return nil, nil } fileDetails, err := fileutils.GetFileDetails(nupkgPath) if err != nil { return nil, err } nPackage.dependency = &buildinfo.Dependency{Id: nuget.Id + ":" + nuget.Version, Checksum: &buildinfo.Checksum{Sha1: fileDetails.Checksum.Sha1, Md5: fileDetails.Checksum.Md5}} // Nuspec file that holds the metadata for the package. nuspecPath := filepath.Join(packagesPath, nPackage.id, nPackage.version, strings.Join([]string{nPackage.id, "nuspec"}, ".")) nuspecContent, err := ioutil.ReadFile(nuspecPath) if err != nil { return nil, errorutils.CheckError(err) } nuspec := &nuspec{} err = xml.Unmarshal(nuspecContent, nuspec) if err != nil { pack := nPackage.id + ":" + nPackage.version log.Warn("Package:", pack, "couldn't be parsed due to:", err.Error(), ". Skipping the package dependency.") return nPackage, nil } for _, dependency := range nuspec.Metadata.Dependencies.Dependencies { nPackage.dependencies[strings.ToLower(dependency.Id)] = true } for _, group := range nuspec.Metadata.Dependencies.Groups { for _, dependency := range group.Dependencies { nPackage.dependencies[strings.ToLower(dependency.Id)] = true } } return nPackage, nil } type nugetPackage struct { id string version string dependency *buildinfo.Dependency dependencies map[string]bool // Set of dependencies } func (nugetPackage *nugetPackage) getDependencies() []string { var dependencies []string for key := range nugetPackage.dependencies { dependencies = append(dependencies, key) } return dependencies } func (extractor *packagesExtractor) getGlobalPackagesCache() (string, error) { localsCmd, err := nuget.NewNugetCmd() if err != nil { return "", err } //nuget locals global-packages -list localsCmd.Command = []string{"locals", "global-packages"} localsCmd.CommandFlags = []string{"-list"} output, err := gofrogcmd.RunCmdOutput(localsCmd) if err != nil { return "", err } globalPackagesPath := strings.TrimSpace(strings.TrimPrefix(output, "global-packages:")) exists, err := fileutils.IsDirExists(globalPackagesPath, false) if err != nil { return "", err } if !exists { return "", errorutils.CheckError(fmt.Errorf("Could not find global packages path at: %s", globalPackagesPath)) } return globalPackagesPath, nil } // packages.config xml objects for unmarshalling type packagesConfig struct { XMLName xml.Name `xml:"packages"` XmlPackages []xmlPackage `xml:"package"` } type xmlPackage struct { Id string `xml:"id,attr"` Version string `xml:"version,attr"` } type nuspec struct { XMLName xml.Name `xml:"package"` Metadata metadata `xml:"metadata"` } type metadata struct { Dependencies xmlDependencies `xml:"dependencies"` } type xmlDependencies struct { Groups []group `xml:"group"` Dependencies []xmlPackage `xml:"dependency"` } type group struct { TargetFramework string `xml:"targetFramework,attr"` Dependencies []xmlPackage `xml:"dependency"` }
{ register(&packagesExtractor{}) }
gen_db.py
#!/usr/bin/env python3 # -*- Coding: UTF-8 -*- # --------------------------------------------------------------------------- # Open Asset Import Library (ASSIMP) # --------------------------------------------------------------------------- # # Copyright (c) 2006-2020, ASSIMP Development Team # # All rights reserved. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the # following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other # materials provided with the distribution. # # * Neither the name of the ASSIMP team, nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior # written permission of the ASSIMP Development Team. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # --------------------------------------------------------------------------- """ Generate the regression database db.zip from the files in the <root>/test/models directory. Older databases are overwritten with no prompt but can be restored using Git as needed. Use --help for usage. On Windows, use ``py run.py <arguments>`` to make sure command line parameters are forwarded to the script. """ import sys import os import subprocess import zipfile import settings import utils usage = """gen_db [assimp_binary] [-i=...] [-e=...] [-p] [-n] The assimp_cmd (or assimp) binary to use is specified by the first command line argument and defaults to ``assimp``. To build, set ``ASSIMP_BUILD_ASSIMP_TOOLS=ON`` in CMake. If generating configs for an IDE, make sure to build the assimp_cmd project. -i,--include: List of file extensions to update dumps for. If omitted, all file extensions are updated except those in `exclude`. Example: -ixyz,abc -i.xyz,.abc --include=xyz,abc -e,--exclude: Merged with settings.exclude_extensions to produce a list of all file extensions to ignore. If dumps exist, they are not altered. If not, theu are not created. -p,--preview: Preview list of file extensions touched by the update. Dont' change anything. -n,--nozip: Don't pack to ZIP archive. Keep all dumps in individual files. """ # ------------------------------------------------------------------------------- def
(d, outfile, file_filter): """ Generate small dump records for all files in 'd' """ print("Processing directory " + d) num = 0 for f in os.listdir(d): fullp = os.path.join(d, f) if os.path.isdir(fullp) and not f == ".svn": num += process_dir(fullp, outfile, file_filter) continue if file_filter(f): for pp in settings.pp_configs_to_test: num += 1 print("DUMP " + fullp + "\n post-processing: " + pp) outf = os.path.join(os.getcwd(), settings.database_name, utils.hashing(fullp, pp)) cmd = [ assimp_bin_path, "dump", fullp, outf, "-b", "-s", "-l" ] + pp.split() outfile.write("assimp dump "+"-"*80+"\n") outfile.flush() if subprocess.call(cmd, stdout=outfile, stderr=outfile, shell=False): print("Failure processing " + fullp) # spit out an empty file to indicate that this failure is expected with open(outf,'wb') as f: pass return num # ------------------------------------------------------------------------------- def make_zip(): """Zip the contents of ./<settings.database_name> to <settings.database_name>.zip using DEFLATE compression to minimize the file size. """ num = 0 zipout = zipfile.ZipFile(settings.database_name + ".zip", "w", zipfile.ZIP_DEFLATED) for f in os.listdir(settings.database_name): p = os.path.join(settings.database_name, f) zipout.write(p, f) if settings.remove_old: os.remove(p) num += 1 if settings.remove_old: os.rmdir(settings.database_name) bad = zipout.testzip() assert bad is None print("="*60) print("Database contains {0} entries".format(num)) # ------------------------------------------------------------------------------- def extract_zip(): """Unzip <settings.database_name>.zip to ./<settings.database_name>""" try: zipout = zipfile.ZipFile(settings.database_name + ".zip", "r", 0) zipout.extractall(path=settings.database_name) except (RuntimeError,IOError) as r: print(r) print("failed to extract previous ZIP contents. "\ "DB is generated from scratch.") # ------------------------------------------------------------------------------- def gen_db(ext_list,outfile): """Generate the crash dump database in ./<settings.database_name>""" try: os.mkdir(settings.database_name) except OSError: pass num = 0 for tp in settings.model_directories: num += process_dir(tp, outfile, lambda x: os.path.splitext(x)[1].lower() in ext_list and not x in settings.files_to_ignore) print("="*60) print("Updated {0} entries".format(num)) # ------------------------------------------------------------------------------- if __name__ == "__main__": def clean(f): f = f.strip("* \'") return "."+f if f[:1] != '.' else f if len(sys.argv) <= 1 or sys.argv[1] == "--help" or sys.argv[1] == "-h": print(usage) sys.exit(0) assimp_bin_path = sys.argv[1] ext_list, preview, nozip = None, False, False for m in sys.argv[2:]: if m[:10]=="--exclude=": settings.exclude_extensions += map(clean, m[10:].split(",")) elif m[:2]=="-e": settings.exclude_extensions += map(clean, m[2:].split(",")) elif m[:10]=="--include=": ext_list = m[10:].split(",") elif m[:2]=="-i": ext_list = m[2:].split(",") elif m=="-p" or m == "--preview": preview = True elif m=="-n" or m == "--nozip": nozip = True else: print("Unrecognized parameter: " + m) sys.exit(-1) outfile = open(os.path.join("..", "results", "gen_regression_db_output.txt"), "w") if ext_list is None: (ext_list, err) = subprocess.Popen([assimp_bin_path, "listext"], stdout=subprocess.PIPE).communicate() ext_list = str(ext_list.strip()).lower().split(";") # todo: Fix for multi dot extensions like .skeleton.xml ext_list = list(filter(lambda f: not f in settings.exclude_extensions, map(clean, ext_list))) print('File extensions processed: ' + ', '.join(ext_list)) if preview: sys.exit(1) extract_zip() gen_db(ext_list,outfile) make_zip() print("="*60) input("Press any key to continue") sys.exit(0) # vim: ai ts=4 sts=4 et sw=4
process_dir
client.py
from collections import namedtuple import inspect import os from ghost import Ghost class Client(object): def __init__(self, url=None): if url: self.url = url assert self.url, "All clients must have a URL attribute" self._attributes = self._collect_attributes() self._class_model = self._setup_class_model() self._ghost = Ghost() def process(self): self._load_ghost() attribute_results = self._process_attributes() self._object_results = self._make_objects(attribute_results) return self._object_results def _setup_class_model(self): class_name = self.__class__.__name__ return namedtuple(class_name + "Response", self._attributes.keys()) def _process_attributes(self): results = [] for attribute_name, attribute in self._attributes.iteritems(): result, resources = self._ghost.evaluate(attribute.query) # If a node was selected, return it's data if isinstance(result, dict): if 'data' in result: result = result['data'] elif 'selector' in result: raise TypeError("The attribute {} returned a selector" " instead of a node.".format(attribute_name)) results.append(result) return results def _make_objects(self, attribute_results):
def _collect_attributes(self): attrs = [(attr_name, attr) for (attr_name, attr) in inspect.getmembers(self) if isinstance(attr, Attribute)] return dict(attrs) def _load_ghost(self): page, extra_resources = self._ghost.open(self.url) # For local testing, page is None if page: # TODO should error better assert page.http_status < 400 # Load jquery jquery_path = os.path.join(os.path.abspath(os.curdir), 'zester', 'fixtures', 'jquery.min.js') jquery_text = open(jquery_path, 'r').read() result, resources = self._ghost.evaluate(jquery_text) class MultipleClient(Client): def _process_attributes(self): results = super(MultipleClient, self)._process_attributes() if not results: return results zipped_results = zip(*results) return zipped_results def _make_objects(self, attribute_results): object_results = [] attribute_names = self._attributes.keys() for attribute_result in attribute_results: result_dict = dict(zip(attribute_names, attribute_result)) object_results.append(self._class_model(**result_dict)) return object_results class SingleClient(Client): def _process_attributes(self): result = super(SingleClient, self)._process_attributes() number_of_attributes = len(self._attributes) if len(result) > number_of_attributes: # If we found more attributes than we were looking for result = result[:number_of_attributes] return result def _make_objects(self, attribute_result): attribute_names = self._attributes.keys() result_dict = dict(zip(attribute_names, attribute_result)) object_result = self._class_model(**result_dict) return object_result class Attribute(object): def __init__(self, selector, modifier=None): self.selector = selector self.modifier = modifier @property def query(self): if self.modifier: # Escaping braces in here base = "$.map({selector}, function(el){{ return {modifier}}});" return base.format(selector=self.selector, modifier=self.modifier) else: return self.selector
raise NotImplementedError()
main.go
/* * Flow Go SDK * * Copyright 2019-2020 Dapper Labs, 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 main import ( "context" "encoding/hex" "fmt" "github.com/onflow/cadence" "google.golang.org/grpc" "github.com/onflow/flow-go-sdk" "github.com/onflow/flow-go-sdk/client" "github.com/onflow/flow-go-sdk/crypto" "github.com/onflow/flow-go-sdk/examples" "github.com/onflow/flow-go-sdk/test" ) func
() { UserSignatureDemo() } var script = []byte(` import Crypto pub fun main( rawPublicKeys: [String], weights: [UFix64], signatures: [String], toAddress: Address, fromAddress: Address, amount: UFix64, ): Bool { let keyList = Crypto.KeyList() var i = 0 for rawPublicKey in rawPublicKeys { keyList.add( PublicKey( publicKey: rawPublicKey.decodeHex(), signatureAlgorithm: SignatureAlgorithm.ECDSA_P256 ), hashAlgorithm: HashAlgorithm.SHA3_256, weight: weights[i], ) i = i + 1 } let signatureSet: [Crypto.KeyListSignature] = [] var j = 0 for signature in signatures { signatureSet.append( Crypto.KeyListSignature( keyIndex: j, signature: signature.decodeHex() ) ) j = j + 1 } let message = toAddress.toBytes() .concat(fromAddress.toBytes()) .concat(amount.toBigEndianBytes()) return keyList.verify( signatureSet: signatureSet, signedData: message, ) } `) func bytesToCadenceArray(b []byte) cadence.Array { values := make([]cadence.Value, len(b)) for i, b := range b { values[i] = cadence.NewUInt8(b) } return cadence.NewArray(values) } func UserSignatureDemo() { ctx := context.Background() flowClient, err := client.New("127.0.0.1:3569", grpc.WithInsecure()) examples.Handle(err) privateKeyA := examples.RandomPrivateKey() publicKeyA := privateKeyA.PublicKey() privateKeyB := examples.RandomPrivateKey() publicKeyB := privateKeyB.PublicKey() addresses := test.AddressGenerator() toAddress := cadence.Address(addresses.New()) fromAddress := cadence.Address(addresses.New()) amount, err := cadence.NewUFix64("100.00") examples.Handle(err) message := append(toAddress.Bytes(), fromAddress.Bytes()...) message = append(message, amount.ToBigEndianBytes()...) signerA := crypto.NewInMemorySigner(privateKeyA, crypto.SHA3_256) signerB := crypto.NewInMemorySigner(privateKeyB, crypto.SHA3_256) signatureA, err := flow.SignUserMessage(signerA, message) examples.Handle(err) signatureB, err := flow.SignUserMessage(signerB, message) examples.Handle(err) publicKeys := cadence.NewArray([]cadence.Value{ cadence.String(hex.EncodeToString(publicKeyA.Encode())), cadence.String(hex.EncodeToString(publicKeyB.Encode())), }) weightA, err := cadence.NewUFix64("0.5") examples.Handle(err) weightB, err := cadence.NewUFix64("0.5") examples.Handle(err) weights := cadence.NewArray([]cadence.Value{ weightA, weightB, }) signatures := cadence.NewArray([]cadence.Value{ cadence.String(hex.EncodeToString(signatureA)), cadence.String(hex.EncodeToString(signatureB)), }) value, err := flowClient.ExecuteScriptAtLatestBlock( ctx, script, []cadence.Value{ publicKeys, weights, signatures, toAddress, fromAddress, amount, }, ) examples.Handle(err) if value == cadence.NewBool(true) { fmt.Println("Signature verification succeeded") } else { fmt.Println("Signature verification failed") } }
main
executor.go
package selenium import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "github.com/TylerBrock/colorjson" "github.com/fatih/color" "github.com/pkg/errors" "github.com/theRealAlpaca/go-selenium/logger" "github.com/theRealAlpaca/go-selenium/types" ) // Describes possible response status code classes. //nolint:deadcode,varcheck const ( classInformational = iota + 1 classSuccessful classRedirection classClientError classServerError ) var f = &colorjson.Formatter{ KeyColor: color.New(color.FgWhite), StringColor: color.New(color.FgGreen), BoolColor: color.New(color.FgYellow), NumberColor: color.New(color.FgCyan), NullColor: color.New(color.FgMagenta), StringMaxLength: 50, DisabledColor: false, Indent: 0, RawStrings: true, } type apiClient struct { baseURL string } type response struct { Value interface{} `json:"value"` } //nolint:errname type errorResponse struct { Err string `json:"error"` Message string `json:"message"` } func (a *apiClient) executeRequest( method, route string, payload interface{}, ) (*response, error) { res, reqErr := a.executeRequestRaw(method, route, payload) if reqErr != nil { if !errors.As(reqErr, &types.ErrFailedRequest) { return nil, errors.Wrap(reqErr, "failed to execute request") } } var r response err := json.Unmarshal(res, &r) if err != nil { return nil, errors.Wrap(err, "failed to unmarshal response") } if reqErr != nil { return &r, reqErr } return &r, nil } func (a *apiClient) executeRequestVoid( method, route string, ) (*response, error) { return a.executeRequest(method, route, struct{}{}) } func (a *apiClient) executeRequestCustom( method, route string, payload, customResponse interface{}, ) (*response, error) { res, err := a.executeRequestRaw(method, route, payload) if err != nil { return nil, errors.Wrap(err, "failed to execute request") } err = json.Unmarshal(res, customResponse) if err == nil { return &response{Value: customResponse}, nil } var errRes *response err = json.Unmarshal(res, &errRes) if err != nil { return nil, errors.Wrap( err, "failed to unmarshal response into errorResponse", ) } return errRes, errors.Wrap(err, "failed to unmarshal response") } func (a *apiClient) executeRequestRaw( method, route string, payload interface{}, ) ([]byte, error) { body, err := json.Marshal(payload) if err != nil { return nil, errors.Wrap(err, "failed to marshal payload") } url := a.baseURL + route req, err := http.NewRequestWithContext( context.Background(), method, url, bytes.NewBuffer(body), ) if err != nil { return nil, errors.Wrap(err, "failed to create request") } if config.LogLevel == logger.DebugLvl { logger.Custom( color.HiCyanString("-> Request "), fmt.Sprintf("%s %s\n\t%s", method, url, formatJSON(body)), ) } res, err := http.DefaultClient.Do(req) if err != nil { return nil, errors.Wrap(err, "failed to send request") } defer res.Body.Close() b, err := io.ReadAll(res.Body) if err != nil { return nil, errors.Wrap(err, "failed to read response body") } var r response // Unmarshaling is needed to format errors err = json.Unmarshal(b, &r) if err != nil { return []byte{}, errors.Wrap(err, "failed to unmarshal response") } if config.LogLevel == logger.DebugLvl { logger.Custom( color.HiGreenString("<- Response "), formatJSON(b), "\n\n", ) } if getStatusClass(res.StatusCode) != classSuccessful { return b, errors.Wrap(types.ErrFailedRequest, r.String()) } return b, nil } func formatJSON(body []byte) string { var data map[string]interface{} //nolint: errcheck json.Unmarshal(body, &data) b, _ := f.Marshal(data) return string(b) } func getStatusClass(code int) int
func (r *response) String() string { switch v := r.Value.(type) { case errorResponse: return v.String() default: return fmt.Sprintf(`"value": %q`, r.Value) } } func (r *response) UnmarshalJSON(data []byte) error { var res struct { Value interface{} `json:"value"` } if err := json.Unmarshal(data, &res); err != nil { return errors.Wrap(err, "failed to unmarshal response") } switch values := res.Value.(type) { case map[string]interface{}: for k, value := range values { if strings.HasPrefix(strings.ToLower(k), "element") { if v, ok := value.(string); ok { r.Value = map[string]string{k: v} return nil } return errors.New("could not convert element to string") } } var errResponse struct { Value errorResponse `json:"value"` } if err := json.Unmarshal(data, &errResponse); err != nil { return errors.Wrap(err, "failed to unmarshal error response") } r.Value = errResponse.Value return nil case []interface{}: var response struct { Value []interface{} `json:"value"` } if err := json.Unmarshal(data, &response); err != nil { return errors.Wrap(err, "failed to unmarshal response") } r.Value = response.Value default: r.Value = res.Value } return nil } func (r *response) getErrorReponse() *errorResponse { if r == nil { return nil } if r.Value == nil { return nil } if errRes, ok := r.Value.(errorResponse); ok { return &errRes } return nil } func (errRes *errorResponse) String() string { return fmt.Sprintf( `"error": %q, "message": %q`, errRes.Err, errRes.Message, ) } func (errRes *errorResponse) Error() string { return errRes.Err }
{ class := code / 100 switch class { case 1, 2, 3, 4, 5: return class default: return 0 } }
StmtIndexConvertFactory_test.go
func TestBuildStmtConvert(t *testing.T) { }
package stmt import "testing"
rollup.config.js
/* eslint-disable no-param-reassign */ // eslint-disable-next-line import/no-extraneous-dependencies import copy from '@guanghechen/rollup-plugin-copy'
// eslint-disable-next-line import/no-anonymous-default-export export default { input: 'index.js', output: { dir: 'lib/esm', format: 'esm', }, plugins: [ copy({ verbose: true, targets: [ { src: 'assets/data/*.json', dest: 'dist/packs', rename: name => `${name}.txt`, transform: async function (source) { return 'Author: guanghechen\n' + source.toString() }, }, { src: 'assets/data/some-folder', dest: 'dist/packs', }, { src: 'assets/data/some/**/*.json', dest: 'dist/packs', }, ], }), ], }
test_reservation.py
# coding: utf-8 """ Waitlisted API Waitlisted API OpenAPI spec version: 2.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git 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. """ from __future__ import absolute_import import os import sys import unittest import waitlisted from waitlisted.rest import ApiException from waitlisted.models.reservation import Reservation class TestReservation(unittest.TestCase): """ Reservation unit test stubs """ def setUp(self):
def tearDown(self): pass def testReservation(self): """ Test Reservation """ model = waitlisted.models.reservation.Reservation() if __name__ == '__main__': unittest.main()
pass
hexapodengine2.py
import pybullet as p import math import pybullet_data import time import random import numpy as np import serial def radToPwm(angle): return ((2000 * angle) / math.pi) + 1500 # t in ms; the closer t is to 0, more accuracy but less smooth motion def updateRealServos(ser, t): # right legs ser.write( f'#0P{radToPwm(-p.getJointState(hexapod_ID, 8)[0])}T{t}#1P{radToPwm(p.getJointState(hexapod_ID, 9)[0])}T{t}#2P{radToPwm(-p.getJointState(hexapod_ID, 10)[0])-100}T{t}\r'.encode( 'utf-8')) ser.write( f'#4P{radToPwm(-p.getJointState(hexapod_ID, 4)[0])}T{t}#5P{radToPwm(p.getJointState(hexapod_ID, 5)[0])}T{t}#6P{radToPwm(-p.getJointState(hexapod_ID, 6)[0])+100}T{t}\r'.encode( 'utf-8')) ser.write( f'#8P{radToPwm(-p.getJointState(hexapod_ID, 0)[0])}T{t}#9P{radToPwm(p.getJointState(hexapod_ID, 1)[0])}T{t}#10P{radToPwm(-p.getJointState(hexapod_ID, 2)[0])}T{t}\r'.encode( 'utf-8')) # left legs ser.write( f'#24P{radToPwm(-p.getJointState(hexapod_ID, 12)[0])}T{t}#25P{radToPwm(p.getJointState(hexapod_ID, 13)[0])}T{t}#26P{radToPwm(-p.getJointState(hexapod_ID, 14)[0])+100}T{t}\r'.encode( 'utf-8')) ser.write( f'#20P{radToPwm(-p.getJointState(hexapod_ID, 16)[0])}T{t}#21P{radToPwm(p.getJointState(hexapod_ID, 17)[0])}T{t}#22P{radToPwm(-p.getJointState(hexapod_ID, 18)[0])}T{t}\r'.encode( 'utf-8')) ser.write( f'#16P{radToPwm(-p.getJointState(hexapod_ID, 20)[0])}T{t}#17P{radToPwm(p.getJointState(hexapod_ID, 21)[0])}T{t}#18P{radToPwm(-p.getJointState(hexapod_ID, 22)[0])-50}T{t}\r'.encode( 'utf-8')) def init_debug_parameters(): for j in list(range(0, 6)): control_IDs.append(p.addUserDebugParameter(f"Pelvis {j}", -servoRangeOfMotion, servoRangeOfMotion, 0)) control_IDs.append(p.addUserDebugParameter(f"Hip {j}", -servoRangeOfMotion, servoRangeOfMotion, 0)) control_IDs.append(p.addUserDebugParameter(f"Knee {j}", -servoRangeOfMotion, servoRangeOfMotion, 0)) def read_debug_parameters(): angles = [] for x in control_IDs: angles.append(p.readUserDebugParameter(x)) return angles def chromosomeCreator(): pos = [] duration = 1 force = 200 # pos.extend([duration] + [0] * NUM_OF_SERVOS) for j in range(LENGTH_OF_SEQUENCE - 1): gaitState = [0] * NUM_OF_SERVOS gaitState[j] = servoRangeOfMotion pos.extend([duration] + gaitState) print(len(pos)) return [duration] + [force] + pos def readGait(progress, chromosome): global firstCycleComplete end_index = LENGTH_OF_SEQUENCE if not firstCycleComplete and progress >= sum([chromosome[x] for x in range(0, len(chromosome), LENGTH_OF_GAIT_STATE)]): firstCycleComplete = True if firstCycleComplete: progress = progress - sum([chromosome[x] for x in range(0, ((LENGTH_OF_START_SEQUENCE - 1) * LENGTH_OF_GAIT_STATE) + 1, LENGTH_OF_GAIT_STATE)]) chromosome = chromosome[LENGTH_OF_START_SEQUENCE * LENGTH_OF_GAIT_STATE:] end_index = LENGTH_OF_CYCLE start_index = 0 total_duration = sum([chromosome[x] for x in range(0, len(chromosome), LENGTH_OF_GAIT_STATE)]) # duration_of_start_sequence = sum([chromosome[x] for x in range(0, ((LENGTH_OF_START_SEQUENCE - 1) * LENGTH_OF_GAIT_STATE) + 1, LENGTH_OF_GAIT_STATE)]) # duration_of_cycle = total_duration - duration_of_start_sequence progress = progress % total_duration current_duration_index = 0 next_duration_index = 0 sum_of_durations = 0 for j in range(start_index, end_index): current_position_index = j * LENGTH_OF_GAIT_STATE sum_of_durations = sum([chromosome[x] for x in range(start_index, current_position_index + 1, LENGTH_OF_GAIT_STATE)]) if progress < sum_of_durations: current_duration_index = current_position_index next_duration_index = (j + 1) * LENGTH_OF_GAIT_STATE if (j + 1) >= end_index: next_duration_index = start_index * LENGTH_OF_GAIT_STATE break current_gait_state = chromosome[current_duration_index + 1: current_duration_index + LENGTH_OF_GAIT_STATE] next_gait_state = chromosome[next_duration_index + 1: next_duration_index + LENGTH_OF_GAIT_STATE] if not firstCycleComplete and current_duration_index == (LENGTH_OF_SEQUENCE - 1) * LENGTH_OF_GAIT_STATE:
interpolated_gait_state = [interpolate(a, b, alpha) for a, b in zip(current_gait_state, next_gait_state)] # print(progress, alpha, sum_of_durations, chromosome[current_duration_index]) return interpolated_gait_state def interpolate(a, b, alpha): return a * (1 - alpha) + b * alpha def resetLegJoints(): p.resetJointStatesMultiDof(hexapod_ID, JOINT_INDEXES, [[0]] * 18, targetVelocities=[[0]] * 18) p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=([0] * 18), forces=([150] * 18)) def resetEnvironment(): resetLegJoints() p.resetBasePositionAndOrientation(hexapod_ID, [0, STARTING_Y, STARTING_HEIGHT + random.uniform(0, 0.002)], [0, 0, 0, 1]) p.stepSimulation() def resetPyBulletSimulation(): global plane_ID global hexapod_ID p.resetSimulation() p.setGravity(0, 0, -9.8) plane_ID = p.loadURDF("plane.urdf", globalScaling=4) # testAngle = p.getQuaternionFromEuler([0, math.pi/2, math.pi]) hexapod_ID = p.loadURDF("robot3.urdf", [0, STARTING_Y, STARTING_HEIGHT + random.uniform(0, 0.002)], [0, 0, 0, 1]) print(p.getEulerFromQuaternion(p.getBasePositionAndOrientation(hexapod_ID)[1])) def gaitScore(bodyID): current_position = p.getBasePositionAndOrientation(bodyID)[0] distance = distanceFromOrigin(bodyID) angle = angleBetweenVectors(np.array([0, 1]), np.array([current_position[0], current_position[1]])) return distance, abs(angle) def distanceFromOrigin(bodyID): return p.getBasePositionAndOrientation(bodyID)[0][1] def angleBetweenVectors(a, b): unit_vector_1 = a / np.linalg.norm(a) unit_vector_2 = b / np.linalg.norm(b) dot_product = np.dot(unit_vector_1, unit_vector_2) angle = np.arccos(dot_product) return angle def inverseCurve(x, a): # 1/e^2 = 0.135 # a = 0.135 # a = 1 # (pi/2.0)^2 = 2.467 # a = 2.467 y = a / (a + (x * x)) return y def collidingLegs(): # numOfCollisions = 0 for j in range(24): aabb = (p.getAABB(hexapod_ID, j)) familyOfLinks = [x for x in range(24) if math.floor(j / 4) == math.floor(x / 4)] + [-1] # collisionObjects = [x[1] for x in p.getOverlappingObjects(aabb[0], aabb[1]) if x[1] not in familyOfLinks and (j not in FEET_INDEXES or x[0] == hexapod_ID)] collisionObjects = [x[1] for x in p.getOverlappingObjects(aabb[0], aabb[1]) if (j not in FEET_INDEXES and (x[1] not in familyOfLinks or x[0] != hexapod_ID)) or (j in FEET_INDEXES and x[1] not in familyOfLinks and x[0] == hexapod_ID)] if len(collisionObjects) > 0: return True return False def runGait(individual): global REAL_HEXAPOD_CONNECTED lastTime = time.time() global firstCycleComplete dt = 0 firstCycleComplete = False initDuration = individual[0] force = individual[1] gaitChromosome = individual[2:] gaitChromosome = ([initDuration] + [0] * NUM_OF_SERVOS) + gaitChromosome resetEnvironment() stabilityScore = 0 heightScore = 0 collisionScore = 0 sampleCounter = 0 p.setRealTimeSimulation(1) while True: if CONFIG_MODE: p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=read_debug_parameters(), forces=([force] * 18)) else: p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=readGait(dt, gaitChromosome), forces=([force] * 18)) if REAL_HEXAPOD_CONNECTED: updateRealServos(ssc32, 100) # Evaluation Metrics hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID) currentStability = sum([abs(angle) for angle in list(p.getEulerFromQuaternion(hexapodBasePosAndOrn[1]))]) currentHeight = abs(1.375 - hexapodBasePosAndOrn[0][2]) stabilityScore += currentStability heightScore += currentHeight #collisionScore += collidingLegs() sampleCounter += 1 # timing variables now = time.time() dt += now - lastTime lastTime = now # Finish evaluation after 12.5 seconds if dt >= 12.5: break hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID) currentPosition = hexapodBasePosAndOrn[0] distance = hexapodBasePosAndOrn[0][1] straightness = abs(angleBetweenVectors(np.array([0, 1]), np.array([currentPosition[0], currentPosition[1]]))) avgHeight = abs(heightScore / sampleCounter) avgStability = stabilityScore / sampleCounter avgNumOfCollisions = collisionScore / sampleCounter fitness_distance = distance / 100.0 fitness_straight = 1.0 - (straightness / math.pi) fitness_stability = inverseCurve(avgStability, 1) fitness_height = inverseCurve(avgHeight, 1) fitness_collisions = round(1 - avgNumOfCollisions, 2) fitness_total = (fitness_distance + fitness_straight + fitness_stability + fitness_height + fitness_collisions) / 5.0 line = f'ID: {UNIQUE_THREAD_ID} | Time Elapsed: {dt} | Evaluation: {fitness_distance, fitness_straight, fitness_stability, fitness_height, fitness_collisions, fitness_total} | Chromosome: {individual}' print(line) with open('C:/Users/Jonathan/Desktop/results_normal_cyclic.txt', 'a') as f: f.write(line) f.write('\n') return fitness_total def sinusoidalTestGait(t): coxa0 = (math.pi / 4) * math.sin((2 * t) + math.pi) femur0 = 0.2 * math.sin((2 * t) + ((5 * math.pi) / 2)) tibia0 = 1.3 * math.sin((0 * t) + ((3 * math.pi) / 2)) coxa1 = (math.pi / 4) * math.sin((2 * t) + 0) femur1 = 0.2 * math.sin((2 * t) + ((3 * math.pi) / 2)) tibia1 = 1.3 * math.sin((0 * t) + ((3 * math.pi) / 2)) return [coxa0, femur0, tibia0, coxa1, femur1, tibia1, coxa0, femur0, tibia0] + [-coxa0, -femur0, -tibia0, -coxa1, -femur1, -tibia1, -coxa0, -femur0, -tibia0] def evaluateGait(individual): lastTime = time.time() numOfPhysicsSteps = 3000 samplesPerEval = 100 stabilityUpdateRate = int(numOfPhysicsSteps / samplesPerEval) stabilityScore = 0 heightScore = 0 collisionScore = 0 global firstCycleComplete while True: dt = 0 firstCycleComplete = False initDuration = individual[0] force = individual[1] gaitChromosome = individual[2:] gaitChromosome = ([initDuration] + [0] * NUM_OF_SERVOS) + gaitChromosome resetEnvironment() for ii in range(numOfPhysicsSteps): if ii % stabilityUpdateRate == 0: hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID) currentStability = sum([abs(angle) for angle in list(p.getEulerFromQuaternion(hexapodBasePosAndOrn[1]))]) currentHeight = abs(TARGET_HEIGHT - hexapodBasePosAndOrn[0][2]) stabilityScore += currentStability heightScore += currentHeight collisionScore += collidingLegs() p.setJointMotorControlArray(hexapod_ID, JOINT_INDEXES, p.POSITION_CONTROL, targetPositions=readGait(dt, gaitChromosome), forces=([force] * 18)) p.stepSimulation() dt += 1. / 240. # time.sleep(1. / 30.) hexapodBasePosAndOrn = p.getBasePositionAndOrientation(hexapod_ID) currentPosition = hexapodBasePosAndOrn[0] distance = hexapodBasePosAndOrn[0][1] # straightness = abs(p.getEulerFromQuaternion(hexapodBasePosAndOrn[1])[2]) straightness = abs(angleBetweenVectors(np.array([0, 1]), np.array([currentPosition[0], currentPosition[1]]))) avgHeight = abs(heightScore / samplesPerEval) avgStability = stabilityScore / samplesPerEval avgNumOfCollisions = collisionScore / samplesPerEval fitness_distance = distance / 100.0 fitness_straight = 1.0 - (straightness / math.pi) fitness_stability = inverseCurve(avgStability, 1) fitness_height = inverseCurve(avgHeight, 1) fitness_collisions = round(1 - avgNumOfCollisions, 2) fitness_total = (fitness_distance + fitness_straight + fitness_stability + fitness_height + fitness_collisions) / 5.0 print(f'ID: {UNIQUE_THREAD_ID} | Time Elapsed: {time.time() - lastTime} | Evaluation: {fitness_distance, fitness_straight, fitness_stability, fitness_height, fitness_collisions, fitness_total} | Chromosome: {individual}') if not math.isnan(distance): break else: print("PyBullet Glitch") resetPyBulletSimulation() return fitness_total, # start of main program MAX_MOTIONS_IN_SEQUENCE = 4 NUM_OF_LEGS = 6 NUM_OF_JOINTS_PER_LEG = 3 NUM_OF_SERVOS = NUM_OF_LEGS * NUM_OF_JOINTS_PER_LEG UNIQUE_THREAD_ID = random.randint(1, 10000) LENGTH_OF_CYCLE = 12 LENGTH_OF_START_SEQUENCE = 2 + 1 LENGTH_OF_SEQUENCE = LENGTH_OF_START_SEQUENCE + LENGTH_OF_CYCLE LENGTH_OF_GAIT_STATE = NUM_OF_SERVOS + 1 STARTING_HEIGHT = 1.375 STARTING_Y = 0.01 TARGET_HEIGHT = STARTING_HEIGHT firstCycleComplete = False REAL_HEXAPOD_CONNECTED = False CONFIG_MODE = False ssc32 = None if REAL_HEXAPOD_CONNECTED: ssc32 = serial.Serial('COM3', 115200, timeout=2) # open serial port control_IDs = [] # PyBullet Init physicsClient = None if __name__ == "__main__": physicsClient = p.connect(p.GUI) else: physicsClient = p.connect(p.DIRECT) p.setAdditionalSearchPath(pybullet_data.getDataPath()) plane_ID = None hexapod_ID = None resetPyBulletSimulation() programStartTime = time.time() servoRangeOfMotion = (math.pi * 3 / 8) JOINT_INDEXES = [x for x in range(0, 24) if (x + 1) % 4 != 0] FEET_INDEXES = [x for x in range(0, 24) if (x + 1) % 4 == 0] p.setRealTimeSimulation(0) print(f'PyBullet Instance ID: {UNIQUE_THREAD_ID}') def main(): init_debug_parameters() print("START") # Back-flipper 400 Gen (use robot2.URDF) # runGait([0.18403936561894646, 300, 0.1549125676230881, -1.0737228551789968, 1.1074034854568302, -0.5075648311566827, 0.9410632472797863, -0.034075539924461766, 0.04087326062084187, 0.016970270367710892, 1.0693994730213368, 1.155687813177694, 0.8737522824643122, -0.8647752630675463, 0.34299370658943856, -1.0211653604035968, 0.9327693440640767, -1.1011770525732225, 0.9557766462321559, 0.12072049734526494, 0.6379668000414453, 0.38230918565376665, 0.38766472211677316, -0.23345728123331336, 0.42693206671590045, 0.7481283759819202, -1.0035764425332458, -0.37743247317618395, 0.09703593626443223, 0.4096524242490998, 0.5659367640154525, -0.48634980239282366, 0.9997166523571077, 0.9918650566996552, 0.3533658070404414, 1.0175827219942823, 0.18743930901921652, -0.4458899131062403, 0.4201947524885313, 0.9657458794711107, 0.44323639067960297, 0.8503041963843176, -1.1368206866652761, -0.5949936064673491, 0.8431072036023203, -0.8259446127674113, -1.0362372103175401, 0.15060262481341474, -0.9859007911949546, -0.21962601316827257, 0.09533520637849181, -0.640348357362408, -0.8041160416557014, -0.7812025840957206, 0.11151372791644286, 0.8274774721561737, -0.587046978534175, -0.32808303668861744, 0.2379704057869646, 0.18775280488712448, -0.4377264809328173, 0.5907623805366229, 0.05202338940205825, -0.2451747086887523, 0.8470984599764407, -0.7682503206243262, 0.3612923441372827, 0.6886023359929412, -0.9693524777736018, 0.304702690167437, -1.1660144413974514, -0.8249616411604217, 0.8945052164694315, 0.17544939809574825, -0.8272460898178078, 1.1407934664917578, -0.2000536217205298, 0.18640987180335764, 0.2679299333926803, 1.145665972340061, 0.9764033023740143, -1.0945467100291453, 0.521372365408202, -0.08805314721161141, -0.38934451999230035, 1.1416905493697052, 0.9003889322068577, -0.8129184705562436, 0.3440473274506305, -0.72472648064133, 0.05399471861877388, 0.5194134990647563, 0.6874785346278812, -0.8122596509146587, -0.650730661490093, -0.7272921738378133, 0.4576376839803699, 0.3904171653145497, -0.9810005319300584, -0.00285443936171912, -0.36535172159131735, 0.6144096327192144, -0.15837248303352225, -0.8994195620240998, -0.550954584675316, 0.6429230964102726, 0.8005796647490672, 0.06531222692534534, 0.34974094724817234, 1.176172791792436, -0.5252710369532949, 0.2649227929594751, 1.175606830532634, 0.9455873746485913, 1.0932290476666615, -0.5309007757921452, 0.2682629673178282, -1.019068207596018, 0.7873164405123094, 0.47109953022389206, 0.9043790189976995, -0.4554792669173991, -0.7129058230136001, 0.06376465587541758, 0.8334084349886761, 0.4891839072422823, -0.8195171322070331, 0.355909241507946, -0.45439362049140547, 0.7612376551762988, -0.05436372347589597, -0.8253395241105608, 0.5353956017148908, -1.1278223769955171, -0.2672704939182695, 0.08236845953569603, -0.3944515835531134, 1.0532839324087664, 0.2152014313163344, -0.32115401363252016, -0.4401831731301486, -0.8316311944948868, -0.8204912647642763, -0.20684288623086328, 0.656586992390969, 1.040632220799805, -0.5681960529259297, -0.8935973924071543, -0.5523442578187371, 1.019030749112957, -0.9889777010534911, -0.7813891126298407, -0.31025456229208886, 0.21737299067653276, 0.11975606760923985, 1.1489133897234511, -0.732747722798833, 0.46248225304712504, 0.8367764473513415, -1.1345064996816838, 0.8487271456519844, 0.47079084546084493, -0.3880313224602788, 0.5726640163660738, 0.3169122624606709, 0.3125375497368141, 1.0725665493127594, 0.04471119068333991, 1.1194888957575166, -0.694350406505744, -0.3409595779421505, 0.6171251620061712, 0.22135934758297232, 0.21247623650675107, 0.8669374876359844, -0.31535073366399385, 0.5538889770906046, 0.3757263311055013, -0.597927592864876, -0.6925085946018497, 0.34871269014582607, -0.7181727784647577, -0.9959175484190584, -0.3941241000777373, 0.5843467229636823, -0.1298465717484976, 1.1265371185410973, 0.10481709067861797, -0.6208804733701672, -0.23209634549660108, 0.09164363735575871, -0.5218291197106613, 0.13407195016157047, -1.0811880597442607, 0.6537001639909427, -0.9112100951312594, 1.1331704450421252, 0.09526547721035253, 1.0691734422557067, 0.28286325422558284, 0.2155840511857598, 0.34219576355889947, -0.06858382641835256, 0.6352320740995255, -0.8534759393001677, -0.30215311605080114, 0.4825461632485498, -0.7878025062942408, 1.1767649332440155, -0.36658719987216254, 0.614083134565041, 0.017395772324190255, -0.8141910253664506, -0.9789440851674488, -0.760947748240976, 0.10514245629454896, -0.012445121344935495, 0.8955364949519948, -0.9407396155918096, -0.5059512257000718, 1.0169038534816517, -0.5661662987702231, 1.0472948411801215, 0.9527469422382762, -1.0438693320196037, -1.0197514641091732, 0.5923565043667608, -1.1513518068819006, 1.1426265213356581, 0.7314115693481198, 0.035878365067006056, 1.1268253186061643, 1.1381898892090025, 0.050668047659784055, -0.3374091279069584, 0.7307081467526516, 0.026235117587053144, 0.5330659472771377, -0.03700545752962979, -0.23289865423067055, -0.03238468060810259, -0.8203158342693152, 0.5683798195792417, -1.1246799094062077, -0.758692396093738, 0.21847165129039725, 0.5696240201910205, -0.3529263485054064, 1.0260220368312303, 0.01224911889098179, -0.1809953840590205, 0.16439486454032642, -1.0079506314517355, -0.7339119466544526, -0.796638067199314, -1.0901440827406046, 0.6979503548178353, 0.7015791939518996, -0.07233693177751095, 0.5560875159234098, 1.1110141779625964, -0.15396573755282433, -1.1582494805739991, -0.12961450456604595, -0.651868837749322, -0.31774126871869124, -0.26337831137926265, 1.1722112677888488]) # Experimenting with stability # runGait([0.29107088383373003, 156.78061666398597, 0.5353900646350714, -1.1333425119926464, 1.0829260730302332, -1.1640892198484636, -0.38152815636010307, -0.7197641554363123, -0.5865711046576539, -0.7927045883259933, 0.00438855244070635, -0.6432876760380152, 0.08594928155643794, 1.0817177784301633, -0.5378762158033574, 0.6930352009582383, 0.3152893767243987, -0.8955744085304733, -0.19691910222378564, -0.6131664945408353, 0.5512774089140886, 0.6670518195451283, -0.19309128337814246, -0.39607435850701944, 0.47480066743434857, -0.37028244976875146, -1.0989195356925148, 0.30442539638418725, -0.9337728215237907, 0.30406338012158807, 1.0455043322618425, -0.06789772225569224, 0.5806250136267157, -1.0375724064199314, -0.3543513598059251, 0.1989952263373842, 0.23561168218655393, 1.0508947475484427, -0.5301435173978837, 0.954111551885351, 0.17938815590296145, 0.12832022231695767, -0.1490689385957007, 1.0330605104523767, -1.0623171252199062, 0.8445117720781832, -0.36027189597546316, 0.5443268480270156, -0.1000204487317421, 0.8404845535139747, 0.7974970727477276, 0.7264552844874479, -0.7000730851293409, -0.759341129282885, 0.7648050158369193, -0.7522289855617343, -0.9984554385243157, 0.08999817877211987, 0.9363902863024169, 0.7202283975791759, -0.3961247258926616, -0.36531006526282306, 0.6003213302935796, 0.38400973936199784, 0.07770508777397611, -0.4360267539477962, -0.5751568134137885, 0.43883791069800354, -0.18052901071260805, -0.20490900220420233, 0.18186013658998493, 0.692889951182456, 1.1009750256518542, -0.5280637382212376, 0.9864059841841444, 0.735701606227071, 0.8506684523432434, 0.19014925787028816, 0.02734747647350761, -0.14246780172817314, -0.16363487369520202, -0.9807750892297045, -0.5974559893332009, 0.7052210645249009, -0.5722152424030353, 0.4150366036529538, 0.8451537180291235, 0.4434838540550997, -0.20824516651145206, 0.6091705295348645, -0.9590250992142602, 0.9808724317974076, 0.4183489440801338, 0.3607884449764098, 0.06383687946190619, 0.5937967791598316, 0.24274029229005406, 0.29029702682807396, -0.603878266910079, -0.08806950361411958, 0.7212683704190836, 0.6724813333613975, -0.18666038908670848, -1.103082059804687, 0.8768587952536211, 0.1404761787154466, -1.0478894200143816, -1.1437694960941056, -1.03754562219342, 0.9085399008442834, 1.1227743423279155, 0.498537990420221, -0.8371826748208432, -0.09808959558757369, -1.0626830441409378, 0.5380159945100353, 0.06381426021825665, -0.5683621599007505, -0.8656452557602182, -0.3593917993503882, -0.33715498495122065, -0.7801978053428386, 0.9153213044740255, -0.7555054418695308, 0.26788356436185146, -0.06902203453873508, 0.25274353461079657, -0.6944626972070734, -1.0430307172162676, 0.01812578724476625, 0.02313415896879832, -0.6806192043426953, 1.100081799618252, 0.827785090927609, 0.3269284020247252, 0.03206468028287163, 0.3034997439357618, -0.2990653227916562, 0.7397771966931967, -0.8780480762102226, -0.08487561447549834, -0.577616393319167, 1.0833921351724336, -0.45990422848121937, -0.6346960024499542, 0.7918294091829395, 0.027155163465394427, 0.19054579609590222, 0.21557173632598228, 0.2980525771157228, -0.7559737274895846, -0.97517502765191, 0.06865090400328322, -0.5031462207447848, 0.10497243089263641, -0.7965555365903747, -1.0373626266104656, -1.0533096615397561, 0.10728070263954059, 0.796368793127805, 0.0718344507091692, -0.9989396260631868, 0.6356575989158342, -0.6255437988888762, 0.9131334879875902, 0.45646847811471414, -1.0169463676260804, -0.3933819058755607, -0.5997997874897212, 0.17878990565350586, -1.1569178781134557, 0.10159645335836587, 0.7154971633906789, 0.17032819164387833, -0.01835367286864094, -0.9505402084183495, 0.9691636502442869, -1.0866819107494512, 0.19673356296061473, -1.0813009593788294, 0.6727946528411259, 1.177458334902635, 1.1463233157921833, 0.145360816245766, -0.7110332186361785, 1.1672615674161702, -0.3210995288856508, -0.3412206078486237, -1.1150104372864078, 0.41469339605306227, -0.2438596429359537, 0.539355647844741, 0.12085515871084321, -0.9647547341312186, 1.0521097335095957, 0.38872376706386774, 0.12699195498661892, -0.1666314031269644, -0.1452609089409052, -0.9161542968661167, -0.0576685820645067, -1.0362064288895902, -0.5438335521979928, 0.6421961281435908, -0.8782675763606693, -0.32039420495397747, 0.6517605169997935, -0.34461234725989986, 1.0265223840919862, -0.9642919006925839, 0.6343523074380544, 0.01045648767965579, 0.3839206068543592, 0.3625094480567086, 0.5988029218201046, -0.8066055092585431, 0.8291837194941895, 0.9966471145724585, -0.5512131701360924, 0.558229602974704, 0.6430208438139704, -0.36772966559972137, 0.9071931330847132, -0.30657207454292457, 0.18015360737564146, -1.1574946716164571, 0.6901959363107916, 0.786073839325254, 1.0524799852271292, -0.48261528673935933, 0.3021126071842598, 0.6780681739932523, 0.2650223276064161, -1.006069056570006, -0.37549673659808014, -0.8831740449899401, 0.6404770888288831, -0.29655423133316006, -0.30248718319006307, 0.2914366205771275, -0.26389183625692514, -1.0895101207281785, 1.0340066693226782, 0.9883010962564867, 0.13283052185185668, -1.0053930692545063, 0.9173399063162657, -1.1359574713434795, -0.9135848528331729, 0.05275828150306455, -0.8544265299335544, -0.6004625904664892, 0.7568333265679985, -0.11361613904339729, -1.0251203832530935, -1.1051123528377, 1.104096469074662, -0.4090842273664589, 0.23362094428508276, 1.122749227526524, 0.2089305257744809, -0.07565225626772398, -0.19006931939016714, 0.9450976678385695, -0.25602949043929973, 0.8979865614568747, -0.7508855781432413, -0.468020831328862]) # NSGA # runGait([0.18229659766382353, 155.6458409097608, 0.9083504748793311, 0.14110476724188775, 1.093443926606583, 0.8999005754220708, 0.8149729234408216, -0.6359985441288066, 0.5861105866627622, 0.9646599108012346, 1.132867106787237, 0.7918013480335797, 1.146016728309355, 1.166593885399247, -1.0830432373628303, -0.9263478251771459, 1.0107748178924647, 0.4646106439794383, -1.169978052196896, 0.0749939582085001, 0.4339923743202392, 0.4579402086767843, 0.4206199667029586, 0.1397555030784438, 1.1401145649029063, 0.09302868565904275, 0.4914790880995965, -0.4651971857366567, 1.1659566230018072, 0.3706345064730484, 0.07552351079101301, -1.1232067067347673, 0.2222935344062407, 0.7748993910829708, 0.13034880610013827, -0.4806035746604289, 0.3172527997840071, 0.5068224937104546, -0.46511584843166, -0.3467931766616326, 0.3427084205149607, -0.32737952333572434, -0.90724945399064, -0.5250338620208708, 0.6880580209305295, -0.5448070713760786, -0.18858065144794406, 0.014731130802321182, 0.05906164696150665, 0.5284225601490862, 0.2234470472115875, -0.6232032858763568, -0.90751250478335, -0.9199446731694133, 0.24647114606718526, 1.1071349261385088, -0.22236693394071033, 0.49967256016722467, 0.8997056992139608, 0.2047903228421882, 0.9318238130993908, -1.1170109958568422, 0.3134441187993395, -0.7308917666312805, -1.069328123854823, -0.8079594196034741, -0.8413209463842631, 1.1062445646940164, -0.03586696528282618, 0.9654148851126274, -0.9432680014273601, 0.5234582594311347, -0.7471694311620266, -1.022219081571329, -1.0800214764917782, 0.7474112702428726, 0.20819166616338916, 0.7215699077419591, 0.38031567283758844, -0.5238628816347054, 1.0770153104321716, -0.6397760818081154, -0.22435045232641265, 1.0706893179893495, -0.5518655141151997, -0.19087636009819303, -0.3512479711738529, -0.6606861068197772, -0.8685585946822181, 0.3604633384909186, 1.0275382741711763, 0.06655444813978417, 0.9935834582186229, 0.7279386983043616, -1.0070347596788973, -0.2442584535361799, -0.3012388201961493, 0.7247939705316814, 0.6269234457029824, -0.009873626827067952, 0.482981540629763, 0.8598378851596727, 0.4741322053329257, 0.675550009524477, 0.346302537230719, -1.1243070756199751, 0.22681429162070263, -0.3097657746518692, 0.6778382742087453, 0.814184670743237, -1.010608111150304, -0.27376846268023297, -0.9948460491716468, 0.5069784751074181, -1.119671608976601, -0.9303075410380663, 0.7246078940736616, -0.6722076482955358, 0.37757103600219066, -0.313874069830721, -0.43472066633036216, -1.1278978108552458, -0.9970308936270744, -0.5565800651858721, -0.9069457748848149, 0.8230975287693061, -0.41294547922588815, 1.1712915826924468, 0.5098575610704372, -0.9343470208547747, -0.7502818925909562, 0.8572882565769667, 1.1527965107091545, -0.5985576253107086, 0.9812633011454751, 0.43198678500041227, 0.5217073857233142, 0.9761183062018322, 0.14128704712955387, -0.2776161554656262, 0.7504777433267875, 1.0294036660645036, 0.09622107476155035, 1.084571969315032, 0.5909472984707462, 0.21678827645458928, -0.20873040261437428, -0.8425470304835826, -0.5794336238166817, -0.7224193962610191, 0.7320581158158446, -0.3615401506592452, 1.1405747073218429, -0.3039589800092729, 0.2894225332294616, 0.26050649010553945, 0.681767611672782, -0.5129831573243372, -0.19268708535592294, 0.2842271081958875, -0.4316514377659478, 0.1747797126503924, 0.16177042672268072, -0.9595387421298439, -0.8913796116466794, -0.2835623569393363, -0.9021243233987757, 0.04675926339236765, 0.5877718252549794, -0.020728046886497195, 0.1960504582672131, 0.828348254755653, -0.3256674408706686, 0.6430416383221862, -0.20525504926868066, -0.8518231015695202, -1.0599288641751397, 0.6287112429011469, 0.12367108041799399, -1.0720406710260566, -0.22472210546705562, 0.8706060321838783, 0.5291724611088444, 0.10250068539672591, 0.7278411385365671, -1.1566550009574674, -0.48415340513814353, -0.14201813891013926, -0.42454015353898894, -0.5588938960807662, -0.3294006824868001, -0.804967243168935, 0.8162080012175026, 0.18496746845666612, 0.3891323361310516, -0.7744570170530798, 0.11870436656346904, 0.9500286012565656, 1.091687566807378, 0.3307255383169255, 0.7118468053052446, -0.9013453096963969, 0.1945196784104959, -0.7862302171325798, 1.0371600096585611, 0.8279744386055418, 0.5349665267082687, -1.0492245155619515, 0.24063714267361025, -0.5253103025206994, -0.6958371376482045, 0.5127663834795291, -0.5668633184192481, 0.028756495211944066, -0.8180067305130339, -0.7325151144334637, 1.0874568313948747, -0.6204051504490435, 0.16734526054734847, 0.9079945409597623, -0.1605782825625574, -0.9493435726574494, 0.9729771352267385, -1.041240909006733, 0.8207784518169133, 0.2019719768666147, -1.1386639991254925, -0.6372470497638072, -0.5284328510489867, -1.1424013728720803, 0.31553420746729177, 1.0380382961752586, -1.1411444021812454, 0.09246165325365872, 0.1706564355825929, -0.6346966931891327, -1.0909483051470628, -0.06566436851792082, -0.2776209741481568, 0.41899201957450416, -0.18759177838803043, 1.1555756485784177, -0.5822077172996798, -0.9193289683677482, -1.0371716158033841, 1.1423430653663564, 0.8779681991740422, 0.7805125432142439, -0.7721653288915576, 0.5155584453512811, 0.14486889941392897, 0.8446819611612648, 0.05327295198343703, -0.33865091333049985, -0.14899995870829524, 0.1953458127677415, 0.8939023739574229, 0.07623855879466708, 0.6130493982347537, 1.0918462763933745, -0.8759140979104185, -0.9919552795899489, 0.531399920610189, 1.035948455011811, -0.6346835942687693, -0.9522149883706655, 0.12740143026457326, 0.9609495300188751]) # 3000 Pop # runGait([0.904983046733017, 159.59983729578843, 0.060696523522925525, -0.30971496430036916, 0.7353270535594881, -0.6505978383780697, 1.1023304598221446, -0.30768612827725195, -1.0234200031222016, 0.0034031598955847732, 0.21330511114420406, 0.9254559265553964, -0.6604354617020531, 0.15158813875789579, -0.7854467191411058, -0.9925929220629403, -0.2080119772713885, 0.9748408255452494, 0.32631902985278716, -1.1409334395171054, 1.0693652898105703, 0.12206649342856929, -0.2847542804409562, 0.4801514292150744, 1.0332765953216592, -0.7938197444031939, 0.2563131442452105, -0.14869709222993316, -0.9347675501625538, -0.524006106702254, -0.11909684998489307, 0.8400278760972555, -0.23718061034206372, -0.337660742691555, -1.1686283476437243, -1.1031105878405127, -0.7646199378803564, 0.6354804367029614, 0.8837680367321205, 0.15899423130435295, 0.6712575159053917, 0.4215958247199955, -0.3373087437071557, -0.9305356508955385, 0.9082056114784287, -0.9284716662471378, -0.04940610858174345, -0.06555931514262112, -0.09399768472542123, 1.1247909715839755, -0.48379285974626773, 0.570525480919135, -0.02569623444311407, 0.10714561439371209, -0.10783544772282928, 0.7051584770708194, -1.0406922832593428, 0.06343296206551907, -0.8505979742277806, 0.10694125521184705, 0.16935548980784373, 1.1420837333010894, 0.24204597235287523, 0.6475736003934104, 0.17055212844135192, 0.49474061804168407, -1.1398076486306385, -0.03973245191392927, -0.939386769890378, -0.402476064224687, 0.025119711897026987, -1.05440268787099, -0.2752953135618634, 1.1685995968528273, 1.1257083961904089, 0.29732029639677987, -0.17567621997968294, 0.9564892264662193, 0.751911791222228, 0.18761642526516176, -0.3232472318368491, 0.7932493092806446, -1.1052582188288498, 0.5487840041424124, -0.70316267873878, 0.5857454028700838, -0.30104018247011155, 0.3990877589811526, -0.27622278756255064, 0.5007368227279884, -0.34255158345432923, 0.7860783873697565, 0.3299290546401101, 0.4212830410670498, -0.5000823971778967, 0.20211647698962795, -0.5954542100162727, 0.7891262765370252, 0.8398523515973949, 0.04208448038937486, -0.24762466260929505, -0.18298569176248317, -0.36744847594043806, 0.11711890578959555, 0.6784909064918407, 0.043547048965568554, 0.915347385672616, 0.1943537417670627, 0.1961032921533715, 0.27380381570388196, -0.6925505753816085, 0.13409295730737364, 0.9238606281112889, 0.7232290263266692, -0.08475645900857555, 1.0918689969424247, 0.11494102395735217, 0.13564497247063464, 0.07791390649505298, 0.09101847685593711, 1.0802565634925867, 0.008017176336832414, -0.40863001168996127, -0.4349722126523693, 0.34453158076792034, -0.6910315034834699, -0.8948888951214328, 0.36598368092354766, -0.43159001817612835, -0.09136672190834433, -0.8265804981583658, -0.41569623861994176, 0.7235977966485335, -0.2699267245166663, 1.0160916486038205, 0.05956580763846824, -0.553446262414352, -0.9234155272540824, -0.5105546990572772, -0.634441156000243, -0.40216456144001933, -0.659878523232472, 0.016898776661833703, 0.04370343683036865, -1.0525099132085054, -0.1360717628812732, 0.5358560458811824, 0.052683861773873776, -0.953171635298017, -0.15148360309076792, 0.8695124128462544, -0.33150174271113014, 1.1018672681161934, 0.8122315339180584, 0.05632606046036302, 0.4062446410358813, 0.9032403720408388, -0.4898652953167396, 0.5547542361296853, 0.34407051580411596, -0.9688368827468914, 0.9051281478921898, -0.382672404368127, -1.0351659289591528, -0.28339507478975706, 0.2604244554458595, 1.141276061674245, 0.9511590958810777, 0.030865821870599747, 0.25589416378172836, -0.899230741333316, -0.6890771547052199, -0.36098686027424987, 0.2046761115043388, -0.003370011028005335, -1.0326969178585779, -0.6399760361033779, 0.2945889455809976, -0.5693772211328435, 0.5190623470719792, 0.9594447543339326, 0.6647471001461713, 0.1765304159915148, 0.43139180526620574, -0.7827997940081548, -0.3212428257056203, 1.08691662804371, 0.5724684958868459, -0.8190711895017851, -0.21893910988788873, 0.43754121343708036, 0.7761978329434286, 0.023307117981586058, -0.8196812812240051, 0.18349841454177002, -0.03275888140948699, -0.9354688626764325, -0.29752922729690606, 0.1038144707355869, 1.157887360987824, -0.012635618639992992, 1.1772296247879417, 1.0476346313277654, 0.10969465515895042, 0.9315375765707544, 0.4127446193866228, 1.027376379551766, -0.21108693714197815, -0.6492523615384952, -0.1992276005394296, 0.9471808298697213, 0.003879051139011558, -1.007300896674733, -0.8988174362275243, 0.4571936981359096, -0.3114735176334528, -1.0288979365415865, 0.21589235355521563, 1.1668173760981395, -1.0513185987779647, 0.12533634979511898, 1.0255130494459233, 0.748872451843244, 0.09667778038896534, -0.984941038411984, -0.07093582524591927, 0.5164103929817825, -0.27201410547664984, -0.3729048874293173, -1.1149579500690774, 0.8813975424355013, 0.621449531061543, -0.6997908270429463, 0.5020729261400154, 1.0064048881599486, -0.7789049856237727, 0.1128585572848923, -0.19354726814305145, -0.464830471290481, 1.093822978982704, -0.7444302566691616, 0.5228503281130006, 1.0127816296546253, -1.1495705447930669, 1.1634921469729014, 1.017059004992762, 0.6538475673570939, 0.2985847382952567, 0.44100054350476847, 0.20413700406627103, -0.7151778221967301, 0.40107695707208585, -0.7845232708359956, 1.126462565607725, -0.7541211894437213, 0.28493713718804164, -0.5111505775098296, 0.053487615522491705, -0.5972630106930484, 0.867696699744679, -0.591697544975821, 0.393417762872977, -0.36433296593800835, -0.8484271043364143, -0.7889442880625308, 0.5526505308931524, 0.36476343329950656, -0.010331075612058583]) # 407 Gen # runGait([0.8781196143633982, 157.10313398974353, 0.33682254295973746, 0.28781781595826333, 0.1860859338114289, -0.20420881621380305, -0.12123927275926893, 0.4063033014361015, -0.20359193737052045, -0.6840192443790235, -0.28254702343692906, 0.5940254747152814, -0.29777220678601746, -0.07426962639294979, 0.9652159747014115, 0.2473752294851017, -0.6107793773528992, -0.13244976914336656, 0.5280864171637462, -0.059421386701237325, -0.07844527791237588, 0.6322545653056038, 0.4724601535718872, -0.3287282121853098, 0.5434097111921933, -0.12151448936067652, -0.06979580112172787, -0.2961931277705389, -0.4805882127012387, 0.3364130911622725, 1.0005701725869078, -0.21847954935067443, 0.1323700155317861, -0.32215689673367087, 0.14430331665049628, 0.09917150470049849, -0.5170401624287033, 0.5409236317536736, -1.02363228425136, -0.5320260643642395, 0.9218582075166826, 0.2807391864517396, -0.5941315102406781, -0.7080454310389085, -0.31585622472883196, -0.009146624918177084, -0.2012219697627285, -0.4409244609725404, 0.8768753147403492, 0.9343776617888977, -0.02141775939762952, -0.26104580922522647, -0.24705414040844845, 0.34300112955081297, -0.3356925840764099, -0.6775278951424454, 0.632154513923834, -0.5828623947214877, -0.5182796152392433, 0.606350185900368, 0.3246392910354486, 0.8302757207728939, -0.0023731755697271803, -0.16107561586683852, -0.5441686853739696, -0.8288171478401807, -0.397679027844255, 1.0145087733378917, 0.5771456856002078, 0.1928252929176832, 0.2801312178087099, -0.424024932102493, 0.028490342932658078, 0.5663828653801755, -0.2578226202044432, 0.4758103361385356, 0.11262059630304765, 0.17852984636877395, 0.7819886760768826, 0.4777904992793935, 1.1215684250587168, 0.7012165047082592, 0.08680724775780826, -0.12794232943092734, -0.02749916734935132, -0.45447494760953283, 0.39467736190532837, 0.556999354112899, -0.47790256532634695, 0.15041111386454983, 1.0555134056088191, 0.1949848324658606, -0.1334691560253397, 0.8282086290450636, 0.41689095269036547, 0.3213829957559171, -0.45920978149223457, 0.6474648195495811, 0.6759097856561475, -1.0097973227736488, 0.5730950969137286, -0.4092749722577607, -0.039674737074665734, 0.18021687378702161, -0.6615793121935327, 0.03142374866540614, -0.7336966171880697, -0.3283666283009425, -0.7807776498788782, 0.04535750599480415, 0.1704720716786568, 0.07139750224822779, -0.39506187566783524, 0.5372040246741976, -1.1473534956177283, -0.4013147582043887, 0.38703856371800294, 0.3971836501834768, 1.1715304273819858, 0.5442662829228595, -0.0980978149061639, -0.4344320237816741, 0.7384324675711982, -0.6187275059274405, -0.3575034072195102, -1.1288861687148302, -0.3261414464285166, 0.7523726891212104, -0.15988727327072425, 0.1131072052563967, 0.34829181401975273, -0.6281159632389499, 0.7689620896680501, -0.12006262327557764, 0.9842080944836419, 0.26578776890675115, 0.5127275308397158, 0.6177831879058816, 0.6136850718675044, -0.7101342612681036, 0.22667486103048795, -0.6637649111191182, -0.49116115181432607, 1.1778110294059096, 0.6536538976088225, 0.337894833822659, -0.8418763216442848, -0.11767229020786187, 0.3713509801518212, -1.062628223739996, -0.6364809135462092, 0.25314885600822956, -0.4532780204714063, -0.9156058815025188, 0.38398735762219094, 0.6504528410510488, -0.8483565675469873, -0.19248354081194868, -0.10272402672891327, -0.21538792572640295, -0.19546972821258218, -0.9483484869960997, 0.022956480787546467, 0.10722697400615173, -0.5339228101100632, -0.35402855681089174, -0.4909015301740968, -0.18175978846992896, 0.6859271886866835, -0.5159021239613567, -0.4536971124614899, 0.33596686235547757, -0.8380097153759376, 0.2564768448158085, -0.17784663515089585, 0.8848479741072743, 0.45734330263531453, -0.09873367668089586, -0.7500713258217162, -0.25406396619910043, -0.9054849581453508, -0.41576987655001807, 0.39503507766193025, -0.5857624014296016, 0.4560242643397691, 0.23900721343893294, 0.4454950080559121, -0.008251391139937114, -0.5778461849029692, 0.49439432908178516, -0.08522125551940313, 0.9544048902657116, 0.26600604145504003, 0.3367464085720411, 1.0096321755173974, 0.5254892106771129, -0.09967034763491985, -0.21229560617239768, 0.5697413449479685, -0.33752083603028504, 0.1099730086514387, 0.6135896282792587, -0.2316015516647347, 0.27698810246217326, -0.41050437696734554, 0.27114015297957794, 0.5172821702323088, -0.8557836333808082, 0.1431613671576169, 0.26614523302465865, -0.9784779658422884, 0.22069893362397217, 0.4698093606975688, -0.3444787910995501, 0.3215750648265838, -0.1275396420123813, -0.16744367567541496, -0.2865130786194499, -0.203914306582315, 0.09531066543160083, -1.0473530567418816, -0.43792746630963003, -0.8246099035388195, -0.1995013012675149, -0.05971337685132197, 0.07864737594828375, -0.7640329802075775, 0.7133374177394672, 0.3450741117987123, -0.6613122911561858, 0.2175616273524131, 0.39585440284780726, -0.6045817099745175, -1.1406619528893633, 0.06642553919379446, 0.17478825655989105, -0.48174098942017146, -0.5192782669857927, -1.1714093392113059, 0.5938325737824399, -0.482930381615228, 1.078819781022143, -0.8684695968207783, -0.15775647868438034, -0.19836857010162148, 0.12721713278404426, 0.20363848723966207, 0.11179394420943511, 0.49603448462048155, 0.3600952668625213, 0.3128222724984558, 0.404650588027724, 0.0840823881356966, 0.19944902798724976, 0.12426183303095407, -0.6113147369273974, -0.40558552009503623, 0.4393747149838387, 1.0064976254947864, 0.02535220524117529, 0.6867814865985039, -0.4423754966018487, 0.20201446246914118, -0.697738158333364, -0.9883884469952561, 0.4564284783687155, -0.9310257794603739, -0.7670742706760328]) # 6000 Pop # runGait([0.5833710183294218, 159.94477382941363, 0.274991231117698, 0.238089263008252, -0.1417409643619611, -0.12761521449834923, -0.19289461538039873, -0.10856112933014755, 0.15968577636162862, -0.17368631551323016, 0.07203736702130702, 0.881941236232128, -0.49131125475461257, 0.41963359660824545, 1.0286266905353563, 0.08461166310190373, -0.0930092118460774, 0.6688730971003121, -0.5272671341802382, 0.3759165556754689, 1.0284225286200426, 0.281022494747565, 0.0009195019049819536, -0.0879260351696233, 0.36182544936252586, 0.1544240116221797, -0.3379165966729512, -0.07107860607401342, -0.35347372811378175, 0.24474628711192828, -0.9554210776881508, -0.2446425071911576, -0.21834542364787896, 0.02941224160898587, 0.19860309964710376, 0.32015885118565973, -0.38463037767537034, 0.2721652517032083, 0.4498871803091191, 0.2843738257583236, 0.501327523282536, 0.669013035550511, -0.37715689084783993, -0.7193636388118547, -0.2383013342521316, -0.17489396233602697, 0.06083890600102712, -0.4034525364101677, -0.24583511137643727, 0.05016350547975096, -0.5231072760701854, 0.0920601174252217, -0.3798879187489547, -0.06425162833626528, 0.1175629295006112, 0.02682125752619795, 0.5075090858782456, -0.16206766607753353, -0.9027943006438802, 0.5191380547248162, 0.1922772367714138, 0.3722573359482723, 0.27824784135917774, -0.36599087581441164, -0.06620007679763394, -0.37707864764924415, -0.3432745401212583, 0.1890972969239655, 0.9771314779636118, -0.6379190437437263, 0.5327515128308239, 1.1266802573644779, 0.4853618562003829, 0.03715655903182573, 0.07311510274068314, 0.5423300464375319, -0.0658356136420452, 0.6733211262326829, 0.5412515512543659, 0.475841545559648, -0.5369352656406974, -0.026774867624149132, -0.27366768812094183, -0.21535394823513682, 1.1272641607914005, -0.6324828192170618, 0.22992240750612652, -0.8332942275738103, -0.4448812583609043, -0.5639998583724821, -0.28504303170819406, -0.13715306369785674, 0.3349484025718961, -0.3700368781101578, 0.20300787227134326, 0.22374862961672667, 0.027970795265832554, 0.7014861172229404, -0.04926493320095343, 0.4402290874741377, 0.3860194514832391, 0.11569030596073443, -0.06036997313965854, 0.1497256975919505, -0.377481545800565, 0.08298090520892161, 0.9438244188255105, -0.48021805376469584, 0.4543715274216308, 0.8678356926851799, -0.003915278924756722, 0.10352872557178089, 0.3358865719916397, 0.4211155579389066, -0.030249314775129762, -0.5658285551195321, 0.2548939424634452, 0.5745275199121783, -0.7796534931283465, 0.3451123282022226, -0.5444761756627212, 0.12200790829540269, -0.25898916669720645, -0.6724214809633824, 0.34635133694786935, -1.0685493620290625, -0.166454962800517, -0.8051985252291386, -0.4306033386198576, 0.3621432335285329, 0.014468787338504891, 0.141080510173102, 0.13964744684544284, -0.15421615523049945, -0.4317859615807832, 0.225587551388641, 0.693207792900198, 0.5533948757767216, 0.20097437713556277, 0.23256665133179352, -0.4990635733731684, 0.37724815041759296, -0.8484710927328951, 0.052329062943848995, -0.6454186305205749, 0.01709338435440333, 0.1426615820133712, -0.7496362823830726, -0.024592492969917387, 0.07160640453502068, -0.2474844962946594, 0.5941575845367926, -0.20960304431184107, 0.6424578239764861, 0.2920273219156567, 0.7036560308915455, -0.8121144845665177, -0.2789410770162129, -0.7413476580353197, 0.08188596178827257, 0.07931227840034549, -0.7207975890283618, -0.6065813517836143, 0.3983191376566657, -0.5635381703226274, 0.4088177741187736, 0.8161358908559947, 0.6554301845419963, 0.04547395492205422, 0.08051995385752733, 0.7945827746307063, 0.11087351442670304, -0.590752837198396, 0.2065658076101474, 0.0751712923684167, 0.6709125887262557, 0.1373187383960103, -0.18183312802940133, -0.4350057499267376, -0.3766430661862623, -0.8199596582372628, -0.14153603961297806, 0.590381220135425, -0.16508543450631305, -0.20708569485397604, -0.34591459093209215, -0.16651848898298874, 0.5178287410957361, -0.03657852374819068, 0.7219509009910949, -0.22937310869060928, 1.1464596068133195, 0.21233031874020497, -0.3609307120798186, -0.41136793770748015, 0.16347336752562386, -0.04569336581669571, -0.12320285070861678, 0.08240315222323638, 0.4579164525630148, 0.10194743670878537, 0.5748048740706077, -0.38484763478500494, 0.8009525610955103, 0.7333605699869847, 0.37124845323434263, -0.03501117975518403, 0.012948485735009754, 0.29139932552493186, 0.34343670572619495, 0.8542624160112243, 0.2047939987143607, 0.3903803959743837, -0.20493239305818473, -1.1287011492813999, -0.32936672671984124, -0.36581898984821176, 0.2451494881151558, -0.5756460181132672, -0.030221322542399086, 0.16449751038968874, -0.3567999251278406, -0.1618212236300447, -0.11207687799559582, 0.05735981109003743, 0.9415542138674963, -0.3554473551841668, 0.5357750527639715, 0.21498207309781378, 0.4532008047694893, 0.21329882952215284, 0.5859846457864504, -0.16362093353740018, 0.1319546289160159, -0.2194715016448026, -0.266878066809855, 0.19007538470038587, -0.6214579041470789, 0.07758190484905561, -0.7515667963793465, 0.24700843522334995, -0.292447662725082, -0.4181253106644778, 0.19564903243421003, 0.19724000917384554, -0.2063833311816462, 0.46455125472211967, -0.0899164519697946, -0.4859666940225116, 0.2204956850628324, 0.5537344147667811, 0.3710020504693896, 0.42084808456566025, 0.22826893049722402, -0.3009973798887208, 0.3133299056345898, -0.5362470634819437, -0.07363025268708201, -0.4903844709824772, -0.4212031706808154, 0.593200663984306, 0.03428638943992187, 0.24491294188014479, 0.46221509482741235, -0.20849095803967968, 0.6337473393725238, -0.05747450930384633, 0.8875435750416844]) # 0 runGait([0.7387319894185713, 147.82355001579506, 0.6305372633499426, -0.6089588304954848, 0.8912756231059142, 0.2812261582743101, -0.5713260153151064, -0.17272091345083518, -0.011128621604706623, -0.802059235021269, -0.07153954960452258, -0.5428904527014263, -0.04381109750503209, 0.09113787494874881, 0.7723570365515549, 0.1241992107232388, 0.8337401506855846, 1.115458030805498, -0.013540807256189336, -0.5839520097163835, -0.7340746975491128, 0.5868023045338302, -0.9298983610216932, 0.5438917235683132, -0.05782837894738324, 0.4198029392031244, -1.0399101725816757, -0.06612708025138092, -0.5082125750188753, 0.9201548240864632, 0.06444257109533891, 0.3314957278066273, 0.43523252410016, 0.0101257284239189, -0.3455692282668785, -0.11991854934521307, 0.8938694635098376, -0.5612059600360004, -1.1311528570896223, -0.5932545380125831, 0.4344991139274895, 0.3428898066225319, -0.2906991777632436, 0.48606253534779564, 0.5357348004370723, 0.08998319318443504, -0.9267085738943713, -0.8937243514792317, 1.0577416788427096, -0.37068573549717954, 0.9165099103165408, -0.8428317356586791, 0.6907079780081538, -0.763945038433602, 1.0409972769402867, -0.7930695812727582, -0.45187653759465174, -0.5161324587418127, -0.7914439627122227, 0.833033591113862, 1.0408039580092332, -0.05381107166535859, 0.8438281153722502, -0.0387362598590002, 0.6164861225837377, -0.6286851880995831, 0.8640915900752995, -0.7744000726632477, -1.1733643185821832, -0.09815300085455836, -0.2477118609768313, 1.024101066375414, -1.147511226358933, 0.35649235792115364, 1.1024258715004915, -1.011618835769622, 0.5915335712528709, -0.030590833481361157, 0.21394935583673327, 0.2677965469007608, 0.5549362872301691, 0.2695802858891776, -0.8655473520001171, -0.13250526441705102, 0.17727687014444649, -1.070467039423309, 0.09651563983885625, -0.9558246154936185, 1.1511036912990131, 0.8111082334542412, -0.3165391333624401, -1.1028022950228613, -0.8702156791239426, -1.1681706777717666, -0.652290858655339, 1.003148181057313, -0.10090114268197192, 0.23187888015208769, 0.5941647728264801, -0.43999609085011204, -0.11509272070881571, -1.0798002236171276, 0.018290046530861526, -0.7279320899826196, -0.498825849932375, 0.5922026329566983, 1.1770495895717317, 1.1658461699766112, 0.5387616073370702, 0.6762210875494419, 0.564309749770725, -0.3035549596906124, -0.23885528257994526, 1.1072615720375825, 0.5666318535111361, -0.45569851974439834, 0.8338190610059566, -0.6359449813770147, 0.2596402577409722, -0.7767216770530929, -0.90418267806025, 0.113288160612949, 0.39315211887973467, 0.15879221931780196, 0.758361875600458, 0.8700712002631037, 0.306520197643136, 0.7532325435435356, -1.0353300637178853, -0.4455790005356547, 0.33046558165864237, -0.41986999994668306, 0.773773975624336, -0.5730775662391308, -0.32242207870145256, 0.5695427482221903, 0.06540060708986029, -1.1068765041634638, 0.8444999211248407, 0.04543079459398691, 0.4642442589105744, -0.6039790052127436, -0.892455957263908, 1.1129699696404938, 0.342772182719143, -1.115584864083039, 1.0625540212723195, -0.057194100238716405, -0.5879196602166177, 0.5790752639491412, 0.6440806383356259, -0.7481329504140624, 0.20534187872140564, -1.0990982256561714, 0.2791331755311888, 0.20300461353714883, -0.8197464538582441, -0.7741517445104196, 0.36122048253607164, 0.813782786457911, 0.39582928554897623, -0.02580819987456784, -1.1628778529586477, 1.0745713708553488, -0.5089798478319643, 1.0062303026439694, 0.6478357664888437, -1.1138156319365986, -0.4955658167644643, 0.01673202498902171, 0.9162968925255734, 1.1449260986124963, 0.45197676369281314, 0.4913407885919339, 0.9059066063082057, -0.6513168739283108, 0.08060475225758434, -0.8062943072398908, -0.5854814411007928, 0.8888342908698426, -0.9445568643031321, -0.7753945536759548, -0.3003503278781188, 0.6951193721206237, 1.0356586073990068, 0.8830749880175515, -1.0664223102877843, -0.609899276809712, 0.8167470737757756, 1.038925181199521, -0.5200440777902839, 0.4128415160980885, 0.8988517426568858, 0.23012308000225246, -0.981407304217973, -0.6000864286294282, -0.8302474366129275, 0.3022460425741058, -0.7232702813935017, 0.3225916050209834, 0.1690591643089261, -0.731263207027456, 1.0793778048303206, 0.6724712011076479, -0.7393802772190122, 0.52180702196962, 0.653704773120031, -0.8435500860065721, -0.503370357216786, 1.0089409411880252, 0.8239113158523748, 0.5789158304017497, 0.8017043064577623, -0.81666613981439, 0.4674783795387365, -0.44533480654686275, -0.4893466194479631, 0.9007928200059672, 0.02483073138245584, -0.5944238649035959, 0.28518215854040774, -0.24733421237552355, -0.8505607276413669, 0.5571358775523416, 0.9045395124615454, -0.6657820640979742, -0.9652597006250097, -0.4591179819423816, 0.05481742210849316, 0.28907992231884405, 0.7124381991670108, -0.6030190226588272, 0.3369808339189879, 0.3038297672106993, -0.995236450812498, 1.0777162746217996, -1.1439340008569936, -0.7047632734591232, -0.532467147310556, -0.7640334064115123, 0.9758524528369246, -0.24433882388927364, -1.019693761734842, -0.11397606855688958, -0.26140300759258983, -0.5755519362573679, 0.15416561480192903, 0.8157008073605059, -0.988078686018823, 0.7532529999268318, 0.31269649944522704, -0.34261705061474756, -0.8905985767822926, 0.6096508828791698, -1.0668100653950248, -0.379130418894862, 0.9096912331462104, -1.001701666565123, 0.6416783457901682, 0.14610426544728483, 0.7031005674547539, 0.4247842879063306, 0.4021107592425244, 0.8928714878416208, -1.089585355806771, 0.5386513324462168, 1.043195877742578, -0.9701398946532979]) # 50 runGait([0.6109376305551025, 147.5781875317787, 0.8620634914832349, -0.5626015076241742, 0.9150007577136691, -0.20417512686545095, 0.6544359094278946, -0.31327506130394855, 0.8452968857390276, 0.13887431059938735, 1.1771529929786608, -0.9178071433237085, 0.21286308614656976, -0.6984312985937364, 0.8250658263071654, 0.38678895878185166, -0.8386364979015601, -0.8324431895189177, -0.31964574670169177, -0.9513705765809792, 0.7833723510749697, 0.9633303649676936, -1.077086285278876, -0.5823511574760045, -0.24329005344133708, 0.36075110180937114, -0.8737875239530779, -0.7120336903431772, 0.9694421297627523, -0.681817972163381, -0.7263666665964092, 0.04202279641735396, 0.5376884588766628, 0.5528900104757648, -0.3762309750477318, -0.5347146669245599, 0.30309856425260817, 0.02701219403931735, -1.1761371301420371, -0.3097959495083542, 0.637250448114133, 0.45383108548435047, -1.0293681131385823, -0.34337946728402396, -0.20240409776563223, -0.30376152527443845, 0.18856656091055635, 0.13958997918335925, 0.14259244107987795, -0.3669671234254508, -0.1371355859726133, -0.3999333309862724, 0.08190816860672162, 0.9531999241577855, 0.4305115008592596, -0.15969404241405846, -0.10706207687230784, -0.5875234717318174, -0.8888652093021814, 0.7018823816096099, 0.0097155460541066, -0.31852823774787353, -0.7161533552571332, -0.6946183251839217, -0.44771872458142625, -0.8020418614747353, 0.08697562850763507, -0.33670122865676794, -0.016255823485752413, -0.44553776220063407, 0.7067040729755709, -0.3305529141109416, -0.12353152419246438, -0.06405724257227025, -0.4289379681288039, 1.0169932699634694, 0.9219679687362414, -0.07926430997569933, 0.8461155106368546, -0.5108459915920485, 0.01721461698106075, 0.25640166227431, -0.0012638280470829346, -0.32081211955480904, 0.965518227098844, 0.07977377006028907, 0.9914084076788008, 0.9368602392194756, 0.79622005627768, -0.12120211619815363, -0.07642712418177038, 0.15250148243132808, 0.8820133072304428, -0.15324005900457768, -0.012947970781577268, 0.5314107654179234, 0.2657806659207431, 0.21867155408318162, -0.5645131510256867, -0.16370059560939496, 0.2210581088064703, 0.39055811273202895, 0.2826802498295499, -0.4229943862011821, -0.835900738908754, 0.9612898958738532, 0.9962752356339487, -0.053303884261599155, 0.30951330649963815, 0.34386442126447203, 0.3167278260159818, 1.0850909905354877, 1.0088643013546652, 0.6148040192088533, -0.32713499022688375, 0.13265347253599408, 0.729050651796031, 0.4385817170037452, -0.8104814221892234, -0.08204642341024995, -0.429968478624448, -1.1469995240847928, 0.05053455747353239, -0.6868806082011671, -0.7681702363623998, -0.6240472813916106, 0.8999904570363008, -0.5540755976757679, -0.1395815200095187, 0.7216419755694113, 0.00341887019974102, -1.1314219417339941, 0.47079825372218626, 0.38634641962439187, -0.4969326894940178, 0.9700897618329442, 0.31738524085942643, 0.5918654468120178, 0.0649345288163781, 0.9223422749742548, -1.062672657821793, 0.30896020749191433, -0.28885102187939604, 0.5103642056497637, 1.1586385214620625, 0.47011741255653366, 0.7362591411689603, 0.695808261288789, -0.6331424834334121, -0.6156728717869878, -0.6958300056305404, -1.1223768304439534, -1.1079218078030504, 0.4832955305303133, 0.7872713684414188, 0.23742695514821588, -1.0325192716558655, -0.5035525254625557, -0.11125895540865731, -0.06707968995471164, -1.0901891398628312, -0.05185746626132734, 0.17939884745186596, -0.7629342237736646, -0.25568469662030346, -0.3436266275846107, 0.5234963038843524, 0.532265503526556, -0.6045831852953002, 0.9974128911214244, -0.17925607028201557, 0.5791020459001643, 0.6873833790287516, 0.21880371572846155, 0.11009481032702205, 0.12865186069194162, -0.3268975846759916, 0.02259596959226029, 0.5559932137864555, 0.5932843214246097, -0.3710969455539212, 0.14529725265287333, 0.7044006452814845, -0.008852974292849092, -0.6124416737681215, 0.9682131380447476, 1.1375649719691259, 0.37091879445775916, 0.9352732490378375, 0.1539095660283667, 0.777440000897248, 0.22606717389632985, 0.6069013838761509, 0.30093397706517244, 1.1442039256026204, -0.7161426712243226, 0.588887225888025, 0.6972839960175987, -0.3500160949784321, 0.5128375679350539, 0.7935689766031192, -0.19559794779993978, -0.6253604887410248, 1.0145936629813255, -0.6706586307879839, 0.003436295592896238, -0.417246076528322, 0.8556308147276876, -0.209938526431461, -1.049104873280623, -0.33207489467651996, 0.6814354585137341, 0.3417057443470919, -0.059172559496654564, -0.8715300782572717, -0.2556518530893984, -1.0671471245233821, 0.3614377209651649, -0.15680078741943126, 1.166195067305183, 0.32081449773971193, 0.18756280575004247, -0.19985672490920128, 0.7805915689741869, -1.0536988894142132, 1.0857317947415768, -0.48900363536886143, -0.425774798688516, 0.17741903723193003, -0.1303947078559029, 0.9502549942826287, 0.5361055442035286, 0.7290061426453971, 0.29795698418990374, 0.26959259813541037, -0.8620031075888178, -1.0011321698786917, -0.48116523293039026, -0.3455270947267371, 0.4655510054575944, 0.21073592473488212, -0.7393279519987309, -0.7331986835493073, -0.19722904469418162, -1.0802395643312521, 0.2934313950761999, 1.1402520649753152, -0.9086071535929683, 0.02395654499079075, 0.3684164909317418, 0.5614399969048851, 0.9946642592430968, 1.124476487906898, 0.19575442149823322, -0.24851818064192416, 0.3905054965095121, -1.0073781554239616, 0.44320833092972917, -1.167994336275549, 0.6853930357205337, 0.09224681578137976, -0.9244241472672434, 0.32327571642704045, -0.08511712913634017, -0.1417785078648055, 1.0629206015460837, 0.3359763967683185, -0.30410336954697426]) # 100 runGait([0.6640463205265905, 140.52675516067927, 0.8199810222722016, -0.25481952456604723, -0.3425457104430286, -0.29895559122008386, -0.03691952728541809, -0.2926749796378846, 0.32589540084946145, -0.917897553277117, -0.1788579132316635, -1.1021614115353857, 0.16879565842355682, 0.9654926553955153, -0.8262395642035657, -0.032366000748803886, -1.035706777515601, 0.421355764319076, 0.7572712816111169, 0.20885822322721553, 0.4327161270350611, 0.9459811540427878, 0.8261945712691102, -1.1252075254946101, 0.47151105047328135, -0.20370646005147414, -0.17791531392877594, -0.1951822044066674, -0.3347713397441206, -0.8437477462605121, 0.6043792513174889, 0.8135465977213642, 0.1161484116712968, 0.2520589879602344, -0.013875994605011654, 0.6015180797865725, -0.6176009285822545, 0.12004417622115887, -0.9961965091337416, -0.3125071727309118, 0.8937107026868603, 0.08912944387701997, -0.06790816311341702, 0.22325347059753536, -0.09025762128409298, -0.011920073737759995, 0.35752949513101395, -0.45906903012374745, -0.788562694194514, -1.0050198450114056, -0.0361372172292605, -0.5954885246272503, 0.26895619166201407, 0.27184604863769407, -0.37353950677917513, 0.40112354341843237, 0.6375471269499228, 0.3141153522934928, -0.9509274229231759, 0.8779304554614856, 0.04594048324209277, 0.2495420932435201, 0.08241559351660238, -0.17642988998764342, -0.4447938485357037, -0.29330972785416387, -1.1174363806073722, -0.9616482147806933, -0.11200817025193116, -0.2108973739829038, 0.7633783825024583, -0.3175711563677784, -0.055385576075883194, -0.23831266165748738, 0.08104352235723783, 0.023356401512964642, -0.24320747848452665, 0.5859836965526846, 0.5423632994485224, -0.1667373762787313, 0.28209152742387117, 0.57278826903801, -0.2032795427955932, -0.4025112301636612, -0.5183539956075682, -0.19265157313585188, 0.17583720556492372, -0.5476355988504892, -0.6627234804934719, -0.11118988812304811, -0.7805070621113364, -0.4529826769989489, 0.7097466060065737, -0.620126964770608, 0.17005073215107458, -0.310351639008707, 0.7097004232177474, 0.6271790085262221, 0.619307086397858, 0.8131713488548474, 0.1497738579998278, 0.02526583014944417, -0.20005273447658806, -0.5474277783268228, -0.9924782021468856, 0.5028217189827595, -0.19263703499936438, 0.20588243107956172, 1.1385437676064627, 0.23883082558624708, 0.004571684392304376, 0.44876050879385027, 0.12812072388391504, -0.24208052529798593, -0.11013899281343525, -1.1196512365364517, 0.9507652902470094, 0.4545046069675115, 0.011125408478537602, 0.6549444015747156, -0.9034580752892476, -0.816680671954233, 0.42267629830319997, -0.610277202583551, 0.5500134814297155, -1.0434024414406398, -0.1937217218579826, 0.5755930968565269, -0.3839059765475241, 0.5719780788906925, 1.0347321090545003, 0.44370082946255346, 0.876765248918222, 0.2923665942100978, 0.9325649935073932, 0.5916765606714397, -0.8204301829871634, 0.5375111299520478, -0.9513662298918846, -0.48330360663587535, -0.014861243621365067, -0.7494281866976655, -0.08825309305806134, -0.9149440954101552, 1.1656564955027569, -0.319007800832239, 0.24788655005464028, -0.3902252669018448, 0.37813696098203525, 1.0257086358944083, -0.22782064462614982, 1.0142953972331836, -0.09326047201660298, -0.9608786031964357, 0.7922821770960228, -0.5752078753307402, -0.8741277024150452, 0.42074556397962476, -0.17088790293716782, -0.27812595030330334, 0.16024650373276178, -0.9015926997014683, 0.16765286991610046, 1.0745410173910972, -0.6109232086797313, -0.6866105711698087, 0.9586175739077698, 0.36069963154315404, -0.8179673245547332, 0.28221064021521486, 0.07881056395367772, 0.9621841067996804, 0.32611659794735176, 0.44963057094757963, 0.07055641109546117, -1.0165648669301155, -0.03825226786436686, -0.2562167100164272, 0.7081096623524648, 1.0925864874641888, 0.7985534527556107, -0.576117648391484, 1.128905296865967, -0.6836316776207304, -0.2843403105351967, -0.2875350090436179, -0.8884226806370785, 1.0867043497721995, 0.15936102064610103, 0.7213678990932757, 0.20189075328906597, 0.21909012756117713, 0.35081305063305934, -0.5533491342604271, -0.39139018059751557, -0.6063198386438513, -0.5324644497030327, -0.9211774284351677, 0.8014720982812371, -0.5110042508153627, 0.9729234799472499, 0.6198329213846822, -0.7172777918874114, 0.71393306635313, -0.8845569787211464, 0.8037248436039608, -0.4005762723352054, -0.41068663652781295, -0.12408256332477458, 0.2156827075982222, -0.5842278773022845, 0.5993604325472786, -0.1714832792903668, -1.073883900675711, 0.5300023789111741, -0.393565753380665, -1.1077691155993767, -0.19722587955218868, -0.10417172968555885, 0.6584848022547337, -0.5329152183955796, -0.3950555151941949, -0.10882724704645816, 1.1644009182829218, 0.1641879666963921, -0.6681618516093505, -0.927583868963644, -1.132447578431215, 0.9601897942960477, -0.3719235237813504, 0.568283689266319, 0.30050241478858897, -0.40449584730595933, 0.4561858885619927, 0.2909602044742249, 0.32523163443121184, 0.42755122870221796, -0.43174561514948073, -0.6752553468030823, 0.4204116282761027, -0.33022122289804556, -0.10054716261882779, -0.4499960947229804, 0.5718195749224134, -0.7769045028417172, 1.119286880787453, 1.0339119406352926, 0.05274713166468337, -0.6460257891457617, 0.8332178051984421, 0.03159851737606184, 0.4659457011446515, -1.1466040486387152, 0.40969329358334694, -0.055850231800543215, 1.0507510732129994, -0.05830916713550008, 0.6673647072199382, -0.93841995086702, -0.5252036523060817, -0.4085500615196542, -0.04419643170246719, 0.5892251042672283, -0.07265048037271993, 0.6495073424232363, 0.41894378985827774, -0.12136863342675985, 1.0354604832131513]) # 150 runGait([0.9676294826559563, 150.70882987508452, 0.7774265785769597, 0.30438411789744857, -1.0457358937004009, 0.06569446508772794, -0.15498365774078185, -0.2377622141182121, -0.5523307256530675, -0.08686467446610878, -1.0526089743219282, 0.8693892350692811, -0.17802396330235765, 0.984292423423254, -0.2150566341031429, 0.06941172841331614, -0.3042670031127815, 0.9739683090160918, 0.3387525680108089, 0.16403610960584877, 0.3348632802624376, 0.726765357781341, -0.9126961896061363, -0.7229583630620422, -0.3051251400627612, -0.18571836602256658, -0.31864411222929206, -0.19706640874261128, -0.11173710313723983, 0.3565369869153394, 0.1971428113859381, -0.2763605210478526, -0.10988448914397031, 0.4865331848012372, 0.19579861099733442, 0.0985008925024958, 0.10508611443908723, -0.5180802186096138, 0.602575401604621, -0.8201174052127542, 0.9018628672824313, 0.0498784872337901, -0.521071153653444, 0.4481479231233141, -0.2524266051402479, -0.253402947342113, -0.3651587489535104, -0.04675187762525251, -0.5284469398758529, 0.2654544927821044, 0.46605508251848005, 0.04966663957014836, 0.2745167545365336, 0.4868187826011344, -0.1497691281628623, -0.19339266529087248, 0.24136863629471383, -0.43924814954512725, -0.6263279786320504, 0.8484699492362705, 0.1585129887321573, -0.2588768245023081, 0.4805335508720735, -0.23474437738054899, -0.33209420118866895, -0.8818001009909548, -0.3070185272881074, 0.32004109284523, 0.6027386544692759, -0.6121775505303508, 0.4490581540464468, 0.5642596329992625, -0.04982483368519975, 0.12126979404157245, 1.03751465671718, 0.3745312020424947, -0.047861781623897426, 0.23215652576049822, 0.48636218211863, -0.1235050817634415, -0.43294538682063655, 0.25467725985917183, -0.3065392897369155, -0.1557890602814631, -0.1535446617220671, -0.594059819196811, 0.2979599287648182, -0.47393639849675195, -0.1498269458086204, -0.5013840640153254, -0.4272045457213613, 0.41099576969282453, 0.435974275195693, -0.4947517141811753, 0.5589410579791683, 0.1652474308641266, 0.40923547743201916, 0.8096533414423498, -0.1614737073645072, 0.1666180159560079, 0.11988387794171795, -0.07807848102820575, -0.7442135781834419, -0.34406828342523743, -0.05221941010307851, 0.3010681255245467, -0.5477604345796725, -0.48790074433118147, 0.5210477108826119, 0.8054612805115671, -0.06963557072433436, -0.15839013687807313, -0.8487419175268571, 0.10322897440577106, 0.28014718041568193, -0.34631485812371793, 0.9430752549792686, 0.47027663953356336, -0.5794821932554436, 0.4692452807674205, -0.11158040045677747, 0.27992277267081245, 0.3776130667252946, -0.6369352430800613, -0.2996620853089707, 0.15891663821065996, -0.2687942812407239, -0.4471464630512332, 0.12797248611817225, 0.03778787082978413, -0.04817441866063496, -0.14364337110596323, 0.2456276684919766, -0.2193460148147342, 0.309322461049816, 0.8838971330552886, 0.9139067446448306, 0.7520794039116794, 0.3506023525822065, -0.25510377807771967, 0.16331308210797202, 0.8879935062411524, -0.5959693041241926, -0.20759495151814522, 0.2108418708456552, -0.7452310360910046, 0.12664881554927482, -0.047080807460529284, 0.4692849434023498, 0.7458543281348985, 0.8107049435101739, 0.7656829635908563, 0.2585428684080011, 0.9841469724781623, 0.8620949405960008, 0.4870555312544564, -1.122938689793093, -0.35529359973828545, -0.327327233145238, -0.3160934335831116, 0.39591363428761267, -1.0579727707301056, -0.31077112675144547, -0.7938933327626483, -0.3590902641595922, 0.19493924076014235, 0.5890886736882655, -0.009036129790468118, 0.596132945850858, -0.03994141013499769, 0.07806084523888342, 0.5692918377135482, 0.4974953937971758, 0.3775889672978954, 0.12873405457093853, 0.3895539355393124, -0.014462890465162359, -0.55425962690001, -0.6132736305766234, -0.41102081373534033, 0.10835255920191245, -0.39706623995337986, -0.05463237156533987, -0.8821361662438925, -0.4293498179030984, -0.44754327412891415, -0.1880089783045697, -0.7609470792799706, -0.3607734401106461, 0.7228114557048017, -0.32350458406045907, 0.003881601223850173, 0.4645169228853948, 0.30933674367871833, -0.5511008060190785, 0.019215497706641993, -0.1901675903409386, -0.2365943643295504, -0.8261367539601678, -0.5582895426381002, 0.8430889595735926, -0.10476902705139379, -0.7224029312799556, 0.27571772103786507, 0.0885536238095041, 0.015217124065685712, 0.3616330436036972, 0.4495807925732856, -0.25846532959546853, 0.02789168870877641, -0.30766351675851644, 0.4048762627077507, 0.27121677550071394, -0.15171546326311514, -0.7757535339112696, 0.07895603889692605, 0.3394112118661255, 0.2762139076230077, -0.8609718868797998, 0.6072119320035823, 0.5713716255007126, -0.6528469102896424, -0.10679737275320846, 0.05933745485535778, 1.0330880833994396, 0.3798427665421174, -0.05376631490501693, 0.35154721956479057, -0.2278546286708691, 1.1215415803557947, 0.37551720594302973, 0.20578900503472414, -1.101421780287494, -0.16904074302935618, -0.3137973325657055, -0.31107743259952253, -0.5054336950181983, -0.6015459471353947, -0.30583499460877933, -0.5710653400947024, -0.9093940918050203, 0.4258975120803453, -0.21935467585339385, 0.7752057901473814, 0.9048914510700778, -0.7846269882405049, 0.42094152311983585, 0.579829888624975, -0.17584369852195275, 0.3434019156849982, 0.4575688137719436, -0.14604013456644133, -0.3645678519465499, 0.369472539160814, 0.8790080502109889, -0.19650675936686374, -0.18752237139683797, 0.5586386030306622, 0.9508801265095614, 0.9411240544168558, -0.345415755136577, -0.14676816884141242, -0.6025122074152638, 1.0662310264379242, 0.18388246055206153, -0.07562722289757418, -0.6679498245650091, 0.18818487201688333]) # 200 runGait([0.9348218778087588, 146.91267362984482, 0.8744564653177251, -0.2311034676019011, -0.0162125073980263, 0.23441739730394234, -0.04068722081101439, -0.01314909472419457, 0.4223694738439635, -0.25574717281863013, 0.11241756397861355, 0.863412621923713, -0.5039035218187172, 0.8097751196961653, 0.5091863473931626, -0.10148835532593689, -0.28922562386776374, 0.5858340382268268, 0.43524750474759666, 0.23821865739642933, 0.46385381613992593, 0.9239038510623541, -0.4014932024069757, -0.7366198054221755, -0.26224195420212393, -0.26567675307257604, -0.6406999273924185, -0.3947291539512541, -0.13202897393736873, -0.36868075869905625, -0.05946923101403889, -0.27726495980956967, -0.5626455668474689, -0.011352949007235264, 0.229512162107839, 0.39705904834877165, -0.4006127993614362, 0.45741277302226363, -0.04872220530283761, 0.939231875796499, 0.9244874997661925, 0.421354026869032, -0.30719169912092076, -0.28374626104543155, 0.036224616108006924, -0.25044075786835196, 0.45388624765306124, -0.2717804606894174, -0.4275921887976257, -0.6646840055520035, -0.14474013946854764, 0.13888294858271502, -0.6177532030009414, 0.2746798600901093, -0.12203515742935869, -0.2628136886221271, 0.38679528157113163, -0.19822470557065894, -0.8884013180032637, 0.9228748319499014, -0.4928839251159022, 0.27037805010739346, -0.36086268564047347, -0.24969367306344575, -0.3336638120272727, -0.19129594916608794, -0.5412798207097986, -0.16378037787753816, 0.8380380076966655, -0.5602998817983854, 0.18838739261107923, 0.5039137894474521, 0.21024282762391727, 0.08436579427566918, 0.6355601001466065, 0.5267180582633789, 0.15087882211657277, 0.2588579542917172, 0.8159804644068003, -0.38735187036573715, -0.40374868821921456, 0.3176228472810542, -0.29327017193023885, -0.5501866453799408, -0.7389217625605805, -0.5615715453807273, 0.3712336142992907, -0.41428358751812816, -0.10726134390360059, -0.4099102222197733, -0.09159826087452744, 0.19893389971361133, -0.13132545262706974, -0.7570399899916764, -0.04170327254544387, 0.6914142826643184, 0.398856999424931, 0.9233641685403612, 0.3554904000885851, 0.07458506209142986, 0.21135000375679375, -0.23744305079600145, -0.013330649851585474, 0.01157025728448935, -0.7142922193662176, -0.057521311631223385, -0.6442594978866643, 0.1356536272774043, 0.9557393672331027, 0.5233808828963422, 0.11374875444427712, 0.09649391854350325, -0.4504172430652743, 0.6539212469538538, 0.1418178498877025, -1.0285250393762446, 0.8140662921364629, 0.22032729153232467, -0.3131857222772149, -0.48190358196718097, -0.6137839859402877, 0.4530943681506018, -0.24490264309157425, -0.7036205243667922, 0.22880630883881176, -0.9353768616975839, -0.22729920059617795, -0.3986687624180637, 0.3771370805444293, 0.2962185862198067, 0.2904151502090839, 0.41187261747985526, 0.5568412571554673, -0.12906786905832562, -0.29816090327711275, 0.6695654120828216, 0.6511164416374783, 0.2354423280825553, -0.2735118074560536, -0.09228336036973724, -0.8324667409784399, -0.5181961380658293, -0.29006499483710846, 0.20790847562845022, -0.5417341319611597, 0.38491216942962997, -0.26276464862820204, -0.4194681593642782, 0.18074940042710627, 0.3028577666580481, 0.7988109336459481, 0.3168960795244507, -0.06708903960865052, 1.065337334032617, 0.5121231247483485, 0.4516447688051512, -1.1319252709654564, 0.36013046523298803, -0.34875120783540486, -0.4784054810104189, -0.6383425055163587, -0.6044113298680207, 0.44898870301162985, -0.8409890804695659, -0.13518983270380686, 0.7206151228912457, 0.6402573302424278, 0.10412067706361405, 0.054761428387725804, 0.7078674741419084, 0.6835347252533357, 0.21226096258043248, -0.3590529214883623, 0.4262896753265209, -0.048765644390856705, 0.38707830574861446, 0.084150534306334, -0.3647673644633279, -0.33591157304158037, 0.543209090584881, -0.9227930221772509, 0.2793779445429621, 0.11437608190319354, -0.7320684310072323, -0.6016577518295898, -0.45131872796737754, 0.05815823303022799, 0.8858937450029887, -0.0019911283316581506, 0.9972537913440365, -0.03610523718702252, 0.7079473862344268, 0.2573924393198488, -0.04475989790206414, -0.046463632383485554, -0.5773905293012538, -0.21619326250264764, -0.18188721111452147, -0.07658954437605886, -0.7681077839396901, 0.09322698951176928, 0.1445427413363699, -0.26358485945073823, -0.35945630531652395, 0.6607553408730602, 0.5395749627096668, -0.06565247358481555, -0.13117986498165218, 0.6166842950843242, 0.4062530279955314, -0.32413286459352975, 0.3382214897259326, 0.060478191467047124, -0.30111192010527943, -0.6852023659365898, -0.6491951557870825, -0.6082929168718781, 1.0411226013092971, -0.6704184953876647, 0.2345803856056618, 0.4849343305291035, -0.18728401603681968, -0.19357983579761226, 0.6070055818353226, -0.1077936670840348, 0.7443380029642911, -0.17385870614262244, 0.4822669757853692, 0.389397991023952, -0.5111936026821581, 0.20633197759969002, 0.1718434261981503, -0.4672185062811099, -0.17236565565445167, -0.13557244311953168, 0.15571859432119767, -0.7500101603166999, -0.23515066300234422, 0.13714967863221472, -0.5267606306271126, 0.13519136956396957, 0.02524328959004487, 0.5235642763509845, 0.8384859468187118, 0.8448970827991501, 0.8107454533312748, 0.5496009157719298, -0.7861009121069743, -0.6234808705813863, 0.4696984323447554, 0.47429018972121284, 0.623971023164932, 0.19594794245176425, -0.08196145489238126, -0.44583013816552275, 0.331803658493219, -0.8110909742267071, -0.21348457194384118, -0.2793726604175222, 0.14931602985100503, 0.12574273195266228, -0.09011644679991501, 0.42322007305737674, 0.4167395715073748, -0.6212842551478526, 0.7246903575782073, -0.06965771001708732, 0.6997039268852637]) # 300 runGait([0.9580170156701137, 156.55023833080287, 0.8697263186451583, 0.41527680177951753, -0.3091878185605595, -0.6992501726886724, -0.3621632626756743, -0.08866639808357406, 0.04011602722874327, 0.07026709630165444, 0.08310069123845333, 0.9771964256154151, -0.400666267244531, 1.0176212186192009, 0.4686604002686661, -0.05444682325152628, -0.3446318452762033, 1.167921573447584, -0.24084550251954484, 0.11520414858809458, -0.9064091144422616, 0.6287846280182579, 0.4042274363728242, -0.17984894184261202, 1.1430310808904414, 0.12829599754811477, -0.2870163134708252, -0.18392037110494033, -0.1249514559839385, 0.40824155792459593, -1.0366104970327679, -0.21924341218226873, -0.10471741599076292, -0.039709787387529435, 0.24308506785995695, 0.5029106171652411, 0.00735981801132328, 0.46310261520766255, 0.2962573675541653, 0.5716571352437573, 0.9229307062858603, 0.4495458291143761, -0.32374844918493895, -0.5428033664800668, -0.1061657887085444, 0.09327418752618749, 0.1360933416106767, -0.05729803839333989, -0.5721972886843723, -0.7501829092993302, -0.15349800908427572, 0.18791462737535045, -0.5470482537350623, 0.0694805637919472, 0.11109949906739805, -0.05080609217009568, -0.10310782753879975, -0.11306331572492027, -0.7342942829959108, 0.5899346008666371, 0.15418825045439946, -0.02081659679571593, 0.23629696966788344, -0.20051899964600228, -0.1124416281658899, -0.2846997071631564, -0.7192552571252601, 0.37433250100587284, 0.4563424915786525, -0.6333746841090807, 0.48199161211899844, 0.7988546437125186, 0.3226337048037727, 0.08751293246797012, 0.6319836666961702, 0.5183905403464221, -0.03681080646589069, 0.32577945075501186, 0.6121356022112711, 0.3422973617966078, -0.38300865284018476, 0.3869972769037436, -0.3438931711267918, -0.2925667840718638, 0.02073915908080158, -0.6601106786744819, 0.18786226365552441, -0.4674216311409396, -0.20596050805709923, -0.6805376409410507, -0.11035629757866405, 0.128064195205727, 0.25006628117465546, -0.3911802588296395, 0.2206671476325982, 0.09977946265209521, -0.8307214146667822, 0.9171381291965639, -0.4940453191512136, 0.1984116913539024, 0.16554188896519878, -0.1928373027542588, 0.035841851144624626, 0.19266064738694355, -0.5850119457302836, 0.2215164403315185, -0.5896064710472241, -0.5102020534325775, 0.7417367519970856, 0.6225121973006423, 0.19164293014838338, -0.05737129492026963, 0.6121162351865662, 0.6866768284728066, 0.14965833690587552, -0.4193640570236367, 0.8160069586540502, 0.4684910259589942, -0.3030223187406086, -0.22660524229484055, -0.26703340415352106, 0.2211243087352533, -0.34540536962148954, -0.49431357086808453, 0.4597744966917602, -1.1664564277056044, -0.42563404464543353, -0.2676448037922594, 0.10874078586225963, 0.30510521880764874, 0.0201911678551102, 0.06799655432754058, 0.2696266035980911, -0.022093390708932178, -0.23885757257157703, 0.23240754800646202, 0.3154235780471931, 0.41222261068120575, 0.21621816215661968, -0.49383086489683936, 0.22028919935866093, 0.3085302761259844, -0.7607054242258245, -0.05524612679499659, -0.4005994571597372, -0.0005409548233603068, 0.09356401716698916, -0.28019790711798187, 0.11366960643707247, 0.11455280438074295, 0.23238882534231647, 0.38151138367739235, -0.6805858547100075, 1.0336614238387605, 0.3031048722576475, 0.3326128459698742, -0.4841094623424372, -0.14572762596592148, -0.6989095508218981, 0.08856510384007225, -0.7833815783352288, -0.6051206720201369, 0.05183879858837576, 0.8525690594373536, -0.21238052918801256, 0.3064353096452067, 0.5227279651783818, -0.26970368473406214, 0.30040315174676463, 0.8044560092955977, -0.31738694194412304, -0.03793873042044421, -0.43780967817899613, 0.44695577264660596, 0.07431440259337181, 0.30468167123379775, -0.17018353015014637, -0.3717841160485929, -0.38018867550367835, -0.8319113906639981, -0.3172654371086346, 0.19103501813376841, 0.7907537210342017, -0.9089959391273528, -0.296319135720049, -0.3417512761829329, -0.023084343039717133, 0.4040896098348129, -0.31660229354210917, 0.20977471047292015, 0.06648686941410495, 0.569876899843004, 0.21573326092963024, 0.12794663668726255, 0.13345639453704178, 0.06166211393616905, -0.03240968584900304, 0.5204613173650747, -0.054310331255427405, -0.606521604737881, 0.1468424637174045, -0.10111301306428899, -0.28436289560722927, 0.8017857089530022, 0.31257612218556174, 0.1945880804760491, -0.6089705211035303, -0.14618931754382708, 0.39343797880425146, -0.5405366749846467, -0.8955466868745385, 0.24857173830306561, -0.18623545173861095, -0.3623886194435283, -0.09699504056721092, -0.3486736104159766, -0.5453068629962625, -0.04010192714300855, -0.5306328827959214, -0.1354335299516863, 0.44670333258196254, -0.29490113171676874, -0.09463147398839705, 0.874510578425735, -0.08994591375239581, 0.9780471833760542, -0.5336783066507795, 0.44298379683008876, -0.44674080020159146, -0.31978046647941477, 0.4387881341782599, 0.5350973549899811, -0.27423388863198106, -0.39599195531628345, -0.17873234672818766, -0.3297290606571569, 0.4175261890217202, -0.41268092911177146, -0.22703685041841498, -0.274965576004083, 0.18191455558091849, -0.4939031672186963, -0.5349104573630611, 0.11079268810336479, 0.29357806459055, -0.7619449431049254, 0.712338129607013, -0.10469146069165344, -0.6452483516150597, 0.27405977939835985, 0.3831614384076198, 0.5368152956549854, 0.1178851135066101, 0.4460847058945193, -0.3883316848615107, 0.29727456716368683, -0.9048653966482885, -0.014346612174598924, -0.30126039008201877, -0.4640418178366639, 0.7986905413889673, -0.07702758460544154, 0.2259118808338296, 0.04026857681135493, -0.26928463274492503, 0.3490075592061821, -0.0973833708982666, 0.6135129639803163]) # 500 runGait([0.7788908289099306, 159.1275018887873, 0.3675002143633652, 0.29358082034076927, -0.15802555334813242, -0.10120259171082222, -0.30648918293561567, -0.05565177235370438, 0.3049336061735364, 0.019485785927701088, 0.07832249749716115, 0.7871716752724793, -0.11324944128855793, 0.33911735703936136, 0.5918403744719638, 0.023601544667689423, -0.28854114361833516, 0.3817510406516811, -0.7632588163737368, 0.022344201194842275, -0.9273228127530271, 0.23720909885208666, 0.15504539382606097, -0.06533263447758221, 0.6586022121665115, -0.29344233757111227, -0.6100745589428764, 0.17959646981207406, -0.2567640532742428, 0.3822693241621865, -0.7185816271396638, -0.17076272358383804, -0.19398205231627866, 0.030812971237587354, 0.13867994513962895, 0.3166621409958447, 0.22733110475404655, 0.5283963851565332, 0.3000850798497766, 0.6660952670105973, 0.78894440862353, 0.5157348667100712, -0.38489800997374557, -0.5993480088686595, -0.18953762119493234, -0.142888877844017, -0.2487995360903048, -0.2553184465203176, -0.6835072531097912, -0.08818770700477133, -0.36234611577801024, 0.1882081759188938, -0.5403677941379689, 0.12135448182929069, 0.13736905269298347, -0.19255224947663963, 0.40446549296965023, -0.12911247255617248, -0.8830555265743198, 0.5421547081545663, 0.19311176458866605, 0.32721151153007055, 0.2615659111455483, -0.3394759597454976, -0.06908691052009064, -0.4945679102133535, -0.664437236127388, 0.455900172021705, 0.9711538928263904, -0.6122014695612167, 0.5055842831599157, 1.0056138878174767, -0.12461961762482054, 0.07270199762420153, 0.1945368404538606, 0.6057165296982737, -0.036218178124653, 0.47457880179122397, 0.561082214156418, 0.5518568617850256, -0.5389721874824412, 0.018553983034344634, -0.33762141187925576, -0.2910578505162613, 0.14535357070447755, -0.5450888267216742, 0.3147936923887069, -0.8630308630441204, -0.35532598921412856, -0.6465004633853288, -0.13894664477940558, -0.05983048923837514, 0.365281504661632, -0.5068437133042195, 0.27739826556422653, 0.19813563846913917, 0.4204274997035509, 0.8205768952006834, 0.20430739373514373, 0.3485830076102606, 0.19097357428020537, 0.11039935013513971, -0.05699918798476541, 0.17873025134016074, -0.5020918329264104, 0.06913567443773855, 0.824576743344076, -0.5181143051990277, 0.5324747932677494, 0.4047169187725307, 0.17512694920182592, 0.09027062872679636, -0.020184312316256805, 0.45759775735791614, 0.3541811364432514, -0.42810856403905084, 0.34330793691017164, 0.37803887536859593, -0.6335568031247926, 0.7451449971471023, -0.422905787574568, 0.1108746870208986, -0.48281598513746043, -0.8845798783329725, 0.2848773437400216, -1.024048537916983, -0.3564009884656577, -0.12474613038765203, -0.20868110635282452, 0.34321844967647513, 0.026989145418742592, 0.0056243347284405665, 0.2157974836543368, -0.13733758298445253, -0.33659375632067434, 0.22898564273416638, 0.5087202771881477, 0.5372813556304213, 0.2763875601801632, -0.0931809119638537, -0.15966469444157633, 0.6929648835534945, -0.6910669985856048, -0.19389406110887974, -0.3902847322396408, 0.14551156290910644, 0.16618646822053293, -0.8039787804703373, 0.15428898913228964, 0.2190997039624487, 0.6297767323586855, 0.679561926817978, -0.25269142672699957, 1.073396465709869, 0.29029445313069896, 0.3205284197358836, -0.8690640106312963, -0.28879170523811604, -0.3779137324309013, 0.11936316568503534, 0.12976155632213082, -0.6265683661237571, -0.4855309257343185, -0.5955282235528421, -0.6845815418683121, 0.4737288107745596, 0.9252056200075451, 0.34567749439018725, 0.0363068008180909, 0.5036072080080863, 0.7640949628326337, 0.23505279305957724, -0.7167717818166955, 0.22850447613489278, -0.030879680605631232, 0.8293535643185203, -0.12780675301767844, -0.4412923860207338, -0.4755533837206397, -0.7447986150788337, -0.351029516667939, 0.14495494618770427, 0.4535847436338252, -0.3531591185986031, -0.3501206760556444, -0.34008350299413603, -0.1719031304459102, 0.5791280201924914, -0.1307266287188878, 0.5722057672119683, -0.15710148018631528, 0.8971534994186912, 0.2136354954365922, 0.10736052402292397, -0.09859594062374435, 0.029800704664000633, -0.036340884369813475, 0.13376827373262254, 0.06508877177327688, 0.3209725597538162, 0.25401652110289125, 0.306412096915022, -0.4062443766586342, 0.8116135654848087, 0.5038625296989976, 0.31304069230057774, 0.27907345633577596, -0.0628432232149184, 0.7488103240677573, 0.26866161782653364, -0.3422913295247829, 0.2620956604170435, 0.3869320718994709, -0.31031616120110883, -0.6430657281164895, -0.22156900833723173, -0.38501223572432874, 0.253328681493752, -0.43126896631860384, 0.13122580788583768, 0.38236533839599784, -0.41315518332835866, -0.06881562913283318, -0.06011531751913962, -0.1786891777692833, 0.5379347036881686, -0.40503481008181036, 0.5715406089598921, 0.09206279188231829, -0.06971523980576558, 0.2873942092356773, 0.5853487864435241, -0.2276481518074298, 0.024954174691643023, -0.45483892434063, -0.24065990358463835, 0.009443952578838826, -0.4484870705490043, 0.020876918478014064, -0.3827342793037868, 0.08765966633266016, -0.27582852508027256, -0.31975146101964735, 0.23584006084015846, 0.29568147715946885, -0.8673046059997449, 0.731200312180833, 0.023929423446759857, -0.573758689689352, 0.20993143702530428, 0.47001185232098075, 0.5565009861719601, 0.4404197794305241, 0.185040383009213, -0.4131600591525496, 0.16851972924086844, -0.4306339258923647, -0.08726456746018109, -0.4968797363532158, 0.11631152950365159, 0.12129503091276284, -0.2797069038719245, 0.28964257172500313, 0.30047606726857523, 0.7797290276248695, 0.6214545112158738, -0.05292732565014542, 0.7730879197180376]) # 750 runGait([0.5798525952403486, 159.40058262811087, 0.2565373666541486, 0.4318803359566548, -0.12670809771496028, -0.18389697331663157, -0.2107828186822762, -0.08822530542530635, 0.22285787517794267, -0.14626266057699905, -0.010708372490804578, 0.8284588168920229, -0.4722713879921887, 0.19208169499854316, 0.7411503431106623, 0.040109802039862204, -0.09388586098031043, 0.3021068442167352, -0.7632253195827811, 0.7506268013480695, 0.9817795923219715, 0.24702479164747443, 0.18619723055382778, -0.01944816101487032, 0.48047453154015674, 0.044027151050185204, -0.3811611523444315, 0.07043423693100055, -0.3519428921487882, 0.06993952938115677, -0.5223378593335369, -0.22654293849301965, -0.3119867211980983, 0.02203965621516251, 0.13948563872031947, 0.303700575374144, -0.38645242345574016, 0.28023524831943847, 0.48072548736928467, 0.23302786453056437, 0.5986122931605656, 0.6980983847283087, -0.34928346917889913, -0.7471794250508657, -0.17324487759716678, -0.17474742917438432, -0.016090144920211283, -0.3939766926275115, -0.22629036214619017, 0.16700221777337937, -0.37273771647989734, 0.09062261530742664, -0.37891402716818134, -0.06917514694333406, 0.17291180959585456, -0.04844904642867835, 0.4909898309834386, -0.12380149375214647, -0.9111999943893617, 0.5239305389825415, 0.18171587810764148, 0.38432773481912763, 0.2485646260803057, -0.34491165699137327, 0.006209690525156852, -0.37412477201907574, -0.4604269737237233, 0.18972851127462684, 0.9223517018397529, -0.6210098084521306, 0.49640907383479516, 1.0891123792650426, 0.49418162637573465, 0.06420244660188437, -0.12089596773664718, 0.550748464763964, -0.06108552913804381, 0.5552559735763302, 0.5522750091665136, 0.4683531478559523, -0.49173267096532985, -0.03517143099932757, 0.06100743363377523, -0.1902922529235461, 1.1122974946275956, -0.6276776253711288, 0.18178541719252822, -0.8132832667298763, -0.4537338576551622, -0.5808862777121856, -0.23668011060600833, 0.09569218539264038, 0.304579054169755, -0.4494551817405288, 0.15870763199473473, 0.3069755905115654, 0.3959705547451262, 0.7213258637748241, 0.3763728637422603, 0.40391108748034943, 0.37339498399229337, 0.01831140131395486, -0.07811735353228262, 0.13357830561871784, -0.3758537743243868, 0.05195547431005445, 0.9379615461508354, -0.5620520288627262, 0.4539455849665125, 0.8143570677050026, 0.004283675773725867, 0.11729610271034435, 0.25800504348420195, 0.3861845305371114, 0.041281706706534374, -0.5754739036307105, 0.25496830847083185, 0.5497065484163852, -0.6197402288256176, 0.4497922477657804, -0.4509130489838098, 0.08492188046586338, -0.3745067142483794, -0.6326481434329293, 0.35798335360645445, -1.0756026955774058, -0.1658013536974587, -0.7407148571190698, -0.4210965495924469, 0.31622190189278027, -0.037060520648369094, 0.027025421714000526, 0.12225503371751616, -0.1873821138347538, -0.39270249305607063, 0.20600245925762312, 0.6985349231049772, 0.538141419017502, 0.28367589673434807, 0.2408451341677153, -0.4857764076187511, 0.3515662648369627, -0.5970692688174171, 0.02074320821791737, -0.4780204081199166, 0.1369717613278151, 0.1389681583857107, -0.7410246577802894, -0.026563078155500804, 0.15750473450145544, -0.13448669931945875, 0.6551277580017717, -0.15601141002050287, 0.7448104569077326, 0.2902755482562471, 0.5364234542988243, -0.7792137180797938, -0.2846168758998948, -0.5839320530147617, 0.0628617276240415, 0.04002665260768596, -0.5479117597172838, -0.34196183099322613, 0.7056701204997842, -0.6647297748826204, 0.42806286178547925, 1.036676035059638, 0.642474334419992, -0.007131427190290577, 0.4639036629286082, 0.7267327436184402, 0.10043705596129168, -0.6440769086811172, 0.21343864782202604, -0.10329009445544304, 0.6425250240843889, 0.05230900542901544, -0.11251073882320739, -0.35085266645906615, -0.4199713623669293, -0.3351922780693797, -0.1672466366670506, 0.5379892464340184, -0.16330627356393349, -0.056804450777555304, -0.4017389922325012, -0.1611244393278351, 0.5367215850055974, 0.26665926782883664, 0.7219467754507272, -0.23576690967651864, 0.9079195952027548, 0.2062387616905374, -0.46534175178439574, -0.10399688011724603, 0.03668728875610021, -0.036926473584827625, -0.10113397006234737, -0.0394881387655676, 0.350606385291519, 0.13403276401659836, 0.5123948398917316, -0.35772789686003825, 0.9668024245923357, 1.027298011515463, 0.48938829842316445, -0.016483670605963077, -0.11757722414303058, 0.2537310530675592, 0.2784246188624572, 0.7695997113771061, 0.20066387160146376, 0.41486141094226053, -0.41256985585307027, -1.0477965177073278, -0.3200262420965195, -0.4739320902039974, 0.1565114856750497, -0.4241862276994479, -0.014128604687211607, 0.16050204319589437, -0.40332695432173227, -0.17516701158934914, -0.11260377701162964, -0.13167892785497093, 0.7970663227025759, -0.5351328770237976, 0.5899558689297649, 0.23041684659804587, -0.15627868369477282, 0.2137694705032495, 0.5696194997458192, -0.17336701928954443, 0.10876003399835937, -0.17072054408485435, -0.329611678752721, -0.14558125057844667, -0.5971107203993231, 0.09088625634430318, -0.9113803135864458, 0.20662562476533045, -0.1850266147294778, -0.3839648611252884, -0.06266604342717771, 0.32620231538556216, -0.4511759755602935, 0.46462930437425676, -0.19098144950012377, -0.45748534958561105, 0.21835806888483988, 0.375990472674876, 0.3152963988042483, 0.4174992880580025, 0.2417839091584328, -0.24397794422280902, 0.35917942428087724, -0.3968249675417042, -0.020614707571517774, -0.5895590906441834, -0.4121546533845332, 0.7169006234784104, 0.00017719522626339322, -0.009118568606292298, 0.43285003350721596, 0.9231244888866221, 0.6350781716028882, 0.025592267149331688, 0.8892290172542283]) # best runGait([0.5833710183294218, 159.94477382941363, 0.274991231117698, 0.238089263008252, -0.1417409643619611, -0.12761521449834923, -0.19289461538039873, -0.10856112933014755, 0.15968577636162862, -0.17368631551323016, 0.07203736702130702, 0.881941236232128, -0.49131125475461257, 0.41963359660824545, 1.0286266905353563, 0.08461166310190373, -0.0930092118460774, 0.6688730971003121, -0.5272671341802382, 0.3759165556754689, 1.0284225286200426, 0.281022494747565, 0.0009195019049819536, -0.0879260351696233, 0.36182544936252586, 0.1544240116221797, -0.3379165966729512, -0.07107860607401342, -0.35347372811378175, 0.24474628711192828, -0.9554210776881508, -0.2446425071911576, -0.21834542364787896, 0.02941224160898587, 0.19860309964710376, 0.32015885118565973, -0.38463037767537034, 0.2721652517032083, 0.4498871803091191, 0.2843738257583236, 0.501327523282536, 0.669013035550511, -0.37715689084783993, -0.7193636388118547, -0.2383013342521316, -0.17489396233602697, 0.06083890600102712, -0.4034525364101677, -0.24583511137643727, 0.05016350547975096, -0.5231072760701854, 0.0920601174252217, -0.3798879187489547, -0.06425162833626528, 0.1175629295006112, 0.02682125752619795, 0.5075090858782456, -0.16206766607753353, -0.9027943006438802, 0.5191380547248162, 0.1922772367714138, 0.3722573359482723, 0.27824784135917774, -0.36599087581441164, -0.06620007679763394, -0.37707864764924415, -0.3432745401212583, 0.1890972969239655, 0.9771314779636118, -0.6379190437437263, 0.5327515128308239, 1.1266802573644779, 0.4853618562003829, 0.03715655903182573, 0.07311510274068314, 0.5423300464375319, -0.0658356136420452, 0.6733211262326829, 0.5412515512543659, 0.475841545559648, -0.5369352656406974, -0.026774867624149132, -0.27366768812094183, -0.21535394823513682, 1.1272641607914005, -0.6324828192170618, 0.22992240750612652, -0.8332942275738103, -0.4448812583609043, -0.5639998583724821, -0.28504303170819406, -0.13715306369785674, 0.3349484025718961, -0.3700368781101578, 0.20300787227134326, 0.22374862961672667, 0.027970795265832554, 0.7014861172229404, -0.04926493320095343, 0.4402290874741377, 0.3860194514832391, 0.11569030596073443, -0.06036997313965854, 0.1497256975919505, -0.377481545800565, 0.08298090520892161, 0.9438244188255105, -0.48021805376469584, 0.4543715274216308, 0.8678356926851799, -0.003915278924756722, 0.10352872557178089, 0.3358865719916397, 0.4211155579389066, -0.030249314775129762, -0.5658285551195321, 0.2548939424634452, 0.5745275199121783, -0.7796534931283465, 0.3451123282022226, -0.5444761756627212, 0.12200790829540269, -0.25898916669720645, -0.6724214809633824, 0.34635133694786935, -1.0685493620290625, -0.166454962800517, -0.8051985252291386, -0.4306033386198576, 0.3621432335285329, 0.014468787338504891, 0.141080510173102, 0.13964744684544284, -0.15421615523049945, -0.4317859615807832, 0.225587551388641, 0.693207792900198, 0.5533948757767216, 0.20097437713556277, 0.23256665133179352, -0.4990635733731684, 0.37724815041759296, -0.8484710927328951, 0.052329062943848995, -0.6454186305205749, 0.01709338435440333, 0.1426615820133712, -0.7496362823830726, -0.024592492969917387, 0.07160640453502068, -0.2474844962946594, 0.5941575845367926, -0.20960304431184107, 0.6424578239764861, 0.2920273219156567, 0.7036560308915455, -0.8121144845665177, -0.2789410770162129, -0.7413476580353197, 0.08188596178827257, 0.07931227840034549, -0.7207975890283618, -0.6065813517836143, 0.3983191376566657, -0.5635381703226274, 0.4088177741187736, 0.8161358908559947, 0.6554301845419963, 0.04547395492205422, 0.08051995385752733, 0.7945827746307063, 0.11087351442670304, -0.590752837198396, 0.2065658076101474, 0.0751712923684167, 0.6709125887262557, 0.1373187383960103, -0.18183312802940133, -0.4350057499267376, -0.3766430661862623, -0.8199596582372628, -0.14153603961297806, 0.590381220135425, -0.16508543450631305, -0.20708569485397604, -0.34591459093209215, -0.16651848898298874, 0.5178287410957361, -0.03657852374819068, 0.7219509009910949, -0.22937310869060928, 1.1464596068133195, 0.21233031874020497, -0.3609307120798186, -0.41136793770748015, 0.16347336752562386, -0.04569336581669571, -0.12320285070861678, 0.08240315222323638, 0.4579164525630148, 0.10194743670878537, 0.5748048740706077, -0.38484763478500494, 0.8009525610955103, 0.7333605699869847, 0.37124845323434263, -0.03501117975518403, 0.012948485735009754, 0.29139932552493186, 0.34343670572619495, 0.8542624160112243, 0.2047939987143607, 0.3903803959743837, -0.20493239305818473, -1.1287011492813999, -0.32936672671984124, -0.36581898984821176, 0.2451494881151558, -0.5756460181132672, -0.030221322542399086, 0.16449751038968874, -0.3567999251278406, -0.1618212236300447, -0.11207687799559582, 0.05735981109003743, 0.9415542138674963, -0.3554473551841668, 0.5357750527639715, 0.21498207309781378, 0.4532008047694893, 0.21329882952215284, 0.5859846457864504, -0.16362093353740018, 0.1319546289160159, -0.2194715016448026, -0.266878066809855, 0.19007538470038587, -0.6214579041470789, 0.07758190484905561, -0.7515667963793465, 0.24700843522334995, -0.292447662725082, -0.4181253106644778, 0.19564903243421003, 0.19724000917384554, -0.2063833311816462, 0.46455125472211967, -0.0899164519697946, -0.4859666940225116, 0.2204956850628324, 0.5537344147667811, 0.3710020504693896, 0.42084808456566025, 0.22826893049722402, -0.3009973798887208, 0.3133299056345898, -0.5362470634819437, -0.07363025268708201, -0.4903844709824772, -0.4212031706808154, 0.593200663984306, 0.03428638943992187, 0.24491294188014479, 0.46221509482741235, -0.20849095803967968, 0.6337473393725238, -0.05747450930384633, 0.8875435750416844]) p.disconnect(physicsClient) if __name__ == "__main__": main()
next_gait_state = chromosome[(LENGTH_OF_START_SEQUENCE * LENGTH_OF_GAIT_STATE) + 1: (LENGTH_OF_START_SEQUENCE * LENGTH_OF_GAIT_STATE) + LENGTH_OF_GAIT_STATE] alpha = (progress - (sum_of_durations - chromosome[current_duration_index])) / chromosome[current_duration_index]
clustergrouptoken.go
/* Copyright 2020 Rancher Labs, 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. */ // Code generated by main. DO NOT EDIT. package v1alpha1 import ( "context" "time" v1alpha1 "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1" scheme "github.com/rancher/fleet/pkg/generated/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" ) // ClusterGroupTokensGetter has a method to return a ClusterGroupTokenInterface. // A group's client should implement this interface. type ClusterGroupTokensGetter interface { ClusterGroupTokens(namespace string) ClusterGroupTokenInterface } // ClusterGroupTokenInterface has methods to work with ClusterGroupToken resources. type ClusterGroupTokenInterface interface { Create(ctx context.Context, clusterGroupToken *v1alpha1.ClusterGroupToken, opts v1.CreateOptions) (*v1alpha1.ClusterGroupToken, error) Update(ctx context.Context, clusterGroupToken *v1alpha1.ClusterGroupToken, opts v1.UpdateOptions) (*v1alpha1.ClusterGroupToken, error) UpdateStatus(ctx context.Context, clusterGroupToken *v1alpha1.ClusterGroupToken, opts v1.UpdateOptions) (*v1alpha1.ClusterGroupToken, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.ClusterGroupToken, error) List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.ClusterGroupTokenList, error) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterGroupToken, err error) ClusterGroupTokenExpansion } // clusterGroupTokens implements ClusterGroupTokenInterface type clusterGroupTokens struct { client rest.Interface ns string } // newClusterGroupTokens returns a ClusterGroupTokens func newClusterGroupTokens(c *FleetV1alpha1Client, namespace string) *clusterGroupTokens { return &clusterGroupTokens{ client: c.RESTClient(), ns: namespace, } } // Get takes name of the clusterGroupToken, and returns the corresponding clusterGroupToken object, and an error if there is any. func (c *clusterGroupTokens) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterGroupToken, err error) { result = &v1alpha1.ClusterGroupToken{} err = c.client.Get(). Namespace(c.ns). Resource("clustergrouptokens"). Name(name). VersionedParams(&options, scheme.ParameterCodec). Do(ctx). Into(result) return } // List takes label and field selectors, and returns the list of ClusterGroupTokens that match those selectors. func (c *clusterGroupTokens) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterGroupTokenList, err error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } result = &v1alpha1.ClusterGroupTokenList{} err = c.client.Get(). Namespace(c.ns). Resource("clustergrouptokens"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Do(ctx). Into(result) return } // Watch returns a watch.Interface that watches the requested clusterGroupTokens. func (c *clusterGroupTokens) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { var timeout time.Duration if opts.TimeoutSeconds != nil { timeout = time.Duration(*opts.TimeoutSeconds) * time.Second } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("clustergrouptokens"). VersionedParams(&opts, scheme.ParameterCodec). Timeout(timeout). Watch(ctx) } // Create takes the representation of a clusterGroupToken and creates it. Returns the server's representation of the clusterGroupToken, and an error, if there is any. func (c *clusterGroupTokens) Create(ctx context.Context, clusterGroupToken *v1alpha1.ClusterGroupToken, opts v1.CreateOptions) (result *v1alpha1.ClusterGroupToken, err error) { result = &v1alpha1.ClusterGroupToken{} err = c.client.Post(). Namespace(c.ns). Resource("clustergrouptokens"). VersionedParams(&opts, scheme.ParameterCodec). Body(clusterGroupToken). Do(ctx). Into(result)
// Update takes the representation of a clusterGroupToken and updates it. Returns the server's representation of the clusterGroupToken, and an error, if there is any. func (c *clusterGroupTokens) Update(ctx context.Context, clusterGroupToken *v1alpha1.ClusterGroupToken, opts v1.UpdateOptions) (result *v1alpha1.ClusterGroupToken, err error) { result = &v1alpha1.ClusterGroupToken{} err = c.client.Put(). Namespace(c.ns). Resource("clustergrouptokens"). Name(clusterGroupToken.Name). VersionedParams(&opts, scheme.ParameterCodec). Body(clusterGroupToken). Do(ctx). Into(result) return } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *clusterGroupTokens) UpdateStatus(ctx context.Context, clusterGroupToken *v1alpha1.ClusterGroupToken, opts v1.UpdateOptions) (result *v1alpha1.ClusterGroupToken, err error) { result = &v1alpha1.ClusterGroupToken{} err = c.client.Put(). Namespace(c.ns). Resource("clustergrouptokens"). Name(clusterGroupToken.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). Body(clusterGroupToken). Do(ctx). Into(result) return } // Delete takes name of the clusterGroupToken and deletes it. Returns an error if one occurs. func (c *clusterGroupTokens) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("clustergrouptokens"). Name(name). Body(&opts). Do(ctx). Error() } // DeleteCollection deletes a collection of objects. func (c *clusterGroupTokens) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { var timeout time.Duration if listOpts.TimeoutSeconds != nil { timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second } return c.client.Delete(). Namespace(c.ns). Resource("clustergrouptokens"). VersionedParams(&listOpts, scheme.ParameterCodec). Timeout(timeout). Body(&opts). Do(ctx). Error() } // Patch applies the patch and returns the patched clusterGroupToken. func (c *clusterGroupTokens) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterGroupToken, err error) { result = &v1alpha1.ClusterGroupToken{} err = c.client.Patch(pt). Namespace(c.ns). Resource("clustergrouptokens"). Name(name). SubResource(subresources...). VersionedParams(&opts, scheme.ParameterCodec). Body(data). Do(ctx). Into(result) return }
return }
run_tests.py
#!/usr/bin/env python import contextlib import docker import subprocess import os.path import sys import time import urllib2 SERVERS = { 'bjoern': ['python', '-m', 'wsgi_benchmark.bjoern_server'], 'cheroot': ['python', '-m', 'wsgi_benchmark.cheroot_server'], 'cheroot_high_concurrency': ['python', '-m', 'wsgi_benchmark.high_concurrency_cheroot_server'], 'eventlet': ['python', '-m', 'wsgi_benchmark.eventlet_server'], 'gunicorn': ['./gunicorn_server.sh'], 'gunicorn_gevent': ['./gevent_gunicorn_server.sh'], 'gunicorn_gthread': ['./gthread_gunicorn_server.sh'], 'gunicorn_meinheld': ['./meinheld_gunicorn_server.sh'], 'gunicorn_high_concurrency': ['./high_concurrency_gunicorn_server.sh'], 'gevent': ['python', '-m', 'wsgi_benchmark.gevent_server'], 'meinheld': ['python', '-m', 'wsgi_benchmark.meinheld_server'], 'uwsgi': ['./uwsgi_server.sh'], 'uwsgi_gevent': ['./gevent_uwsgi_server.sh'], 'uwsgi_high_concurrency': ['./high_concurrency_uwsgi_server.sh'], 'uwsgi_threaded': ['./threaded_uwsgi_server.sh'], 'waitress': ['python', '-m', 'wsgi_benchmark.waitress_server'], 'waitress_high_concurrency': ['python', '-m', 'wsgi_benchmark.high_concurrency_waitress_server'], 'werkzeug': ['python', '-m', 'wsgi_benchmark.werkzeug_server'], 'werkzeug_threading': ['python', '-m', 'wsgi_benchmark.threading_werkzeug_server'], 'werkzeug_forking': ['python', '-m', 'wsgi_benchmark.forking_werkzeug_server'], 'wsgiref': ['python', '-m', 'wsgi_benchmark.wsgiref_server'], 'wsgiref_threading': ['python', '-m', 'wsgi_benchmark.threading_wsgiref_server'], 'wsgiref_forking': ['python', '-m', 'wsgi_benchmark.forking_wsgiref_server'] } GATLING_SCENARIOS = { 'hello_world': 'HelloWorldSimulation', 'numeric_nogil': 'NumericNoGilSimulation', 'native_io': 'NativeIOSimulation', 'socket_io': 'SocketIOSimulation', 'sendfile': 'SendfileSimulation', 'dynamic_file': 'DynamicFileSimulation', 'sha512': 'SHA512Simulation', 'forward_request': 'ForwardSimulation', 'gzip': 'GzipSimulation', 'numeric_gil': 'NumericGilSimulation' } def build_image():
@contextlib.contextmanager def server(command, server_name): container = docker.from_env().containers.run( 'wsgi_benchmark', command, name='wsgi_benchmark-{}'.format(server_name), detach=True, ports={'8765/tcp': 8765}) print "{server_name} running as container {container.id}".format(**locals()) try: for i in xrange(30): try: assert urllib2.urlopen('http://localhost:8765/hello_world').read() == 'Hello World' except: time.sleep(1) else: break else: raise RuntimeError("Could not start server process: {}" .format(server_name)) yield container finally: container.remove(force=True) if __name__ == '__main__': build_image() for server_name, server_command in sorted(SERVERS.items()): print "Testing {server_name} starts".format(**locals()) with server(server_command, server_name): print "Success" with open('results/misc_results.txt', 'w') as misc_results: for server_name, command in sorted(SERVERS.items()): with server(command, server_name): try: hash_result = subprocess.check_output( 'head -c 65536 /dev/zero | curl -T - -y 5 http://localhost:8765/sha512', shell=True) success = hash_result == '73e4153936dab198397b74ee9efc26093dda721eaab2f8d92786891153b45b04265a161b169c988edb0db2c53124607b6eaaa816559c5ce54f3dbc9fa6a7a4b2' except: success = False misc_results.write( '{server_name}-chunked: {success}\n'.format(**locals())) with server(command, server_name): interrupted_result = subprocess.call( ['curl', 'http://localhost:8765/interrupted']) success = interrupted_result != 0 misc_results.write( '{server_name}-interrupted: {success}\n'.format(**locals())) with server(command, server_name): subprocess.call(['slowhttptest', '-g', '-X', '-v', '1', '-i', '3', '-l', '30', '-c', '300', '-o', '{server_name}-slow_read'.format(**locals()), '-u', 'http://localhost:8765/dynamic_file'], cwd='results') with server(command, server_name): subprocess.call(['slowhttptest', '-g', '-H', '-v', '1', '-i', '3', '-l', '30', '-c', '300', '-o', '{server_name}-slow_headers'.format(**locals()), '-u', 'http://localhost:8765/hello_world'], cwd='results') with server(command, server_name): subprocess.call(['slowhttptest', '-g', '-B', '-v', '1', '-i', '3', '-l', '30', '-c', '300', '-o', '{server_name}-slow_body'.format(**locals()), '-u', 'http://localhost:8765/sha512'], cwd='results') for scenario_name, scenario_class in sorted(GATLING_SCENARIOS.items()): with server(command, server_name) as server_container: container = docker.from_env().containers.run( 'wsgi_benchmark', [ 'mvn', '-Dgatling.simulationClass=io.github.jamespic.wsgi_benchmark.%s' % scenario_class, '-Dgatling.outputName=%s-%s' % ( scenario_name, server_name), '-Dgatling.resultsFolder=/results', 'integration-test' ], name='wsgi_benchmark_gatling_{scenario_name}_{server_name}'.format(**locals()), links={server_container.name: 'wsgi_benchmark_server'}, volumes={os.path.abspath('results'): {'bind': '/results', 'mode': 'rw'}}, environment={'TARGET_HOSTNAME': 'wsgi_benchmark_server'}, working_dir='/wsgi_benchmark/gatling', detach=True ) try: for line in container.logs(stdout=True, stderr=True, stream=True): sys.stdout.write(line) finally: container.remove(force=True)
docker.from_env().images.build(path='.', tag='wsgi_benchmark')
main.go
// Copyright 2019 Northern.tech AS // // 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 main import ( "context" "fmt" "os" "strings" "github.com/mendersoftware/go-lib-micro/config" "github.com/mendersoftware/go-lib-micro/log" mstore "github.com/mendersoftware/go-lib-micro/store" "github.com/urfave/cli" dconfig "github.com/mendersoftware/deployments/config" "github.com/mendersoftware/deployments/store/mongo" ) func main() { doMain(os.Args) } func doMain(args []string) { var configPath string app := cli.NewApp() app.Usage = "Deployments Service" app.Version = CreateVersionString() app.Flags = []cli.Flag{ cli.StringFlag{ Name: "config", Usage: "Configuration `FILE`. Supports JSON, TOML, YAML and HCL formatted configs.", Destination: &configPath, }, } app.Commands = []cli.Command{ { Name: "server", Usage: "Run the service as a server", Flags: []cli.Flag{ cli.BoolFlag{ Name: "automigrate", Usage: "Run database migrations before starting.", }, }, Action: cmdServer, }, { Name: "migrate", Usage: "Run migrations and exit", Flags: []cli.Flag{ cli.StringFlag{ Name: "tenant", Usage: "Tenant ID (optional).", }, }, Action: cmdMigrate, }, } app.Action = cmdServer app.Before = func(args *cli.Context) error { err := config.FromConfigFile(configPath, dconfig.Defaults) if err != nil { return cli.NewExitError( fmt.Sprintf("error loading configuration: %s", err), 1) } // Enable setting config values by environment variables config.Config.SetEnvPrefix("DEPLOYMENTS") config.Config.AutomaticEnv() config.Config.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) return nil } app.Run(args) } func cmdServer(args *cli.Context) error { ctx := context.Background() devSetup := args.GlobalBool("dev") l := log.New(log.Ctx{}) if devSetup { l.Infof("setting up development configuration") config.Config.Set(dconfig.SettingMiddleware, dconfig.EnvDev) } l.Printf("Deployments Service, version %s starting up", CreateVersionString()) dbClient, err := mongo.NewMongoClient(ctx, config.Config) if err != nil { return cli.NewExitError( fmt.Sprintf("failed to connect to db: %v", err), 3) } defer dbClient.Disconnect(ctx) err = mongo.Migrate(ctx, mongo.DbVersion, dbClient, args.Bool("automigrate")) if err != nil { return cli.NewExitError( fmt.Sprintf("failed to run migrations: %v", err), 3) } err = RunServer(config.Config) if err != nil { return cli.NewExitError(err.Error(), 4) } return nil } func cmdMigrate(args *cli.Context) error
{ ctx := context.Background() tenant := args.String("tenant") db := mstore.DbNameForTenant(tenant, mongo.DbName) dbClient, err := mongo.NewMongoClient(ctx, config.Config) if err != nil { return cli.NewExitError( fmt.Sprintf("failed to connect to db: %v", err), 3) } defer dbClient.Disconnect(ctx) err = mongo.MigrateSingle(ctx, db, mongo.DbVersion, dbClient, true) if err != nil { return cli.NewExitError( fmt.Sprintf("failed to run migrations: %v", err), 3) } return nil }
job_search_response_embedded.py
""" Bundesagentur für Arbeit: Jobsuche API Die größte Stellendatenbank Deutschlands durchsuchen, Details zu Stellenanzeigen und Informationen über Arbeitgeber abrufen. <br><br> Die Authentifizierung funktioniert per OAuth 2 Client Credentials mit JWTs. Folgende Client-Credentials können dafür verwendet werden:<br><br> **ClientID:** c003a37f-024f-462a-b36d-b001be4cd24a <br> **ClientSecret:** 32a39620-32b3-4307-9aa1-511e3d7f48a8 # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from deutschland.jobsuche.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, ) from ..model_utils import OpenApiModel from deutschland.jobsuche.exceptions import ApiAttributeError def lazy_import(): from deutschland.jobsuche.model.job_search_response_embedded_jobs import ( JobSearchResponseEmbeddedJobs, ) globals()["JobSearchResponseEmbeddedJobs"] = JobSearchResponseEmbeddedJobs class JobSearchResponseEmbedded(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = {} validations = {} @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return ( bool, date, datetime, dict, float, int, list, str, none_type, ) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { "jobs": ([JobSearchResponseEmbeddedJobs],), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { "jobs": "jobs", # noqa: E501 } read_only_vars = {} _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """JobSearchResponseEmbedded - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) jobs ([JobSearchResponseEmbeddedJobs]): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) self = super(OpenApiModel, cls).__new__(cls) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None ): # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set( [ "_data_store", "_check_type", "_spec_property_naming", "_path_to_item", "_configuration", "_visited_composed_classes", ] ) @convert_js_args_to_python_args def __init
*args, **kwargs): # noqa: E501 """JobSearchResponseEmbedded - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) jobs ([JobSearchResponseEmbeddedJobs]): [optional] # noqa: E501 """ _check_type = kwargs.pop("_check_type", True) _spec_property_naming = kwargs.pop("_spec_property_naming", False) _path_to_item = kwargs.pop("_path_to_item", ()) _configuration = kwargs.pop("_configuration", None) _visited_composed_classes = kwargs.pop("_visited_composed_classes", ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if ( var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None ): # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError( f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes." )
__(self,
mode-c_cpp.js
ace.define("ace/mode/c_cpp",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/c_cpp_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("../tokenizer").Tokenizer,o=e("./c_cpp_highlight_rules").c_cppHighlightRules,u=e("./matching_brace_outdent").MatchingBraceOutdent,a=e("../range").Range,f=e("./behaviour/cstyle").CstyleBehaviour,l=e("./folding/cstyle").FoldMode,c=function(){this.HighlightRules=o,this.$outdent=new u,this.$behaviour=new f,this.foldingRules=new l};r.inherits(c,i),function(){this.lineCommentStart="//",this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e),s=i.tokens,o=i.state;if(s.length&&s[s.length-1].type=="comment")return r;if(e=="start"){var u=t.match(/^.*[\{\(\[]\s*$/);u&&(r+=n)}else if(e=="doc-start"){if(o=="start")return"";var u=t.match(/^\s*(\/?)\*/);u&&(u[1]&&(r+=" "),r+="* ")}return r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.$id="ace/mode/c_cpp"}.call(c.prototype),t.Mode=c}),ace.define("ace/mode/c_cpp_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./doc_comment_highlight_rules").DocCommentHighlightRules,s=e("./text_highlight_rules").TextHighlightRules,o=t.cFunctions="\\b(?:hypot(?:f|l)?|s(?:scanf|ystem|nprintf|ca(?:nf|lb(?:n(?:f|l)?|ln(?:f|l)?))|i(?:n(?:h(?:f|l)?|f|l)?|gn(?:al|bit))|tr(?:s(?:tr|pn)|nc(?:py|at|mp)|c(?:spn|hr|oll|py|at|mp)|to(?:imax|d|u(?:l(?:l)?|max)|k|f|l(?:d|l)?)|error|pbrk|ftime|len|rchr|xfrm)|printf|et(?:jmp|vbuf|locale|buf)|qrt(?:f|l)?|w(?:scanf|printf)|rand)|n(?:e(?:arbyint(?:f|l)?|xt(?:toward(?:f|l)?|after(?:f|l)?))|an(?:f|l)?)|c(?:s(?:in(?:h(?:f|l)?|f|l)?|qrt(?:f|l)?)|cos(?:h(?:f)?|f|l)?|imag(?:f|l)?|t(?:ime|an(?:h(?:f|l)?|f|l)?)|o(?:s(?:h(?:f|l)?|f|l)?|nj(?:f|l)?|pysign(?:f|l)?)|p(?:ow(?:f|l)?|roj(?:f|l)?)|e(?:il(?:f|l)?|xp(?:f|l)?)|l(?:o(?:ck|g(?:f|l)?)|earerr)|a(?:sin(?:h(?:f|l)?|f|l)?|cos(?:h(?:f|l)?|f|l)?|tan(?:h(?:f|l)?|f|l)?|lloc|rg(?:f|l)?|bs(?:f|l)?)|real(?:f|l)?|brt(?:f|l)?)|t(?:ime|o(?:upper|lower)|an(?:h(?:f|l)?|f|l)?|runc(?:f|l)?|gamma(?:f|l)?|mp(?:nam|file))|i(?:s(?:space|n(?:ormal|an)|cntrl|inf|digit|u(?:nordered|pper)|p(?:unct|rint)|finite|w(?:space|c(?:ntrl|type)|digit|upper|p(?:unct|rint)|lower|al(?:num|pha)|graph|xdigit|blank)|l(?:ower|ess(?:equal|greater)?)|al(?:num|pha)|gr(?:eater(?:equal)?|aph)|xdigit|blank)|logb(?:f|l)?|max(?:div|abs))|di(?:v|fftime)|_Exit|unget(?:c|wc)|p(?:ow(?:f|l)?|ut(?:s|c(?:har)?|wc(?:har)?)|error|rintf)|e(?:rf(?:c(?:f|l)?|f|l)?|x(?:it|p(?:2(?:f|l)?|f|l|m1(?:f|l)?)?))|v(?:s(?:scanf|nprintf|canf|printf|w(?:scanf|printf))|printf|f(?:scanf|printf|w(?:scanf|printf))|w(?:scanf|printf)|a_(?:start|copy|end|arg))|qsort|f(?:s(?:canf|e(?:tpos|ek))|close|tell|open|dim(?:f|l)?|p(?:classify|ut(?:s|c|w(?:s|c))|rintf)|e(?:holdexcept|set(?:e(?:nv|xceptflag)|round)|clearexcept|testexcept|of|updateenv|r(?:aiseexcept|ror)|get(?:e(?:nv|xceptflag)|round))|flush|w(?:scanf|ide|printf|rite)|loor(?:f|l)?|abs(?:f|l)?|get(?:s|c|pos|w(?:s|c))|re(?:open|e|ad|xp(?:f|l)?)|m(?:in(?:f|l)?|od(?:f|l)?|a(?:f|l|x(?:f|l)?)?))|l(?:d(?:iv|exp(?:f|l)?)|o(?:ngjmp|cal(?:time|econv)|g(?:1(?:p(?:f|l)?|0(?:f|l)?)|2(?:f|l)?|f|l|b(?:f|l)?)?)|abs|l(?:div|abs|r(?:int(?:f|l)?|ound(?:f|l)?))|r(?:int(?:f|l)?|ound(?:f|l)?)|gamma(?:f|l)?)|w(?:scanf|c(?:s(?:s(?:tr|pn)|nc(?:py|at|mp)|c(?:spn|hr|oll|py|at|mp)|to(?:imax|d|u(?:l(?:l)?|max)|k|f|l(?:d|l)?|mbs)|pbrk|ftime|len|r(?:chr|tombs)|xfrm)|to(?:b|mb)|rtomb)|printf|mem(?:set|c(?:hr|py|mp)|move))|a(?:s(?:sert|ctime|in(?:h(?:f|l)?|f|l)?)|cos(?:h(?:f|l)?|f|l)?|t(?:o(?:i|f|l(?:l)?)|exit|an(?:h(?:f|l)?|2(?:f|l)?|f|l)?)|b(?:s|ort))|g(?:et(?:s|c(?:har)?|env|wc(?:har)?)|mtime)|r(?:int(?:f|l)?|ound(?:f|l)?|e(?:name|alloc|wind|m(?:ove|quo(?:f|l)?|ainder(?:f|l)?))|a(?:nd|ise))|b(?:search|towc)|m(?:odf(?:f|l)?|em(?:set|c(?:hr|py|mp)|move)|ktime|alloc|b(?:s(?:init|towcs|rtowcs)|towc|len|r(?:towc|len))))\\b",u=function(){var e="break|case|continue|default|do|else|for|goto|if|_Pragma|return|switch|while|catch|operator|try|throw|using",t="asm|__asm__|auto|bool|_Bool|char|_Complex|double|enum|float|_Imaginary|int|long|short|signed|struct|typedef|union|unsigned|void|class|wchar_t|template",n="const|extern|register|restrict|static|volatile|inline|private:|protected:|public:|friend|explicit|virtual|export|mutable|typename",r="and|and_eq|bitand|bitor|compl|not|not_eq|or|or_eq|typeid|xor|xor_eqconst_cast|dynamic_cast|reinterpret_cast|static_cast|sizeof|namespace",s="NULL|true|false|TRUE|FALSE",u=this.$keywords=this.createKeywordMapper({"keyword.control":e,"storage.type":t,"storage.modifier":n,"keyword.operator":r,"variable.language":"this","constant.language":s},"identifier"),a="[a-zA-Z\\$_¡-￿][a-zA-Zd\\$_¡-￿]*\\b";this.$rules={start:[{token:"comment",regex:"\\/\\/.*$"},i.getStartRule("doc-start"),{token:"comment",regex:"\\/\\*",next:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:'["].*\\\\$',next:"qqstring"},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:"string",regex:"['].*\\\\$",next:"qstring"},{token:"constant.numeric",regex:"0[xX][0-9a-fA-F]+(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b"},{token:"constant.numeric",regex:"[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b"},{token:"keyword",regex:"#\\s*(?:include|import|pragma|line|define|undef|if|ifdef|else|elif|ifndef)\\b",next:"directive"},{token:"keyword",regex:"(?:#\\s*endif)\\b"},{token:"support.function.C99.c",regex:o},{token:u,regex:"[a-zA-Z_$][a-zA-Z0-9_$]*\\b"},{token:"keyword.operator",regex:"!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"},{token:"punctuation.operator",regex:"\\?|\\:|\\,|\\;|\\."},{token:"paren.lparen",regex:"[[({]"},{token:"paren.rparen",regex:"[\\])}]"},{token:"text",regex:"\\s+"}],comment:[{token:"comment",regex:".*?\\*\\/",next:"start"},{token:"comment",regex:".+"}],qqstring:[{token:"string",regex:'(?:(?:\\\\.)|(?:[^"\\\\]))*?"',next:"start"},{token:"string",regex:".+"}],qstring:[{token:"string",regex:"(?:(?:\\\\.)|(?:[^'\\\\]))*?'",next:"start"},{token:"string",regex:".+"}],directive:[{token:"constant.other.multiline",regex:/\\/},{token:"constant.other.multiline",regex:/.*\\/},{token:"constant.other",regex:"\\s*<.+?>",next:"start"},{token:"constant.other",regex:'\\s*["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]',next:"start"},{token:"constant.other",regex:"\\s*['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']",next:"start"},{token:"constant.other",regex:/[^\\\/]+/,next:"start"}]},this.embedRules(i,"doc-",[i.getEndRule("start")])};r.inherits(u,s),t.c_cppHighlightRules=u}),ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./text_highlight_rules").TextHighlightRules,s=function(){this.$rules={start:[{token:"comment.doc.tag",regex:"@[\\w\\d_]+"},{token:"comment.doc.tag",regex:"\\bTODO\\b"},{defaultToken:"comment.doc"}]}};r.inherits(s,i),s.getStartRule=function(e){return{token:"comment.doc",regex:"\\/\\*(?=\\*)",next:e}},s.getEndRule=function(e){return{token:"comment.doc",regex:"\\*\\/",next:e}},t.DocCommentHighlightRules=s}),ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"],function(e,t,n){var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("../../token_iterator").TokenIterator,o=e("../../lib/lang"),u=["text","paren.rparen","punctuation.operator"],a=["text","paren.rparen","punctuation.operator","comment"],f=0,l=-1,c="",h=0,p=-1,d="",v="",m=function(){m.isSaneInsertion=function(e,t){var n=e.getCursorPosition(),r=new s(t,n.row,n.column);if(!this.$matchTokenType(r.getCurrentToken()||"text",u)){var i=new s(t,n.row,n.column+1);if(!this.$matchTokenType(i.getCurrentToken()||"text",u))return!1}return r.stepForward(),r.getCurrentTokenRow()!==n.row||this.$matchTokenType(r.getCurrentToken()||"text",a)},m.$matchTokenType=function(e,t){return t.indexOf(e.type||e)>-1},m.recordAutoInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isAutoInsertedClosing(r,i,c[0])||(f=0),l=r.row,c=n+i.substr(r.column),f++},m.recordMaybeInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isMaybeInsertedClosing(r,i)||(h=0),p=r.row,d=i.substr(0,r.column)+n,v=i.substr(r.column),h++},m.isAutoInsertedClosing=function(e,t,n){return f>0&&e.row===l&&n===c[0]&&t.substr(e.column)===c},m.isMaybeInsertedClosing=function(e,t){return h>0&&e.row===p&&t.substr(e.column)===v&&t.substr(0,e.column)==d},m.popAutoInsertedClosing=function(){c=c.substr(1),f--},m.clearMaybeInsertedClosing=function(){h=0,p=-1},this.add("braces","insertion",function(e,t,n,r,i){var s=n.getCursorPosition(),u=r.doc.getLine(s.row);if(i=="{"){var a=n.getSelectionRange(),f=r.doc.getTextRange(a);if(f!==""&&f!=="{"&&n.getWrapBehavioursEnabled())return{text:"{"+f+"}",selection:!1};if(m.isSaneInsertion(n,r))return/[\]\}\)]/.test(u[s.column])||n.inMultiSelectMode?(m.recordAutoInsert(n,r,"}"),{text:"{}",selection:[1,1]}):(m.recordMaybeInsert(n,r,"{"),{text:"{",selection:[1,1]})}else if(i=="}"){var l=u.substring(s.column,s.column+1);if(l=="}"){var c=r.$findOpeningBracket("}",{column:s.column+1,row:s.row});if(c!==null&&m.isAutoInsertedClosing(s,u,i))return m.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}else{if(i=="\n"||i=="\r\n"){var p="";m.isMaybeInsertedClosing(s,u)&&(p=o.stringRepeat("}",h),m.clearMaybeInsertedClosing());var l=u.substring(s.column,s.column+1);if(l==="}"){var d=r.findMatchingBracket({row:s.row,column:s.column+1},"}");if(!d)return null;var v=this.$getIndent(r.getLine(d.row))}else{if(!p)return;var v=this.$getIndent(u)}var g=v+r.getTabString();return{text:"\n"+g+"\n"+v+p,selection:[1,g.length,1,g.length]}}m.clearMaybeInsertedClosing()}}),this.add("braces","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="{"){var o=r.doc.getLine(i.start.row),u=o.substring(i.end.column,i.end.column+1);if(u=="}")return i.end.column++,i;h--}}),this.add("parens","insertion",function(e,t,n,r,i){if(i=="("){var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"("+o+")",selection:!1};if(m.isSaneInsertion(n,r))return m.recordAutoInsert(n,r,")"),{text:"()",selection:[1,1]}}else if(i==")"){var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f==")"){var l=r.$findOpeningBracket(")",{column:u.column+1,row:u.row});if(l!==null&&m.isAutoInsertedClosing(u,a,i))return m.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="("){var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==")")return i.end.column++,i}}),this.add("brackets","insertion",function(e,t,n,r,i){if(i=="["){var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"["+o+"]",selection:!1};if(m.isSaneInsertion(n,r))return m.recordAutoInsert(n,r,"]"),{text:"[]",selection:[1,1]}}else if(i=="]"){var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f=="]"){var l=r.$findOpeningBracket("]",{column:u.column+1,row:u.row});if(l!==null&&m.isAutoInsertedClosing(u,a,i))return m.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("brackets","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="["){var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u=="]")return i.end.column++,i}}),this.add("string_dquotes","insertion",function(e,t,n,r,i){if(i=='"'||i=="'"){var s=i,o=n.getSelectionRange(),u=r.doc.getTextRange(o);if(u!==""&&u!=="'"&&u!='"'&&n.getWrapBehavioursEnabled())return{text:s+u+s,selection:!1};var a=n.getCursorPosition(),f=r.doc.getLine(a.row),l=f.substring(a.column-1,a.column);if(l=="\\")return null;var c=r.getTokens(o.start.row),h=0,p,d=-1;for(var v=0;v<c.length;v++){p=c[v],p.type=="string"?d=-1:d<0&&(d=p.value.indexOf(s));if(p.value.length+h>o.start.column)break;h+=c[v].value.length}if(!p||d<0&&p.type!=="comment"&&(p.type!=="string"||o.start.column!==p.value.length+h-1&&p.value.lastIndexOf(s)===p.value.length-1)){if(!m.isSaneInsertion(n,r))return;return{text:s+s,selection:[1,1]}}if(p&&p.type==="string"){var g=f.substring(a.column,a.column+1);if(g==s)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&(s=='"'||s=="'")){var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==s)return i.end.column++,i}})};r.inherits(m,i),t.CstyleBehaviour=m}),ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n),s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)}}.call(o.prototype)})
engine.py
""" Copyright 2020 Tianshu AI Platform. 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. ============================================================= """ import torch import torch.nn as nn import abc, math, weakref, typing, time from typing import Any, Callable, Optional, Sequence import numpy as np from kamal.core.engine.events import DefaultEvents, Event from kamal.core import tasks from kamal.utils import set_mode, move_to_device, get_logger from collections import defaultdict import numbers import contextlib class State(object): def __init__(self): self.iter = 0 self.max_iter = None self.epoch_length = None self.dataloader = None self.seed = None self.metrics=dict() self.batch=None @property def current_epoch(self): if self.epoch_length is not None: return self.iter // self.epoch_length return None @property def max_epoch(self): if self.epoch_length is not None: return self.max_iter // self.epoch_length return None @property def current_batch_index(self): if self.epoch_length is not None: return self.iter % self.epoch_length return None @property def max_batch_index(self): return self.epoch_length def __repr__(self):
rep = "State:\n" for attr, value in self.__dict__.items(): if not isinstance(value, (numbers.Number, str, dict)): value = type(value) rep += "\t{}: {}\n".format(attr, value) return rep class Engine(abc.ABC): def __init__(self, logger=None, tb_writer=None): self._logger = logger if logger else get_logger(name='kamal', color=True) self._tb_writer = tb_writer self._callbacks = defaultdict(list) self._allowed_events = [ *DefaultEvents ] self._state = State() def reset(self): self._state = State() def run(self, step_fn: Callable, dataloader, max_iter, start_iter=0, epoch_length=None): self.state.iter = self._state.start_iter = start_iter self.state.max_iter = max_iter self.state.epoch_length = epoch_length if epoch_length else len(dataloader) self.state.dataloader = dataloader self.state.dataloader_iter = iter(dataloader) self.state.step_fn = step_fn self.trigger_events(DefaultEvents.BEFORE_RUN) for self.state.iter in range( start_iter, max_iter ): if self.state.epoch_length!=None and \ self.state.iter%self.state.epoch_length==0: # Epoch Start self.trigger_events(DefaultEvents.BEFORE_EPOCH) self.trigger_events(DefaultEvents.BEFORE_STEP) self.state.batch = self._get_batch() step_output = step_fn(self, self.state.batch) if isinstance(step_output, dict): self.state.metrics.update(step_output) self.trigger_events(DefaultEvents.AFTER_STEP) if self.state.epoch_length!=None and \ (self.state.iter+1)%self.state.epoch_length==0: # Epoch End self.trigger_events(DefaultEvents.AFTER_EPOCH) self.trigger_events(DefaultEvents.AFTER_RUN) def _get_batch(self): try: batch = next( self.state.dataloader_iter ) except StopIteration: self.state.dataloader_iter = iter(self.state.dataloader) # reset iterator batch = next( self.state.dataloader_iter ) if not isinstance(batch, (list, tuple)): batch = [ batch, ] # no targets return batch @property def state(self): return self._state @property def logger(self): return self._logger @property def tb_writer(self): return self._tb_writer def add_callback(self, event: Event, callbacks ): if not isinstance(callbacks, Sequence): callbacks = [callbacks] if event in self._allowed_events: for callback in callbacks: if callback not in self._callbacks[event]: if event.trigger!=event.default_trigger: callback = self._trigger_wrapper(self, event.trigger, callback ) self._callbacks[event].append( callback ) callbacks = [ RemovableCallback(self, event, c) for c in callbacks ] return ( callbacks[0] if len(callbacks)==1 else callbacks ) def remove_callback(self, event, callback): for c in self._callbacks[event]: if c==callback: self._callbacks.remove( callback ) return True return False @staticmethod def _trigger_wrapper(engine, trigger, callback): def wrapper(*args, **kwargs) -> Any: if trigger(engine): return callback(engine) return wrapper def trigger_events(self, *events): for e in events: if e in self._allowed_events: for callback in self._callbacks[e]: callback(self) def register_events(self, *events): for e in events: if e not in self._allowed_events: self._allowed_events.apped( e ) @contextlib.contextmanager def save_current_callbacks(self): temp = self._callbacks self._callbacks = defaultdict(list) yield self._callbacks = temp class RemovableCallback: def __init__(self, engine, event, callback): self._engine = weakref.ref(engine) self._callback = weakref.ref(callback) self._event = weakref.ref(event) @property def callback(self): return self._callback() def remove(self): engine = self._engine() callback = self._callback() event = self._event() return engine.remove_callback(event, callback)
promise.rs
use std::{ any::Any, fmt::Debug, sync::Arc, thread::{self, JoinHandle}, }; use druid::{ widget::{prelude::*, Controller, ControllerHost}, Data, ExtEventSink, Point, Selector, SingleUse, Target, WidgetExt, WidgetPod, }; use crate::data::{Promise, PromiseState}; pub struct
<T, D, E> { func: Arc<dyn Fn(&D) -> Result<T, E> + Sync + Send + 'static>, handle: Option<JoinHandle<()>>, } struct AsyncResult { result: Box<dyn Any + Send>, deferred: Box<dyn Any + Send>, } const ASYNC_RESULT: Selector<SingleUse<AsyncResult>> = Selector::new("promise.async_result"); impl<T, D, E> AsyncAction<T, D, E> where T: Send + 'static, D: Send + 'static, E: Send + 'static, { pub fn new<F>(func: F) -> Self where F: Fn(&D) -> Result<T, E> + Sync + Send + 'static, { Self { func: Arc::new(func), handle: None, } } fn spawn_action(&mut self, self_id: WidgetId, event_sink: ExtEventSink, deferred: D) { dbg!(self_id); let old_handle = self.handle.replace(thread::spawn({ let func = self.func.clone(); move || { let result = AsyncResult { result: Box::new(func(&deferred)), deferred: Box::new(deferred), }; event_sink .submit_command( ASYNC_RESULT, SingleUse::new(result), Target::Widget(self_id), ) .unwrap(); } })); if old_handle.is_some() { log::warn!("async action pending"); } } } impl<T, D, E, W> Controller<Promise<T, D, E>, W> for AsyncAction<T, D, E> where T: Send + Data, D: Send + Data + PartialEq, E: Send + Data + Debug, W: Widget<Promise<T, D, E>>, { fn event( &mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut Promise<T, D, E>, env: &Env, ) { match event { Event::Command(cmd) if cmd.is(ASYNC_RESULT) => { let payload = cmd.get_unchecked(ASYNC_RESULT).take().unwrap(); let deferred = payload.deferred.downcast().unwrap(); let result = payload.result.downcast().unwrap(); if data.is_deferred(&deferred) { match *result { Ok(val) => { data.resolve(*deferred, val); } Err(err) => { log::error!("async: {:?}", err); data.reject(*deferred, err); } } } self.handle.take(); } _ => { child.event(ctx, event, data, env); } } } fn lifecycle( &mut self, child: &mut W, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &Promise<T, D, E>, env: &Env, ) { if let LifeCycle::WidgetAdded = event { if let Promise::Deferred { def } = data { self.spawn_action(ctx.widget_id(), ctx.get_external_handle(), def.to_owned()); } } child.lifecycle(ctx, event, data, env) } fn update( &mut self, child: &mut W, ctx: &mut UpdateCtx, old_data: &Promise<T, D, E>, data: &Promise<T, D, E>, env: &Env, ) { if !old_data.same(data) { if let Promise::Deferred { def } = data { self.spawn_action(ctx.widget_id(), ctx.get_external_handle(), def.to_owned()); } } child.update(ctx, old_data, data, env) } } pub struct Async<T, D, E> { def_maker: Box<dyn Fn() -> Box<dyn Widget<D>>>, res_maker: Box<dyn Fn() -> Box<dyn Widget<T>>>, err_maker: Box<dyn Fn() -> Box<dyn Widget<E>>>, widget: PromiseWidget<T, D, E>, } #[allow(clippy::large_enum_variant)] enum PromiseWidget<T, D, E> { Empty, Deferred(WidgetPod<D, Box<dyn Widget<D>>>), Resolved(WidgetPod<T, Box<dyn Widget<T>>>), Rejected(WidgetPod<E, Box<dyn Widget<E>>>), } impl<D: Data, T: Data, E: Data> Async<T, D, E> { pub fn new<WD, WT, WE>( def_maker: impl Fn() -> WD + 'static, res_maker: impl Fn() -> WT + 'static, err_maker: impl Fn() -> WE + 'static, ) -> Self where WD: Widget<D> + 'static, WT: Widget<T> + 'static, WE: Widget<E> + 'static, { Self { def_maker: Box::new(move || def_maker().boxed()), res_maker: Box::new(move || res_maker().boxed()), err_maker: Box::new(move || err_maker().boxed()), widget: PromiseWidget::Empty, } } fn rebuild_widget(&mut self, state: PromiseState) { self.widget = match state { PromiseState::Empty => PromiseWidget::Empty, PromiseState::Deferred => PromiseWidget::Deferred(WidgetPod::new((self.def_maker)())), PromiseState::Resolved => PromiseWidget::Resolved(WidgetPod::new((self.res_maker)())), PromiseState::Rejected => PromiseWidget::Rejected(WidgetPod::new((self.err_maker)())), }; } } impl<D: Data, T: Data, E: Data> Widget<Promise<T, D, E>> for Async<T, D, E> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut Promise<T, D, E>, env: &Env) { if data.state() == self.widget.state() { match data { Promise::Empty => {} Promise::Deferred { def } => { self.widget.with_deferred(|w| w.event(ctx, event, def, env)); } Promise::Resolved { val, .. } => { self.widget.with_resolved(|w| w.event(ctx, event, val, env)); } Promise::Rejected { err, .. } => { self.widget.with_rejected(|w| w.event(ctx, event, err, env)); } }; } } fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &Promise<T, D, E>, env: &Env, ) { if data.state() != self.widget.state() { // Possible if getting lifecycle after an event that changed the data, // or on WidgetAdded. self.rebuild_widget(data.state()); } assert_eq!(data.state(), self.widget.state(), "{:?}", event); match data { Promise::Empty => {} Promise::Deferred { def } => { self.widget .with_deferred(|w| w.lifecycle(ctx, event, def, env)); } Promise::Resolved { val, .. } => { self.widget .with_resolved(|w| w.lifecycle(ctx, event, val, env)); } Promise::Rejected { err, .. } => { self.widget .with_rejected(|w| w.lifecycle(ctx, event, err, env)); } }; } fn update( &mut self, ctx: &mut UpdateCtx, old_data: &Promise<T, D, E>, data: &Promise<T, D, E>, env: &Env, ) { if old_data.state() != data.state() { self.rebuild_widget(data.state()); ctx.children_changed(); } else { match data { Promise::Empty => {} Promise::Deferred { def } => { self.widget.with_deferred(|w| w.update(ctx, def, env)); } Promise::Resolved { val, .. } => { self.widget.with_resolved(|w| w.update(ctx, val, env)); } Promise::Rejected { err, .. } => { self.widget.with_rejected(|w| w.update(ctx, err, env)); } }; } } fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &Promise<T, D, E>, env: &Env, ) -> Size { match data { Promise::Empty => None, Promise::Deferred { def } => self.widget.with_deferred(|w| { let size = w.layout(ctx, bc, def, env); w.set_origin(ctx, def, env, Point::ORIGIN); size }), Promise::Resolved { val, .. } => self.widget.with_resolved(|w| { let size = w.layout(ctx, bc, val, env); w.set_origin(ctx, val, env, Point::ORIGIN); size }), Promise::Rejected { err, .. } => self.widget.with_rejected(|w| { let size = w.layout(ctx, bc, err, env); w.set_origin(ctx, err, env, Point::ORIGIN); size }), } .unwrap_or_default() } fn paint(&mut self, ctx: &mut PaintCtx, data: &Promise<T, D, E>, env: &Env) { match data { Promise::Empty => {} Promise::Deferred { def } => { self.widget.with_deferred(|w| w.paint(ctx, def, env)); } Promise::Resolved { val, .. } => { self.widget.with_resolved(|w| w.paint(ctx, val, env)); } Promise::Rejected { err, .. } => { self.widget.with_rejected(|w| w.paint(ctx, err, env)); } }; } } impl<T, D, E> PromiseWidget<T, D, E> { fn state(&self) -> PromiseState { match self { Self::Empty => PromiseState::Empty, Self::Deferred(_) => PromiseState::Deferred, Self::Resolved(_) => PromiseState::Resolved, Self::Rejected(_) => PromiseState::Rejected, } } fn with_deferred<R, F: FnOnce(&mut WidgetPod<D, Box<dyn Widget<D>>>) -> R>( &mut self, f: F, ) -> Option<R> { if let Self::Deferred(widget) = self { Some(f(widget)) } else { None } } fn with_resolved<R, F: FnOnce(&mut WidgetPod<T, Box<dyn Widget<T>>>) -> R>( &mut self, f: F, ) -> Option<R> { if let Self::Resolved(widget) = self { Some(f(widget)) } else { None } } fn with_rejected<R, F: FnOnce(&mut WidgetPod<E, Box<dyn Widget<E>>>) -> R>( &mut self, f: F, ) -> Option<R> { if let Self::Rejected(widget) = self { Some(f(widget)) } else { None } } } impl<T, D, E> Async<T, D, E> where T: Send + Data, D: Send + Data + PartialEq, E: Send + Data + Debug, { pub fn on_deferred<F>(self, func: F) -> ControllerHost<Self, AsyncAction<T, D, E>> where F: Fn(&D) -> Result<T, E> + Sync + Send + 'static, { ControllerHost::new(self, AsyncAction::new(func)) } }
AsyncAction
baselayers-demo.component.ts
import { Component } from '@angular/core'; import { latLng, tileLayer } from '@vchangal/leaflet'; @Component({ selector: 'leafletBaselayersDemo', templateUrl: './baselayers-demo.component.html' }) export class
{ // Open Street Map and Open Cycle Map definitions LAYER_OCM = { id: 'opencyclemap', name: 'Open Cycle Map', enabled: true, layer: tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Open Cycle Map' }) }; LAYER_OSM = { id: 'openstreetmap', name: 'Open Street Map', enabled: false, layer: tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Open Street Map' }) }; // Values to bind to Leaflet Directive layersControlOptions = { position: 'bottomright' }; baseLayers = { 'Open Street Map': this.LAYER_OSM.layer, 'Open Cycle Map': this.LAYER_OCM.layer }; options = { zoom: 10, center: latLng(46.879966, -121.726909) }; }
LeafletBaseLayersDemoComponent
Login.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { FormattedMessage } from 'react-intl'; import {Link} from 'react-router'; // Import Style import styles from '../../main.css'; export function Login(props) { return ( <div className={styles.page}> <div className={styles.Container}> <div className={styles.user}> <div className={styles.userHeader}> <h3 className={styles.userTitle}>Login to <span className={styles.appName}>UNB Attendance Services</span></h3> <form className={styles.form}> <input className={styles.input} id="username" placeholder="Username"/> <input className={styles.input} id="password" placeholder="Password" type="password"/> </form> <button className={styles.btn} onClick={submit}> Submit </button> </div> <div className={styles.underBar}> <label>New User? <Link to={'/signup'}>Register Here</Link> </label> </div> </div> </div> </div> ); } function
(){ debugger; var user = document.getElementById("username").value; var pass = document.getElementById("password").value; var req = new XMLHttpRequest(); var params = '{"username":"' + user + '", "password":"' + pass + '"}'; req.open("POST", "api/login"); req.setRequestHeader("Content-type", "application/json"); //req.setRequestHeader("Cookie", "sessionID=22f5832147f5650c6a1a999fbd97695d"); document.cookie = "sessionID=22f5832147f5650c6a1a999fbd97695d"; req.onreadystatechange = function(){ debugger; if(req.readyState == 4 && req.status == 200) { var serverResponse = JSON.parse(req.responseText); document.cookie = "isAdmin=" + serverResponse.isAdmin + ""; document.cookie = "username=" + serverResponse.username + ""; if(serverResponse.isAdmin){ window.location.href = "/instructor_home"; }else{ window.location.href = "/student_home"; } } } req.send(params); } // Actions required to provide data for this component to render in sever side. //HomePage.need = [params => { //return fetchPost(params.cuid); //}]; // Retrieve data from store as props function mapStateToProps(state, props) { return { //post: getPost(state, props.params.cuid), }; } Login.propTypes = { // post: PropTypes.shape({ // name: PropTypes.string.isRequired, // title: PropTypes.string.isRequired, // content: PropTypes.string.isRequired, // slug: PropTypes.string.isRequired, // cuid: PropTypes.string.isRequired, // }).isRequired, }; export default connect(mapStateToProps)(Login);
submit
kube.go
// Package kube provides helper utilities common for kubernetes package kube import ( "context" "encoding/json" "fmt" "reflect" "regexp" "strings" "time" "github.com/ghodss/yaml" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/api/equality" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "k8s.io/kubernetes/pkg/kubectl/scheme" "github.com/argoproj/argo-cd/common" jsonutil "github.com/argoproj/argo-cd/util/json" ) const ( listVerb = "list" watchVerb = "watch" ) const ( SecretKind = "Secret" ServiceKind = "Service" EndpointsKind = "Endpoints" DeploymentKind = "Deployment" ReplicaSetKind = "ReplicaSet" StatefulSetKind = "StatefulSet" DaemonSetKind = "DaemonSet" IngressKind = "Ingress" JobKind = "Job" PersistentVolumeClaimKind = "PersistentVolumeClaim" CustomResourceDefinitionKind = "CustomResourceDefinition" PodKind = "Pod" NetworkPolicyKind = "NetworkPolicy" PodSecurityPolicyKind = "PodSecurityPolicy" ) var ( // obsoleteExtensionsKinds contains list of obsolete kinds from extensions group and corresponding name of new group obsoleteExtensionsKinds = map[string]string{ DaemonSetKind: "apps", ReplicaSetKind: "apps", DeploymentKind: "apps", NetworkPolicyKind: "networking.k8s.io", PodSecurityPolicyKind: "policy", } ) type ResourceKey struct { Group string Kind string Namespace string Name string } func (k *ResourceKey) String() string { return fmt.Sprintf("%s/%s/%s/%s", k.Group, k.Kind, k.Namespace, k.Name) } func isObsoleteExtensionsGroupKind(group string, kind string) (string, bool) { if group == "extensions" { newGroup, ok := obsoleteExtensionsKinds[kind] return newGroup, ok } return "", false } func NewResourceKey(group string, kind string, namespace string, name string) ResourceKey { if newGroup, ok := isObsoleteExtensionsGroupKind(group, kind); ok { group = newGroup } return ResourceKey{Group: group, Kind: kind, Namespace: namespace, Name: name} } func GetResourceKey(obj *unstructured.Unstructured) ResourceKey { gvk := obj.GroupVersionKind() return NewResourceKey(gvk.Group, gvk.Kind, obj.GetNamespace(), obj.GetName()) } // TestConfig tests to make sure the REST config is usable func TestConfig(config *rest.Config) error { kubeclientset, err := kubernetes.NewForConfig(config) if err != nil { return fmt.Errorf("REST config invalid: %s", err) } _, err = kubeclientset.ServerVersion() if err != nil { return fmt.Errorf("REST config invalid: %s", err) } return nil } // ToUnstructured converts a concrete K8s API type to a un unstructured object func ToUnstructured(obj interface{}) (*unstructured.Unstructured, error) { uObj, err := runtime.NewTestUnstructuredConverter(equality.Semantic).ToUnstructured(obj) if err != nil { return nil, err } return &unstructured.Unstructured{Object: uObj}, nil } // MustToUnstructured converts a concrete K8s API type to a un unstructured object and panics if not successful func MustToUnstructured(obj interface{}) *unstructured.Unstructured { uObj, err := ToUnstructured(obj) if err != nil { panic(err) } return uObj } // GetAppInstanceLabel returns the application instance name from labels func GetAppInstanceLabel(un *unstructured.Unstructured, key string) string { if labels := un.GetLabels(); labels != nil { return labels[key] } return "" } // UnsetLabel removes our app labels from an unstructured object func UnsetLabel(target *unstructured.Unstructured, key string) { if labels := target.GetLabels(); labels != nil { if _, ok := labels[key]; ok { delete(labels, key) if len(labels) == 0 { unstructured.RemoveNestedField(target.Object, "metadata", "labels") } else { target.SetLabels(labels) } } } } // SetAppInstanceLabel the recommended app.kubernetes.io/instance label against an unstructured object // Uses the legacy labeling if environment variable is set func SetAppInstanceLabel(target *unstructured.Unstructured, key, val string) error { labels := target.GetLabels() if labels == nil { labels = make(map[string]string) } labels[key] = val target.SetLabels(labels) if key != common.LabelKeyLegacyApplicationName { // we no longer label the pod template sub resources in v0.11 return nil } gvk := schema.FromAPIVersionAndKind(target.GetAPIVersion(), target.GetKind()) // special case for deployment and job types: make sure that derived replicaset, and pod has // the application label switch gvk.Group { case "apps", "extensions": switch gvk.Kind { case DeploymentKind, ReplicaSetKind, StatefulSetKind, DaemonSetKind: templateLabels, ok, err := unstructured.NestedMap(target.UnstructuredContent(), "spec", "template", "metadata", "labels") if err != nil { return err } if !ok || templateLabels == nil { templateLabels = make(map[string]interface{}) } templateLabels[key] = val err = unstructured.SetNestedMap(target.UnstructuredContent(), templateLabels, "spec", "template", "metadata", "labels") if err != nil { return err } // The following is a workaround for issue #335. In API version extensions/v1beta1 or // apps/v1beta1, if a spec omits spec.selector then k8s will default the // spec.selector.matchLabels to match spec.template.metadata.labels. This means Argo CD // labels can potentially make their way into spec.selector.matchLabels, which is a bad // thing. The following logic prevents this behavior. switch target.GetAPIVersion() { case "apps/v1beta1", "extensions/v1beta1": selector, _, err := unstructured.NestedMap(target.UnstructuredContent(), "spec", "selector") if err != nil { return err } if len(selector) == 0 { // If we get here, user did not set spec.selector in their manifest. We do not want // our Argo CD labels to get defaulted by kubernetes, so we explicitly set the labels // for them (minus the Argo CD labels). delete(templateLabels, key) err = unstructured.SetNestedMap(target.UnstructuredContent(), templateLabels, "spec", "selector", "matchLabels") if err != nil { return err } } } } case "batch": switch gvk.Kind { case JobKind: templateLabels, ok, err := unstructured.NestedMap(target.UnstructuredContent(), "spec", "template", "metadata", "labels") if err != nil { return err } if !ok || templateLabels == nil { templateLabels = make(map[string]interface{}) } templateLabels[key] = val err = unstructured.SetNestedMap(target.UnstructuredContent(), templateLabels, "spec", "template", "metadata", "labels") if err != nil { return err } } } return nil } func ToGroupVersionResource(groupVersion string, apiResource *metav1.APIResource) schema.GroupVersionResource { gvk := schema.FromAPIVersionAndKind(groupVersion, apiResource.Kind) gv := gvk.GroupVersion() return gv.WithResource(apiResource.Name) } func ToResourceInterface(dynamicIf dynamic.Interface, apiResource *metav1.APIResource, resource schema.GroupVersionResource, namespace string) dynamic.ResourceInterface { if apiResource.Namespaced { return dynamicIf.Resource(resource).Namespace(namespace) } return dynamicIf.Resource(resource) } func IsCRDGroupVersionKind(gvk schema.GroupVersionKind) bool { return gvk.Kind == CustomResourceDefinitionKind && gvk.Group == "apiextensions.k8s.io" } func IsCRD(obj *unstructured.Unstructured) bool { return IsCRDGroupVersionKind(obj.GroupVersionKind()) } type apiResourceInterface struct { groupVersion schema.GroupVersion apiResource metav1.APIResource resourceIf dynamic.ResourceInterface } type filterFunc func(apiResource *metav1.APIResource) bool func filterAPIResources(config *rest.Config, resourceFilter ResourceFilter, filter filterFunc, namespace string) ([]apiResourceInterface, error) { dynamicIf, err := dynamic.NewForConfig(config) if err != nil { return nil, err } disco, err := discovery.NewDiscoveryClientForConfig(config) if err != nil { return nil, err } serverResources, err := disco.ServerPreferredResources() if err != nil { if len(serverResources) == 0 { return nil, err } log.Warnf("Partial success when performing preferred resource discovery: %v", err) } apiResIfs := make([]apiResourceInterface, 0) for _, apiResourcesList := range serverResources { gv, err := schema.ParseGroupVersion(apiResourcesList.GroupVersion) if err != nil { gv = schema.GroupVersion{} } if resourceFilter.IsExcludedResource(gv.Group, apiResourcesList.Kind, config.Host) { continue } for _, apiResource := range apiResourcesList.APIResources { if _, ok := isObsoleteExtensionsGroupKind(gv.Group, apiResource.Kind); ok || gv.Group == "" && apiResource.Kind == "Event" { continue } if filter(&apiResource) { resource := ToGroupVersionResource(apiResourcesList.GroupVersion, &apiResource) resourceIf := ToResourceInterface(dynamicIf, &apiResource, resource, namespace) gv, err := schema.ParseGroupVersion(apiResourcesList.GroupVersion) if err != nil { return nil, err } apiResIf := apiResourceInterface{ groupVersion: gv, apiResource: apiResource, resourceIf: resourceIf, } apiResIfs = append(apiResIfs, apiResIf) } } } return apiResIfs, nil } // isSupportedVerb returns whether or not a APIResource supports a specific verb func isSupportedVerb(apiResource *metav1.APIResource, verb string) bool { for _, v := range apiResource.Verbs { if v == verb { return true } } return false } // See: https://github.com/ksonnet/ksonnet/blob/master/utils/client.go func ServerResourceForGroupVersionKind(disco discovery.DiscoveryInterface, gvk schema.GroupVersionKind) (*metav1.APIResource, error) { resources, err := disco.ServerResourcesForGroupVersion(gvk.GroupVersion().String()) if err != nil { return nil, err } for _, r := range resources.APIResources { if r.Kind == gvk.Kind { log.Debugf("Chose API '%s' for %s", r.Name, gvk) return &r, nil } } return nil, apierr.NewNotFound(schema.GroupResource{Group: gvk.Group, Resource: gvk.Kind}, "") } // cleanKubectlOutput makes the error output of kubectl a little better to read func cleanKubectlOutput(s string) string { s = strings.TrimSpace(s) s = strings.Replace(s, ": error validating \"STDIN\"", "", -1) s = strings.Replace(s, ": unable to recognize \"STDIN\"", "", -1) s = strings.Replace(s, ": error when creating \"STDIN\"", "", -1) s = strings.Replace(s, "; if you choose to ignore these errors, turn validation off with --validate=false", "", -1) s = strings.Replace(s, "error: error", "error", -1) return s } // WriteKubeConfig takes a rest.Config and writes it as a kubeconfig at the specified path func WriteKubeConfig(restConfig *rest.Config, namespace, filename string) error { kubeConfig := NewKubeConfig(restConfig, namespace) return clientcmd.WriteToFile(*kubeConfig, filename) } // NewKubeConfig converts a clientcmdapi.Config (kubeconfig) from a rest.Config func NewKubeConfig(restConfig *rest.Config, namespace string) *clientcmdapi.Config { return &clientcmdapi.Config{ CurrentContext: restConfig.Host, Contexts: map[string]*clientcmdapi.Context{ restConfig.Host: { Cluster: restConfig.Host, AuthInfo: restConfig.Host, Namespace: namespace, }, }, Clusters: map[string]*clientcmdapi.Cluster{ restConfig.Host: { Server: restConfig.Host, InsecureSkipTLSVerify: restConfig.TLSClientConfig.Insecure, CertificateAuthority: restConfig.TLSClientConfig.CAFile, CertificateAuthorityData: restConfig.TLSClientConfig.CAData, }, }, AuthInfos: map[string]*clientcmdapi.AuthInfo{ restConfig.Host: newAuthInfo(restConfig), }, } } // newAuthInfo returns an AuthInfo from a rest config, detecting if the rest.Config is an // in-cluster config and automatically setting the token path appropriately. func newAuthInfo(restConfig *rest.Config) *clientcmdapi.AuthInfo { authInfo := clientcmdapi.AuthInfo{} haveCredentials := false if restConfig.TLSClientConfig.CertFile != "" { authInfo.ClientCertificate = restConfig.TLSClientConfig.CertFile haveCredentials = true } if len(restConfig.TLSClientConfig.CertData) > 0 { authInfo.ClientCertificateData = restConfig.TLSClientConfig.CertData haveCredentials = true } if restConfig.TLSClientConfig.KeyFile != "" { authInfo.ClientKey = restConfig.TLSClientConfig.KeyFile haveCredentials = true } if len(restConfig.TLSClientConfig.KeyData) > 0 { authInfo.ClientKeyData = restConfig.TLSClientConfig.KeyData haveCredentials = true } if restConfig.Username != "" { authInfo.Username = restConfig.Username haveCredentials = true } if restConfig.Password != "" { authInfo.Password = restConfig.Password haveCredentials = true } if restConfig.BearerToken != "" { authInfo.Token = restConfig.BearerToken haveCredentials = true } if restConfig.ExecProvider != nil { authInfo.Exec = restConfig.ExecProvider haveCredentials = true } if restConfig.ExecProvider == nil && !haveCredentials { // If no credentials were set (or there was no exec provider), we assume in-cluster config. // In-cluster configs from the go-client will no longer set bearer tokens, so we set the // well known token path. See issue #774 authInfo.TokenFile = "/var/run/secrets/kubernetes.io/serviceaccount/token" } return &authInfo } var diffSeparator = regexp.MustCompile(`\n---`) // SplitYAML splits a YAML file into unstructured objects. Returns list of all unstructured objects // found in the yaml. If any errors occurred, returns the first one func SplitYAML(out string) ([]*unstructured.Unstructured, error) { parts := diffSeparator.Split(out, -1) var objs []*unstructured.Unstructured var firstErr error for _, part := range parts { var objMap map[string]interface{} err := yaml.Unmarshal([]byte(part), &objMap) if err != nil { if firstErr == nil { firstErr = fmt.Errorf("Failed to unmarshal manifest: %v", err) } continue } if len(objMap) == 0 { // handles case where theres no content between `---` continue } var obj unstructured.Unstructured err = yaml.Unmarshal([]byte(part), &obj) if err != nil { if firstErr == nil { firstErr = fmt.Errorf("Failed to unmarshal manifest: %v", err) } continue } remObj, err := Remarshal(&obj) if err != nil { log.Warnf("Failed to remarshal oject: %v", err) } else { obj = *remObj } objs = append(objs, &obj) } return objs, firstErr } // Remarshal checks resource kind and version and re-marshal using corresponding struct custom marshaller. // This ensures that expected resource state is formatter same as actual resource state in kubernetes // and allows to find differences between actual and target states more accurately. func Remarshal(obj *unstructured.Unstructured) (*unstructured.Unstructured, error) { data, err := json.Marshal(obj) if err != nil { return nil, err } item, err := scheme.Scheme.New(obj.GroupVersionKind()) if err != nil
// This will drop any omitempty fields, perform resource conversion etc... unmarshalledObj := reflect.New(reflect.TypeOf(item).Elem()).Interface() err = json.Unmarshal(data, &unmarshalledObj) if err != nil { return nil, err } unstrBody, err := runtime.DefaultUnstructuredConverter.ToUnstructured(unmarshalledObj) if err != nil { return nil, err } // remove all default values specified by custom formatter (e.g. creationTimestamp) unstrBody = jsonutil.RemoveMapFields(obj.Object, unstrBody) return &unstructured.Unstructured{Object: unstrBody}, nil } // WatchWithRetry returns channel of watch events or errors of failed to call watch API. func WatchWithRetry(ctx context.Context, getWatch func() (watch.Interface, error)) chan struct { *watch.Event Error error } { ch := make(chan struct { *watch.Event Error error }) execute := func() (bool, error) { w, err := getWatch() if err != nil { return false, err } for { select { case event, ok := <-w.ResultChan(): if ok { ch <- struct { *watch.Event Error error }{Event: &event, Error: nil} } else { return true, nil } case <-ctx.Done(): return false, nil } } } go func() { defer close(ch) for { retry, err := execute() if err != nil { ch <- struct { *watch.Event Error error }{Error: err} } if !retry { return } time.Sleep(time.Second) } }() return ch }
{ return nil, err }
01-list-properties.py
#!/usr/bin/env python3 # Copyright 2017 The Imaging Source Europe 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. # # This example will show you how to list available properties # import sys import gi gi.require_version("Tcam", "0.1") gi.require_version("Gst", "1.0") from gi.repository import Tcam, Gst def list_properties(camera): property_names = camera.get_tcam_property_names() for name in property_names: (ret, value, min_value, max_value, default_value, step_size, value_type, flags, category, group) = camera.get_tcam_property(name) if not ret: print("could not receive value {}".format(name)) continue if value_type == "integer" or value_type == "double": print("{}({}) value: {} default: {} min: {} max: {} grouping: {} - {}".format(name, value_type, value, default_value, min_value, max_value, category, group)) elif value_type == "string": print("{}(string) value: {} default: {} grouping: {} - {}".format(name, value, default_value, category, group)) elif value_type == "button": print("{}(button) grouping is {} - {}".format(name, category, group)) elif value_type == "boolean": print("{}(boolean) value: {} default: {} grouping: {} - {}".format(name, value,
group)) elif value_type == "enum": enum_entries = camera.get_tcam_menu_entries(name) print("{}(enum) value: {} default: {} grouping {} - {}".format(name, value, default_value, category, group)) print("Entries: ") for entry in enum_entries: print("\t {}".format(entry)) else: print("This should not happen.") def block_until_playing(pipeline): while True: # wait 0.1 seconds for something to happen change_return, state, pending = pipeline.get_state(100000000) if change_return == Gst.StateChangeReturn.SUCCESS: return True elif change_return == Gst.StateChangeReturn.FAILURE: print("Failed to change state {} {} {}".format(change_return, state, pending)) return False def main(): Gst.init(sys.argv) # init gstreamer # this line sets the gstreamer default logging level # it can be removed in normal applications # gstreamer logging can contain verry useful information # when debugging your application # see https://gstreamer.freedesktop.org/documentation/tutorials/basic/debugging-tools.html # for further details Gst.debug_set_default_threshold(Gst.DebugLevel.WARNING) pipeline = Gst.parse_launch("tcambin name=source ! fakesink") if not pipeline: print("Unable to create pipeline") return 1 # set this to a specific camera serial if you # do not want to use the default camera serial = None # get the tcambin to retrieve a property list through it source = pipeline.get_by_name("source") # serial is defined, thus make the source open that device if serial is not None: source.set_property("serial", serial) print("Properties before state PLAYING:") list_properties(source) # in the READY state the camera will always be initialized # in the PLAYING sta1te additional properties may appear from gstreamer elements pipeline.set_state(Gst.State.PLAYING) # helper function to ensure we have the right state # alternatively wait for the first image if not block_until_playing(pipeline): print("Unable to start pipeline") print("Properties during state PLAYING:") list_properties(source) pipeline.set_state(Gst.State.NULL) return 0 if __name__ == "__main__": sys.exit(main())
default_value, category,
bitcoin_pl.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Kin</source> <translation>O Kin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Kin&lt;/b&gt; version</source> <translation>Wersja &lt;b&gt;Kin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Oprogramowanie eksperymentalne. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Prawo autorskie</translation> </message> <message> <location line="+0"/> <source>The Kin developers</source> <translation>Deweloperzy Kin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Książka Adresowa</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Kliknij dwukrotnie, aby edytować adres lub etykietę</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Utwórz nowy adres</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Skopiuj aktualnie wybrany adres do schowka</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nowy Adres</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Kin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tutaj znajdują się twoje adresy Kin do odbioru płatności. Możesz nadać oddzielne adresy dla każdego z wysyłających monety, żeby śledzić oddzielnie ich opłaty.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiuj adres</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Pokaż Kod &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Kin address</source> <translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Podpisz wiado&amp;mość</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Usuń zaznaczony adres z listy</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Eksportuj dane z aktywnej karty do pliku</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Eksportuj</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Kin address</source> <translation>Zweryfikuj wiadomość, aby upewnić się, że została podpisana odpowiednim adresem Kin.</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Zweryfikuj wiadomość</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Usuń</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Kin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Tutaj znajdują się Twoje adresy Kin do wysyłania płatności. Zawsze sprawdzaj ilość i adres odbiorcy przed wysyłką monet.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopiuj &amp;Etykietę</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Edytuj</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Wyślij monety</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksportuj książkę adresową</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Plik *.CSV (rozdzielany przecinkami)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Błąd podczas eksportowania</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Błąd zapisu do pliku %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etykieta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez etykiety)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Okienko Hasła</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Wpisz hasło</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nowe hasło</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Powtórz nowe hasło</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Wprowadź nowe hasło dla portfela.&lt;br/&gt;Proszę użyć hasła składającego się z &lt;b&gt;10 lub więcej losowych znaków&lt;/b&gt; lub &lt;b&gt;ośmiu lub więcej słów&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Zaszyfruj portfel</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ta operacja wymaga hasła do portfela ażeby odblokować portfel.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Odblokuj portfel</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ta operacja wymaga hasła do portfela ażeby odszyfrować portfel.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Odszyfruj portfel</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Zmień hasło</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Podaj stare i nowe hasło do portfela.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potwierdź szyfrowanie portfela</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR KINS&lt;/b&gt;!</source> <translation>Uwaga: Jeśli zaszyfrujesz swój portfel i zgubisz hasło to &lt;b&gt;STRACISZ WSZYSTKIE SWOJE KIN&apos;Y&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jesteś pewien, że chcesz zaszyfrować swój portfel?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>WAŻNE: Wszystkie wykonane wcześniej kopie pliku portfela powinny być zamienione na nowe, szyfrowane pliki. Z powodów bezpieczeństwa, poprzednie kopie nieszyfrowanych plików portfela staną się bezużyteczne jak tylko zaczniesz korzystać z nowego, szyfrowanego portfela.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Uwaga: Klawisz Caps Lock jest włączony</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portfel zaszyfrowany</translation> </message> <message> <location line="-56"/> <source>Kin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your kins from being stolen by malware infecting your computer.</source> <translation>Program Kin zamknie się aby dokończyć proces szyfrowania. Pamiętaj, że szyfrowanie portfela nie zabezpiecza w pełni Twoich kinów przed kradzieżą przez wirusy lub trojany mogące zainfekować Twój komputer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Szyfrowanie portfela nie powiodło się</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Szyfrowanie portfela nie powiodło się z powodu wewnętrznego błędu. Twój portfel nie został zaszyfrowany.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Podane hasła nie są takie same.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Odblokowanie portfela nie powiodło się</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Wprowadzone hasło do odszyfrowania portfela jest niepoprawne.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Odszyfrowywanie portfela nie powiodło się</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Hasło portfela zostało pomyślnie zmienione.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Podpisz wiado&amp;mość...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synchronizacja z siecią...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>P&amp;odsumowanie</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Pokazuje ogólny zarys portfela</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakcje</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Przeglądaj historię transakcji</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Edytuj listę zapisanych adresów i i etykiet</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Pokaż listę adresów do otrzymywania płatności</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Zakończ</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Zamknij program</translation> </message> <message> <location line="+4"/> <source>Show information about Kin</source> <translation>Pokaż informację o Kin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Pokazuje informacje o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opcje...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Zaszyfruj Portf&amp;el</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Wykonaj kopię zapasową...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Zmień hasło...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importowanie bloków z dysku...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Ponowne indeksowanie bloków na dysku...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Kin address</source> <translation>Wyślij monety na adres Kin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Kin</source> <translation>Zmienia opcje konfiguracji kina</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Zapasowy portfel w innej lokalizacji</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Zmień hasło użyte do szyfrowania portfela</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Okno debudowania</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Otwórz konsolę debugowania i diagnostyki</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Zweryfikuj wiadomość...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Kin</source> <translation>Kin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portfel</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>Wyślij</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>Odbie&amp;rz</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adresy</translation> </message> <message> <location line="+22"/> <source>&amp;About Kin</source> <translation>O Kin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Pokaż / Ukryj</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Pokazuje lub ukrywa główne okno</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Szyfruj klucze prywatne, które są powiązane z twoim portfelem</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Kin addresses to prove you own them</source> <translation>Podpisz wiadomości swoim adresem aby udowodnić jego posiadanie</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Kin addresses</source> <translation>Zweryfikuj wiadomość, aby upewnić się, że została podpisana odpowiednim adresem Kin.</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Plik</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>P&amp;referencje</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>Pomo&amp;c</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Pasek zakładek</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Kin client</source> <translation>Kin klient</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Kin network</source> <translation><numerusform>%n aktywne połączenie do sieci Kin</numerusform><numerusform>%n aktywne połączenia do sieci Kin</numerusform><numerusform>%n aktywnych połączeń do sieci Kin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Przetworzono (w przybliżeniu) %1 z %2 bloków historii transakcji.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Pobrano %1 bloków z historią transakcji.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n godzina</numerusform><numerusform>%n godzin</numerusform><numerusform>%n godzin</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dzień</numerusform><numerusform>%n dni</numerusform><numerusform>%n dni</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n tydzień</numerusform><numerusform>%n tygodni</numerusform><numerusform>%n tygodni</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Ostatni otrzymany blok został wygenerowany %1 temu.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Błąd</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Ostrzeżenie</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informacja</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Transakcja przekracza limit. Możesz wysłać ją płacąc prowizję %1, która zostaje przekazana do węzłów, które ją prześlą i pomoże wspierać sieć Kin. Czy chcesz zapłacić prowizję?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Aktualny</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Łapanie bloków...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Potwierdź prowizję transakcyjną</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transakcja wysłana</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transakcja przychodząca</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Kwota: %2 Typ: %3 Adres: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Obsługa URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Kin address or malformed URI parameters.</source> <translation>URI nie może zostać przetworzony! Prawdopodobnie błędny adres Kin bądź nieprawidłowe parametry URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portfel jest &lt;b&gt;zaszyfrowany&lt;/b&gt; i obecnie &lt;b&gt;niezablokowany&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portfel jest &lt;b&gt;zaszyfrowany&lt;/b&gt; i obecnie &lt;b&gt;zablokowany&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Kin can no longer continue safely and will quit.</source> <translation>Błąd krytyczny. Kin nie może kontynuować bezpiecznie więc zostanie zamknięty.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Sieć Alert</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Edytuj adres</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etykieta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Etykieta skojarzona z tym wpisem w książce adresowej</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Ten adres jest skojarzony z wpisem w książce adresowej. Może być zmodyfikowany jedynie dla adresów wysyłających.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nowy adres odbiorczy</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nowy adres wysyłania</translation> </message> <message>
</message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Edytuj adres wysyłania</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Wprowadzony adres &quot;%1&quot; już istnieje w książce adresowej.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Kin address.</source> <translation>Wprowadzony adres &quot;%1&quot; nie jest poprawnym adresem Kin.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nie można było odblokować portfela.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Tworzenie nowego klucza nie powiodło się.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Kin-Qt</source> <translation>Kin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>wersja</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Użycie:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opcje konsoli</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI opcje</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Ustaw Język, na przykład &quot;pl_PL&quot; (domyślnie: systemowy)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Uruchom zminimalizowany</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Pokazuj okno powitalne przy starcie (domyślnie: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opcje</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>Główne</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Płać prowizję za transakcje</translation> </message> <message> <location line="+31"/> <source>Automatically start Kin after logging in to the system.</source> <translation>Automatycznie uruchamia Kin po zalogowaniu do systemu.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Kin on system login</source> <translation>Uruchamiaj Kin wraz z zalogowaniem do &amp;systemu</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Przywróć domyślne wszystkie ustawienia klienta.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Z&amp;resetuj Ustawienia</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Sieć</translation> </message> <message> <location line="+6"/> <source>Automatically open the Kin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatycznie otwiera port klienta Kin na routerze. Ta opcja dzieła tylko jeśli twój router wspiera UPnP i jest ono włączone.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapuj port używając &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Kin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Podłącz się do sieci Kin przez proxy SOCKS (np. gdy łączysz się poprzez Tor&apos;a)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Połącz się przez proxy SOCKS</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP: </translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Adres IP serwera proxy (np. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port proxy (np. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>Wersja &amp;SOCKS</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS wersja serwera proxy (np. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Okno</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Pokazuj tylko ikonę przy zegarku po zminimalizowaniu okna.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizuj do paska przy zegarku zamiast do paska zadań</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimalizuje zamiast zakończyć działanie programu przy zamykaniu okna. Kiedy ta opcja jest włączona, program zakończy działanie po wybieraniu Zamknij w menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimalizuj przy zamknięciu</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Wyświetlanie</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Język &amp;Użytkownika:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Kin.</source> <translation>Można tu ustawić język interfejsu uzytkownika. Żeby ustawienie przyniosło skutek trzeba uruchomić ponownie Kin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Jednostka pokazywana przy kwocie:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Wybierz podział jednostki pokazywany w interfejsie oraz podczas wysyłania monet</translation> </message> <message> <location line="+9"/> <source>Whether to show Kin addresses in the transaction list or not.</source> <translation>Pokazuj adresy Kin na liście transakcji.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Wyświetlaj adresy w liście transakcji</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Anuluj</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>Z&amp;astosuj</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>domyślny</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Potwierdź reset ustawień</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Niektóre ustawienia mogą wymagać ponownego uruchomienia klienta, żeby zacząć działać.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Czy chcesz kontynuować?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Ostrzeżenie</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Kin.</source> <translation>To ustawienie zostanie zastosowane po restarcie Kin</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Adres podanego proxy jest nieprawidłowy</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formularz</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Kin network after a connection is established, but this process has not completed yet.</source> <translation>Wyświetlana informacja może być nieaktualna. Twój portfel synchronizuje się automatycznie z siecią kin, zaraz po tym jak uzyskano połączenie, ale proces ten nie został jeszcze ukończony.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Niepotwierdzony:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portfel</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Niedojrzały: </translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Balans wydobycia, który jeszcze nie dojrzał</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Ostatnie transakcje&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Twoje obecne saldo</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Suma transakcji, które nie zostały jeszcze potwierdzone, i które nie zostały wliczone do twojego obecnego salda</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>desynchronizacja</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start kin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Okno Dialogowe Kodu QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Prośba o płatność</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Kwota:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etykieta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Wiadomość:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Zapi&amp;sz jako...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Błąd kodowania URI w Kodzie QR.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Podana ilość jest nieprawidłowa, proszę sprawdzić</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Wynikowy URI jest zbyt długi, spróbuj zmniejszyć tekst etykiety / wiadomości</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Zapisz Kod QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Obraz PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nazwa klienta</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>NIEDOSTĘPNE</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Wersja klienta</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informacje</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Używana wersja OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Czas uruchomienia</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Sieć</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Liczba połączeń</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>W sieci testowej</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Ciąg bloków</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Aktualna liczba bloków</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Szacowana ilość bloków</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Czas ostatniego bloku</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Otwórz</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opcje konsoli</translation> </message> <message> <location line="+7"/> <source>Show the Kin-Qt help message to get a list with possible Kin command-line options.</source> <translation>Pokaż pomoc Kin-Qt, aby zobaczyć listę wszystkich opcji linii poleceń</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Pokaż</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data kompilacji</translation> </message> <message> <location line="-104"/> <source>Kin - Debug window</source> <translation>Kin - Okno debudowania</translation> </message> <message> <location line="+25"/> <source>Kin Core</source> <translation>Rdzeń BitCoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Kin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Wyczyść konsolę</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Kin RPC console.</source> <translation>Witam w konsoli Kin RPC</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Użyj strzałek do przewijania historii i &lt;b&gt;Ctrl-L&lt;/b&gt; aby wyczyścić ekran</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Wpisz &lt;b&gt;help&lt;/b&gt; aby uzyskać listę dostępnych komend</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Wyślij płatność</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Wyślij do wielu odbiorców na raz</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Dodaj Odbio&amp;rce</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Wyczyść wszystkie pola transakcji</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Wyczyść &amp;wszystko</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potwierdź akcję wysyłania</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>Wy&amp;syłka</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; do %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potwierdź wysyłanie monet</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Czy na pewno chcesz wysłać %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> i </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adres odbiorcy jest nieprawidłowy, proszę poprawić</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Kwota do zapłacenia musi być większa od 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Kwota przekracza twoje saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Suma przekracza twoje saldo, gdy doliczymy %1 prowizji transakcyjnej.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Znaleziono powtórzony adres, można wysłać tylko raz na każdy adres podczas operacji wysyłania.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Błąd: Tworzenie transakcji zakończone niepowodzeniem!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Błąd: transakcja została odrzucona. Może się to zdarzyć, gdy monety z Twojego portfela zostały już wydane, na przykład gdy używałeś kopii wallet.dat i kiny które tam wydałeś nie zostały jeszcze odjęte z portfela z którego teraz korzystasz.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formularz</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Zapłać dla:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adres, na który wysłasz płatności (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Wprowadź etykietę dla tego adresu by dodać go do książki adresowej</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etykieta:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Wybierz adres z książki adresowej</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Wklej adres ze schowka</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Usuń tego odbiorce</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Kin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Wprowadź adres Kin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Podpisy - Podpisz / zweryfikuj wiadomość</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>Podpi&amp;sz Wiadomość</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Możesz podpisywać wiadomości swoimi adresami aby udowodnić, że jesteś ich właścicielem. Uważaj, aby nie podpisywać niczego co wzbudza Twoje podejrzenia, ponieważ ktoś może stosować phishing próbując nakłonić Cię do ich podpisania. Akceptuj i podpisuj tylko w pełni zrozumiałe komunikaty i wiadomości.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Wprowadź adres Kin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Wybierz adres z książki kontaktowej</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Wklej adres ze schowka</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Wprowadź wiadomość, którą chcesz podpisać, tutaj</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Podpis</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopiuje aktualny podpis do schowka systemowego</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Kin address</source> <translation>Podpisz wiadomość aby dowieść, że ten adres jest twój</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Podpisz Wiado&amp;mość</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Zresetuj wszystkie pola podpisanej wiadomości</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Wyczyść &amp;wszystko</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Zweryfikuj wiadomość</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Wprowadź adres Kin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Kin address</source> <translation>Zweryfikuj wiadomość, aby upewnić się, że została podpisana odpowiednim adresem Kin.</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Zweryfikuj Wiado&amp;mość</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Resetuje wszystkie pola weryfikacji wiadomości</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Kin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Wprowadź adres Kin (np. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Kliknij &quot;Podpisz Wiadomość&quot; żeby uzyskać podpis</translation> </message> <message> <location line="+3"/> <source>Enter Kin signature</source> <translation>Wprowadź podpis Kin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Podany adres jest nieprawidłowy.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Proszę sprawdzić adres i spróbować ponownie.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Wprowadzony adres nie odnosi się do klucza.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Odblokowanie portfela zostało anulowane.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Klucz prywatny dla podanego adresu nie jest dostępny</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Podpisanie wiadomości nie powiodło się</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Wiadomość podpisana.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Podpis nie może zostać zdekodowany.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Sprawdź podpis i spróbuj ponownie.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Weryfikacja wiadomości nie powiodła się.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Wiadomość zweryfikowana.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Kin developers</source> <translation>Deweloperzy Kin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otwórz do %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/niezatwierdzone</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potwierdzeń</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, emitowany przez %n węzeł</numerusform><numerusform>, emitowany przez %n węzły</numerusform><numerusform>, emitowany przez %n węzłów</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Źródło</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Wygenerowano</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Do</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>własny adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etykieta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Przypisy</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>niezaakceptowane</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Prowizja transakcji</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Kwota netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Wiadomość</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentarz</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transakcji</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Wygenerowane monety muszą zaczekać 120 bloków zanim będzie można je wydać. Kiedy wygenerowałeś ten blok, został on wyemitowany do sieci, aby dodać go do łańcucha bloków. Jeśli to się nie powiedzie nie zostanie on zaakceptowany i wygenerowanych monet nie będzie można wysyłać. Może się to czasami zdarzyć jeśli inny węzeł wygeneruje blok tuż przed tobą.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informacje debugowania</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transakcja</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Wejścia</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>prawda</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>fałsz</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nie został jeszcze pomyślnie wyemitowany</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Otwórz dla %n bloku</numerusform><numerusform>Otwórz dla %n następnych bloków</numerusform><numerusform>Otwórz dla %n następnych bloków</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nieznany</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Szczegóły transakcji</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ten panel pokazuje szczegółowy opis transakcji</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Kwota</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform>Otwórz dla %n następnych bloków</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otwórz do %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 potwierdzeń)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Niezatwierdzony (%1 z %2 potwierdzeń)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Zatwierdzony (%1 potwierdzeń)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Balans wydobycia będzie dostępny zaraz po tym, jak dojrzeje. Pozostał %n blok</numerusform><numerusform>Balans wydobycia będzie dostępny zaraz po tym, jak dojrzeje. Pozostało %n bloków</numerusform><numerusform>Balans wydobycia będzie dostępny zaraz po tym, jak dojrzeje. Pozostało %n bloków</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ten blok nie został odebrany przez jakikolwiek inny węzeł i prawdopodobnie nie zostanie zaakceptowany!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Wygenerowano ale nie zaakceptowano</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Otrzymane przez</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Odebrano od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Wysłano do</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Płatność do siebie</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Wydobyto</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(brak)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcji. Najedź na pole, aby zobaczyć liczbę potwierdzeń.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data i czas odebrania transakcji.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Rodzaj transakcji.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Adres docelowy transakcji.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Kwota usunięta z lub dodana do konta.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Wszystko</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Dzisiaj</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>W tym tygodniu</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>W tym miesiącu</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>W zeszłym miesiącu</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>W tym roku</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Zakres...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Otrzymane przez</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Wysłano do</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Do siebie</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Wydobyto</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Inne</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Wprowadź adres albo etykietę żeby wyszukać</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min suma</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopiuj adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiuj etykietę</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiuj kwotę</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Skopiuj ID transakcji</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Edytuj etykietę</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Pokaż szczegóły transakcji</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Eksportuj Dane Transakcyjne</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>CSV (rozdzielany przecinkami)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potwierdzony</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etykieta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Błąd podczas eksportowania</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Błąd zapisu do pliku %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Zakres:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>do</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Wyślij płatność</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Eksportuj</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Eksportuj dane z aktywnej karty do pliku</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Kopia Zapasowa Portfela</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Dane Portfela (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Nie udało się wykonać kopii zapasowej</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Wystąpił błąd przy zapisywaniu portfela do nowej lokalizacji.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Wykonano Kopię Zapasową</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Dane portfela zostały poprawnie zapisane w nowym miejscu.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Kin version</source> <translation>Wersja Kin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Użycie:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or kind</source> <translation>Wyślij polecenie do -server lub kind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lista poleceń</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Uzyskaj pomoc do polecenia</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opcje:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: kin.conf)</source> <translation>Wskaż plik konfiguracyjny (domyślnie: kin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: kind.pid)</source> <translation>Wskaż plik pid (domyślnie: kin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Wskaż folder danych</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Ustaw rozmiar w megabajtach cache-u bazy danych (domyślnie: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 2333 or testnet: 12333)</source> <translation>Nasłuchuj połączeń na &lt;port&gt; (domyślnie: 2333 lub testnet: 12333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Utrzymuj maksymalnie &lt;n&gt; połączeń z peerami (domyślnie: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Podłącz się do węzła aby otrzymać adresy peerów i rozłącz</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Podaj swój publiczny adres</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Próg po którym nastąpi rozłączenie nietrzymających się zasad peerów (domyślnie: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Czas w sekundach, przez jaki nietrzymający się zasad peerzy nie będą mogli ponownie się podłączyć (domyślnie: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Wystąpił błąd podczas ustawiania portu RPC %u w tryb nasłuchu: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 2332 or testnet: 12332)</source> <translation>Nasłuchuj połączeń JSON-RPC na &lt;port&gt; (domyślnie: 2332 or testnet: 12332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptuj linię poleceń oraz polecenia JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Uruchom w tle jako daemon i przyjmuj polecenia</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Użyj sieci testowej</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Akceptuj połączenia z zewnątrz (domyślnie: 1 jeśli nie ustawiono -proxy lub -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=kinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Kin Alert&quot; [email protected] </source> <translation>%s, musisz ustawić rpcpassword w pliku konfiguracyjnym:⏎ %s⏎ Zalecane jest użycie losowego hasła:⏎ rpcuser=kinrpc⏎ rpcpassword=%s⏎ (nie musisz pamiętać tego hasła)⏎ Użytkownik i hasło nie mogą być takie same.⏎ Jeśli plik nie istnieje, utwórz go z uprawnieniami tylko-do-odczytu dla właściciela.⏎ Zalecane jest ustawienie alertnotify aby poinformować o problemach:⏎ na przykład: alertnotify=echo %%s | mail -s &quot;Alarm Kin&quot; [email protected]⏎</translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Wystąpił błąd podczas ustawiania portu RPC %u w tryb nasłuchu dla IPv6, korzystam z IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Skojarz z podanym adresem. Użyj formatu [host]:port dla IPv6 </translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Kin is probably already running.</source> <translation>Nie można zablokować folderu danych %s. Kin prawdopodobnie już działa.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Uruchom polecenie przy otrzymaniu odpowiedniego powiadomienia (%s w poleceniu jest podstawiane za komunikat)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Wykonaj polecenie, kiedy transakcja portfela ulegnie zmianie (%s w poleceniu zostanie zastąpione przez TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Ustaw maksymalny rozmiar transakcji o wysokim priorytecie/niskiej prowizji w bajtach (domyślnie: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Ostrzeżenie: -paytxfee jest bardzo duży. To jest prowizja za transakcje, którą płacisz, gdy wysyłasz monety.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Uwaga: Wyświetlone transakcje mogą nie być poprawne! Możliwe, że potrzebujesz aktualizacji bądź inne węzły jej potrzebują</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Kin will not work properly.</source> <translation>Uwaga: Sprawdź czy data i czas na Twoim komputerze są prawidłowe! Jeśli nie to Kin nie będzie działał prawidłowo.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Ostrzeżenie: błąd odczytu wallet.dat! Wszystkie klucze zostały odczytane, ale może brakować pewnych danych transakcji lub wpisów w książce adresowej lub mogą one być nieprawidłowe.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Ostrzeżenie: Odtworzono dane z uszkodzonego pliku wallet.dat! Oryginalny wallet.dat został zapisany jako wallet.{timestamp}.bak w %s; jeśli twoje saldo lub transakcje są niepoprawne powinieneś odtworzyć kopię zapasową.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Próbuj odzyskać klucze prywatne z uszkodzonego wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opcje tworzenia bloku:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Łącz tylko do wskazanego węzła</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Wykryto uszkodzoną bazę bloków</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Odkryj własny adres IP (domyślnie: 1 kiedy w trybie nasłuchu i brak -externalip )</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Czy chcesz teraz przebudować bazę bloków?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Błąd inicjowania bloku bazy danych</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Błąd inicjowania środowiska bazy portfela %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Błąd ładowania bazy bloków</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Błąd ładowania bazy bloków</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Błąd: Mało miejsca na dysku!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Błąd: Zablokowany portfel, nie można utworzyć transakcji!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Błąd: błąd systemu:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Próba otwarcia jakiegokolwiek portu nie powiodła się. Użyj -listen=0 jeśli tego chcesz.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Nie udało się odczytać informacji bloku</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Nie udało się odczytać bloku.</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Nie udało się zsynchronizować indeksu bloków.</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Nie udało się zapisać indeksu bloków.</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Nie udało się zapisać informacji bloku</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Nie udało się zapisać bloku</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Nie udało się zapisać do bazy monet</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Nie udało się zapisać indeksu transakcji</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Nie udało się zapisać danych odtwarzających</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Wyszukaj połączenia wykorzystując zapytanie DNS (domyślnie 1 jeśli nie użyto -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Generuj monety (domyślnie: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Ile bloków sprawdzić przy starcie (domyślnie: 288, 0 = wszystkie)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Jak dokładna jest weryfikacja bloku (0-4, domyślnie: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Odbuduj indeks łańcucha bloków z obecnych plików blk000??.dat</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Ustaw liczbę wątków do odwołań RPC (domyślnie: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Weryfikacja bloków...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Weryfikacja portfela...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importuj bloki z zewnętrznego pliku blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Ustaw liczbę wątków skryptu weryfikacji (do 16, 0 = auto, &lt;0 = zostawia taką ilość rdzenie wolnych, domyślnie: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informacja</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Nieprawidłowy adres -tor: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Utrzymuj pełen indeks transakcji (domyślnie: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksymalny bufor odbioru na połączenie, &lt;n&gt;*1000 bajtów (domyślnie: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksymalny bufor wysyłu na połączenie, &lt;n&gt;*1000 bajtów (domyślnie: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Akceptuj tylko łańcuch bloków zgodny z wbudowanymi punktami kontrolnymi (domyślnie: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Łącz z węzłami tylko w sieci &lt;net&gt; (IPv4, IPv6 lub Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Poprzedź informacje debugowania znacznikiem czasowym</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Kin Wiki for SSL setup instructions)</source> <translation>Opcje SSL: (odwiedź Kin Wiki w celu uzyskania instrukcji)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Wybierz używaną wersje socks serwera proxy (4-5, domyślnie:5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Wyślij informację/raport do konsoli zamiast do pliku debug.log.</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Wyślij informację/raport do debuggera.</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Ustaw maksymalny rozmiar bloku w bajtach (domyślnie: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Ustaw minimalny rozmiar bloku w bajtach (domyślnie: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Zmniejsz plik debug.log przy starcie programu (domyślnie: 1 jeśli nie użyto -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Wskaż czas oczekiwania bezczynności połączenia w milisekundach (domyślnie: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Błąd systemu:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Używaj UPnP do mapowania portu nasłuchu (domyślnie: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Używaj UPnP do mapowania portu nasłuchu (domyślnie: 1 gdy nasłuchuje)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nazwa użytkownika dla połączeń JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Ostrzeżenie</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Uwaga: Ta wersja jest przestarzała, aktualizacja wymagana!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Musisz przebudować bazę używając parametru -reindex aby zmienić -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat uszkodzony, odtworzenie się nie powiodło</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Hasło do połączeń JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Przyjmuj połączenia JSON-RPC ze wskazanego adresu IP</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Wysyłaj polecenia do węzła działającego na &lt;ip&gt; (domyślnie: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Wykonaj polecenie kiedy najlepszy blok ulegnie zmianie (%s w komendzie zastanie zastąpione przez hash bloku)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Zaktualizuj portfel do najnowszego formatu.</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Ustaw rozmiar puli kluczy na &lt;n&gt; (domyślnie: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Przeskanuj blok łańcuchów żeby znaleźć zaginione transakcje portfela</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Użyj OpenSSL (https) do połączeń JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Plik certyfikatu serwera (domyślnie: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Klucz prywatny serwera (domyślnie: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Aceptowalne szyfry (domyślnie: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ta wiadomość pomocy</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nie można przywiązać %s na tym komputerze (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Łączy przez proxy socks</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Zezwól -addnode, -seednode i -connect na łączenie się z serwerem DNS</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Wczytywanie adresów...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Błąd ładowania wallet.dat: Uszkodzony portfel</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Kin</source> <translation>Błąd ładowania wallet.dat: Portfel wymaga nowszej wersji Kin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Kin to complete</source> <translation>Portfel wymaga przepisania: zrestartuj Kina żeby ukończyć</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Błąd ładowania wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Nieprawidłowy adres -proxy: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Nieznana sieć w -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Nieznana wersja proxy w -socks: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Nie można uzyskać adresu -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nie można uzyskać adresu -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nieprawidłowa kwota dla -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Nieprawidłowa kwota</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Niewystarczające środki</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Ładowanie indeksu bloku...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Dodaj węzeł do łączenia się and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Kin is probably already running.</source> <translation>Nie można przywiązać %s na tym komputerze. Kin prawdopodobnie już działa.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation> </translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Wczytywanie portfela...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nie można dezaktualizować portfela</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nie można zapisać domyślnego adresu</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ponowne skanowanie...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Wczytywanie zakończone</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Aby użyć opcji %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Błąd</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Musisz ustawić rpcpassword=&lt;hasło&gt; w pliku configuracyjnym: %s Jeżeli plik nie istnieje, utwórz go z uprawnieniami właściciela-tylko-do-odczytu.</translation> </message> </context> </TS>
<location line="+3"/> <source>Edit receiving address</source> <translation>Edytuj adres odbioru</translation>
constraints-groups-parsing.ts
// Structs and functions that manage the frontend of Constraint groups. This // data is later parsed into actual Constraints by "constraints-parsing.ts" // The available constraints on a local group level. const GroupMenu = ['contains', 'excludes', 'is size', 'has attribute', 'has attribute relationship']; // The available mathematical relations between Atoms and Attributes. const RelationMenu = ['=', '≠', '>', '≥', '<', '≤']; // The available constraints on a global level. const GlobalMenu =['position', 'vertical position', 'vertical alignment', 'attribute relationship', 'attribute balance']; // The available arthimetic operations to perform on values. const MathMenu = ['+', '-', '×', '÷', '±']; interface ProtoGroup { // A primitive type that will eventually be parsed into a full ConsGroup object readonly name: string; readonly constraints: ProtoConstraint[]; } class ProtoGrou
object that statefully stores/updates ProtoConstraint objects derived // from user input. The actual ConsIndex type is initialized from this data // when the user places the program into solving mode. all: ProtoGroup[]; globalConstraints: ProtoConstraint[]; atomNames: string[]; attributeNames: string[]; constraintConstants: [string[], string[], string[], string[]]; constructor() { this.all = []; this.globalConstraints = []; this.atomNames = []; this.attributeNames = []; this.constraintConstants = [GroupMenu, RelationMenu, GlobalMenu, MathMenu]; } names(): string[] { return this.all.map(x => x.name); } update(pi: ProtoIndex) { this.atomNames = pi.all.map(x => x.name); const xs = pi.all.reduce((acc,x)=> acc.concat(x.attributes.map(y => { return y.name.toLowerCase(); })), []); this.attributeNames = Array.from(new Set(xs)).sort(); } addGroup() { this.all.push({name: 'Group ' + this.all.length.toString(), constraints: []}); } deleteGroup(n: number) { this.all.splice(n, 1); } copyGroup(n: number) { const x = JSON.parse(JSON.stringify(this.all[n])); this.all.splice(n, 0, x); } upGroup(n: number) { if (n == 0 || this.all.length <= 1) { return; } this.all.splice(n-1, 2, this.all[n], this.all[n-1]); } downGroup(n: number) { if (n == (this.all.length - 1) || this.all.length <= 1) { return; } this.all.splice(n, 2, this.all[n+1], this.all[n]); } addConstraint(n: number) { this.all[n].constraints.push([0, 0, 0, 0, 0, 0, 0, 0]); } deleteConstraint(n: number, m: number) { this.all[n].constraints.splice(m, 1); } addGlobalConstraint() { this.globalConstraints.push([0, 0, 0, 0, 0, 0, 0, 0]); } deleteGlobalConstraint(n: number) { this.globalConstraints.splice(n, 1); } } Vue.component('consContains', { // Frontend to a "contains item" Constraint. props: ['constraint', 'items', 'constants'], template: ` <span class="constraint"> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[0]" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in items" :value="n">{{ x }}</option> </select> </span> ` }); Vue.component('consSize', { // Frontend to an "is size" Constraint. props: ['constraint', 'constants'], template: ` <span class="constraint"> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[0]" :value="n">{{ x }}</option> </select> between <input class="numField" type="number" v-model="constraint[1]"></input> and <input class="numField" type="number" v-model="constraint[2]"></input> </span> ` }); Vue.component('consAttribute', { // Frontend to a "has attribute" Constraint. props: ['constraint', 'attributes', 'constants'], template: ` <span class="constraint"> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[0]" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in attributes" :value="n">{{ x }}</option> </select> between <input class="numField" type="number" v-model="constraint[2]"></input> and <input class="numField" type="number" v-model="constraint[3]"></input> </span> ` }); Vue.component('consAttributeRelation', { // Frontend to a "has attribute relationship" Constraint. props: ['constraint', 'attributes', 'constants'], template: ` <span class="constraint"> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[0]" :value="n">{{ x }}</option> </select> where <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in attributes" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[2]"> <option v-for="(x, n) in constants[1]" :value="n">{{ x }}</option> </select> ( <select class="dropdown" v-model="constraint[3]"> <option v-for="(x, n) in attributes" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[4]"> <option v-for="(x, n) in constants[3]" :value="n">{{ x }}</option> </select> <input class="numField" type="number" v-model="constraint[5]"></input> ) </span> ` }); Vue.component('group', { // Frontend to a local Constraint group. props: ['group', 'attributes', 'items', 'constants'], template: ` <li class="group"> <span class="groupButtons"> <button @click="$emit('delete-group')">x</button> <button @click="$emit('copy-group')">Copy</button> <button @click="$emit('up-group')">↑</button> <button @click="$emit('down-group')">↓</button> </span> <div class="atomForm"> <label>Name:</label> <input type="text" class="makeAtomName" v-model="group.name"></input> </div> <ul class="groupConstraints"> <li v-for="(x, n) in group.constraints"> <button @click="$emit('delete-group-constraint', n)">x</button> <consContains v-if="x[0] === 0" :constraint="x" :items="items" :constants="constants" :key="n"> </consContains> <consContains v-else-if="x[0] === 1" :constraint="x" :items="items" :constants="constants" :key="n"> </consContains> <consSize v-else-if="x[0] === 2" :constraint="x" :constants="constants"> </consSize> <consAttribute v-else-if="x[0] === 3" :constraint="x" :attributes="attributes" :constants="constants" key="n"> </consAttribute> <consAttributeRelation v-else :constraint="x" :attributes="attributes" :constants="constants" key="n"> </consAttributeRelation> </li> </ul> <button class="groupAddButton" @click="$emit('add-group-constraint')"> + Constraint </button> </li> ` }); Vue.component('consPosition', { // Frontend to a global Atom position Constraint. props: ['constraint', 'items', 'constants'], template: ` <span class="constraint"> <button @click="$emit('delete-global-constraint')">x</button> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[2]" :value="n">{{ x }}</option> </select> where <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in items" :value="n">{{ x }}</option> </select> <select v-if="constraint[4] !== 4" class="dropdown" v-model="constraint[2]"> <option v-for="(x, n) in constants[1]" :value="n"> {{ x }} </option> </select> <select v-else class="dropdown" v-model="constraint[2]"> <option v-for="(x, n) in constants[1]" :value="n"> {{ x }} </option> </select> ( <select class="dropdown" v-model="constraint[3]"> <option v-for="(x, n) in items" :value="n">{{ x }}</option> </select> <select v-if="constraint[2]>1" class="dropdown" v-model="constraint[4]"> <option v-for="(x, n) in constants[3]" :value="n"> {{ x }} </option> </select> <select v-else class="dropdown" v-model="constraint[4]"> <option v-for="(x, n) in constants[3]" :value="n"> {{ x }} </option> </select> <input class="numField" type="text" v-model="constraint[5]"></input> ) </span> ` }); Vue.component('consVerticalPosition', { // Frontend to a global Atom alignment Constraint. props: ['constraint', 'items', 'constants'], template: ` <span class="constraint"> <button @click="$emit('delete-global-constraint')">x</button> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[2]" :value="n">{{ x }}</option> </select> where <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in items" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[2]"> <option v-for="(x, n) in constants[1]" :value="n">{{ x }}</option> </select> column number <input class="numField" type="text" v-model="constraint[3]"></input> in rows of <input class="numField" type="text" v-model="constraint[4]"></input> </span> ` }); Vue.component('consAlignment', { // Frontend to a global Atom alignment Constraint. props: ['constraint', 'items', 'constants'], template: ` <span class="constraint"> <button @click="$emit('delete-global-constraint')">x</button> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[2]" :value="n">{{ x }}</option> </select> where <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in items" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[2]"> <option v-for="(x, n) in constants[1]" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[3]"> <option v-for="(x, n) in items" :value="n">{{ x }}</option> </select> in rows of <input class="numField" type="text" v-model="constraint[4]"></input> </span> ` }); Vue.component('consGlobalAttributeRelation', { // Frontend to a global attribute relation Constraint. props: ['constraint', 'attributes', 'groups', 'constants'], template: ` <span class="constraint"> <button @click="$emit('delete-global-constraint')">x</button> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[2]" :value="n">{{ x }}</option> </select> where <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in groups" :value="n">{{ x }}</option> </select> 's <select class="dropdown" v-model="constraint[2]"> <option v-for="(x, n) in attributes" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[3]"> <option v-for="(x, n) in constants[1]" :value="n">{{ x }}</option> </select> ( <select class="dropdown" v-model="constraint[4]"> <option v-for="(x, n) in groups" :value="n">{{ x }}</option> </select> 's <select class="dropdown" v-model="constraint[5]"> <option v-for="(x, n) in attributes" :value="n">{{ x }}</option> </select> <select class="dropdown" v-model="constraint[6]"> <option v-for="(x, n) in constants[3]" :value="n">{{ x }}</option> </select> <input class="numField" type="text" v-model="constraint[7]"></input> ) </span> ` }); Vue.component('consAttributeBalance', { // Frontend to a global attribute balance Constraint. props: ['constraint', 'attributes', 'constants'], template: ` <span class="constraint"> <button @click="$emit('delete-global-constraint')">x</button> <select class="dropdown" v-model="constraint[0]"> <option v-for="(x, n) in constants[2]" :value="n">{{ x }}</option> </select> of <select class="dropdown" v-model="constraint[1]"> <option v-for="(x, n) in attributes" :value="n">{{ x }}</option> </select> </span> ` }); Vue.component('globalGroup', { // Frontend to collection of global Constraints. props: ['constraints', 'attributes', 'items', 'groups', 'constants'], template: ` <div id="dummyDiv"> <div id="globalConstraints"> <ul> <li v-for="(x, n) in constraints"> <consPosition v-if="x[0] === 0" :constraint="x" :items="items" :constants="constants" :key="n" @delete-global-constraint="$emit('delete-global-constraint', n)"> </consPosition> <consVerticalPosition v-else-if="x[0] === 1" :constraint="x" :items="items" :constants="constants" :key="n" @delete-global-constraint="$emit('delete-global-constraint', n)"> </consVerticalPosition> <consAlignment v-else-if="x[0] === 2" :constraint="x" :items="items" :constants="constants" :key="n" @delete-global-constraint="$emit('delete-global-constraint', n)"> </consAlignment> <consGlobalAttributeRelation v-else-if="x[0] === 3" :constraint="x" :attributes="attributes" :groups="groups" :constants="constants" :key="n" @delete-global-constraint="$emit('delete-global-constraint', n)"> </consGlobalAttributeRelation> <consAttributeBalance v-else-if="x[0] === 4" :constraint="x" :attributes="attributes" :constants="constants" :key="n" @delete-global-constraint="$emit('delete-global-constraint', n)"> </consAttributeBalance> </li> </ul> </div> <button class="bigButton" @click="$emit('add-global-constraint')"> + Global Constraint </button> </div> ` }); Vue.component('groups', { // Frontend to index of all Constraint groups. props: ['tip', 'index', 'globalTip', 'groupIndex'], methods: { groupNames(pgi: ProtoGroupIndex) { return pgi.all.map(x => x.name); } }, template: ` <div id="paneContents"> <tip :tip="tip"></tip> <ul id="groups"> <group v-for="(x, n) in index.all" :group="x" :items="index.atomNames" :attributes="index.attributeNames" :constants="index.constraintConstants" :key="n" @delete-group="$emit('delete-group', n)" @copy-group="$emit('copy-group', n)" @up-group="$emit('up-group', n)" @down-group="$emit('down-group', n)" @add-group-constraint="$emit('add-group-constraint', n)" @delete-group-constraint="$emit('delete-group-constraint', n, ...arguments)"> </group> </ul> <button class="bigButton" @click="$emit('add-group')">+ Group</button> <tip :tip="globalTip"></tip> <globalGroup :constraints="index.globalConstraints" :attributes="index.attributeNames" :items="index.atomNames" :groups="groupNames(groupIndex)" :constants="index.constraintConstants" @add-global-constraint="$emit('add-global-constraint')" @delete-global-constraint="$emit('delete-global-constraint', ...arguments)"> </globalGroup> </div> ` });
pIndex { // An
edit.village.component.ts
import { Component, Inject } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { MatSnackBar } from '@angular/material'; import { HttpRequestServiceService } from '../../services/http-request-service.service'; export interface EditVillageDialogData { villageName: string; oldVillageName: string; } @Component({ selector: 'app-edit.village', templateUrl: './edit.village.component.html', styleUrls: ['./edit.village.component.css'] }) export class
{ editVillageInfo: any = { newVillageName: '', } httpRequestServiceService: HttpRequestServiceService; phoneFormControl = new FormControl('', [ Validators.required, Validators.minLength(10), Validators.maxLength(12), Validators.pattern('[0-9]+') // validates input is digit ]); constructor( public dialogRef: MatDialogRef<EditVillageComponent>, @Inject(MAT_DIALOG_DATA) public data: EditVillageDialogData, HttpRequestServiceService: HttpRequestServiceService, public snackBar: MatSnackBar) { this.httpRequestServiceService = HttpRequestServiceService; this.editVillageInfo.oldVillageName = data.oldVillageName; this.editVillageInfo.newVillageName = data.oldVillageName; } onNoClick(): void { this.dialogRef.close(); } onEditVillageSubmit(): void { this.httpRequestServiceService.updateVillageInfo(this.editVillageInfo) .subscribe(data => { if (data['responseCode'] == 200) { this.dialogRef.close(data); this.openSnackBar(data['responseMessage'], "SUCCESS"); } else { this.openSnackBar(data['responseMessage'], "ERROR"); } }) } openSnackBar(message: string, action: string, ) { this.snackBar.open(message, action, { announcementMessage: "announce", data: "data", direction: "ltr", duration: 2000 }) } }
EditVillageComponent
aarp_test.go
// Copyright (c) 2009-2020 Rob Braun <[email protected]> and others // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of Rob Braun nor the names of his contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package aarp import ( "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/sfiera/multitalk/pkg/ddp" "github.com/sfiera/multitalk/pkg/ethernet" ) func
(t *testing.T) { cases := []struct { name, hex string expected Packet }{{ "AARP", "0001809b0604" + // Ethernet-LLAP bridging "0003" + // Probe "080007b4b1ce" + "00ff005f" + // This is (tentatively) my address "000000000000" + "00ff005f", // Anyone out there using that address? Packet{ EthernetLLAPBridging, Body{ Opcode: ProbeOp, Src: AddrPair{ Hardware: ethernet.Addr{0x08, 0x00, 0x07, 0xb4, 0xb1, 0xce}, Proto: ddp.Addr{Network: 65280, Node: 95}, }, Dst: AddrPair{ Hardware: ethernet.Addr{}, Proto: ddp.Addr{Network: 65280, Node: 95}, }, }, }, }} for _, c := range cases { t.Run(c.name, func(t *testing.T) { assert := assert.New(t) p := Packet{} if assert.NoError(Unmarshal(unhex(c.hex), &p)) { assert.Equal(c.expected, p) } }) } } func TestError(t *testing.T) { cases := []struct { name, hex, err string }{{ "empty", "", "read aarp header: EOF", }} for _, c := range cases { t.Run(c.name, func(t *testing.T) { assert := assert.New(t) p := Packet{} err := Unmarshal(unhex(c.hex), &p) if assert.Error(err) { assert.Equal(c.err, err.Error()) } }) } } func unhex(s string) []byte { data := []byte{} for i := 0; i < len(s); i += 2 { n, err := strconv.ParseUint(s[i:i+2], 16, 8) if err != nil { panic(err) } data = append(data, byte(n)) } return data }
TestUnmarshalNoError
region-list.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RegionListComponent } from './region-list.component'; describe('RegionListComponent', () => { let component: RegionListComponent; let fixture: ComponentFixture<RegionListComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ RegionListComponent ] }) .compileComponents();
fixture = TestBed.createComponent(RegionListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
})); beforeEach(() => {
biobio.py
from dataclasses import dataclass from typing import List import click import desert import marshmallow import requests API_URL = "https://www.biobiochile.cl/lista/api/get-todo?limit={limit}" @dataclass class
: post_hour: str post_title: str post_content: str schema = desert.schema(New, meta={"unknown": marshmallow.EXCLUDE}, many=True) def last_news(limit: int = 10) -> List[New]: url = API_URL.format(limit=limit) try: with requests.get(url) as response: response.raise_for_status() data = response.json() data.reverse() return schema.load(data) except (requests.RequestException, marshmallow.ValidationError) as error: message = str(error) raise click.ClickException(message)
New
message_transfers.rs
//! Send a transfer to an address. //! //! Run with: //! //! ``` //! cargo run --example message_transfers //! ``` use anyhow::Result; use iota::{ bundle::{Address, Tag, TransactionField}, client::Transfer, ternary::TryteBuf, }; use iota_conversion::Trinary; #[smol_potat::main] async fn main() -> Result<()>
{ // Prepare a vector of transfers let mut transfers = Vec::new(); // Push the transfer to vector. transfers.push(Transfer { // Address is 81 trytes. address: Address::from_inner_unchecked( TryteBuf::try_from_str( "RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVA", ) .unwrap() .as_trits() .encode(), ), // We are using a zero balance seed so we make a zero value transfer here value: 0, message: Some(String::from(" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla dapibus eros at tincidunt fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed mattis orci felis, vel pulvinar est sodales non. Vestibulum placerat luctus dapibus. Quisque finibus lacus a mauris fermentum eleifend. Maecenas pharetra justo nunc, in egestas magna suscipit at. Vivamus dictum at est pharetra porttitor. Integer ac neque elementum, feugiat lorem a, suscipit nisi. Etiam vel vehicula ligula. In bibendum aliquet vulputate. Pellentesque tincidunt elementum convallis. Maecenas auctor erat quis gravida pellentesque. Nam posuere gravida nisl. Ut tincidunt vitae neque placerat varius. Aliquam eget ultrices sem. Sed iaculis convallis magna at porttitor. Ut blandit ut ipsum id pellentesque. Vestibulum a egestas nisi, at auctor arcu. Nulla bibendum ut magna nec elementum. In sed ipsum nec nunc tincidunt porttitor. Sed sed aliquam enim. Sed ut elementum sapien, sit amet porta magna. Donec eget nulla nec sem sodales mollis at vel magna. In rhoncus ornare lectus a aliquet. Curabitur sodales elit eget leo efficitur cursus. Proin eget neque dictum, luctus ipsum sed, porta ex. Morbi eget libero sem. Etiam vitae dignissim nunc. In elementum eu augue eget malesuada. Suspendisse at ornare erat, et convallis elit. Suspendisse rhoncus metus odio, sed ornare quam consectetur ut. Suspendisse a nunc vel leo iaculis varius. Aliquam erat volutpat. Nullam semper vulputate odio, et sagittis nunc ultrices non. Curabitur sit amet sem laoreet, egestas magna in, eleifend orci. Maecenas tincidunt nunc a eros sollicitudin, quis gravida tellus interdum. Curabitur id ipsum diam. Proin at massa urna. Sed neque mauris, efficitur vitae congue nec, posuere a magna. Vestibulum nunc tortor, euismod non faucibus a, aliquet eget sapien. Vivamus eros dui, viverra at mauris a, cursus pulvinar turpis. Vivamus non tempor leo. Donec condimentum nisl a turpis aliquam aliquet. Phasellus sollicitudin ultricies orci, ac ultrices leo. Praesent ultricies, quam accumsan ornare sodales, massa lacus tempus nunc, sed convallis metus dui et nibh. Aenean ultrices porttitor enim. Vestibulum vel ante at neque laoreet sollicitudin ut nec purus. Donec tortor lectus, egestas non gravida nec, consequat eu orci. Sed id vehicula eros. Aliquam leo odio, finibus nec placerat sit amet, dignissim in est. Suspendisse in neque auctor, bibendum nunc non, luctus dolor. Nulla convallis felis ac libero egestas, at egestas nunc consequat. Suspendisse tellus massa, consequat non felis facilisis, maximus convallis tortor. Fusce porta nunc est, et facilisis dolor imperdiet vitae. Vivamus ullamcorper erat et dignissim mattis. Nulla maximus, nisi vel lobortis gravida, arcu neque blandit ante, at sodales risus enim a metus. Nulla quis finibus mauris. ")), tag: Some(Tag::try_from_inner(TryteBuf::try_from_str("LOREMIPSUM99999999999999999") .unwrap() .as_trits() .encode()).unwrap()), }); // Create a client instance iota::Client::add_node("https://nodes.comnet.thetangle.org")?; // Call send_transfers api // Below is just a dummy seed which just serves as an example. // If you want to replace your own. It probably should be a seed with balance on comnet/devnet. let res = iota::Client::send_transfers(None) // Input the transfers .transfers(transfers) // We are sending to comnet, so mwm should be 10. It's 14 by default if you don't call this. .min_weight_magnitude(10) // Sending to the node and receive the response .send() .await?; // The response of send_transfers is vector of Transaction type. We choose the first one and see what is its bundle hash println!("{:?}", res[0].bundle().to_inner().as_i8_slice().trytes()); Ok(()) }
runAll.py
#! /usr/bin/env python from __future__ import print_function import sys import os import glob pFiles = glob.glob('*_p.py') caseDict = {}
for pf in pFiles: caseDict[pf] = set(glob.glob(pf[:-5]+'*_n.py')) #fix cases were problem name is a subset of some other problem name for pf1 in pFiles: for pf2 in pFiles: if pf2.find(pf1[:-4]): nf1Set=set(glob.glob(pf1[:-5]+'*_n.py')) caseDict[pf2] -= nf1Set for pf in pFiles: print(pf) print(caseDict[pf]) for p,nList in caseDict.items(): if len(nList) == 0: sys.stdout.write("\n----------------Skipping "+p+". No n file----------------------\n") sys.stdout.flush() else: for n in nList: args = ('proteusRun.py',p,n,'-l 4','-b','runAllBatch.py') sys.stdout.write("\n----------------Running "+p+"---"+n+"\n") sys.stdout.flush() os.spawnvpe(os.P_WAIT,'proteusRun.py',args,os.environ)
config.rs
use serde_derive::{Deserialize, Serialize}; use std::{collections::HashMap, fs::File, io::BufReader, path::Path}; #[derive(Serialize, Deserialize, Debug)] #[serde(deny_unknown_fields)] pub struct ConfigContainer { pub destinations: HashMap<String, DestinationConfig>, pub sources: HashMap<String, SourceConfig>, pub retryagent: Option<RetryAgentConfig>, pub mappings: HashMap<String, Vec<String>>, } impl ConfigContainer { pub fn from_file<P: AsRef<Path>>(path: P) -> Result<ConfigContainer, String> { let config_file = File::open(path).map_err(|_| "Failed to open config file".to_owned())?; let reader = BufReader::new(config_file); let config: ConfigContainer = serde_json::from_reader(reader) .map_err(|e| format!("Failed to parse config file: {}", e))?; config.validate()?; Ok(config) } fn validate(&self) -> Result<(), String> { for (srcname, dsts) in &self.mappings { if !self.sources.contains_key(srcname) { return Err(format!("Unknown source: {} specified in mappings", srcname)); } for dstname in dsts { if !self.destinations.contains_key(dstname) { return Err(format!( "Unknown destination: {} specified in mappings", dstname
for srcname in self.sources.keys() { if self.mappings.get(srcname).is_none() { return Err(format!("Source: {} has no mapping", srcname)); } } if let Some(RetryAgentConfig::Filesystem(config)) = &self.retryagent { if !Path::new(&config.path).exists() { return Err("FilesystemRetryAgent: Path does not exist".to_string()); } } Ok(()) } } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] #[serde(tag = "type")] pub enum AuthMethod { #[serde(rename = "plain")] Plain { user: String, password: String }, #[serde(rename = "login")] Login { user: String, password: String }, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] #[serde(tag = "type")] pub enum Encryption { #[serde(rename = "none")] None, #[serde(rename = "ssl")] Ssl, #[serde(rename = "starttls")] Starttls, } // ############# // # Sources // ############# #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct ImapPollSourceConfig { pub server: String, pub port: u16, pub interval: u64, pub keep: bool, pub auth: AuthMethod, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct ImapIdleSourceConfig { pub server: String, pub port: u16, pub path: String, pub renewinterval: u64, pub keep: bool, pub auth: AuthMethod, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct TestSourceConfig { pub delay: u64, pub interval: u64, } #[derive(Serialize, Deserialize, Debug)] #[serde(deny_unknown_fields)] #[serde(tag = "type")] pub enum SourceConfig { #[serde(rename = "test")] Test(TestSourceConfig), #[serde(rename = "imap_poll")] ImapPoll(ImapPollSourceConfig), #[serde(rename = "imap_idle")] ImapIdle(ImapIdleSourceConfig), } // ############# // # Destinations // ############# #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct SmtpDestinationConfig { pub server: String, pub port: u16, pub encryption: Encryption, pub auth: Option<AuthMethod>, pub recipient: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct TestDestinationConfig { pub fail_n_first: u16, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct ExecDestinationConfig { pub executable: String, pub arguments: Option<Vec<String>>, pub environment: Option<HashMap<String, String>>, } #[derive(Serialize, Deserialize, Debug)] #[serde(deny_unknown_fields)] #[serde(tag = "type")] pub enum DestinationConfig { #[serde(rename = "test")] Test(TestDestinationConfig), #[serde(rename = "smtp")] Smtp(SmtpDestinationConfig), #[serde(rename = "exec")] Exec(ExecDestinationConfig), } // ############# // # RetryAgent // ############# #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct MemoryRetryAgentConfig { pub delay: u64, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct FilesystemRetryAgentConfig { pub delay: u64, pub path: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] #[serde(tag = "type")] pub enum RetryAgentConfig { #[serde(rename = "memory")] Memory(MemoryRetryAgentConfig), #[serde(rename = "filesystem")] Filesystem(FilesystemRetryAgentConfig), }
)); } } }
matcher.go
package matcheng import ( "sort" "sync" "github.com/xar-network/xar-network/pkg/conv" "github.com/xar-network/xar-network/pkg/log" "github.com/xar-network/xar-network/types/store" sdk "github.com/cosmos/cosmos-sdk/types" ) type Order struct { ID store.EntityID Price sdk.Uint Quantity sdk.Uint } type MatchResults struct { ClearingPrice sdk.Uint Fills []Fill MatchTable []MatchEntry BidAggregates []AggregatePrice AskAggregates []AggregatePrice } type Matcher struct { bids []Order asks []Order mtx sync.Mutex } var logger = log.WithModule("matcher") type MatchEntry [3]sdk.Uint type AggregatePrice [2]sdk.Uint var zero = sdk.ZeroUint() func
() *Matcher { return &Matcher{ bids: make([]Order, 0), asks: make([]Order, 0), } } // merge prices into one big list // iterate over prices // choose the price at with # of sells > # of buys // walk back one price - that's clearing. // degen case: vertical line (then choose midpoint) // other degen case: no overlap. func (m *Matcher) EnqueueOrder(oType Direction, id store.EntityID, price sdk.Uint, quantity sdk.Uint) { m.mtx.Lock() defer m.mtx.Unlock() order := &Order{ ID: id, Price: price, Quantity: quantity, } if oType == Bid { m.enqueueBid(order) } else { m.enqueueAsk(order) } } func (m *Matcher) Match() *MatchResults { m.mtx.Lock() defer m.mtx.Unlock() if len(m.bids) == 0 || len(m.asks) == 0 { logger.Info("no bids or asks in this block") return nil } // handle degenerate case 1: no matches if m.bids[len(m.bids)-1].Price.LT(m.asks[0].Price) { logger.Info("highest bid price is lower than lowest ask price") return nil } // [price, supply, demand] var matchTable []MatchEntry var askAggs []AggregatePrice var wg sync.WaitGroup wg.Add(2) go func() { i := 0 for _, ask := range m.asks { if len(matchTable) == 0 { matchTable = append(matchTable, MatchEntry{ask.Price, ask.Quantity, zero}) askAggs = append(askAggs, AggregatePrice{ask.Price, ask.Quantity}) i++ continue } last := len(matchTable) - 1 if matchTable[last][0].Equal(ask.Price) { matchTable[last][1] = matchTable[last][1].Add(ask.Quantity) askAggs[last][1] = askAggs[last][1].Add(ask.Quantity) continue } matchTable = append(matchTable, MatchEntry{ ask.Price, matchTable[i-1][1].Add(ask.Quantity), zero, }) askAggs = append(askAggs, AggregatePrice{ ask.Price, matchTable[i-1][1].Add(ask.Quantity), }) i++ } wg.Done() }() var bidAggs []AggregatePrice go func() { for i := len(m.bids) - 1; i >= 0; i-- { bid := m.bids[i] if len(bidAggs) == 0 { bidAggs = append(bidAggs, [2]sdk.Uint{ bid.Price, bid.Quantity, }) continue } if bidAggs[0][0].Equal(bid.Price) { bidAggs[0][1] = bidAggs[0][1].Add(bid.Quantity) continue } bidAggs = append([]AggregatePrice{ {bid.Price, bidAggs[0][1].Add(bid.Quantity)}, }, bidAggs...) } wg.Done() }() wg.Wait() var lastInsertion int for _, agg := range bidAggs { j := sort.Search(len(matchTable), func(i int) bool { return matchTable[i][0].GTE(agg[0]) }) if j == len(matchTable) { carry := zero if len(matchTable) > 0 { carry = matchTable[j-1][1] } matchTable = append(matchTable, MatchEntry{agg[0], carry, agg[1]}) } else if matchTable[j][0].Equal(agg[0]) { matchTable[j][2] = matchTable[j][2].Add(agg[1]) } else { curr := zero if j > 0 { curr = matchTable[j-1][1] } matchTable = append(matchTable, MatchEntry{}) copy(matchTable[j+1:], matchTable[j:]) matchTable[j] = MatchEntry{agg[0], curr, agg[1]} } for i := lastInsertion; i < j; i++ { matchTable[i][2] = matchTable[i][2].Add(agg[1]) } lastInsertion = j + 1 } clearingPrice := zero aggSupply := zero aggDemand := zero crossPoint := 0 for i, entry := range matchTable { crossed := i > 0 && calcDir(matchTable[i-1]) != calcDir(matchTable[i]) if crossed { crossSup, crossDem := entry[1], entry[2] var topIdx int for j := i + 1; j < len(matchTable); j++ { testEntry := matchTable[j] if !crossSup.Equal(testEntry[1]) || !crossDem.Equal(testEntry[2]) { break } topIdx = j } if topIdx != 0 { diff := matchTable[topIdx][0].Sub(matchTable[i][0]) mid := matchTable[i][0].Add(diff.Quo(sdk.NewUint(2))) clearingPrice = mid aggSupply = crossSup aggDemand = crossDem break } crossPoint = i } if i > 0 && matchTable[i-1][1].GT(zero) && crossed { break } clearingPrice = entry[0] aggSupply = entry[1] aggDemand = entry[2] } // check for other edge case: horizontal cross if clearingPrice.Equal(matchTable[len(matchTable)-1][0]) && crossPoint < len(matchTable)-1 { entry := matchTable[crossPoint] if entry[1].GT(sdk.ZeroUint()) && entry[2].GT(sdk.ZeroUint()) { clearingPrice = entry[0] aggSupply = entry[1] aggDemand = entry[2] } } aggDemandDec := sdk.NewDecFromBigInt(conv.SDKUint2Big(aggDemand)) aggSupplyDec := sdk.NewDecFromBigInt(conv.SDKUint2Big(aggSupply)) proRataDec := aggSupplyDec.Quo(aggDemandDec) proRataRecip := sdk.OneDec().Quo(proRataDec) overOne := proRataDec.GT(sdk.OneDec()) maxBidVolume := sdk.NewDecFromInt(aggDemandDec.Mul(proRataDec).RoundInt()) maxAskVolume := sdk.NewDecFromInt(aggSupplyDec.Mul(proRataRecip).RoundInt()) matchedBidVolume := sdk.ZeroDec() var fills []Fill for i := len(m.bids) - 1; i >= 0; i-- { bid := m.bids[i] if bid.Price.LT(clearingPrice) || matchedBidVolume.Equal(maxAskVolume) { break } var qtyInt sdk.Uint if overOne { qtyInt = bid.Quantity } else { qtyDec := sdk.NewDecFromBigInt(conv.SDKUint2Big(bid.Quantity)).Mul(proRataDec).Ceil() qtyInt = sdk.NewUintFromString(qtyDec.RoundInt().String()) if matchedBidVolume.Add(qtyDec).GT(maxBidVolume) { qtyDec = maxBidVolume.Sub(matchedBidVolume) qtyInt = sdk.NewUintFromString(qtyDec.RoundInt().String()) } matchedBidVolume = matchedBidVolume.Add(qtyDec) if qtyInt.IsZero() { continue } } fills = append(fills, Fill{ OrderID: bid.ID, QtyFilled: qtyInt, QtyUnfilled: bid.Quantity.Sub(qtyInt), }) } matchedAskVolume := sdk.ZeroDec() for _, ask := range m.asks { if ask.Price.GT(clearingPrice) || matchedAskVolume.Equal(maxAskVolume) { break } var qtyInt sdk.Uint if overOne { qtyDec := proRataRecip.Mul(sdk.NewDecFromBigInt(conv.SDKUint2Big(ask.Quantity))).Ceil() qtyInt = sdk.NewUintFromString(qtyDec.RoundInt().String()) if matchedAskVolume.Add(qtyDec).GT(maxAskVolume) { qtyDec = maxAskVolume.Sub(matchedAskVolume) qtyInt = sdk.NewUintFromString(qtyDec.RoundInt().String()) } matchedAskVolume = matchedAskVolume.Add(qtyDec) if qtyInt.IsZero() { continue } } else { qtyInt = ask.Quantity } fills = append(fills, Fill{ OrderID: ask.ID, QtyFilled: qtyInt, QtyUnfilled: ask.Quantity.Sub(qtyInt), }) } logger.Info( "generated match results", "fill_count", len(fills), "bid_count", len(m.bids), "ask_count", len(m.asks), ) return &MatchResults{ ClearingPrice: clearingPrice, Fills: fills, MatchTable: matchTable, BidAggregates: bidAggs, AskAggregates: askAggs, } } func (m *Matcher) Reset() { m.mtx.Lock() defer m.mtx.Unlock() m.bids = make([]Order, 0) m.asks = make([]Order, 0) } // lowest bid (buy price) first func (m *Matcher) enqueueBid(order *Order) { if len(m.bids) == 0 { m.bids = append(m.bids, *order) return } i := sort.Search(len(m.bids), func(i int) bool { tester := m.bids[i] if tester.Price.Equal(order.Price) { return tester.ID.Cmp(order.ID) < 0 } return tester.Price.GT(order.Price) }) m.bids = append(m.bids, Order{}) copy(m.bids[i+1:], m.bids[i:]) m.bids[i] = *order } // lowest ask (sell price) first func (m *Matcher) enqueueAsk(order *Order) { if len(m.asks) == 0 { m.asks = append(m.asks, *order) return } i := sort.Search(len(m.asks), func(i int) bool { tester := m.asks[i] if tester.Price.Equal(order.Price) { return tester.ID.Cmp(order.ID) < 0 } return tester.Price.GT(order.Price) }) m.asks = append(m.asks, Order{}) copy(m.asks[i+1:], m.asks[i:]) m.asks[i] = *order } func calcDir(entry [3]sdk.Uint) int { if entry[1].GT(entry[2]) { return 1 } else if entry[1].Equal(entry[2]) { return 0 } return -1 }
NewMatcher
audit.py
import codecs import io import json import os import platform import sys import hashlib from builtins import input from collections import defaultdict from copy import deepcopy from functools import lru_cache from detect_secrets.core.baseline import merge_results from detect_secrets.core.bidirectional_iterator import BidirectionalIterator from detect_secrets.core.code_snippet import CodeSnippetHighlighter from detect_secrets.core.color import AnsiColor from detect_secrets.core.color import colorize from detect_secrets.core.common import write_baseline_to_file from detect_secrets.core.protection import hide_secret from detect_secrets.plugins.common import initialize from detect_secrets.plugins.common.util import get_mapping_from_secret_type_to_class_name from detect_secrets.util import get_git_remotes from detect_secrets.util import get_git_sha class SecretNotFoundOnSpecifiedLineError(Exception): def __init__(self, line): super(SecretNotFoundOnSpecifiedLineError, self).__init__( 'ERROR: Secret not found on line {}!\n'.format(line) + 'Try recreating your baseline to fix this issue.', ) class RedundantComparisonError(Exception): pass AUDIT_RESULT_TO_STRING = { True: 'true-positives', False: 'false-positives', None: 'unknowns', } EMPTY_PLUGIN_AUDIT_RESULT = { 'results': { 'true-positives': defaultdict(list), 'false-positives': defaultdict(list), 'unknowns': defaultdict(list), }, 'config': {}, } EMPTY_STATS_RESULT = { 'signal': '0.00%', 'true-positives': { 'count': 0, 'files': defaultdict(int), }, 'false-positives': { 'count': 0, 'files': defaultdict(int), }, 'unknowns': { 'count': 0, 'files': defaultdict(int), }, } def audit_baseline(baseline_filename): original_baseline = _get_baseline_from_file(baseline_filename) if not original_baseline: return files_removed = _remove_nonexistent_files_from_baseline(original_baseline) all_secrets = list(_secret_generator(original_baseline)) secrets_with_choices = [ (filename, secret) for filename, secret in all_secrets if 'is_secret' not in secret ] total_choices = len(secrets_with_choices) secret_iterator = BidirectionalIterator(secrets_with_choices) current_secret_index = 0 for filename, secret in secret_iterator: _clear_screen() current_secret_index += 1 try: _print_context( filename=filename, secret=secret, count=current_secret_index, total=total_choices, plugins_used=original_baseline['plugins_used'], custom_plugin_paths=original_baseline['custom_plugin_paths'], ) decision = _get_user_decision(can_step_back=secret_iterator.can_step_back()) except SecretNotFoundOnSpecifiedLineError: decision = _get_user_decision( prompt_secret_decision=False, can_step_back=secret_iterator.can_step_back(), ) if decision == 'q': print('Quitting...') break if decision == 'b': current_secret_index -= 2 secret_iterator.step_back_on_next_iteration() _handle_user_decision(decision, secret) if current_secret_index == 0 and not files_removed: print('Nothing to audit!') return print('Saving progress...') results = defaultdict(list) for filename, secret in all_secrets: results[filename].append(secret) original_baseline['results'] = merge_results( original_baseline['results'], dict(results), ) write_baseline_to_file( filename=baseline_filename, data=original_baseline, ) def compare_baselines(old_baseline_filename, new_baseline_filename): """ This function enables developers to more easily configure plugin settings, by comparing two generated baselines and highlighting their differences. For effective use, a few assumptions are made: 1. Baselines are sorted by (filename, line_number, hash). This allows for a deterministic order, when doing a side-by-side comparison. 2. Baselines are generated for the same codebase snapshot. This means that we won't have cases where secrets are moved around; only added or removed. Note: We don't want to do a version check, because we want to be able to use this functionality across versions (to see how the new version fares compared to the old one). """ if old_baseline_filename == new_baseline_filename: raise RedundantComparisonError old_baseline = _get_baseline_from_file(old_baseline_filename) new_baseline = _get_baseline_from_file(new_baseline_filename) _remove_nonexistent_files_from_baseline(old_baseline) _remove_nonexistent_files_from_baseline(new_baseline) # We aggregate the secrets first, so that we can display a total count. secrets_to_compare = _get_secrets_to_compare(old_baseline, new_baseline) total_reviews = len(secrets_to_compare) current_index = 0 secret_iterator = BidirectionalIterator(secrets_to_compare) for filename, secret, is_removed in secret_iterator: _clear_screen() current_index += 1 header = '{} {}' if is_removed: plugins_used = old_baseline['plugins_used'] custom_plugin_paths = old_baseline['custom_plugin_paths'] header = header.format( colorize('Status:', AnsiColor.BOLD), '>> {} <<'.format( colorize('REMOVED', AnsiColor.RED), ), ) else: plugins_used = new_baseline['plugins_used'] custom_plugin_paths = new_baseline['custom_plugin_paths'] header = header.format( colorize('Status:', AnsiColor.BOLD), '>> {} <<'.format( colorize('ADDED', AnsiColor.LIGHT_GREEN), ), ) try: _print_context( filename=filename, secret=secret, count=current_index, total=total_reviews, plugins_used=plugins_used, custom_plugin_paths=custom_plugin_paths, additional_header_lines=header, force_line_printing=is_removed, ) decision = _get_user_decision( can_step_back=secret_iterator.can_step_back(), prompt_secret_decision=False, ) except SecretNotFoundOnSpecifiedLineError: decision = _get_user_decision(prompt_secret_decision=False) if decision == 'q': print('Quitting...') break if decision == 'b': # pragma: no cover current_index -= 2 secret_iterator.step_back_on_next_iteration() def determine_audit_results(baseline, baseline_path, hide=False): """ Given a baseline which has been audited, returns a dictionary describing the results of each plugin in the following form: { "plugins": { "plugin_name1": { "results": { "true-positives": [ list of { filename: { 'line': '...', 'plaintext':'...', } } for secrets with `is_secret: true` caught by this plugin], "false-positives": [ list of { filename: { 'line': '...', 'plaintext':'...', } } for secrets with `is_secret: false` caught by this plugin], "unknowns": [ list of { filename: { 'line': '...', 'plaintext':'...', } } for secrets with no `is_secret` entry caught by this plugin] }, "config": {configuration used for the plugin} }, ... }, "repo_info": { "remote": "remote url", "sha": "sha of repo checkout" }, } """ all_secrets = _secret_generator(baseline) audit_results = { 'plugins': defaultdict(lambda: deepcopy(EMPTY_PLUGIN_AUDIT_RESULT)), 'stats': deepcopy(EMPTY_STATS_RESULT), } secret_type_to_plugin_name = get_mapping_from_secret_type_to_class_name( custom_plugin_paths=baseline['custom_plugin_paths'], ) total = 0 for filename, secret in all_secrets: file_contents = _open_file_with_cache(filename) secret_info = {} secret_info['line'] = _get_file_line(filename, secret['line_number']) try: potential_secret = get_raw_secret_value( secret=secret, plugins_used=baseline['plugins_used'], custom_plugin_paths=baseline['custom_plugin_paths'], file_handle=io.StringIO(file_contents), filename=filename, ) secret_info['plaintext'] = potential_secret.secret_value secret_info['identifier'] = hashlib.sha512((secret_info['plaintext'] + filename).encode('utf-8')).hexdigest() potential_secret.line_numbers.reverse() secret_info['line_numbers'] = potential_secret.line_numbers if hide: if potential_secret.hidden_secret == None or potential_secret.hidden_line == None: potential_secret.hidden_secret = hide_secret(potential_secret.secret_value) potential_secret.hidden_line = secret_info['line'].replace(potential_secret.secret_value, potential_secret.hidden_secret) secret_info['plaintext'] = potential_secret.hidden_secret secret_info['line'] = potential_secret.hidden_line except SecretNotFoundOnSpecifiedLineError: secret_info['plaintext'] = None secret_info['identifier'] = None plugin_name = secret_type_to_plugin_name[secret['type']] audit_result = AUDIT_RESULT_TO_STRING[secret.get('is_secret')] audit_results['plugins'][plugin_name]['results'][audit_result][filename].append(secret_info) audit_results['stats'][audit_result]['count'] += len(secret_info['line_numbers']) audit_results['stats'][audit_result]['files'][filename] += len(secret_info['line_numbers']) total += len(secret_info['line_numbers']) audit_results['stats']['signal'] = '{:.2f}%'.format( ( float(audit_results['stats']['true-positives']['count']) / total ) * 100 if total > 0 else 0.00, ) for plugin_config in baseline['plugins_used']: plugin_name = plugin_config['name'] if plugin_name not in audit_results['plugins']: continue audit_results['plugins'][plugin_name]['config'].update(plugin_config) git_repo_path = os.path.dirname(os.path.abspath(baseline_path)) git_sha = get_git_sha(git_repo_path) git_remotes = get_git_remotes(git_repo_path) if git_sha and git_remotes: audit_results['repo_info'] = { 'remote': git_remotes[0], 'sha': git_sha, } return audit_results def print_audit_results(baseline_filename, hide=False): baseline = _get_baseline_from_file(baseline_filename) if not baseline: print('Failed to retrieve baseline from {filename}'.format(filename=baseline_filename)) return print( json.dumps( determine_audit_results( baseline, baseline_filename, hide ), indent=2, sort_keys=True, ), ) def _get_baseline_from_file(filename): # pragma: no cover try: with open(filename) as f: baseline = json.loads(f.read()) if 'custom_plugin_paths' in baseline: # We turn custom_plugins_paths into a tuple so that we can # @lru_cache all the functions that take it as an argument. baseline['custom_plugin_paths'] = tuple(baseline['custom_plugin_paths']) return baseline except (IOError, json.decoder.JSONDecodeError): print('Not a valid baseline file!', file=sys.stderr) return def _remove_nonexistent_files_from_baseline(baseline): files_removed = False for filename in baseline['results'].copy(): if not os.path.exists(filename): del baseline['results'][filename] files_removed = True return files_removed def _secret_generator(baseline): """Generates secrets to audit, from the baseline""" for filename, secrets in baseline['results'].items(): for secret in secrets: yield filename, secret def _get_secrets_to_compare(old_baseline, new_baseline): """ :rtype: list(tuple) :param: tuple is in the following format: filename: str; filename where identified secret is found secret: dict; PotentialSecret json representation is_secret_removed: bool; has the secret been removed from the new baseline? """ def _check_string(a, b): if a == b: return 0 if a < b: return -1 return 1 def _check_secret(a, b): if a == b: return 0 if a['line_number'] < b['line_number']: return -1 elif a['line_number'] > b['line_number']: return 1 return _check_string(a['hashed_secret'], b['hashed_secret']) secrets_to_compare = [] for old_filename, new_filename in _comparison_generator( sorted(old_baseline['results'].keys()), sorted(new_baseline['results'].keys()), compare_fn=_check_string, ): if not new_filename: secrets_to_compare += list( map( lambda x: (old_filename, x, True), old_baseline['results'][old_filename], ), ) continue elif not old_filename: secrets_to_compare += list( map( lambda x: (new_filename, x, False), new_baseline['results'][new_filename], ), ) continue for old_secret, new_secret in _comparison_generator( old_baseline['results'][old_filename], new_baseline['results'][new_filename], compare_fn=_check_secret, ): if old_secret == new_secret: # If they are the same, no point flagging it. continue if old_secret: secrets_to_compare.append( (old_filename, old_secret, True), ) else: secrets_to_compare.append( (new_filename, new_secret, False), ) return secrets_to_compare def _comparison_generator(old_list, new_list, compare_fn): """ :type old_list: sorted list :type new_list: sorted list :type compare_fn: function :param compare_fn: takes two arguments, A and B returns 0 if equal returns -1 if A is less than B else returns 1 """ old_index = 0 new_index = 0 while old_index < len(old_list) and new_index < len(new_list): old_value = old_list[old_index] new_value = new_list[new_index] status = compare_fn(old_value, new_value) if status == 0: yield (old_value, new_value) old_index += 1 new_index += 1 elif status == -1: yield (old_value, None) old_index += 1 else: yield (None, new_value) new_index += 1 # Catch leftovers. Only one of these while statements should run. while old_index < len(old_list): yield (old_list[old_index], None) old_index += 1 while new_index < len(new_list): yield (None, new_list[new_index]) new_index += 1 def _clear_screen(): # pragma: no cover try: command = 'clear' if platform.system() == 'Windows': command = 'cls'
def _print_context( # pragma: no cover filename, secret, count, total, plugins_used, custom_plugin_paths, additional_header_lines=None, force_line_printing=False, ): """ :type filename: str :param filename: the file currently scanned. :type secret: dict, in PotentialSecret.json() format :param secret: the secret, represented in the baseline file. :type count: int :param count: current count of secrets scanned so far :type total: int :param total: total number of secrets in baseline :type plugins_used: list :param plugins_used: output of "plugins_used" in baseline. e.g. >>> [ ... { ... 'name': 'Base64HighEntropyString', ... 'base64_limit': 4.5, ... }, ... ] :type custom_plugin_paths: Tuple[str] :param custom_plugin_paths: possibly empty tuple of paths that have custom plugins. :type additional_header_lines: str :param additional_header_lines: any additional lines to add to the header of the interactive audit display. :type force_line_printing: bool :param force_line_printing: if True, will print the lines of code even if it doesn't find the secret expected :raises: SecretNotFoundOnSpecifiedLineError """ print( '{} {} {} {}\n{} {}\n{} {}'.format( colorize('Secret: ', AnsiColor.BOLD), colorize(str(count), AnsiColor.PURPLE), colorize('of', AnsiColor.BOLD), colorize(str(total), AnsiColor.PURPLE), colorize('Filename: ', AnsiColor.BOLD), colorize(filename, AnsiColor.PURPLE), colorize('Secret Type:', AnsiColor.BOLD), colorize(secret['type'], AnsiColor.PURPLE), ), ) if additional_header_lines: print(additional_header_lines) print('-' * 10) error_obj = None try: secret_with_context = _get_secret_with_context( filename=filename, secret=secret, plugins_used=plugins_used, custom_plugin_paths=custom_plugin_paths, force_line_printing=force_line_printing, ) print(secret_with_context) except SecretNotFoundOnSpecifiedLineError as e: error_obj = e print(e) print('-' * 10) if error_obj: raise error_obj def _get_user_decision(prompt_secret_decision=True, can_step_back=False): """ :type prompt_secret_decision: bool :param prompt_secret_decision: if False, won't ask to label secret. """ allowable_user_input = ['s', 'q'] if prompt_secret_decision: allowable_user_input.extend(['y', 'n']) if can_step_back: allowable_user_input.append('b') user_input = None while user_input not in allowable_user_input: if user_input: print('Invalid input.') if 'y' in allowable_user_input: user_input_string = 'Is this a valid secret? i.e. not a false-positive (y)es, (n)o, ' else: user_input_string = 'What would you like to do? ' if 'b' in allowable_user_input: user_input_string += '(b)ack, ' user_input_string += '(s)kip, (q)uit: ' user_input = input(user_input_string) if user_input: user_input = user_input[0].lower() return user_input def _handle_user_decision(decision, secret): if decision == 'y': secret['is_secret'] = True elif decision == 'n': secret['is_secret'] = False elif decision == 's' and 'is_secret' in secret: del secret['is_secret'] @lru_cache(maxsize=1) def _open_file_with_cache(filename): """ Reads the input file and returns the result as a string. This caches opened files to ensure that the audit functionality doesn't unnecessarily re-open the same file. """ try: with codecs.open(filename, encoding='utf-8') as f: return f.read() except (OSError, IOError): return None def _get_file_line(filename, line_number): """ Attempts to read a given line from the input file. """ file_content = _open_file_with_cache(filename) if not file_content: return None return file_content.splitlines()[line_number - 1] def _get_secret_with_context( filename, secret, plugins_used, custom_plugin_paths, lines_of_context=5, force_line_printing=False, ): """ Displays the secret, with surrounding lines of code for better context. :type filename: str :param filename: filename where secret resides in :type secret: dict, PotentialSecret.json() format :param secret: the secret listed in baseline :type plugins_used: list :param plugins_used: output of "plugins_used" in baseline. e.g. >>> [ ... { ... 'name': 'Base64HighEntropyString', ... 'base64_limit': 4.5, ... }, ... ] :type custom_plugin_paths: Tuple[str] :param custom_plugin_paths: possibly empty tuple of paths that have custom plugins. :type lines_of_context: int :param lines_of_context: number of lines displayed before and after secret. :type force_line_printing: bool :param force_line_printing: if True, will print the lines of code even if it doesn't find the secret expected :raises: SecretNotFoundOnSpecifiedLineError """ try: file_content = _open_file_with_cache(filename) if not file_content: raise SecretNotFoundOnSpecifiedLineError(secret['line_number']) file_lines = file_content.splitlines() snippet = CodeSnippetHighlighter().get_code_snippet( file_lines, secret['line_number'], lines_of_context=lines_of_context, ) potential_secret = get_raw_secret_value( secret=secret, plugins_used=plugins_used, custom_plugin_paths=custom_plugin_paths, file_handle=io.StringIO(file_content), filename=filename, ) raw_secret_value = potential_secret.secret_value try: snippet.highlight_line(raw_secret_value) except ValueError: raise SecretNotFoundOnSpecifiedLineError(secret['line_number']) except SecretNotFoundOnSpecifiedLineError: if not force_line_printing: raise snippet.target_line = colorize( snippet.target_line, AnsiColor.BOLD, ) return snippet.add_line_numbers() def get_raw_secret_value( secret, plugins_used, custom_plugin_paths, file_handle, filename, ): """ :type secret: dict :param secret: see caller's docstring :type plugins_used: list :param plugins_used: output of "plugins_used" in baseline. e.g. >>> [ ... { ... 'name': 'Base64HighEntropyString', ... 'base64_limit': 4.5, ... }, ... ] :type custom_plugin_paths: Tuple[str] :param custom_plugin_paths: possibly empty tuple of paths that have custom plugins. :type file_handle: file object :param file_handle: Open handle to file where the secret is :type filename: str :param filename: this is needed, because PotentialSecret uses this as a means of comparing whether two secrets are equal. """ plugin = initialize.from_secret_type( secret_type=secret['type'], plugins_used=plugins_used, custom_plugin_paths=custom_plugin_paths, ) plugin_secrets = plugin.analyze(file_handle, filename) # Return value of matching secret for plugin_secret in plugin_secrets: if plugin_secret.secret_hash == secret['hashed_secret']: return plugin_secret raise SecretNotFoundOnSpecifiedLineError(secret['line_number'])
os.system(command) except: pass
client.rs
// Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0. use std::collections::HashMap; use std::fmt; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use std::u64; use futures::channel::mpsc; use futures::compat::{Compat, Future01CompatExt}; use futures::executor::block_on; use futures::future::{self, BoxFuture, FutureExt, TryFutureExt}; use futures::sink::SinkExt; use futures::stream::StreamExt; use grpcio::{CallOption, EnvBuilder, Environment, WriteFlags}; use kvproto::metapb; use kvproto::pdpb::{self, Member}; use kvproto::replication_modepb::{ RegionReplicationStatus, ReplicationStatus, StoreDrAutoSyncStatus, }; use security::SecurityManager; use tikv_util::time::{duration_to_sec, Instant}; use tikv_util::timer::GLOBAL_TIMER_HANDLE; use tikv_util::{box_err, debug, error, info, thd_name, warn}; use tikv_util::{Either, HandyRwLock}; use txn_types::TimeStamp; use yatp::task::future::TaskCell; use yatp::ThreadPool; use super::metrics::*; use super::util::{check_resp_header, sync_request, Client, PdConnector}; use super::{BucketStat, Config, FeatureGate, PdFuture, UnixSecs}; use super::{Error, PdClient, RegionInfo, RegionStat, Result, REQUEST_TIMEOUT}; const CQ_COUNT: usize = 1; const CLIENT_PREFIX: &str = "pd"; pub struct RpcClient { cluster_id: u64, pd_client: Arc<Client>, monitor: Arc<ThreadPool<TaskCell>>, } impl RpcClient { pub fn new( cfg: &Config, shared_env: Option<Arc<Environment>>, security_mgr: Arc<SecurityManager>, ) -> Result<RpcClient> { block_on(Self::new_async(cfg, shared_env, security_mgr)) } pub async fn new_async( cfg: &Config, shared_env: Option<Arc<Environment>>, security_mgr: Arc<SecurityManager>, ) -> Result<RpcClient> { let env = shared_env.unwrap_or_else(|| { Arc::new( EnvBuilder::new() .cq_count(CQ_COUNT) .name_prefix(thd_name!(CLIENT_PREFIX)) .build(), ) }); // -1 means the max. let retries = match cfg.retry_max_count { -1 => std::isize::MAX, v => v.saturating_add(1), }; let monitor = Arc::new( yatp::Builder::new(thd_name!("pdmonitor")) .max_thread_count(1) .build_future_pool(), ); let pd_connector = PdConnector::new(env.clone(), security_mgr.clone()); for i in 0..retries { match pd_connector.validate_endpoints(cfg).await { Ok((client, target, members, tso)) => { let cluster_id = members.get_header().get_cluster_id(); let rpc_client = RpcClient { cluster_id, pd_client: Arc::new(Client::new( Arc::clone(&env), security_mgr.clone(), client, members, target, tso, cfg.enable_forwarding, )), monitor: monitor.clone(), }; // spawn a background future to update PD information periodically let duration = cfg.update_interval.0; let client = Arc::downgrade(&rpc_client.pd_client); let update_loop = async move { loop { let ok = GLOBAL_TIMER_HANDLE .delay(std::time::Instant::now() + duration) .compat() .await .is_ok(); if !ok { warn!("failed to delay with global timer"); continue; } match client.upgrade() { Some(cli) => { let req = cli.reconnect(false).await; if let Err(e) = req { warn!("failed to update PD client"; "error"=> ?e); // will update later anyway } } // if the client has been dropped, we can stop None => break, } } }; // `update_loop` contains RwLock that may block the monitor. // Since the monitor does not have other critical task, it // is not a major issue. rpc_client.monitor.spawn(update_loop); let client = Arc::downgrade(&rpc_client.pd_client); let retry_interval = cfg.retry_interval.0; let tso_check = async move { while let Some(cli) = client.upgrade() { let closed_fut = cli.inner.rl().tso.closed(); closed_fut.await; info!("TSO stream is closed, reconnect to PD"); while let Err(e) = cli.reconnect(true).await { warn!("failed to update PD client"; "error"=> ?e); let _ = GLOBAL_TIMER_HANDLE .delay(std::time::Instant::now() + retry_interval) .compat() .await; } } }; rpc_client.monitor.spawn(tso_check); return Ok(rpc_client); } Err(e) => { if i as usize % cfg.retry_log_every == 0 { warn!("validate PD endpoints failed"; "err" => ?e); } let _ = GLOBAL_TIMER_HANDLE .delay(std::time::Instant::now() + cfg.retry_interval.0) .compat() .await; } } } Err(box_err!("endpoints are invalid")) } /// Creates a new request header. fn header(&self) -> pdpb::RequestHeader { let mut header = pdpb::RequestHeader::default(); header.set_cluster_id(self.cluster_id); header } /// Gets the leader of PD. pub fn get_leader(&self) -> Member { self.pd_client.get_leader() } /// Re-establishes connection with PD leader in synchronized fashion. pub fn reconnect(&self) -> Result<()> { block_on(self.pd_client.reconnect(true)) } /// Creates a new call option with default request timeout. #[inline] pub fn call_option(client: &Client) -> CallOption { client .inner .rl() .target_info() .call_option() .timeout(Duration::from_secs(REQUEST_TIMEOUT)) } /// Gets given key's Region and Region's leader from PD. fn get_region_and_leader( &self, key: &[u8], ) -> PdFuture<(metapb::Region, Option<metapb::Peer>)> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_region"]) .start_coarse_timer(); let mut req = pdpb::GetRegionRequest::default(); req.set_header(self.header()); req.set_region_key(key.to_vec()); let executor = move |client: &Client, req: pdpb::GetRegionRequest| { let handler = client .inner .rl() .client_stub .get_region_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| { panic!("fail to request PD {} err {:?}", "get_region_async_opt", e) }); Box::pin(async move { let mut resp = handler.await?; check_resp_header(resp.get_header())?; let region = if resp.has_region() { resp.take_region() } else { return Err(Error::RegionNotFound(req.region_key)); }; let leader = if resp.has_leader() { Some(resp.take_leader()) } else { None }; Ok((region, leader)) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn get_store_and_stats(&self, store_id: u64) -> PdFuture<(metapb::Store, pdpb::StoreStats)> { let timer = Instant::now(); let mut req = pdpb::GetStoreRequest::default(); req.set_header(self.header()); req.set_store_id(store_id); let executor = move |client: &Client, req: pdpb::GetStoreRequest| { let handler = client .inner .rl() .client_stub .get_store_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| panic!("fail to request PD {} err {:?}", "get_store_async", e)); Box::pin(async move { let mut resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_store_async"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; let store = resp.take_store(); if store.get_state() != metapb::StoreState::Tombstone { Ok((store, resp.take_stats())) } else { Err(Error::StoreTombstone(format!("{:?}", store))) } }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } } impl fmt::Debug for RpcClient { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("RpcClient") .field("cluster_id", &self.cluster_id) .field("leader", &self.get_leader()) .finish() } } const LEADER_CHANGE_RETRY: usize = 10; impl PdClient for RpcClient { fn load_global_config(&self, list: Vec<String>) -> PdFuture<HashMap<String, String>> { use kvproto::pdpb::LoadGlobalConfigRequest; let mut req = LoadGlobalConfigRequest::new(); req.set_names(list.into()); let executor = |client: &Client, req| match client .inner .rl() .client_stub .clone() .load_global_config_async(&req) { Ok(grpc_response) => Box::pin(async move { match grpc_response.await { Ok(grpc_response) => { let mut res = HashMap::with_capacity(grpc_response.get_items().len()); for c in grpc_response.get_items() { if c.has_error() { error!("failed to load global config with key {:?}", c.get_error()); } else { res.insert(c.get_name().to_owned(), c.get_value().to_owned()); } } Ok(res) } Err(err) => Err(box_err!("{:?}", err)), } }) as PdFuture<_>, Err(err) => Box::pin(async move { Err(box_err!("{:?}", err)) }) as PdFuture<_>, }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn watch_global_config( &self, ) -> Result<grpcio::ClientSStreamReceiver<pdpb::WatchGlobalConfigResponse>> { use kvproto::pdpb::WatchGlobalConfigRequest; let req = WatchGlobalConfigRequest::default(); sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.watch_global_config(&req) }) } fn get_cluster_id(&self) -> Result<u64>
fn bootstrap_cluster( &self, stores: metapb::Store, region: metapb::Region, ) -> Result<Option<ReplicationStatus>> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["bootstrap_cluster"]) .start_coarse_timer(); let mut req = pdpb::BootstrapRequest::default(); req.set_header(self.header()); req.set_store(stores); req.set_region(region); let mut resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.bootstrap_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp.replication_status.take()) } fn is_cluster_bootstrapped(&self) -> Result<bool> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["is_cluster_bootstrapped"]) .start_coarse_timer(); let mut req = pdpb::IsBootstrappedRequest::default(); req.set_header(self.header()); let resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.is_bootstrapped_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp.get_bootstrapped()) } fn alloc_id(&self) -> Result<u64> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["alloc_id"]) .start_coarse_timer(); let mut req = pdpb::AllocIdRequest::default(); req.set_header(self.header()); let resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.alloc_id_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp.get_id()) } fn put_store(&self, store: metapb::Store) -> Result<Option<ReplicationStatus>> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["put_store"]) .start_coarse_timer(); let mut req = pdpb::PutStoreRequest::default(); req.set_header(self.header()); req.set_store(store); let mut resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.put_store_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp.replication_status.take()) } fn get_store(&self, store_id: u64) -> Result<metapb::Store> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_store"]) .start_coarse_timer(); let mut req = pdpb::GetStoreRequest::default(); req.set_header(self.header()); req.set_store_id(store_id); let mut resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.get_store_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; let store = resp.take_store(); if store.get_state() != metapb::StoreState::Tombstone { Ok(store) } else { Err(Error::StoreTombstone(format!("{:?}", store))) } } fn get_store_async(&self, store_id: u64) -> PdFuture<metapb::Store> { self.get_store_and_stats(store_id).map_ok(|x| x.0).boxed() } fn get_all_stores(&self, exclude_tombstone: bool) -> Result<Vec<metapb::Store>> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_all_stores"]) .start_coarse_timer(); let mut req = pdpb::GetAllStoresRequest::default(); req.set_header(self.header()); req.set_exclude_tombstone_stores(exclude_tombstone); let mut resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.get_all_stores_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp.take_stores().into()) } fn get_cluster_config(&self) -> Result<metapb::Cluster> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_cluster_config"]) .start_coarse_timer(); let mut req = pdpb::GetClusterConfigRequest::default(); req.set_header(self.header()); let mut resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.get_cluster_config_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp.take_cluster()) } fn get_region(&self, key: &[u8]) -> Result<metapb::Region> { block_on(self.get_region_and_leader(key)).map(|x| x.0) } fn get_region_info(&self, key: &[u8]) -> Result<RegionInfo> { block_on(self.get_region_and_leader(key)).map(|x| RegionInfo::new(x.0, x.1)) } fn get_region_async<'k>(&'k self, key: &'k [u8]) -> BoxFuture<'k, Result<metapb::Region>> { self.get_region_and_leader(key).map_ok(|x| x.0).boxed() } fn get_region_info_async<'k>(&'k self, key: &'k [u8]) -> BoxFuture<'k, Result<RegionInfo>> { self.get_region_and_leader(key) .map_ok(|x| RegionInfo::new(x.0, x.1)) .boxed() } fn get_region_by_id(&self, region_id: u64) -> PdFuture<Option<metapb::Region>> { let timer = Instant::now(); let mut req = pdpb::GetRegionByIdRequest::default(); req.set_header(self.header()); req.set_region_id(region_id); let executor = move |client: &Client, req: pdpb::GetRegionByIdRequest| { let handler = client .inner .rl() .client_stub .get_region_by_id_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| { panic!("fail to request PD {} err {:?}", "get_region_by_id", e) }); Box::pin(async move { let mut resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_region_by_id"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; if resp.has_region() { Ok(Some(resp.take_region())) } else { Ok(None) } }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn get_region_leader_by_id( &self, region_id: u64, ) -> PdFuture<Option<(metapb::Region, metapb::Peer)>> { let timer = Instant::now(); let mut req = pdpb::GetRegionByIdRequest::default(); req.set_header(self.header()); req.set_region_id(region_id); let executor = move |client: &Client, req: pdpb::GetRegionByIdRequest| { let handler = client .inner .rl() .client_stub .get_region_by_id_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| { panic!("fail to request PD {} err {:?}", "get_region_by_id", e) }); Box::pin(async move { let mut resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_region_by_id"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; if resp.has_region() { Ok(Some((resp.take_region(), resp.take_leader()))) } else { Ok(None) } }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn region_heartbeat( &self, term: u64, region: metapb::Region, leader: metapb::Peer, region_stat: RegionStat, replication_status: Option<RegionReplicationStatus>, ) -> PdFuture<()> { PD_HEARTBEAT_COUNTER_VEC.with_label_values(&["send"]).inc(); let mut req = pdpb::RegionHeartbeatRequest::default(); req.set_term(term); req.set_header(self.header()); req.set_region(region); req.set_leader(leader); req.set_down_peers(region_stat.down_peers.into()); req.set_pending_peers(region_stat.pending_peers.into()); req.set_bytes_written(region_stat.written_bytes); req.set_keys_written(region_stat.written_keys); req.set_bytes_read(region_stat.read_bytes); req.set_keys_read(region_stat.read_keys); req.set_query_stats(region_stat.query_stats); req.set_approximate_size(region_stat.approximate_size); req.set_approximate_keys(region_stat.approximate_keys); req.set_cpu_usage(region_stat.cpu_usage); if let Some(s) = replication_status { req.set_replication_status(s); } let mut interval = pdpb::TimeInterval::default(); interval.set_start_timestamp(region_stat.last_report_ts.into_inner()); interval.set_end_timestamp(UnixSecs::now().into_inner()); req.set_interval(interval); let executor = |client: &Client, req: pdpb::RegionHeartbeatRequest| { let mut inner = client.inner.wl(); if let Either::Left(ref mut left) = inner.hb_sender { debug!("heartbeat sender is refreshed"); let sender = left.take().expect("expect region heartbeat sink"); let (tx, rx) = mpsc::unbounded(); let pending_heartbeat = Arc::new(AtomicU64::new(0)); inner.hb_sender = Either::Right(tx); inner.pending_heartbeat = pending_heartbeat.clone(); inner.client_stub.spawn(async move { let mut sender = sender.sink_map_err(Error::Grpc); let mut last_report = u64::MAX; let result = sender .send_all(&mut rx.map(|r| { let last = pending_heartbeat.fetch_sub(1, Ordering::Relaxed); // Sender will update pending at every send operation, so as long as // pending task is increasing, pending count should be reported by // sender. if last + 10 < last_report || last == 1 { PD_PENDING_HEARTBEAT_GAUGE.set(last as i64 - 1); last_report = last; } if last > last_report { last_report = last - 1; } Ok((r, WriteFlags::default())) })) .await; match result { Ok(()) => { sender.get_mut().cancel(); info!("cancel region heartbeat sender"); } Err(e) => { error!(?e; "failed to send heartbeat"); } }; }); } let last = inner.pending_heartbeat.fetch_add(1, Ordering::Relaxed); PD_PENDING_HEARTBEAT_GAUGE.set(last as i64 + 1); let sender = inner .hb_sender .as_mut() .right() .expect("expect region heartbeat sender"); let ret = sender .unbounded_send(req) .map_err(|e| Error::Other(Box::new(e))); Box::pin(future::ready(ret)) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn handle_region_heartbeat_response<F>(&self, _: u64, f: F) -> PdFuture<()> where F: Fn(pdpb::RegionHeartbeatResponse) + Send + 'static, { self.pd_client.handle_region_heartbeat_response(f) } fn ask_split(&self, region: metapb::Region) -> PdFuture<pdpb::AskSplitResponse> { let timer = Instant::now(); let mut req = pdpb::AskSplitRequest::default(); req.set_header(self.header()); req.set_region(region); let executor = move |client: &Client, req: pdpb::AskSplitRequest| { let handler = client .inner .rl() .client_stub .ask_split_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| panic!("fail to request PD {} err {:?}", "ask_split", e)); Box::pin(async move { let resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["ask_split"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; Ok(resp) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn ask_batch_split( &self, region: metapb::Region, count: usize, ) -> PdFuture<pdpb::AskBatchSplitResponse> { let timer = Instant::now(); let mut req = pdpb::AskBatchSplitRequest::default(); req.set_header(self.header()); req.set_region(region); req.set_split_count(count as u32); let executor = move |client: &Client, req: pdpb::AskBatchSplitRequest| { let handler = client .inner .rl() .client_stub .ask_batch_split_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| panic!("fail to request PD {} err {:?}", "ask_batch_split", e)); Box::pin(async move { let resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["ask_batch_split"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; Ok(resp) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn store_heartbeat( &self, mut stats: pdpb::StoreStats, report_opt: Option<pdpb::StoreReport>, dr_autosync_status: Option<StoreDrAutoSyncStatus>, ) -> PdFuture<pdpb::StoreHeartbeatResponse> { let timer = Instant::now(); let mut req = pdpb::StoreHeartbeatRequest::default(); req.set_header(self.header()); stats .mut_interval() .set_end_timestamp(UnixSecs::now().into_inner()); req.set_stats(stats); if let Some(report) = report_opt { req.set_store_report(report); } if let Some(status) = dr_autosync_status { req.set_dr_autosync_status(status); } let executor = move |client: &Client, req: pdpb::StoreHeartbeatRequest| { let feature_gate = client.feature_gate.clone(); let handler = client .inner .rl() .client_stub .store_heartbeat_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| panic!("fail to request PD {} err {:?}", "store_heartbeat", e)); Box::pin(async move { let resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["store_heartbeat"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; match feature_gate.set_version(resp.get_cluster_version()) { Err(_) => warn!("invalid cluster version: {}", resp.get_cluster_version()), Ok(true) => info!("set cluster version to {}", resp.get_cluster_version()), _ => {} }; Ok(resp) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn report_batch_split(&self, regions: Vec<metapb::Region>) -> PdFuture<()> { let timer = Instant::now(); let mut req = pdpb::ReportBatchSplitRequest::default(); req.set_header(self.header()); req.set_regions(regions.into()); let executor = move |client: &Client, req: pdpb::ReportBatchSplitRequest| { let handler = client .inner .rl() .client_stub .report_batch_split_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| { panic!("fail to request PD {} err {:?}", "report_batch_split", e) }); Box::pin(async move { let resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["report_batch_split"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; Ok(()) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn scatter_region(&self, mut region: RegionInfo) -> Result<()> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["scatter_region"]) .start_coarse_timer(); let mut req = pdpb::ScatterRegionRequest::default(); req.set_header(self.header()); req.set_region_id(region.get_id()); if let Some(leader) = region.leader.take() { req.set_leader(leader); } req.set_region(region.region); let resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.scatter_region_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header()) } fn handle_reconnect<F: Fn() + Sync + Send + 'static>(&self, f: F) { self.pd_client.on_reconnect(Box::new(f)) } fn get_gc_safe_point(&self) -> PdFuture<u64> { let timer = Instant::now(); let mut req = pdpb::GetGcSafePointRequest::default(); req.set_header(self.header()); let executor = move |client: &Client, req: pdpb::GetGcSafePointRequest| { let option = Self::call_option(client); let handler = client .inner .rl() .client_stub .get_gc_safe_point_async_opt(&req, option) .unwrap_or_else(|e| { panic!("fail to request PD {} err {:?}", "get_gc_saft_point", e) }); Box::pin(async move { let resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_gc_safe_point"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; Ok(resp.get_safe_point()) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn get_store_stats_async(&self, store_id: u64) -> BoxFuture<'_, Result<pdpb::StoreStats>> { self.get_store_and_stats(store_id).map_ok(|x| x.1).boxed() } fn get_operator(&self, region_id: u64) -> Result<pdpb::GetOperatorResponse> { let _timer = PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["get_operator"]) .start_coarse_timer(); let mut req = pdpb::GetOperatorRequest::default(); req.set_header(self.header()); req.set_region_id(region_id); let resp = sync_request(&self.pd_client, LEADER_CHANGE_RETRY, |client| { client.get_operator_opt(&req, Self::call_option(&self.pd_client)) })?; check_resp_header(resp.get_header())?; Ok(resp) } fn batch_get_tso(&self, count: u32) -> PdFuture<TimeStamp> { let begin = Instant::now(); let executor = move |client: &Client, _| { // Remove Box::pin and Compat when GLOBAL_TIMER_HANDLE supports futures 0.3 let ts_fut = Compat::new(Box::pin(client.inner.rl().tso.get_timestamp(count))); let with_timeout = GLOBAL_TIMER_HANDLE .timeout( ts_fut, std::time::Instant::now() + Duration::from_secs(REQUEST_TIMEOUT), ) .compat(); Box::pin(async move { let ts = with_timeout.await.map_err(|e| { if let Some(inner) = e.into_inner() { inner } else { box_err!("get timestamp timeout") } })?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["tso"]) .observe(duration_to_sec(begin.saturating_elapsed())); Ok(ts) }) as PdFuture<_> }; self.pd_client .request((), executor, LEADER_CHANGE_RETRY) .execute() } fn feature_gate(&self) -> &FeatureGate { &self.pd_client.feature_gate } fn report_min_resolved_ts(&self, store_id: u64, min_resolved_ts: u64) -> PdFuture<()> { let timer = Instant::now(); let mut req = pdpb::ReportMinResolvedTsRequest::default(); req.set_header(self.header()); req.set_store_id(store_id); req.set_min_resolved_ts(min_resolved_ts); let executor = move |client: &Client, req: pdpb::ReportMinResolvedTsRequest| { let handler = client .inner .rl() .client_stub .report_min_resolved_ts_async_opt(&req, Self::call_option(client)) .unwrap_or_else(|e| panic!("fail to request PD {} err {:?}", "min_resolved_ts", e)); Box::pin(async move { let resp = handler.await?; PD_REQUEST_HISTOGRAM_VEC .with_label_values(&["min_resolved_ts"]) .observe(duration_to_sec(timer.saturating_elapsed())); check_resp_header(resp.get_header())?; Ok(()) }) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } fn report_region_buckets(&self, bucket_stat: &BucketStat, period: Duration) -> PdFuture<()> { PD_BUCKETS_COUNTER_VEC.with_label_values(&["send"]).inc(); let mut buckets = metapb::Buckets::default(); buckets.set_region_id(bucket_stat.meta.region_id); buckets.set_version(bucket_stat.meta.version); buckets.set_keys(bucket_stat.meta.keys.clone().into()); buckets.set_period_in_ms(period.as_millis() as u64); buckets.set_stats(bucket_stat.stats.clone()); let mut req = pdpb::ReportBucketsRequest::default(); req.set_header(self.header()); req.set_buckets(buckets); req.set_region_epoch(bucket_stat.meta.region_epoch.clone()); let executor = |client: &Client, req: pdpb::ReportBucketsRequest| { let mut inner = client.inner.wl(); if let Either::Left(ref mut left) = inner.buckets_sender { debug!("region buckets sender is refreshed"); let sender = left.take().expect("expect report region buckets sink"); let (tx, rx) = mpsc::unbounded(); let pending_buckets = Arc::new(AtomicU64::new(0)); inner.buckets_sender = Either::Right(tx); inner.pending_buckets = pending_buckets.clone(); let resp = inner.buckets_resp.take().unwrap(); inner.client_stub.spawn(async { let res = resp.await; warn!("region buckets stream exited: {:?}", res); }); inner.client_stub.spawn(async move { let mut sender = sender.sink_map_err(Error::Grpc); let mut last_report = u64::MAX; let result = sender .send_all(&mut rx.map(|r| { let last = pending_buckets.fetch_sub(1, Ordering::Relaxed); // Sender will update pending at every send operation, so as long as // pending task is increasing, pending count should be reported by // sender. if last + 10 < last_report || last == 1 { PD_PENDING_BUCKETS_GAUGE.set(last as i64 - 1); last_report = last; } if last > last_report { last_report = last - 1; } Ok((r, WriteFlags::default())) })) .await; match result { Ok(()) => { sender.get_mut().cancel(); info!("cancel region buckets sender"); } Err(e) => { error!(?e; "failed to send region buckets"); } }; }); } let last = inner.pending_buckets.fetch_add(1, Ordering::Relaxed); PD_PENDING_BUCKETS_GAUGE.set(last as i64 + 1); let sender = inner .buckets_sender .as_mut() .right() .expect("expect region buckets sender"); let ret = sender .unbounded_send(req) .map_err(|e| Error::Other(Box::new(e))); Box::pin(future::ready(ret)) as PdFuture<_> }; self.pd_client .request(req, executor, LEADER_CHANGE_RETRY) .execute() } } pub struct DummyPdClient { pub next_ts: TimeStamp, } impl DummyPdClient { pub fn new() -> DummyPdClient { DummyPdClient { next_ts: TimeStamp::zero(), } } } impl Default for DummyPdClient { fn default() -> Self { Self::new() } } impl PdClient for DummyPdClient { fn batch_get_tso(&self, _count: u32) -> PdFuture<TimeStamp> { Box::pin(future::ok(self.next_ts)) } }
{ Ok(self.cluster_id) }
FactionResourcesRequirementSetOperators.d.ts
import { CollectionCache, CollectionKey } from "../../../common"; export declare namespace FactionResourcesRequirementSetOperators { const KEY: CollectionKey; class Entry { private readonly collectionCache; readonly operatorKey: string; constructor(collectionCache: CollectionCache, values: any);
} } export default FactionResourcesRequirementSetOperators;
ext.js
function onLoaded() { var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName != "FLPR"){ loadJSX(); } var appNames = ["PHXS"]; for (var i = 0; i < appNames.length; i++) { var name = appNames[i]; if (appName.indexOf(name) >= 0) { var btn = document.getElementById("btn_" + name); if (btn) btn.disabled = false; } } updateThemeWithAppSkinInfo(csInterface.hostEnvironment.appSkinInfo); // Update the color of the panel when the theme color of the product changed. csInterface.addEventListener(CSInterface.THEME_COLOR_CHANGED_EVENT, onAppThemeColorChanged); } /** * Update the theme with the AppSkinInfo retrieved from the host product. */ function updateThemeWithAppSkinInfo(appSkinInfo) { //Update the background color of the panel var panelBackgroundColor = appSkinInfo.panelBackgroundColor.color; document.body.bgColor = toHex(panelBackgroundColor); var styleId = "ppstyle"; var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName == "PHXS"){ addRule(styleId, "button, select, input[type=button], input[type=submit]", "border-radius:3px;"); } if(appName == "PHXS" || appName == "PPRO" || appName == "PRLD") { //////////////////////////////////////////////////////////////////////////////////////////////// // NOTE: Below theme related code are only suitable for Photoshop. // // If you want to achieve same effect on other products please make your own changes here. //
var gradientBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 40) + " , " + toHex(panelBackgroundColor, 10) + ");"; var gradientDisabledBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 15) + " , " + toHex(panelBackgroundColor, 5) + ");"; var boxShadow = "-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);"; var boxActiveShadow = "-webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);"; var isPanelThemeLight = panelBackgroundColor.red > 127; var fontColor, disabledFontColor; var borderColor; var inputBackgroundColor; var gradientHighlightBg; if(isPanelThemeLight) { fontColor = "#000000;"; disabledFontColor = "color:" + toHex(panelBackgroundColor, -70) + ";"; borderColor = "border-color: " + toHex(panelBackgroundColor, -90) + ";"; inputBackgroundColor = toHex(panelBackgroundColor, 54) + ";"; gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -40) + " , " + toHex(panelBackgroundColor,-50) + ");"; } else { fontColor = "#ffffff;"; disabledFontColor = "color:" + toHex(panelBackgroundColor, 100) + ";"; borderColor = "border-color: " + toHex(panelBackgroundColor, -45) + ";"; inputBackgroundColor = toHex(panelBackgroundColor, -20) + ";"; gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -20) + " , " + toHex(panelBackgroundColor, -30) + ");"; } //Update the default text style with pp values addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";"); addRule(styleId, "button, select, input[type=text], input[type=button], input[type=submit]", borderColor); addRule(styleId, "button, select, input[type=button], input[type=submit]", gradientBg); addRule(styleId, "button, select, input[type=button], input[type=submit]", boxShadow); addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", gradientHighlightBg); addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", boxActiveShadow); addRule(styleId, "[disabled]", gradientDisabledBg); addRule(styleId, "[disabled]", disabledFontColor); addRule(styleId, "input[type=text]", "padding:1px 3px;"); addRule(styleId, "input[type=text]", "background-color: " + inputBackgroundColor) + ";"; addRule(styleId, "input[type=text]:focus", "background-color: #ffffff;"); addRule(styleId, "input[type=text]:focus", "color: #000000;"); } else { // For AI, ID and FL use old implementation addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + reverseColor(panelBackgroundColor) + "; background-color:" + toHex(panelBackgroundColor, 20)); addRule(styleId, "button", "border-color: " + toHex(panelBgColor, -50)); } } function addRule(stylesheetId, selector, rule) { var stylesheet = document.getElementById(stylesheetId); if (stylesheet) { stylesheet = stylesheet.sheet; if( stylesheet.addRule ){ stylesheet.addRule(selector, rule); } else if( stylesheet.insertRule ){ stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length); } } } function reverseColor(color, delta) { return toHex({red:Math.abs(255-color.red), green:Math.abs(255-color.green), blue:Math.abs(255-color.blue)}, delta); } /** * Convert the Color object to string in hexadecimal format; */ function toHex(color, delta) { function computeValue(value, delta) { var computedValue = !isNaN(delta) ? value + delta : value; if (computedValue < 0) { computedValue = 0; } else if (computedValue > 255) { computedValue = 255; } computedValue = computedValue.toString(16); return computedValue.length == 1 ? "0" + computedValue : computedValue; } var hex = ""; if (color) { with (color) { hex = computeValue(red, delta) + computeValue(green, delta) + computeValue(blue, delta); }; } return "#" + hex; } function onAppThemeColorChanged(event) { // Should get a latest HostEnvironment object from application. var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo; // Gets the style information such as color info from the skinInfo, // and redraw all UI controls of your extension according to the style info. updateThemeWithAppSkinInfo(skinInfo); } /** * Load JSX file into the scripting context of the product. All the jsx files in * folder [ExtensionRoot]/jsx will be loaded. */ function loadJSX() { var csInterface = new CSInterface(); var extensionRoot = csInterface.getSystemPath(SystemPath.EXTENSION) + "/jsx/"; csInterface.evalScript('$._ext.evalFiles("' + extensionRoot + '")'); } function evalScript(script, callback) { new CSInterface().evalScript(script, callback); } function onClickButton(ppid) { if(ppid == "FLPR"){ var jsfl = 'fl.createDocument(); fl.getDocumentDOM().addNewText({left:100, top:100, right:300, bottom:300} , "Hello Flash!" ); '; evalScript(jsfl); } else { var extScript = "$._ext_" + ppid + ".run()"; evalScript(extScript); } }
////////////////////////////////////////////////////////////////////////////////////////////////
login_test.go
package password_test import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "strings" "testing" "time" "github.com/ory/jsonschema/v3" "github.com/ory/x/errorsx" "github.com/ory/kratos/selfservice/strategy/oidc" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/ory/x/pointerx" "github.com/ory/viper" "github.com/ory/kratos/driver/configuration" "github.com/ory/kratos/identity" "github.com/ory/kratos/internal" "github.com/ory/kratos/schema" "github.com/ory/kratos/selfservice/errorx" "github.com/ory/kratos/selfservice/flow/login" "github.com/ory/kratos/selfservice/form" "github.com/ory/kratos/selfservice/strategy/password" "github.com/ory/kratos/x" ) func nlr(exp time.Duration) *login.Request
func TestLoginNew(t *testing.T) { _, reg := internal.NewRegistryDefault(t) s := reg.LoginStrategies().MustStrategy(identity.CredentialsTypePassword).(*password.Strategy) s.WithTokenGenerator(x.FakeCSRFTokenGeneratorWithToken("anti-rf-token")) reg.LoginStrategies().MustStrategy(identity.CredentialsTypeOIDC).(*oidc.Strategy).WithTokenGenerator(x.FakeCSRFTokenGeneratorWithToken("anti-rf-token")) reg.LoginHandler().WithTokenGenerator(x.FakeCSRFTokenGeneratorWithToken("anti-rf-token")) reg.SelfServiceErrorManager().WithTokenGenerator(x.FakeCSRFTokenGeneratorWithToken("anti-rf-token")) router := x.NewRouterPublic() admin := x.NewRouterAdmin() reg.LoginHandler().RegisterPublicRoutes(router) reg.LoginHandler().RegisterAdminRoutes(admin) s.RegisterLoginRoutes(router) ts := httptest.NewServer(router) defer ts.Close() errTs, uiTs, returnTs := errorx.NewErrorTestServer(t, reg), httptest.NewServer(login.TestRequestHandler(t, reg)), newReturnTs(t, reg) defer errTs.Close() defer uiTs.Close() defer returnTs.Close() viper.Set(configuration.ViperKeyURLsError, errTs.URL+"/error-ts") viper.Set(configuration.ViperKeyURLsLogin, uiTs.URL+"/login-ts") viper.Set(configuration.ViperKeyURLsSelfPublic, ts.URL) viper.Set(configuration.ViperKeySelfServiceLoginAfterConfig+"."+string(identity.CredentialsTypePassword), hookConfig(returnTs.URL+"/return-ts")) viper.Set(configuration.ViperKeyDefaultIdentityTraitsSchemaURL, "file://./stub/login.schema.json") viper.Set(configuration.ViperKeySecretsSession, []string{"not-a-secure-session-key"}) viper.Set(configuration.ViperKeyURLsDefaultReturnTo, returnTs.URL+"/return-ts") makeRequest := func(lr *login.Request, payload string, forceRequestID *string, jar *cookiejar.Jar) (*http.Response, []byte) { lr.RequestURL = ts.URL require.NoError(t, reg.LoginRequestPersister().CreateLoginRequest(context.TODO(), lr)) c := ts.Client() if jar == nil { c.Jar, _ = cookiejar.New(&cookiejar.Options{}) } else { c.Jar = jar } requestID := lr.ID.String() if forceRequestID != nil { requestID = *forceRequestID } res, err := c.Post(ts.URL+password.LoginPath+"?request="+requestID, "application/x-www-form-urlencoded", strings.NewReader(payload)) require.NoError(t, err) defer res.Body.Close() require.EqualValues(t, http.StatusOK, res.StatusCode, "Request: %+v\n\t\tResponse: %s", res.Request, res) body, err := ioutil.ReadAll(res.Body) require.NoError(t, err) return res, body } ensureFieldsExist := func(t *testing.T, body []byte) { checkFormContent(t, body, "identifier", "password", "csrf_token") } createIdentity := func(identifier, password string) { p, _ := reg.PasswordHasher().Generate([]byte(password)) require.NoError(t, reg.PrivilegedIdentityPool().CreateIdentity(context.Background(), &identity.Identity{ ID: x.NewUUID(), Traits: identity.Traits(fmt.Sprintf(`{"subject":"%s"}`, identifier)), Credentials: map[identity.CredentialsType]identity.Credentials{ identity.CredentialsTypePassword: { Type: identity.CredentialsTypePassword, Identifiers: []string{identifier}, Config: json.RawMessage(`{"hashed_password":"` + string(p) + `"}`), }, }, })) } t.Run("should show the error ui because the request is malformed", func(t *testing.T) { lr := nlr(0) res, body := makeRequest(lr, "14=)=!(%)$/ZP()GHIÖ", nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts", "%+v", res.Request) assert.Equal(t, lr.ID.String(), gjson.GetBytes(body, "id").String(), "%s", body) assert.Equal(t, "/action", gjson.GetBytes(body, "methods.password.config.action").String(), "%s", body) assert.Contains(t, gjson.GetBytes(body, "methods.password.config.errors.0.message").String(), `invalid URL escape`) }) t.Run("should show the error ui because the request id missing", func(t *testing.T) { lr := nlr(time.Minute) res, body := makeRequest(lr, url.Values{}.Encode(), pointerx.String(""), nil) require.Contains(t, res.Request.URL.Path, "error-ts") assert.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(body, "0.code").Int(), "%s", body) assert.Equal(t, "Bad Request", gjson.GetBytes(body, "0.status").String(), "%s", body) assert.Contains(t, gjson.GetBytes(body, "0.reason").String(), "request query parameter is missing or invalid", "%s", body) }) t.Run("should return an error because the request does not exist", func(t *testing.T) { lr := nlr(0) res, body := makeRequest(lr, url.Values{ "identifier": {"identifier"}, "password": {"password"}, }.Encode(), pointerx.String(x.NewUUID().String()), nil) require.Contains(t, res.Request.URL.Path, "error-ts") assert.Equal(t, int64(http.StatusNotFound), gjson.GetBytes(body, "0.code").Int(), "%s", body) assert.Equal(t, "Not Found", gjson.GetBytes(body, "0.status").String(), "%s", body) assert.Contains(t, gjson.GetBytes(body, "0.message").String(), "Unable to locate the resource", "%s", body) }) t.Run("should redirect to login init because the request is expired", func(t *testing.T) { lr := nlr(-time.Hour) res, body := makeRequest(lr, url.Values{ "identifier": {"identifier"}, "password": {"password"}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts") assert.NotEqual(t, lr.ID, gjson.GetBytes(body, "id")) assert.Contains(t, gjson.GetBytes(body, "methods.oidc.config.errors.0").String(), "expired", "%s", body) assert.Contains(t, gjson.GetBytes(body, "methods.password.config.errors.0").String(), "expired", "%s", body) }) t.Run("should return an error because the credentials are invalid (user does not exist)", func(t *testing.T) { lr := nlr(time.Hour) res, body := makeRequest(lr, url.Values{ "identifier": {"identifier"}, "password": {"password"}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts") assert.Equal(t, lr.ID.String(), gjson.GetBytes(body, "id").String(), "%s", body) assert.Equal(t, "/action", gjson.GetBytes(body, "methods.password.config.action").String()) assert.Equal(t, `the provided credentials are invalid, check for spelling mistakes in your password or username, email address, or phone number`, gjson.GetBytes(body, "methods.password.config.errors.0.message").String()) }) t.Run("should return an error because no identifier is set", func(t *testing.T) { lr := nlr(time.Hour) res, body := makeRequest(lr, url.Values{ "password": {"password"}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts") // Let's ensure that the payload is being propagated properly. assert.Equal(t, lr.ID.String(), gjson.GetBytes(body, "id").String()) assert.Equal(t, "/action", gjson.GetBytes(body, "methods.password.config.action").String()) ensureFieldsExist(t, body) assert.Equal(t, "missing properties: identifier", gjson.GetBytes(body, "methods.password.config.fields.#(name==identifier).errors.0.message").String(), "%s", body) // The password value should not be returned! assert.Empty(t, gjson.GetBytes(body, "methods.password.config.fields.#(name==password).value").String()) }) t.Run("should return an error because no password is set", func(t *testing.T) { lr := nlr(time.Hour) res, body := makeRequest(lr, url.Values{ "identifier": {"identifier"}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts") // Let's ensure that the payload is being propagated properly. assert.Equal(t, lr.ID.String(), gjson.GetBytes(body, "id").String()) assert.Equal(t, "/action", gjson.GetBytes(body, "methods.password.config.action").String()) ensureFieldsExist(t, body) assert.Equal(t, "missing properties: password", gjson.GetBytes(body, "methods.password.config.fields.#(name==password).errors.0.message").String(), "%s", body) assert.Equal(t, "anti-rf-token", gjson.GetBytes(body, "methods.password.config.fields.#(name==csrf_token).value").String()) assert.Equal(t, "identifier", gjson.GetBytes(body, "methods.password.config.fields.#(name==identifier).value").String(), "%s", body) // This must not include the password! assert.Empty(t, gjson.GetBytes(body, "methods.password.config.fields.#(name==password).value").String()) }) t.Run("should return an error because the credentials are invalid (password not correct)", func(t *testing.T) { identifier, pwd := "login-identifier-6", "password" createIdentity(identifier, pwd) lr := nlr(time.Hour) res, body := makeRequest(lr, url.Values{ "identifier": {identifier}, "password": {"not-password"}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts") assert.Equal(t, lr.ID.String(), gjson.GetBytes(body, "id").String()) assert.Equal(t, "/action", gjson.GetBytes(body, "methods.password.config.action").String()) ensureFieldsExist(t, body) assert.Equal(t, errorsx.Cause(schema.NewInvalidCredentialsError()).(*jsonschema.ValidationError).Message, gjson.GetBytes(body, "methods.password.config.errors.0.message").String(), "%s", body, ) // This must not include the password! assert.Empty(t, gjson.GetBytes(body, "methods.password.config.fields.#(name==password).value").String()) }) t.Run("should pass because everything is a-ok", func(t *testing.T) { identifier, pwd := "login-identifier-7", "password" createIdentity(identifier, pwd) lr := nlr(time.Hour) res, body := makeRequest(lr, url.Values{ "identifier": {identifier}, "password": {pwd}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "return-ts", "%s", res.Request.URL.String()) assert.Equal(t, identifier, gjson.GetBytes(body, "identity.traits.subject").String(), "%s", body) }) t.Run("should return an error because not passing validation and reset previous errors and values", func(t *testing.T) { lr := &login.Request{ ID: x.NewUUID(), ExpiresAt: time.Now().Add(time.Minute), Methods: map[identity.CredentialsType]*login.RequestMethod{ identity.CredentialsTypePassword: { Method: identity.CredentialsTypePassword, Config: &login.RequestMethodConfig{ RequestMethodConfigurator: &password.RequestMethod{ HTMLForm: &form.HTMLForm{ Method: "POST", Action: "/action", Errors: []form.Error{{Message: "some error"}}, Fields: form.Fields{ { Value: "baz", Name: "identifier", Errors: []form.Error{{Message: "err"}}, }, { Value: "bar", Name: "password", Errors: []form.Error{{Message: "err"}}, }, }, }, }, }, }, }, } res, body := makeRequest(lr, url.Values{ "identifier": {"registration-identifier-9"}, // "password": {uuid.New().String()}, }.Encode(), nil, nil) require.Contains(t, res.Request.URL.Path, "login-ts") assert.Equal(t, lr.ID.String(), gjson.GetBytes(body, "id").String()) assert.Equal(t, "/action", gjson.GetBytes(body, "methods.password.config.action").String()) ensureFieldsExist(t, body) assert.Empty(t, gjson.GetBytes(body, "methods.password.config.fields.#(name==identity).value")) assert.Empty(t, gjson.GetBytes(body, "methods.password.config.fields.#(name==identity).error")) assert.Empty(t, gjson.GetBytes(body, "methods.password.config.error")) assert.Contains(t, gjson.GetBytes(body, "methods.password.config.fields.#(name==password).errors.0").String(), "missing properties: password", "%s", body) }) t.Run("should be a new session with forced flag", func(t *testing.T) { identifier, pwd := "login-identifier-reauth", "password" createIdentity(identifier, pwd) jar, err := cookiejar.New(&cookiejar.Options{}) require.NoError(t, err) _, body1 := makeRequest(nlr(time.Hour), url.Values{ "identifier": {identifier}, "password": {pwd}, }.Encode(), nil, jar) lr2 := nlr(time.Hour) lr2.Forced = true res, body2 := makeRequest(lr2, url.Values{ "identifier": {identifier}, "password": {pwd}, }.Encode(), nil, jar) require.Contains(t, res.Request.URL.Path, "return-ts", "%s", res.Request.URL.String()) assert.Equal(t, identifier, gjson.GetBytes(body2, "identity.traits.subject").String(), "%s", body2) assert.NotEqual(t, gjson.GetBytes(body1, "sid").String(), gjson.GetBytes(body2, "sid").String(), "%s\n\n%s\n", body1, body2) }) t.Run("should be the same session without forced flag", func(t *testing.T) { identifier, pwd := "login-identifier-no-reauth", "password" createIdentity(identifier, pwd) jar, err := cookiejar.New(&cookiejar.Options{}) require.NoError(t, err) _, body1 := makeRequest(nlr(time.Hour), url.Values{ "identifier": {identifier}, "password": {pwd}, }.Encode(), nil, jar) lr2 := nlr(time.Hour) res, body2 := makeRequest(lr2, url.Values{ "identifier": {identifier}, "password": {pwd}, }.Encode(), nil, jar) require.Contains(t, res.Request.URL.Path, "return-ts", "%s", res.Request.URL.String()) assert.Equal(t, identifier, gjson.GetBytes(body2, "identity.traits.subject").String(), "%s", body2) assert.Equal(t, gjson.GetBytes(body1, "sid").String(), gjson.GetBytes(body2, "sid").String(), "%s\n\n%s\n", body1, body2) }) }
{ id := x.NewUUID() return &login.Request{ ID: id, IssuedAt: time.Now().UTC(), ExpiresAt: time.Now().UTC().Add(exp), RequestURL: "remove-this-if-test-fails", Methods: map[identity.CredentialsType]*login.RequestMethod{ identity.CredentialsTypePassword: { Method: identity.CredentialsTypePassword, Config: &login.RequestMethodConfig{ RequestMethodConfigurator: &form.HTMLForm{ Method: "POST", Action: "/action", Fields: form.Fields{ { Name: "identifier", Type: "text", Required: true, }, { Name: "password", Type: "password", Required: true, }, { Name: form.CSRFTokenName, Type: "hidden", Required: true, Value: "anti-rf-token", }, }, }, }, }, }, } }
buttonBarsActions.js
import ACTIONS from './actionTypes/index'; /** * Initiate the workflow by making request for the button bars data. * @function * @return {action} */ export const fetchData = () => ({ type: ACTIONS.BUTTON_BARS.FETCH }); /** * Save the data into the store. This is a destructive operation. * @function * @param {{ buttons: [number], bars: [number] }} data - the data to store. * @return {action}
type: ACTIONS.BUTTON_BARS.SAVE, value: data }); /** * Update the given Bar by index, adding the given percentage to the value. This could be a negative number, decrementing the value. * @function * @param {{index:number,percentage:number}} data - the data to store. * @return {action} */ export const updateBar = (data) => ({ type: ACTIONS.BUTTON_BARS.UPDATE, value: data });
*/ export const saveData = data => ({
local_cache.rs
use core::hash::{BuildHasher, Hash}; use std::cell::UnsafeCell; use std::collections::HashMap; use std::pin::Pin; /// A cache with a very specific niche. When reading from shared, two-tier storage, if you miss the cache and need to fetch from /// the cold tier, then you also need a place to store the fetched data. Rather than doing interior mutation of the storage, /// which requires synchronization, the fetched data can be stored in a thread-local cache, the `LocalCache`. /// /// # Safety /// /// We guarantee in these APIs that all references returned are valid until `LocalCache::drain_iter` is called, even as new /// values are added to the map. The invariants are: /// 1. Once a value is placed here, it will never get dropped or moved until calling `drain_iter` or `delete`. /// 2. Callers of `delete` must take precautions to ensure no one is borrowing the deleted data. /// 3. Returned references must be dropped before calling `drain_iter` (since it borrows self mutably). /// 4. The values are placed into `Pin<Box<V>>` so the memory address is guaranteed stable. pub struct LocalCache<K, V, H> { store: UnsafeCell<HashMap<K, Pin<Box<V>>, H>>, } impl<K, V, H> Default for LocalCache<K, V, H> where H: Default, { fn default() -> Self { Self::new() } } impl<K, V, H> LocalCache<K, V, H> where H: Default, { pub fn new() -> Self { LocalCache { store: UnsafeCell::new(HashMap::with_hasher(Default::default())), } } } impl<K, V, H> LocalCache<K, V, H> where K: Eq + Hash, H: Default + BuildHasher, { pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn len(&self) -> usize { let store = unsafe { &*self.store.get() }; store.len() } /// Fetch the value for `key`. pub fn get(&self, key: K) -> Option<&V> { let store = unsafe { &*self.store.get() }; store.get(&key).map(|v| &**v) } /// Fetch the value for `key`. If it's not here, call `f` to fetch it. pub fn get_or_insert_with(&self, key: K, f: impl FnOnce() -> V) -> &V { let mut_store = unsafe { &mut *self.store.get() }; mut_store.entry(key).or_insert_with(|| Box::pin(f())) } /// Deletes the value at `key`. /// /// # Safety /// This is only safe if you know that no one is currently borrowing the value at `key`. pub unsafe fn
(&self, key: &K) { let mut_store = &mut *self.store.get(); mut_store.remove(key); } /// Consume and iterate over all (key, value) pairs. pub fn drain_iter(&mut self) -> impl '_ + Iterator<Item = (K, V)> { self.store .get_mut() .drain() .map(|(k, v)| (k, unsafe { *Pin::into_inner_unchecked(v) })) } }
delete
anime.py
from typing import Optional, List, Dict from mal import config from mal.mal import _MAL class Anime(_MAL): def __init__(self, mal_id: int, timeout: int = config.TIMEOUT): """ Anime query by ID :param mal_id: MyAnimeList ID :param timeout: Timeout in seconds """ super().__init__(mal_id, "anime", timeout) def reload(self) -> None: """ Reload anime query :return: None """ self.__init__(self._mal_id) def _get_op_ed(self, option) -> List[str]: """ Get list of OP or ED :param option: "op" or "ed" :return: List of OP or ED """ themes = [] if option == "op": data = self._page.find("div", {"class": "opnening"}).parent else: data = self._page.find("div", {"class": "ending"}).parent data = data.findChildren("span", {"class": "theme-song"}) if data: if len(data) > 1: for theme in data: themes.append(theme.text[4:]) else: themes = [data[0].text] return themes @property def episodes(self) -> Optional[int]: """ Get episodes :return: Episodes count """ try: self._episodes except AttributeError: self._episodes = self._get_span_text(self._border_spans, "Episodes:", int) return self._episodes @property def aired(self) -> Optional[str]: """ Get aired :return: Aired status """ try: self._aired except AttributeError: self._aired = self._get_span_text(self._border_spans, "Aired:", str) return self._aired @property def premiered(self) -> Optional[str]: """ Get premiered :return: Premiered status """ try: self._premiered except AttributeError: self._premiered = self._get_span_text(self._border_spans, "Premiered:", str) return self._premiered @property def broadcast(self) -> Optional[str]: """ Get broadcast :return: Broadcast status """ try: self._broadcast except AttributeError: self._broadcast = self._get_span_text(self._border_spans, "Broadcast:", str) return self._broadcast @property def producers(self) -> List[str]: """ Get producers :return: List of producers """ try: self._producers except AttributeError: self._producers = self._get_span_text( self._border_spans, "Producers:", list ) return self._producers @property def licensors(self) -> List[str]: """ Get licensors :return: List of licensors """ try: self._licensors except AttributeError: self._licensors = self._get_span_text( self._border_spans, "Licensors:", list ) return self._licensors @property def studios(self) -> List[str]: """ Get studios :return: List of studios """ try: self._studios except AttributeError: self._studios = self._get_span_text(self._border_spans, "Studios:", list) return self._studios @property def source(self) -> Optional[str]: """ Get source :return: Source """ try: self._source except AttributeError: self._source = self._get_span_text(self._border_spans, "Source:", str) return self._source @property def duration(self) -> Optional[str]: """ Get duration :return: Duration string """ try: self._duration except AttributeError: self._duration = self._get_span_text(self._border_spans, "Duration:", str) return self._duration @property def rating(self) -> Optional[str]: """ Get age rating :return: Age rating """ try: self._rating except AttributeError: self._rating = self._get_span_text(self._border_spans, "Rating:", str) return self._rating @property def related_anime(self) -> Dict[str, List[str]]: """ Get related anime :return: Dict of related anime """ try: self._related_anime except AttributeError: self._related_anime = self._get_related() return self._related_anime @property def opening_themes(self) -> List[str]: """ Get opening themes :return: List of opening themes """ try: self._opening_themes except AttributeError:
@property def ending_themes(self) -> List[str]: """ Get ending themes :return: List of ending themes """ try: self._ending_themes except AttributeError: self._ending_themes = self._get_op_ed("ed") return self._ending_themes @property def synopsis(self) -> Optional[str]: """ Get synopsis :return: Synopsis text """ try: self._synopsis except AttributeError: self._synopsis = self._get_itemprop_value( self._page, "description", "p", str ) return self._synopsis @property def background(self) -> Optional[str]: """ Get background info :return: Background info """ try: self._background except AttributeError: self._background = self._parse_background("div") return self._background
self._opening_themes = self._get_op_ed("op") return self._opening_themes
types.go
package slack type ( // StandardResponse is the generic response received after a Web API request. // See https://api.slack.com/web#responses StandardResponse struct { OK bool `json:"ok"` Stuff string `json:"stuff,omitempty"` Warning string `json:"warning,omitempty"` Error string `json:"error,omitempty"` ResponseMetadata MessageArray `json:"response_metadata,omitempty"` } // MessageArray is a container for an array of error strings MessageArray struct { Messages []string `json:"messages,omitempty"` } // WebhookElement not sure? WebhookElement struct { URL string `json:"url,omitempty"` Channel string `json:"channel,omitempty"` ConfigurationURL string `json:"configuration_url,omitempty"` } // TeamInfo see https://api.slack.com/methods/team.info TeamInfo struct { OK bool `json:"ok"` Error string `json:"error,omitempty"` Team TeamElement `json:"team"` } // TeamElement see https://api.slack.com/methods/team.info TeamElement struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` Domain string `json:"domain,omitempty"` EmailDomain string `json:"email_domain,omitempty"` Icon *IconElement `json:"icon,omitempty"` EnterpriseID string `json:"enterprise_id,omitempty"` EnterpriseName string `json:"enterprise_name,omitempty"` } // IconElement see https://api.slack.com/methods/team.info IconElement struct { Image44 string `json:"image_34,omitempty"` Image68 string `json:"image_68,omitempty"` Image88 string `json:"image_88,omitempty"` Image102 string `json:"image_102,omitempty"` Image132 string `json:"image_132,omitempty"` ImageDefault bool `json:"image_default,omitempty"` } )
programs.rs
#![cfg(any(feature = "bpf_c", feature = "bpf_rust"))] #[macro_use] extern crate solana_bpf_loader_program; use itertools::izip; use log::{log_enabled, trace, Level::Trace}; use solana_account_decoder::parse_bpf_loader::{ parse_bpf_upgradeable_loader, BpfUpgradeableLoaderAccountType, }; use solana_bpf_loader_program::{ create_vm, serialization::{deserialize_parameters, serialize_parameters}, syscalls::register_syscalls, BpfError, ThisInstructionMeter, }; use solana_bpf_rust_invoke::instructions::*; use solana_bpf_rust_realloc::instructions::*; use solana_bpf_rust_realloc_invoke::instructions::*; use solana_cli_output::display::println_transaction; use solana_rbpf::{ static_analysis::Analysis, vm::{Config, Executable, Tracer}, }; use solana_runtime::{ bank::{Bank, ExecuteTimings, TransactionBalancesSet, TransactionResults}, bank_client::BankClient, genesis_utils::{create_genesis_config, GenesisConfigInfo}, loader_utils::{ load_buffer_account, load_program, load_upgradeable_program, set_upgrade_authority, upgrade_program, }, }; use solana_sdk::{ account::{AccountSharedData, ReadableAccount}, account_utils::StateMut, bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, client::SyncClient, clock::MAX_PROCESSING_AGE, compute_budget::{ComputeBudget, ComputeBudgetInstruction}, entrypoint::{MAX_PERMITTED_DATA_INCREASE, SUCCESS}, instruction::{AccountMeta, CompiledInstruction, Instruction, InstructionError}, keyed_account::KeyedAccount, loader_instruction, message::{Message, SanitizedMessage}, process_instruction::{InvokeContext, MockInvokeContext}, pubkey::Pubkey, signature::{keypair_from_seed, Keypair, Signer}, system_instruction::{self, MAX_PERMITTED_DATA_LENGTH}, system_program, sysvar, sysvar::{clock, rent}, transaction::{Transaction, TransactionError}, }; use solana_transaction_status::{ token_balances::collect_token_balances, ConfirmedTransaction, InnerInstructions, TransactionStatusMeta, TransactionWithStatusMeta, UiTransactionEncoding, }; use std::{ cell::RefCell, collections::HashMap, convert::TryFrom, convert::TryInto, env, fs::File, io::Read, path::PathBuf, str::FromStr, sync::Arc, }; /// BPF program file extension const PLATFORM_FILE_EXTENSION_BPF: &str = "so"; /// Create a BPF program file name fn create_bpf_path(name: &str) -> PathBuf { let mut pathbuf = { let current_exe = env::current_exe().unwrap(); PathBuf::from(current_exe.parent().unwrap().parent().unwrap()) }; pathbuf.push("bpf/"); pathbuf.push(name); pathbuf.set_extension(PLATFORM_FILE_EXTENSION_BPF); pathbuf } fn load_bpf_program( bank_client: &BankClient, loader_id: &Pubkey, payer_keypair: &Keypair, name: &str, ) -> Pubkey { let elf = read_bpf_program(name); load_program(bank_client, payer_keypair, loader_id, elf) } fn read_bpf_program(name: &str) -> Vec<u8> { let path = create_bpf_path(name); let mut file = File::open(&path).unwrap_or_else(|err| { panic!("Failed to open {}: {}", path.display(), err); }); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); elf } #[cfg(feature = "bpf_rust")] fn write_bpf_program( bank_client: &BankClient, loader_id: &Pubkey, payer_keypair: &Keypair, program_keypair: &Keypair, elf: &[u8], ) { let chunk_size = 256; // Size of chunk just needs to fit into tx let mut offset = 0; for chunk in elf.chunks(chunk_size) { let instruction = loader_instruction::write(&program_keypair.pubkey(), loader_id, offset, chunk.to_vec()); let message = Message::new(&[instruction], Some(&payer_keypair.pubkey())); bank_client .send_and_confirm_message(&[payer_keypair, &program_keypair], message) .unwrap(); offset += chunk_size as u32; } } fn load_upgradeable_bpf_program( bank_client: &BankClient, payer_keypair: &Keypair, buffer_keypair: &Keypair, executable_keypair: &Keypair, authority_keypair: &Keypair, name: &str, ) { let path = create_bpf_path(name); let mut file = File::open(&path).unwrap_or_else(|err| { panic!("Failed to open {}: {}", path.display(), err); }); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); load_upgradeable_program( bank_client, payer_keypair, buffer_keypair, executable_keypair, authority_keypair, elf, ); } fn load_upgradeable_buffer( bank_client: &BankClient, payer_keypair: &Keypair, buffer_keypair: &Keypair, buffer_authority_keypair: &Keypair, name: &str, ) { let path = create_bpf_path(name); let mut file = File::open(&path).unwrap_or_else(|err| { panic!("Failed to open {}: {}", path.display(), err); }); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); load_buffer_account( bank_client, payer_keypair, &buffer_keypair, buffer_authority_keypair, &elf, ); } fn upgrade_bpf_program( bank_client: &BankClient, payer_keypair: &Keypair, buffer_keypair: &Keypair, executable_pubkey: &Pubkey, authority_keypair: &Keypair, name: &str, ) { load_upgradeable_buffer( bank_client, payer_keypair, buffer_keypair, authority_keypair, name, ); upgrade_program( bank_client, payer_keypair, executable_pubkey, &buffer_keypair.pubkey(), &authority_keypair, &payer_keypair.pubkey(), ); } fn run_program( name: &str, loader_id: &Pubkey, program_id: &Pubkey, parameter_accounts: Vec<KeyedAccount>, instruction_data: &[u8], ) -> Result<u64, InstructionError> { let mut file = File::open(create_bpf_path(name)).unwrap(); let mut data = vec![]; file.read_to_end(&mut data).unwrap(); let mut invoke_context = MockInvokeContext::new(&program_id, parameter_accounts); let (parameter_bytes, account_lengths) = serialize_parameters( &loader_id, program_id, &invoke_context.get_keyed_accounts().unwrap()[1..], &instruction_data, ) .unwrap(); let compute_meter = invoke_context.get_compute_meter(); let mut instruction_meter = ThisInstructionMeter { compute_meter }; let config = Config { enable_instruction_tracing: true, ..Config::default() }; let mut executable = <dyn Executable<BpfError, ThisInstructionMeter>>::from_elf( &data, None, config, register_syscalls(&mut invoke_context).unwrap(), ) .unwrap(); executable.jit_compile().unwrap(); let mut instruction_count = 0; let mut tracer = None; for i in 0..2 { let mut parameter_bytes = parameter_bytes.clone(); { invoke_context.set_return_data(Vec::new()).unwrap(); let mut vm = create_vm( &loader_id, executable.as_ref(), parameter_bytes.as_slice_mut(), &mut invoke_context, &account_lengths, ) .unwrap(); let result = if i == 0 { vm.execute_program_interpreted(&mut instruction_meter) } else { vm.execute_program_jit(&mut instruction_meter) }; assert_eq!(SUCCESS, result.unwrap()); if i == 1 { assert_eq!(instruction_count, vm.get_total_instruction_count()); } instruction_count = vm.get_total_instruction_count(); if config.enable_instruction_tracing { if i == 1 { if !Tracer::compare(tracer.as_ref().unwrap(), vm.get_tracer()) { let analysis = Analysis::from_executable(executable.as_ref()); let stdout = std::io::stdout(); println!("TRACE (interpreted):"); tracer .as_ref() .unwrap() .write(&mut stdout.lock(), &analysis) .unwrap(); println!("TRACE (jit):"); vm.get_tracer() .write(&mut stdout.lock(), &analysis) .unwrap(); assert!(false); } else if log_enabled!(Trace) { let analysis = Analysis::from_executable(executable.as_ref()); let mut trace_buffer = Vec::<u8>::new(); tracer .as_ref() .unwrap() .write(&mut trace_buffer, &analysis) .unwrap(); let trace_string = String::from_utf8(trace_buffer).unwrap(); trace!("BPF Program Instruction Trace:\n{}", trace_string); } } tracer = Some(vm.get_tracer().clone()); } } let parameter_accounts = invoke_context.get_keyed_accounts().unwrap(); deserialize_parameters( &loader_id, parameter_accounts, parameter_bytes.as_slice(), &account_lengths, true, ) .unwrap(); } Ok(instruction_count) } fn process_transaction_and_record_inner( bank: &Bank, tx: Transaction, ) -> (Result<(), TransactionError>, Vec<Vec<CompiledInstruction>>) { let signature = tx.signatures.get(0).unwrap().clone(); let txs = vec![tx]; let tx_batch = bank.prepare_batch(txs).unwrap(); let (mut results, _, mut inner_instructions, _transaction_logs) = bank .load_execute_and_commit_transactions( &tx_batch, MAX_PROCESSING_AGE, false, true, false, &mut ExecuteTimings::default(), ); let result = results .fee_collection_results .swap_remove(0) .and_then(|_| bank.get_signature_status(&signature).unwrap()); ( result, inner_instructions .swap_remove(0) .expect("cpi recording should be enabled"), ) } fn execute_transactions(bank: &Bank, txs: Vec<Transaction>) -> Vec<ConfirmedTransaction> { let batch = bank.prepare_batch(txs.clone()).unwrap(); let mut timings = ExecuteTimings::default(); let mut mint_decimals = HashMap::new(); let tx_pre_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals); let ( TransactionResults { execution_results, .. }, TransactionBalancesSet { pre_balances, post_balances, .. }, inner_instructions, transaction_logs, ) = bank.load_execute_and_commit_transactions( &batch, std::usize::MAX, true, true, true, &mut timings, ); let tx_post_token_balances = collect_token_balances(&bank, &batch, &mut mint_decimals); izip!( txs.iter(), execution_results.into_iter(), inner_instructions.into_iter(), pre_balances.into_iter(), post_balances.into_iter(), tx_pre_token_balances.into_iter(), tx_post_token_balances.into_iter(), transaction_logs.into_iter(), ) .map( |( tx, (execute_result, nonce_rollback), inner_instructions, pre_balances, post_balances, pre_token_balances, post_token_balances, log_messages, )| { let lamports_per_signature = nonce_rollback .map(|nonce_rollback| nonce_rollback.lamports_per_signature()) .unwrap_or_else(|| { bank.get_lamports_per_signature_for_blockhash(&tx.message().recent_blockhash) }) .expect("lamports_per_signature must exist"); let fee = Bank::get_fee_for_message_with_lamports_per_signature( &SanitizedMessage::try_from(tx.message().clone()).unwrap(), lamports_per_signature, ); let inner_instructions = inner_instructions.map(|inner_instructions| { inner_instructions .into_iter() .enumerate() .map(|(index, instructions)| InnerInstructions { index: index as u8, instructions, }) .filter(|i| !i.instructions.is_empty()) .collect() }); let tx_status_meta = TransactionStatusMeta { status: execute_result, fee, pre_balances, post_balances, pre_token_balances: Some(pre_token_balances), post_token_balances: Some(post_token_balances), inner_instructions, log_messages, rewards: None, }; ConfirmedTransaction { slot: bank.slot(), transaction: TransactionWithStatusMeta { transaction: tx.clone(), meta: Some(tx_status_meta), }, block_time: None, } }, ) .collect() } fn print_confirmed_tx(name: &str, confirmed_tx: ConfirmedTransaction) { let block_time = confirmed_tx.block_time; let tx = confirmed_tx.transaction.transaction.clone(); let encoded = confirmed_tx.encode(UiTransactionEncoding::JsonParsed); println!("EXECUTE {} (slot {})", name, encoded.slot); println_transaction(&tx, &encoded.transaction.meta, " ", None, block_time); } #[test] #[cfg(any(feature = "bpf_c", feature = "bpf_rust"))] fn test_program_bpf_sanity() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[ ("alloc", true), ("bpf_to_bpf", true), ("float", true), ("multiple_static", true), ("noop", true), ("noop++", true), ("panic", false), ("relative_call", true), ("return_data", true), ("sanity", true), ("sanity++", true), ("secp256k1_recover", true), ("sha", true), ("struct_pass", true), ("struct_ret", true), ]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[ ("solana_bpf_rust_128bit", true), ("solana_bpf_rust_alloc", true), ("solana_bpf_rust_custom_heap", true), ("solana_bpf_rust_dep_crate", true), ("solana_bpf_rust_external_spend", false), ("solana_bpf_rust_iter", true), ("solana_bpf_rust_many_args", true), ("solana_bpf_rust_membuiltins", true), ("solana_bpf_rust_noop", true), ("solana_bpf_rust_panic", false), ("solana_bpf_rust_param_passing", true), ("solana_bpf_rust_rand", true), ("solana_bpf_rust_sanity", true), ("solana_bpf_rust_secp256k1_recover", true), ("solana_bpf_rust_sha", true), ]); } for program in programs.iter() { println!("Test program: {:?}", program.0); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); // Call user program let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.0); let account_metas = vec![ AccountMeta::new(mint_keypair.pubkey(), true), AccountMeta::new(Keypair::new().pubkey(), false), ]; let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); if program.1 { assert!(result.is_ok()); } else { assert!(result.is_err()); } } } #[test] #[cfg(any(feature = "bpf_c", feature = "bpf_rust"))] fn test_program_bpf_loader_deprecated() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[("deprecated_loader")]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[("solana_bpf_rust_deprecated_loader")]); } for program in programs.iter() { println!("Test program: {:?}", program); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_deprecated_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let program_id = load_bpf_program( &bank_client, &bpf_loader_deprecated::id(), &mint_keypair, program, ); let account_metas = vec![AccountMeta::new(mint_keypair.pubkey(), true)]; let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert!(result.is_ok()); } } #[test] fn test_program_bpf_duplicate_accounts() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[("dup_accounts")]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[("solana_bpf_rust_dup_accounts")]); } for program in programs.iter() { println!("Test program: {:?}", program); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program); let payee_account = AccountSharedData::new(10, 1, &program_id); let payee_pubkey = Pubkey::new_unique(); bank.store_account(&payee_pubkey, &payee_account); let account = AccountSharedData::new(10, 1, &program_id); let pubkey = Pubkey::new_unique(); let account_metas = vec![ AccountMeta::new(mint_keypair.pubkey(), true), AccountMeta::new(payee_pubkey, false), AccountMeta::new(pubkey, false), AccountMeta::new(pubkey, false), ]; bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert!(result.is_ok()); assert_eq!(data[0], 1); bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[2], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert!(result.is_ok()); assert_eq!(data[0], 2); bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[3], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert!(result.is_ok()); assert_eq!(data[0], 3); bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[4], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let lamports = bank_client.get_balance(&pubkey).unwrap(); assert!(result.is_ok()); assert_eq!(lamports, 11); bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[5], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let lamports = bank_client.get_balance(&pubkey).unwrap(); assert!(result.is_ok()); assert_eq!(lamports, 12); bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[6], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let lamports = bank_client.get_balance(&pubkey).unwrap(); assert!(result.is_ok()); assert_eq!(lamports, 13); let keypair = Keypair::new(); let pubkey = keypair.pubkey(); let account_metas = vec![ AccountMeta::new(mint_keypair.pubkey(), true), AccountMeta::new(payee_pubkey, false), AccountMeta::new(pubkey, false), AccountMeta::new_readonly(pubkey, true), AccountMeta::new_readonly(program_id, false), ]; bank.store_account(&pubkey, &account); let instruction = Instruction::new_with_bytes(program_id, &[7], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); let result = bank_client.send_and_confirm_message(&[&mint_keypair, &keypair], message); assert!(result.is_ok()); } } #[test] fn test_program_bpf_error_handling() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[("error_handling")]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[("solana_bpf_rust_error_handling")]); } for program in programs.iter() { println!("Test program: {:?}", program); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program); let account_metas = vec![AccountMeta::new(mint_keypair.pubkey(), true)]; let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert!(result.is_ok()); let instruction = Instruction::new_with_bytes(program_id, &[2], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidAccountData) ); let instruction = Instruction::new_with_bytes(program_id, &[3], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(0)) ); let instruction = Instruction::new_with_bytes(program_id, &[4], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(42)) ); let instruction = Instruction::new_with_bytes(program_id, &[5], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let result = result.unwrap_err().unwrap(); if TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) != result { assert_eq!( result, TransactionError::InstructionError(0, InstructionError::InvalidError) ); } let instruction = Instruction::new_with_bytes(program_id, &[6], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let result = result.unwrap_err().unwrap(); if TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) != result { assert_eq!( result, TransactionError::InstructionError(0, InstructionError::InvalidError) ); } let instruction = Instruction::new_with_bytes(program_id, &[7], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); let result = result.unwrap_err().unwrap(); if TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) != result { assert_eq!( result, TransactionError::InstructionError(0, InstructionError::AccountBorrowFailed) ); } let instruction = Instruction::new_with_bytes(program_id, &[8], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidInstructionData) ); let instruction = Instruction::new_with_bytes(program_id, &[9], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::MaxSeedLengthExceeded) ); } } #[test] #[cfg(any(feature = "bpf_c", feature = "bpf_rust"))] fn test_return_data_and_log_data_syscall() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[("log_data")]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[("solana_bpf_rust_log_data")]); } for program in programs.iter() { let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program); bank.freeze(); let account_metas = vec![AccountMeta::new(mint_keypair.pubkey(), true)]; let instruction = Instruction::new_with_bytes(program_id, &[1, 2, 3, 0, 4, 5, 6], account_metas); let blockhash = bank.last_blockhash(); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); let transaction = Transaction::new(&[&mint_keypair], message, blockhash); let result = bank.simulate_transaction(transaction.try_into().unwrap()); assert!(result.result.is_ok()); assert_eq!(result.logs[1], "Program data: AQID BAUG"); assert_eq!( result.logs[3], format!("Program return: {} CAFE", program_id) ); } } #[test] fn test_program_bpf_invoke_sanity() { solana_logger::setup(); #[allow(dead_code)] #[derive(Debug)] enum Languages { C, Rust, } let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.push((Languages::C, "invoke", "invoked", "noop")); } #[cfg(feature = "bpf_rust")] { programs.push(( Languages::Rust, "solana_bpf_rust_invoke", "solana_bpf_rust_invoked", "solana_bpf_rust_noop", )); } for program in programs.iter() { println!("Test program: {:?}", program); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let invoke_program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.1); let invoked_program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.2); let noop_program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, program.3); let argument_keypair = Keypair::new(); let account = AccountSharedData::new(42, 100, &invoke_program_id); bank.store_account(&argument_keypair.pubkey(), &account); let invoked_argument_keypair = Keypair::new(); let account = AccountSharedData::new(10, 10, &invoked_program_id); bank.store_account(&invoked_argument_keypair.pubkey(), &account); let from_keypair = Keypair::new(); let account = AccountSharedData::new(84, 0, &system_program::id()); bank.store_account(&from_keypair.pubkey(), &account); let (derived_key1, bump_seed1) = Pubkey::find_program_address(&[b"You pass butter"], &invoke_program_id); let (derived_key2, bump_seed2) = Pubkey::find_program_address(&[b"Lil'", b"Bits"], &invoked_program_id); let (derived_key3, bump_seed3) = Pubkey::find_program_address(&[derived_key2.as_ref()], &invoked_program_id); let mint_pubkey = mint_keypair.pubkey(); let account_metas = vec![ AccountMeta::new(mint_pubkey, true), AccountMeta::new(argument_keypair.pubkey(), true), AccountMeta::new_readonly(invoked_program_id, false), AccountMeta::new(invoked_argument_keypair.pubkey(), true), AccountMeta::new_readonly(invoked_program_id, false), AccountMeta::new(argument_keypair.pubkey(), true), AccountMeta::new(derived_key1, false), AccountMeta::new(derived_key2, false), AccountMeta::new_readonly(derived_key3, false), AccountMeta::new_readonly(system_program::id(), false), AccountMeta::new(from_keypair.pubkey(), true), AccountMeta::new_readonly(solana_sdk::ed25519_program::id(), false), AccountMeta::new_readonly(invoke_program_id, false), ]; // success cases let instruction = Instruction::new_with_bytes( invoke_program_id, &[TEST_SUCCESS, bump_seed1, bump_seed2, bump_seed3], account_metas.clone(), ); let noop_instruction = Instruction::new_with_bytes(noop_program_id, &[], vec![]); let message = Message::new(&[instruction, noop_instruction], Some(&mint_pubkey)); let tx = Transaction::new( &[ &mint_keypair, &argument_keypair, &invoked_argument_keypair, &from_keypair, ], message.clone(), bank.last_blockhash(), ); let (result, inner_instructions) = process_transaction_and_record_inner(&bank, tx); assert_eq!(result, Ok(())); let invoked_programs: Vec<Pubkey> = inner_instructions[0] .iter() .map(|ix| message.account_keys[ix.program_id_index as usize].clone()) .collect(); let expected_invoked_programs = match program.0 { Languages::C => vec![ system_program::id(), system_program::id(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), ], Languages::Rust => vec![ system_program::id(), system_program::id(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), system_program::id(), invoked_program_id.clone(), ], }; assert_eq!(invoked_programs.len(), expected_invoked_programs.len()); assert_eq!(invoked_programs, expected_invoked_programs); let no_invoked_programs: Vec<Pubkey> = inner_instructions[1] .iter() .map(|ix| message.account_keys[ix.program_id_index as usize].clone()) .collect(); assert_eq!(no_invoked_programs.len(), 0); // failure cases let do_invoke_failure_test_local = |test: u8, expected_error: TransactionError, expected_invoked_programs: &[Pubkey]| { println!("Running failure test #{:?}", test); let instruction_data = &[test, bump_seed1, bump_seed2, bump_seed3]; let signers = vec![ &mint_keypair, &argument_keypair, &invoked_argument_keypair, &from_keypair, ]; let instruction = Instruction::new_with_bytes( invoke_program_id, instruction_data, account_metas.clone(), ); let message = Message::new(&[instruction], Some(&mint_pubkey)); let tx = Transaction::new(&signers, message.clone(), bank.last_blockhash()); let (result, inner_instructions) = process_transaction_and_record_inner(&bank, tx); let invoked_programs: Vec<Pubkey> = inner_instructions[0] .iter() .map(|ix| message.account_keys[ix.program_id_index as usize].clone()) .collect(); assert_eq!(result, Err(expected_error)); assert_eq!(invoked_programs, expected_invoked_programs); }; do_invoke_failure_test_local( TEST_PRIVILEGE_ESCALATION_SIGNER, TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation), &[invoked_program_id.clone()], ); do_invoke_failure_test_local( TEST_PRIVILEGE_ESCALATION_WRITABLE, TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation), &[invoked_program_id.clone()], ); do_invoke_failure_test_local( TEST_PPROGRAM_NOT_EXECUTABLE, TransactionError::InstructionError(0, InstructionError::AccountNotExecutable), &[], ); do_invoke_failure_test_local( TEST_EMPTY_ACCOUNTS_SLICE, TransactionError::InstructionError(0, InstructionError::MissingAccount), &[], ); do_invoke_failure_test_local( TEST_CAP_SEEDS, TransactionError::InstructionError(0, InstructionError::MaxSeedLengthExceeded), &[], ); do_invoke_failure_test_local( TEST_CAP_SIGNERS, TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete), &[], ); do_invoke_failure_test_local( TEST_INSTRUCTION_DATA_TOO_LARGE, TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete), &[], ); do_invoke_failure_test_local( TEST_INSTRUCTION_META_TOO_LARGE, TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete), &[], ); do_invoke_failure_test_local( TEST_RETURN_ERROR, TransactionError::InstructionError(0, InstructionError::Custom(42)), &[invoked_program_id.clone()], ); do_invoke_failure_test_local( TEST_PRIVILEGE_DEESCALATION_ESCALATION_SIGNER, TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation), &[invoked_program_id.clone()], ); do_invoke_failure_test_local( TEST_PRIVILEGE_DEESCALATION_ESCALATION_WRITABLE, TransactionError::InstructionError(0, InstructionError::PrivilegeEscalation), &[invoked_program_id.clone()], ); do_invoke_failure_test_local( TEST_WRITABLE_DEESCALATION_WRITABLE, TransactionError::InstructionError(0, InstructionError::ReadonlyDataModified), &[invoked_program_id.clone()], ); do_invoke_failure_test_local( TEST_NESTED_INVOKE_TOO_DEEP, TransactionError::InstructionError(0, InstructionError::CallDepth), &[ invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), invoked_program_id.clone(), ], ); do_invoke_failure_test_local( TEST_EXECUTABLE_LAMPORTS, TransactionError::InstructionError(0, InstructionError::ExecutableLamportChange), &[invoke_program_id.clone()], ); do_invoke_failure_test_local( TEST_CALL_PRECOMPILE, TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete), &[], ); do_invoke_failure_test_local( TEST_RETURN_DATA_TOO_LARGE, TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete), &[], ); // Check resulting state assert_eq!(43, bank.get_balance(&derived_key1)); let account = bank.get_account(&derived_key1).unwrap(); assert_eq!(&invoke_program_id, account.owner()); assert_eq!( MAX_PERMITTED_DATA_INCREASE, bank.get_account(&derived_key1).unwrap().data().len() ); for i in 0..20 { assert_eq!(i as u8, account.data()[i]); } // Attempt to realloc into unauthorized address space let account = AccountSharedData::new(84, 0, &system_program::id()); bank.store_account(&from_keypair.pubkey(), &account); bank.store_account(&derived_key1, &AccountSharedData::default()); let instruction = Instruction::new_with_bytes( invoke_program_id, &[ TEST_ALLOC_ACCESS_VIOLATION, bump_seed1, bump_seed2, bump_seed3, ], account_metas.clone(), ); let message = Message::new(&[instruction], Some(&mint_pubkey)); let tx = Transaction::new( &[ &mint_keypair, &argument_keypair, &invoked_argument_keypair, &from_keypair, ], message.clone(), bank.last_blockhash(), ); let (result, inner_instructions) = process_transaction_and_record_inner(&bank, tx); let invoked_programs: Vec<Pubkey> = inner_instructions[0] .iter() .map(|ix| message.account_keys[ix.program_id_index as usize].clone()) .collect(); assert_eq!(invoked_programs, vec![system_program::id()]); assert_eq!( result.unwrap_err(), TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete) ); } } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_program_id_spoofing() { let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let malicious_swap_pubkey = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_spoof1", ); let malicious_system_pubkey = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_spoof1_system", ); let from_pubkey = Pubkey::new_unique(); let account = AccountSharedData::new(10, 0, &system_program::id()); bank.store_account(&from_pubkey, &account); let to_pubkey = Pubkey::new_unique(); let account = AccountSharedData::new(0, 0, &system_program::id()); bank.store_account(&to_pubkey, &account); let account_metas = vec![ AccountMeta::new_readonly(system_program::id(), false), AccountMeta::new_readonly(malicious_system_pubkey, false), AccountMeta::new(from_pubkey, false), AccountMeta::new(to_pubkey, false), ]; let instruction = Instruction::new_with_bytes(malicious_swap_pubkey, &[], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::MissingRequiredSignature) ); assert_eq!(10, bank.get_balance(&from_pubkey)); assert_eq!(0, bank.get_balance(&to_pubkey)); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_caller_has_access_to_cpi_program() { let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let caller_pubkey = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_caller_access", ); let caller2_pubkey = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_caller_access", ); let account_metas = vec![ AccountMeta::new_readonly(caller_pubkey, false), AccountMeta::new_readonly(caller2_pubkey, false), ]; let instruction = Instruction::new_with_bytes(caller_pubkey, &[1], account_metas.clone()); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::MissingAccount) ); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_ro_modify() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_pubkey = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_ro_modify", ); let test_keypair = Keypair::new(); let account = AccountSharedData::new(10, 0, &system_program::id()); bank.store_account(&test_keypair.pubkey(), &account); let account_metas = vec![ AccountMeta::new_readonly(system_program::id(), false), AccountMeta::new(test_keypair.pubkey(), true), ]; let instruction = Instruction::new_with_bytes(program_pubkey, &[1], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); let result = bank_client.send_and_confirm_message(&[&mint_keypair, &test_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete) ); let instruction = Instruction::new_with_bytes(program_pubkey, &[3], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); let result = bank_client.send_and_confirm_message(&[&mint_keypair, &test_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete) ); let instruction = Instruction::new_with_bytes(program_pubkey, &[4], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); let result = bank_client.send_and_confirm_message(&[&mint_keypair, &test_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete) ); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_call_depth() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_call_depth", ); let instruction = Instruction::new_with_bincode( program_id, &(ComputeBudget::default().max_call_depth - 1), vec![], ); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert!(result.is_ok()); let instruction = Instruction::new_with_bincode(program_id, &ComputeBudget::default().max_call_depth, vec![]); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert!(result.is_err()); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_compute_budget() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_noop", ); let message = Message::new( &[ ComputeBudgetInstruction::request_units(1), Instruction::new_with_bincode(program_id, &0, vec![]), ], Some(&mint_keypair.pubkey()), ); let result = bank_client.send_and_confirm_message(&[&mint_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(1, InstructionError::ProgramFailedToComplete), ); } #[test] fn assert_instruction_count() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[ ("alloc", 1237), ("bpf_to_bpf", 96), ("multiple_static", 52), ("noop", 5), ("noop++", 5), ("relative_call", 26), ("return_data", 980), ("sanity", 1246), ("sanity++", 1250), ("secp256k1_recover", 25383), ("sha", 1328), ("struct_pass", 108), ("struct_ret", 28), ]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[ ("solana_bpf_rust_128bit", 584), ("solana_bpf_rust_alloc", 7388), ("solana_bpf_rust_custom_heap", 535), ("solana_bpf_rust_dep_crate", 47), ("solana_bpf_rust_external_spend", 506), ("solana_bpf_rust_iter", 824), ("solana_bpf_rust_many_args", 941), ("solana_bpf_rust_mem", 3085), ("solana_bpf_rust_membuiltins", 3976), ("solana_bpf_rust_noop", 480), ("solana_bpf_rust_param_passing", 146), ("solana_bpf_rust_rand", 487), ("solana_bpf_rust_sanity", 1716), ("solana_bpf_rust_secp256k1_recover", 25216), ("solana_bpf_rust_sha", 30704), ]); } let mut passed = true; println!("\n {:36} expected actual diff", "BPF program"); for program in programs.iter() { let loader_id = bpf_loader::id(); let program_id = Pubkey::new_unique(); let key = Pubkey::new_unique(); let mut program_account = RefCell::new(AccountSharedData::new(0, 0, &loader_id)); let mut account = RefCell::new(AccountSharedData::default()); let parameter_accounts = vec![ KeyedAccount::new(&program_id, false, &mut program_account), KeyedAccount::new(&key, false, &mut account), ]; let count = run_program(program.0, &loader_id, &program_id, parameter_accounts, &[]).unwrap(); let diff: i64 = count as i64 - program.1 as i64; println!( " {:36} {:8} {:6} {:+5} ({:+3.0}%)", program.0, program.1, count, diff, 100.0_f64 * count as f64 / program.1 as f64 - 100.0_f64, ); if count > program.1 { passed = false; } } assert!(passed); } #[cfg(any(feature = "bpf_rust"))] #[test] fn test_program_bpf_instruction_introspection() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50_000); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_instruction_introspection", ); // Passing transaction let account_metas = vec![AccountMeta::new_readonly(sysvar::instructions::id(), false)]; let instruction0 = Instruction::new_with_bytes(program_id, &[0u8, 0u8], account_metas.clone()); let instruction1 = Instruction::new_with_bytes(program_id, &[0u8, 1u8], account_metas.clone()); let instruction2 = Instruction::new_with_bytes(program_id, &[0u8, 2u8], account_metas); let message = Message::new( &[instruction0, instruction1, instruction2], Some(&mint_keypair.pubkey()), ); let result = bank_client.send_and_confirm_message(&[&mint_keypair], message); assert!(result.is_ok()); // writable special instructions11111 key, should not be allowed let account_metas = vec![AccountMeta::new(sysvar::instructions::id(), false)]; let instruction = Instruction::new_with_bytes(program_id, &[0], account_metas); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), // sysvar write locks are demoted to read only. So this will no longer // cause InvalidAccountIndex error. TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete), ); // No accounts, should error let instruction = Instruction::new_with_bytes(program_id, &[0], vec![]); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert!(result.is_err()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::NotEnoughAccountKeys) ); assert!(bank.get_account(&sysvar::instructions::id()).is_none()); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_test_use_latest_executor() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let panic_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_panic", ); let program_keypair = Keypair::new(); // Write the panic program into the program account let elf = read_bpf_program("solana_bpf_rust_panic"); let message = Message::new( &[system_instruction::create_account( &mint_keypair.pubkey(), &program_keypair.pubkey(), 1, elf.len() as u64 * 2, &bpf_loader::id(), )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &program_keypair], message) .is_ok()); write_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, &program_keypair, &elf, ); // Finalize the panic program, but fail the tx let message = Message::new( &[ loader_instruction::finalize(&program_keypair.pubkey(), &bpf_loader::id()), Instruction::new_with_bytes(panic_id, &[0], vec![]), ], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &program_keypair], message) .is_err()); // Write the noop program into the same program account let elf = read_bpf_program("solana_bpf_rust_noop"); write_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, &program_keypair, &elf, ); // Finalize the noop program let message = Message::new( &[loader_instruction::finalize( &program_keypair.pubkey(), &bpf_loader::id(), )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &program_keypair], message) .is_ok()); // Call the noop program, should get noop not panic let message = Message::new( &[Instruction::new_with_bytes( program_keypair.pubkey(), &[0], vec![], )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair], message) .is_ok()); } #[ignore] // Invoking BPF loaders from CPI not allowed #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_test_use_latest_executor2() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let invoke_and_error = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_invoke_and_error", ); let invoke_and_ok = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_invoke_and_ok", ); let program_keypair = Keypair::new(); // Write the panic program into the program account let elf = read_bpf_program("solana_bpf_rust_panic"); let message = Message::new( &[system_instruction::create_account( &mint_keypair.pubkey(), &program_keypair.pubkey(), 1, elf.len() as u64 * 2, &bpf_loader::id(), )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &program_keypair], message) .is_ok()); write_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, &program_keypair, &elf, ); // - invoke finalize and return error, swallow error let mut instruction = loader_instruction::finalize(&program_keypair.pubkey(), &bpf_loader::id()); instruction.accounts.insert( 0, AccountMeta { is_signer: false, is_writable: false, pubkey: instruction.program_id, }, ); instruction.program_id = invoke_and_ok; instruction.accounts.insert( 0, AccountMeta { is_signer: false, is_writable: false, pubkey: invoke_and_error, }, ); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &program_keypair], message) .is_ok()); // invoke program, verify not found let message = Message::new( &[Instruction::new_with_bytes( program_keypair.pubkey(), &[0], vec![], )], Some(&mint_keypair.pubkey()), ); assert_eq!( bank_client .send_and_confirm_message(&[&mint_keypair], message) .unwrap_err() .unwrap(), TransactionError::InvalidProgramForExecution ); // Write the noop program into the same program account let elf = read_bpf_program("solana_bpf_rust_noop"); write_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, &program_keypair, &elf, ); // Finalize the noop program let message = Message::new( &[loader_instruction::finalize( &program_keypair.pubkey(), &bpf_loader::id(), )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &program_keypair], message) .is_ok()); // Call the program, should get noop, not panic let message = Message::new( &[Instruction::new_with_bytes( program_keypair.pubkey(), &[0], vec![], )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair], message) .is_ok()); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_upgrade()
#[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_upgrade_and_invoke_in_same_tx() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); // Deploy upgrade program let buffer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let program_id = program_keypair.pubkey(); let authority_keypair = Keypair::new(); load_upgradeable_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_keypair, &authority_keypair, "solana_bpf_rust_noop", ); let invoke_instruction = Instruction::new_with_bytes( program_id, &[0], vec![ AccountMeta::new(program_id.clone(), false), AccountMeta::new(clock::id(), false), ], ); // Call upgradeable program let result = bank_client.send_and_confirm_instruction(&mint_keypair, invoke_instruction.clone()); assert!(result.is_ok()); // Prepare for upgrade let buffer_keypair = Keypair::new(); load_upgradeable_buffer( &bank_client, &mint_keypair, &buffer_keypair, &authority_keypair, "solana_bpf_rust_panic", ); // Invoke, then upgrade the program, and then invoke again in same tx let message = Message::new( &[ invoke_instruction.clone(), bpf_loader_upgradeable::upgrade( &program_id, &buffer_keypair.pubkey(), &authority_keypair.pubkey(), &mint_keypair.pubkey(), ), invoke_instruction, ], Some(&mint_keypair.pubkey()), ); let tx = Transaction::new( &[&mint_keypair, &authority_keypair], message.clone(), bank.last_blockhash(), ); let (result, _) = process_transaction_and_record_inner(&bank, tx); assert_eq!( result.unwrap_err(), TransactionError::InstructionError(2, InstructionError::ProgramFailedToComplete) ); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_invoke_upgradeable_via_cpi() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let invoke_and_return = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_invoke_and_return", ); // Deploy upgradeable program let buffer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let program_id = program_keypair.pubkey(); let authority_keypair = Keypair::new(); load_upgradeable_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_keypair, &authority_keypair, "solana_bpf_rust_upgradeable", ); let mut instruction = Instruction::new_with_bytes( invoke_and_return, &[0], vec![ AccountMeta::new_readonly(program_id, false), AccountMeta::new_readonly(program_id, false), AccountMeta::new_readonly(clock::id(), false), ], ); // Call invoker program to invoke the upgradeable program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(42)) ); // Upgrade program let buffer_keypair = Keypair::new(); upgrade_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_id, &authority_keypair, "solana_bpf_rust_upgraded", ); // Call the upgraded program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(43)) ); // Set a new authority let new_authority_keypair = Keypair::new(); set_upgrade_authority( &bank_client, &mint_keypair, &program_id, &authority_keypair, Some(&new_authority_keypair.pubkey()), ); // Upgrade back to the original program let buffer_keypair = Keypair::new(); upgrade_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_id, &new_authority_keypair, "solana_bpf_rust_upgradeable", ); // Call original program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(42)) ); } #[test] #[cfg(any(feature = "bpf_c", feature = "bpf_rust"))] fn test_program_bpf_disguised_as_bpf_loader() { solana_logger::setup(); let mut programs = Vec::new(); #[cfg(feature = "bpf_c")] { programs.extend_from_slice(&[("noop")]); } #[cfg(feature = "bpf_rust")] { programs.extend_from_slice(&[("solana_bpf_rust_noop")]); } for program in programs.iter() { let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_deprecated_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let program_id = load_bpf_program( &bank_client, &bpf_loader_deprecated::id(), &mint_keypair, program, ); let account_metas = vec![AccountMeta::new_readonly(program_id, false)]; let instruction = Instruction::new_with_bytes(bpf_loader_deprecated::id(), &[1], account_metas); let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::IncorrectProgramId) ); } } #[test] #[cfg(feature = "bpf_c")] fn test_program_bpf_c_dup() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let account_address = Pubkey::new_unique(); let account = AccountSharedData::new_data(42, &[1_u8, 2, 3], &system_program::id()).unwrap(); bank.store_account(&account_address, &account); let bank_client = BankClient::new(bank); let program_id = load_bpf_program(&bank_client, &bpf_loader::id(), &mint_keypair, "ser"); let account_metas = vec![ AccountMeta::new_readonly(account_address, false), AccountMeta::new_readonly(account_address, false), ]; let instruction = Instruction::new_with_bytes(program_id, &[4, 5, 6, 7], account_metas); bank_client .send_and_confirm_instruction(&mint_keypair, instruction) .unwrap(); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_upgrade_via_cpi() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); let invoke_and_return = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_invoke_and_return", ); // Deploy upgradeable program let buffer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let program_id = program_keypair.pubkey(); let authority_keypair = Keypair::new(); load_upgradeable_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_keypair, &authority_keypair, "solana_bpf_rust_upgradeable", ); let program_account = bank_client.get_account(&program_id).unwrap().unwrap(); let programdata_address = match program_account.state() { Ok(bpf_loader_upgradeable::UpgradeableLoaderState::Program { programdata_address, }) => programdata_address, _ => unreachable!(), }; let original_programdata = bank_client .get_account_data(&programdata_address) .unwrap() .unwrap(); let mut instruction = Instruction::new_with_bytes( invoke_and_return, &[0], vec![ AccountMeta::new_readonly(program_id, false), AccountMeta::new_readonly(program_id, false), AccountMeta::new_readonly(clock::id(), false), ], ); // Call the upgradable program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(42)) ); // Load the buffer account let path = create_bpf_path("solana_bpf_rust_upgraded"); let mut file = File::open(&path).unwrap_or_else(|err| { panic!("Failed to open {}: {}", path.display(), err); }); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); let buffer_keypair = Keypair::new(); load_buffer_account( &bank_client, &mint_keypair, &buffer_keypair, &authority_keypair, &elf, ); // Upgrade program via CPI let mut upgrade_instruction = bpf_loader_upgradeable::upgrade( &program_id, &buffer_keypair.pubkey(), &authority_keypair.pubkey(), &mint_keypair.pubkey(), ); upgrade_instruction.program_id = invoke_and_return; upgrade_instruction .accounts .insert(0, AccountMeta::new(bpf_loader_upgradeable::id(), false)); let message = Message::new(&[upgrade_instruction], Some(&mint_keypair.pubkey())); bank_client .send_and_confirm_message(&[&mint_keypair, &authority_keypair], message) .unwrap(); // Call the upgraded program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(43)) ); // Validate that the programdata was actually overwritten let programdata = bank_client .get_account_data(&programdata_address) .unwrap() .unwrap(); assert_ne!(programdata, original_programdata); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_upgrade_self_via_cpi() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let noop_program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_noop", ); // Deploy upgradeable program let buffer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let program_id = program_keypair.pubkey(); let authority_keypair = Keypair::new(); load_upgradeable_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_keypair, &authority_keypair, "solana_bpf_rust_invoke_and_return", ); let mut invoke_instruction = Instruction::new_with_bytes( program_id, &[0], vec![ AccountMeta::new_readonly(noop_program_id, false), AccountMeta::new_readonly(noop_program_id, false), AccountMeta::new_readonly(clock::id(), false), ], ); // Call the upgraded program invoke_instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, invoke_instruction.clone()); assert!(result.is_ok()); // Prepare for upgrade let buffer_keypair = Keypair::new(); load_upgradeable_buffer( &bank_client, &mint_keypair, &buffer_keypair, &authority_keypair, "solana_bpf_rust_panic", ); // Invoke, then upgrade the program, and then invoke again in same tx let message = Message::new( &[ invoke_instruction.clone(), bpf_loader_upgradeable::upgrade( &program_id, &buffer_keypair.pubkey(), &authority_keypair.pubkey(), &mint_keypair.pubkey(), ), invoke_instruction, ], Some(&mint_keypair.pubkey()), ); let tx = Transaction::new( &[&mint_keypair, &authority_keypair], message.clone(), bank.last_blockhash(), ); let (result, _) = process_transaction_and_record_inner(&bank, tx); assert_eq!( result.unwrap_err(), TransactionError::InstructionError(2, InstructionError::ProgramFailedToComplete) ); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_set_upgrade_authority_via_cpi() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); // Deploy CPI invoker program let invoke_and_return = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_invoke_and_return", ); // Deploy upgradeable program let buffer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let program_id = program_keypair.pubkey(); let authority_keypair = Keypair::new(); load_upgradeable_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_keypair, &authority_keypair, "solana_bpf_rust_upgradeable", ); // Set program upgrade authority instruction to invoke via CPI let new_upgrade_authority_key = Keypair::new().pubkey(); let mut set_upgrade_authority_instruction = bpf_loader_upgradeable::set_upgrade_authority( &program_id, &authority_keypair.pubkey(), Some(&new_upgrade_authority_key), ); // Invoke set_upgrade_authority via CPI invoker program set_upgrade_authority_instruction.program_id = invoke_and_return; set_upgrade_authority_instruction .accounts .insert(0, AccountMeta::new(bpf_loader_upgradeable::id(), false)); let message = Message::new( &[set_upgrade_authority_instruction], Some(&mint_keypair.pubkey()), ); bank_client .send_and_confirm_message(&[&mint_keypair, &authority_keypair], message) .unwrap(); // Assert upgrade authority was changed let program_account_data = bank_client.get_account_data(&program_id).unwrap().unwrap(); let program_account = parse_bpf_upgradeable_loader(&program_account_data).unwrap(); let upgrade_authority_key = match program_account { BpfUpgradeableLoaderAccountType::Program(ui_program) => { let program_data_account_key = Pubkey::from_str(&ui_program.program_data).unwrap(); let program_data_account_data = bank_client .get_account_data(&program_data_account_key) .unwrap() .unwrap(); let program_data_account = parse_bpf_upgradeable_loader(&program_data_account_data).unwrap(); match program_data_account { BpfUpgradeableLoaderAccountType::ProgramData(ui_program_data) => ui_program_data .authority .map(|a| Pubkey::from_str(&a).unwrap()), _ => None, } } _ => None, }; assert_eq!(Some(new_upgrade_authority_key), upgrade_authority_key); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_upgradeable_locks() { fn setup_program_upgradeable_locks( payer_keypair: &Keypair, buffer_keypair: &Keypair, program_keypair: &Keypair, ) -> (Arc<Bank>, Transaction, Transaction) { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(2_000_000_000); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); load_upgradeable_bpf_program( &bank_client, &mint_keypair, buffer_keypair, program_keypair, payer_keypair, "solana_bpf_rust_panic", ); // Load the buffer account let path = create_bpf_path("solana_bpf_rust_noop"); let mut file = File::open(&path).unwrap_or_else(|err| { panic!("Failed to open {}: {}", path.display(), err); }); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); load_buffer_account( &bank_client, &mint_keypair, buffer_keypair, &payer_keypair, &elf, ); bank_client .send_and_confirm_instruction( &mint_keypair, system_instruction::transfer( &mint_keypair.pubkey(), &payer_keypair.pubkey(), 1_000_000_000, ), ) .unwrap(); let invoke_tx = Transaction::new( &[payer_keypair], Message::new( &[Instruction::new_with_bytes( program_keypair.pubkey(), &[0; 0], vec![], )], Some(&payer_keypair.pubkey()), ), bank.last_blockhash(), ); let upgrade_tx = Transaction::new( &[payer_keypair], Message::new( &[bpf_loader_upgradeable::upgrade( &program_keypair.pubkey(), &buffer_keypair.pubkey(), &payer_keypair.pubkey(), &payer_keypair.pubkey(), )], Some(&payer_keypair.pubkey()), ), bank.last_blockhash(), ); (bank, invoke_tx, upgrade_tx) } let payer_keypair = keypair_from_seed(&[56u8; 32]).unwrap(); let buffer_keypair = keypair_from_seed(&[11; 32]).unwrap(); let program_keypair = keypair_from_seed(&[77u8; 32]).unwrap(); let results1 = { let (bank, invoke_tx, upgrade_tx) = setup_program_upgradeable_locks(&payer_keypair, &buffer_keypair, &program_keypair); execute_transactions(&bank, vec![upgrade_tx, invoke_tx]) }; let results2 = { let (bank, invoke_tx, upgrade_tx) = setup_program_upgradeable_locks(&payer_keypair, &buffer_keypair, &program_keypair); execute_transactions(&bank, vec![invoke_tx, upgrade_tx]) }; if false { println!("upgrade and invoke"); for result in &results1 { print_confirmed_tx("result", result.clone()); } println!("invoke and upgrade"); for result in &results2 { print_confirmed_tx("result", result.clone()); } } if let Some(ref meta) = results1[0].transaction.meta { assert_eq!(meta.status, Ok(())); } else { panic!("no meta"); } if let Some(ref meta) = results1[1].transaction.meta { assert_eq!(meta.status, Err(TransactionError::AccountInUse)); } else { panic!("no meta"); } if let Some(ref meta) = results2[0].transaction.meta { assert_eq!( meta.status, Err(TransactionError::InstructionError( 0, InstructionError::ProgramFailedToComplete )) ); } else { panic!("no meta"); } if let Some(ref meta) = results2[1].transaction.meta { assert_eq!(meta.status, Err(TransactionError::AccountInUse)); } else { panic!("no meta"); } } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_finalize() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_pubkey = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_finalize", ); let noop_keypair = Keypair::new(); // Write the noop program into the same program account let elf = read_bpf_program("solana_bpf_rust_noop"); let message = Message::new( &[system_instruction::create_account( &mint_keypair.pubkey(), &noop_keypair.pubkey(), 1, elf.len() as u64 * 2, &bpf_loader::id(), )], Some(&mint_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message(&[&mint_keypair, &noop_keypair], message) .is_ok()); write_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, &noop_keypair, &elf, ); let account_metas = vec![ AccountMeta::new(noop_keypair.pubkey(), true), AccountMeta::new_readonly(bpf_loader::id(), false), AccountMeta::new(rent::id(), false), ]; let instruction = Instruction::new_with_bytes(program_pubkey, &[], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_keypair.pubkey())); let result = bank_client.send_and_confirm_message(&[&mint_keypair, &noop_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ProgramFailedToComplete) ); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_ro_account_modify() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_ro_account_modify", ); let argument_keypair = Keypair::new(); let account = AccountSharedData::new(42, 100, &program_id); bank.store_account(&argument_keypair.pubkey(), &account); let from_keypair = Keypair::new(); let account = AccountSharedData::new(84, 0, &system_program::id()); bank.store_account(&from_keypair.pubkey(), &account); let mint_pubkey = mint_keypair.pubkey(); let account_metas = vec![ AccountMeta::new_readonly(argument_keypair.pubkey(), false), AccountMeta::new_readonly(program_id, false), ]; let instruction = Instruction::new_with_bytes(program_id, &[0], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_pubkey)); let result = bank_client.send_and_confirm_message(&[&mint_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ReadonlyDataModified) ); let instruction = Instruction::new_with_bytes(program_id, &[1], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_pubkey)); let result = bank_client.send_and_confirm_message(&[&mint_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ReadonlyDataModified) ); let instruction = Instruction::new_with_bytes(program_id, &[2], account_metas.clone()); let message = Message::new(&[instruction], Some(&mint_pubkey)); let result = bank_client.send_and_confirm_message(&[&mint_keypair], message); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::ReadonlyDataModified) ); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_realloc() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mint_pubkey = mint_keypair.pubkey(); let signer = &[&mint_keypair]; let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_realloc", ); let mut bump = 0; let keypair = Keypair::new(); let pubkey = keypair.pubkey(); let account = AccountSharedData::new(42, 5, &program_id); bank.store_account(&pubkey, &account); // Realloc RO account let mut instruction = realloc(&program_id, &pubkey, 0, &mut bump); instruction.accounts[0].is_writable = false; assert_eq!( bank_client .send_and_confirm_message(signer, Message::new(&[instruction], Some(&mint_pubkey),),) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::ReadonlyDataModified) ); // Realloc account to overflow assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&program_id, &pubkey, usize::MAX, &mut bump)], Some(&mint_pubkey), ), ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc account to 0 bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(0, data.len()); // Realloc to max + 1 assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[realloc( &program_id, &pubkey, MAX_PERMITTED_DATA_INCREASE + 1, &mut bump )], Some(&mint_pubkey), ), ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc to max length in max increase increments for i in 0..MAX_PERMITTED_DATA_LENGTH as usize / MAX_PERMITTED_DATA_INCREASE { let mut bump = i as u64; bank_client .send_and_confirm_message( signer, Message::new( &[realloc_extend_and_fill( &program_id, &pubkey, MAX_PERMITTED_DATA_INCREASE, 1, &mut bump, )], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!((i + 1) * MAX_PERMITTED_DATA_INCREASE, data.len()); } for i in 0..data.len() { assert_eq!(data[i], 1); } // and one more time should fail assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[realloc_extend( &program_id, &pubkey, MAX_PERMITTED_DATA_INCREASE, &mut bump )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc to 0 bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(0, data.len()); // Realloc and assign bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( program_id, &[REALLOC_AND_ASSIGN], vec![AccountMeta::new(pubkey, false)], )], Some(&mint_pubkey), ), ) .unwrap(); let account = bank.get_account(&pubkey).unwrap(); assert_eq!(&solana_sdk::system_program::id(), account.owner()); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(MAX_PERMITTED_DATA_INCREASE, data.len()); // Realloc to 0 with wrong owner assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::AccountDataSizeChanged) ); // realloc and assign to self via cpi assert_eq!( bank_client .send_and_confirm_message( &[&mint_keypair, &keypair], Message::new( &[Instruction::new_with_bytes( program_id, &[REALLOC_AND_ASSIGN_TO_SELF_VIA_SYSTEM_PROGRAM], vec![ AccountMeta::new(pubkey, true), AccountMeta::new(solana_sdk::system_program::id(), false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::AccountDataSizeChanged) ); // Assign to self and realloc via cpi bank_client .send_and_confirm_message( &[&mint_keypair, &keypair], Message::new( &[Instruction::new_with_bytes( program_id, &[ASSIGN_TO_SELF_VIA_SYSTEM_PROGRAM_AND_REALLOC], vec![ AccountMeta::new(pubkey, true), AccountMeta::new(solana_sdk::system_program::id(), false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let account = bank.get_account(&pubkey).unwrap(); assert_eq!(&program_id, account.owner()); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(2 * MAX_PERMITTED_DATA_INCREASE, data.len()); // Realloc to 0 bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(0, data.len()); // zero-init bank_client .send_and_confirm_message( &[&mint_keypair, &keypair], Message::new( &[Instruction::new_with_bytes( program_id, &[ZERO_INIT], vec![AccountMeta::new(pubkey, true)], )], Some(&mint_pubkey), ), ) .unwrap(); } #[cfg(feature = "bpf_rust")] #[test] fn test_program_bpf_realloc_invoke() { solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mint_pubkey = mint_keypair.pubkey(); let signer = &[&mint_keypair]; let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_program!(); bank.add_builtin(&name, &id, entrypoint); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); let realloc_program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_realloc", ); let realloc_invoke_program_id = load_bpf_program( &bank_client, &bpf_loader::id(), &mint_keypair, "solana_bpf_rust_realloc_invoke", ); let mut bump = 0; let keypair = Keypair::new(); let pubkey = keypair.pubkey().clone(); let account = AccountSharedData::new(42, 5, &realloc_program_id); bank.store_account(&pubkey, &account); let invoke_keypair = Keypair::new(); let invoke_pubkey = invoke_keypair.pubkey().clone(); // Realloc RO account assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_ZERO_RO], vec![ AccountMeta::new_readonly(pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::ReadonlyDataModified) ); // Realloc account to 0 bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&realloc_program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(0, data.len()); // Realloc to max + 1 assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_MAX_PLUS_ONE], vec![ AccountMeta::new(pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc to max twice assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_MAX_TWICE], vec![ AccountMeta::new(pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc to max length in max increase increments for i in 0..MAX_PERMITTED_DATA_LENGTH as usize / MAX_PERMITTED_DATA_INCREASE { bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_EXTEND_MAX, 1, i as u8, (i / 255) as u8], vec![ AccountMeta::new(pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!((i + 1) * MAX_PERMITTED_DATA_INCREASE, data.len()); } for i in 0..data.len() { assert_eq!(data[i], 1); } // and one more time should fail assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_EXTEND_MAX, 2, 1, 1], vec![ AccountMeta::new(pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc to 0 bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&realloc_program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(0, data.len()); // Realloc and assign bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_AND_ASSIGN], vec![ AccountMeta::new(pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let account = bank.get_account(&pubkey).unwrap(); assert_eq!(&solana_sdk::system_program::id(), account.owner()); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(MAX_PERMITTED_DATA_INCREASE, data.len()); // Realloc to 0 with wrong owner assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&realloc_program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::AccountDataSizeChanged) ); // realloc and assign to self via system program assert_eq!( bank_client .send_and_confirm_message( &[&mint_keypair, &keypair], Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_AND_ASSIGN_TO_SELF_VIA_SYSTEM_PROGRAM], vec![ AccountMeta::new(pubkey, true), AccountMeta::new_readonly(realloc_program_id, false), AccountMeta::new_readonly(solana_sdk::system_program::id(), false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::AccountDataSizeChanged) ); // Assign to self and realloc via system program bank_client .send_and_confirm_message( &[&mint_keypair, &keypair], Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_ASSIGN_TO_SELF_VIA_SYSTEM_PROGRAM_AND_REALLOC], vec![ AccountMeta::new(pubkey, true), AccountMeta::new_readonly(realloc_program_id, false), AccountMeta::new_readonly(solana_sdk::system_program::id(), false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let account = bank.get_account(&pubkey).unwrap(); assert_eq!(&realloc_program_id, account.owner()); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(2 * MAX_PERMITTED_DATA_INCREASE, data.len()); // Realloc to 0 bank_client .send_and_confirm_message( signer, Message::new( &[realloc(&realloc_program_id, &pubkey, 0, &mut bump)], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&pubkey).unwrap().unwrap(); assert_eq!(0, data.len()); // Realloc to 100 and check via CPI let invoke_account = AccountSharedData::new(42, 5, &realloc_invoke_program_id); bank.store_account(&invoke_pubkey, &invoke_account); bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_INVOKE_CHECK], vec![ AccountMeta::new(invoke_pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client .get_account_data(&invoke_pubkey) .unwrap() .unwrap(); assert_eq!(100, data.len()); for i in 0..5 { assert_eq!(data[i], 0); } for i in 5..data.len() { assert_eq!(data[i], 2); } // Realloc rescursively and fill data let invoke_keypair = Keypair::new(); let invoke_pubkey = invoke_keypair.pubkey().clone(); let invoke_account = AccountSharedData::new(42, 0, &realloc_invoke_program_id); bank.store_account(&invoke_pubkey, &invoke_account); let mut instruction_data = vec![]; instruction_data.extend_from_slice(&[INVOKE_REALLOC_RECURSIVE, 1]); instruction_data.extend_from_slice(&100_usize.to_le_bytes()); bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &instruction_data, vec![ AccountMeta::new(invoke_pubkey, false), AccountMeta::new_readonly(realloc_invoke_program_id, false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client .get_account_data(&invoke_pubkey) .unwrap() .unwrap(); assert_eq!(200, data.len()); for i in 0..100 { assert_eq!(data[i], 1); } for i in 100..200 { assert_eq!(data[i], 2); } // Create account, realloc, check let new_keypair = Keypair::new(); let new_pubkey = new_keypair.pubkey().clone(); let mut instruction_data = vec![]; instruction_data.extend_from_slice(&[INVOKE_CREATE_ACCOUNT_REALLOC_CHECK, 1]); instruction_data.extend_from_slice(&100_usize.to_le_bytes()); bank_client .send_and_confirm_message( &[&mint_keypair, &new_keypair], Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &instruction_data, vec![ AccountMeta::new(mint_pubkey, true), AccountMeta::new(new_pubkey, true), AccountMeta::new(solana_sdk::system_program::id(), false), AccountMeta::new_readonly(realloc_invoke_program_id, false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client.get_account_data(&new_pubkey).unwrap().unwrap(); assert_eq!(200, data.len()); let account = bank.get_account(&new_pubkey).unwrap(); assert_eq!(&realloc_invoke_program_id, account.owner()); // Invoke, dealloc, and assign let pre_len = 100; let new_len = pre_len * 2; let mut invoke_account = AccountSharedData::new(42, pre_len, &realloc_program_id); invoke_account.set_data_from_slice(&vec![1; pre_len]); bank.store_account(&invoke_pubkey, &invoke_account); let mut instruction_data = vec![]; instruction_data.extend_from_slice(&[INVOKE_DEALLOC_AND_ASSIGN, 1]); instruction_data.extend_from_slice(&pre_len.to_le_bytes()); bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &instruction_data, vec![ AccountMeta::new(invoke_pubkey, false), AccountMeta::new_readonly(realloc_invoke_program_id, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ), ) .unwrap(); let data = bank_client .get_account_data(&invoke_pubkey) .unwrap() .unwrap(); assert_eq!(new_len, data.len()); for i in 0..new_len { assert_eq!(data[i], 0); } // Realloc to max invoke max let invoke_account = AccountSharedData::new(42, 0, &realloc_invoke_program_id); bank.store_account(&invoke_pubkey, &invoke_account); assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_REALLOC_MAX_INVOKE_MAX], vec![ AccountMeta::new(invoke_pubkey, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); // Realloc invoke max twice let invoke_account = AccountSharedData::new(42, 0, &realloc_program_id); bank.store_account(&invoke_pubkey, &invoke_account); assert_eq!( bank_client .send_and_confirm_message( signer, Message::new( &[Instruction::new_with_bytes( realloc_invoke_program_id, &[INVOKE_INVOKE_MAX_TWICE], vec![ AccountMeta::new(invoke_pubkey, false), AccountMeta::new_readonly(realloc_invoke_program_id, false), AccountMeta::new_readonly(realloc_program_id, false), ], )], Some(&mint_pubkey), ) ) .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidRealloc) ); }
{ solana_logger::setup(); let GenesisConfigInfo { genesis_config, mint_keypair, .. } = create_genesis_config(50); let mut bank = Bank::new_for_tests(&genesis_config); let (name, id, entrypoint) = solana_bpf_loader_upgradeable_program!(); bank.add_builtin(&name, &id, entrypoint); let bank_client = BankClient::new(bank); // Deploy upgrade program let buffer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let program_id = program_keypair.pubkey(); let authority_keypair = Keypair::new(); load_upgradeable_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_keypair, &authority_keypair, "solana_bpf_rust_upgradeable", ); let mut instruction = Instruction::new_with_bytes( program_id, &[0], vec![ AccountMeta::new(program_id.clone(), false), AccountMeta::new(clock::id(), false), ], ); // Call upgrade program let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(42)) ); // Upgrade program let buffer_keypair = Keypair::new(); upgrade_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_id, &authority_keypair, "solana_bpf_rust_upgraded", ); // Call upgraded program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction.clone()); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(43)) ); // Set a new authority let new_authority_keypair = Keypair::new(); set_upgrade_authority( &bank_client, &mint_keypair, &program_id, &authority_keypair, Some(&new_authority_keypair.pubkey()), ); // Upgrade back to the original program let buffer_keypair = Keypair::new(); upgrade_bpf_program( &bank_client, &mint_keypair, &buffer_keypair, &program_id, &new_authority_keypair, "solana_bpf_rust_upgradeable", ); // Call original program instruction.data[0] += 1; let result = bank_client.send_and_confirm_instruction(&mint_keypair, instruction); assert_eq!( result.unwrap_err().unwrap(), TransactionError::InstructionError(0, InstructionError::Custom(42)) ); }
surface.rs
use geom::{Rect,Px}; #[derive(Copy,Clone)] pub struct Colour(u32); impl Colour { pub fn from_argb32(argb32: u32) -> Colour { Colour(argb32) } pub fn from_rgb(r: u8, g: u8, b: u8) -> Colour { let argb32 = 0 << 24 | (r as u32) << 16 | (g as u32) << 8 | (b as u32); Colour( argb32 ) } //pub fn black() -> Colour { Colour(0) } //pub fn ltgray() -> Colour { Colour(0xDD_DD_DD) } //pub fn gray() -> Colour { Colour(0x55_55_55) } //pub fn white() -> Colour { Colour(0xFF_FF_FF) } pub fn as_argb32(&self) -> u32 { self.0 } pub const fn theme_text() -> Colour { Colour(0x00_000000) } pub const fn theme_text_alt() -> Colour { Colour(0x00_606060) } pub const fn theme_border_main() -> Colour { Colour(0x00_C0C0C0) } pub const fn theme_border_alt() -> Colour { Colour(0x00_E0E0E0) } pub const fn theme_text_bg() -> Colour { Colour(0xF8FFF8) } pub const fn theme_body_bg() -> Colour { Colour(0x002000) } /// Alpha value, 0 = opaque, 255 = transparent pub fn alpha(&self) -> u8 { (self.0 >> 24) as u8 } pub fn red (&self) -> u8 { (self.0 >> 16) as u8 } pub fn green(&self) -> u8 { (self.0 >> 8) as u8 } pub fn
(&self) -> u8 { (self.0 >> 0) as u8 } pub fn blend_alpha(lower: Colour, upper: Colour, alpha: u8) -> Colour { let alpha: u32 = alpha as u32; if alpha == 0 { upper } else if alpha == 255 { lower } else { let r = Self::blend_component( alpha, lower.red(), upper.red() ); let g = Self::blend_component( alpha, lower.green(), upper.green() ); let b = Self::blend_component( alpha, lower.blue(), upper.blue() ); Colour::from_rgb(r,g,b) } } pub fn blend(lower: Colour, upper: Colour) -> Colour { Colour::blend_alpha(lower, upper, upper.alpha()) } fn blend_component(alpha: u32, lower: u8, upper: u8) -> u8 { let val_by_255 = lower as u32 * alpha + upper as u32 * (255 - alpha); (val_by_255 / 255) as u8 } } #[derive(Default)] pub struct Surface { width: usize, dirty: ::std::cell::Cell<Rect<Px>>, data: ::std::cell::RefCell<Vec<u32>>, } impl Surface { pub fn new() -> Surface { Default::default() } fn height(&self) -> u32 { if self.width == 0 { assert_eq!(self.data.borrow().len(), 0); 0 } else { (self.data.borrow().len() / self.width) as u32 } } /// Blit to the passed GUI window pub fn blit_to_win(&self, win: &::syscalls::gui::Window) { let dirty: Rect<Px> = self.dirty.get(); self.dirty.set(Default::default()); let first_row = dirty.y().0 as usize; let row_count = dirty.height().0 as usize; let first_col = dirty.x().0 as usize; let col_count = dirty.width().0 as usize; if row_count == 0 || col_count == 0 { kernel_log!("Surface::blit_to_win - nothing to blit"); } else { // Blit just the dirty region win.blit_rect( first_col as u32, first_row as u32, col_count as u32, row_count as u32, &self.data.borrow()[first_row*self.width + first_col .. ][ .. row_count*self.width - first_col], self.width ); } } pub fn invalidate_all(&mut self) { self.dirty.set( self.rect() ); } /// Resize the surface (clearing existing content) pub fn resize(&mut self, dims: ::syscalls::gui::Dims, fill: Colour) { self.width = dims.w as usize; *self.data.borrow_mut() = vec![fill.as_argb32(); dims.w as usize * dims.h as usize]; // On resize, set dirty area to full area of the surface self.invalidate_all(); } /// Obtain a rect covering the entire surface pub fn rect(&self) -> Rect<Px> { Rect::new(0, 0, self.width as u32, self.height()) } /// Obtain a view into this surface pub fn slice(&self, rect: Rect<Px>) -> SurfaceView { let rect = self.rect().intersect(&rect); //kernel_log!("Surface::slice - rect={:?}", rect); SurfaceView { surf: self, rect: rect } } fn foreach_scanlines<F: FnMut(usize, &mut [u32])>(&self, rect_o: Rect<Px>, mut f: F) { // Update dirty region with this rect let rect = self.rect().intersect(&rect_o); //let mut dr = self.dirty.borrow_mut(); if self.dirty.get().is_empty() { self.dirty.set(rect); } else { self.dirty.set( self.dirty.get().union(&rect) ); } //kernel_log!("foreach_scanlines(rect_o={:?} [ rect={:?} ], F={})", rect_o, rect, type_name!(F)); for (i, row) in self.data.borrow_mut().chunks_mut(self.width).skip(rect.y().0 as usize).take(rect.height().0 as usize).enumerate() { //kernel_log!("{}: {} {}..{} row.len()={}", i, rect.y().0 as usize + i, rect.x().0, rect.x2().0, row.len()); f( i, &mut row[rect.x().0 as usize .. rect.x2().0 as usize] ); } //kernel_log!("- done"); } } // TODO: Support masking region (for clipping left/top of text) #[derive(Clone)] pub struct SurfaceView<'a> { surf: &'a Surface, rect: Rect<Px>, } impl<'a> SurfaceView<'a> { /// Obtain a full rectangle of this surface pub fn rect(&self) -> Rect<Px> { Rect::new(0, 0, self.width(), self.height()) } pub fn width(&self) -> u32 { self.rect.width().0 } pub fn height(&self) -> u32 { self.rect.height().0 } /// Create a sub-view of the surface pub fn slice(&self, rect: Rect<Px>) -> SurfaceView { SurfaceView { surf: self.surf, rect: self.rect.intersect(&rect.offset(self.rect.x(), self.rect.y())), } } /// Iterate over scanlines in a rect (scanlines are [u32] xRGB32) pub fn foreach_scanlines<F: FnMut(usize, &mut [u32])>(&self, rect: Rect<Px>, f: F) { self.surf.foreach_scanlines( self.rect.relative(&rect), f ) } /// Fill a region with a solid colour pub fn fill_rect(&self, rect: Rect<Px>, colour: Colour) { self.foreach_scanlines(rect, |_, line| for px in line.iter_mut() { *px = colour.as_argb32(); } ); } pub fn draw_rect(&self, rect: Rect<Px>, lw: Px, colour: Colour) { let inner_min = lw.0 as usize; let inner_max = (rect.h.0 - lw.0) as usize; assert!(inner_min > 0); self.foreach_scanlines(rect, |i, line| if inner_min <= i && i < inner_max { for px in line[.. inner_min].iter_mut() { *px = colour.as_argb32(); } for px in line[(rect.w.0 - lw.0) as usize .. ].iter_mut() { *px = colour.as_argb32(); } } else { for px in line.iter_mut() { *px = colour.as_argb32(); } } ); } pub fn size_text<It: Iterator<Item=char>>(chars: It) -> (u32,u32) { let mut st = S_FONT.get_renderer(); let mut chars = chars.peekable(); let mut dims = (0,0); while let Some( (w,h) ) = st.size_grapheme(&mut chars) { dims.0 += w; dims.1 = ::std::cmp::max(dims.1, h); } dims } /// Draw characters yielded from the passed iterator using the default font pub fn draw_text<It: Iterator<Item=char>>(&self, mut rect: Rect<Px>, chars: It, colour: Colour) -> usize { let mut st = S_FONT.get_renderer(); let mut chars = chars.peekable(); while let Some( (w,_h) ) = st.render_grapheme(&mut chars, colour) { self.foreach_scanlines(rect, |i, line| { for (d,s) in Iterator::zip( line.iter_mut(), st.buffer(i, w as usize) ) { *d = Colour::blend( Colour::from_argb32(*d), Colour::from_argb32(*s) ).as_argb32(); } }); rect = rect.offset(::geom::Px(w), ::geom::Px(0)); } rect.x().0 as usize } pub fn draw_text_fmt(&self, rect: Rect<Px>, colour: Colour) -> TextFmtWrite { TextFmtWrite(self, S_FONT.get_renderer(), colour, rect) } } pub struct TextFmtWrite<'a>(&'a SurfaceView<'a>, MonoFontRender, Colour, Rect<Px>); impl<'a> TextFmtWrite<'a> { fn blit(&mut self, w: u32, _h: u32) { self.0.foreach_scanlines(self.3, |i, line| { for (d,s) in Iterator::zip( line.iter_mut(), self.1.buffer(i, w as usize) ) { *d = Colour::blend( Colour::from_argb32(*d), Colour::from_argb32(*s) ).as_argb32(); } }); self.3 = self.3.offset(::geom::Px(w), ::geom::Px(0)); } } impl<'a> ::std::fmt::Write for TextFmtWrite<'a> { fn write_str(&mut self, s: &str) -> ::std::fmt::Result { for c in s.chars() { try!( self.write_char(c) ); } Ok( () ) } fn write_char(&mut self, c: char) -> ::std::fmt::Result { if ! c.is_combining() { if let Some((w,h)) = self.1.get_rendered_dims() { self.blit(w, h); } } self.1.render_char(self.2, c); Ok( () ) } } impl<'a> ::std::ops::Drop for TextFmtWrite<'a> { fn drop(&mut self) { if let Some((w,h)) = self.1.get_rendered_dims() { self.blit(w, h); } } } // -------------------------------------------------------------------- // Fallback/simple monospace font (Classic VGA, aka CP437) // -------------------------------------------------------------------- static S_FONT: MonoFont = MonoFont::new(); struct MonoFont; impl MonoFont { const fn new() -> MonoFont { MonoFont } fn get_renderer(&self) -> MonoFontRender { MonoFontRender { buffer: [0; 8*16], } } } include!("../../Graphics/font_cp437_8x16.rs"); struct MonoFontRender { buffer: [u32; 8*16], } impl MonoFontRender { pub fn size_grapheme<It: Iterator<Item=char>>(&mut self, it: &mut ::std::iter::Peekable<It>) -> Option<(u32,u32)> { if let Some(_ch) = it.next() { while it.peek().map(|c| c.is_combining()).unwrap_or(false) { it.next(); } Some( (8,16) ) } else { None } } pub fn render_grapheme<It: Iterator<Item=char>>(&mut self, it: &mut ::std::iter::Peekable<It>, colour: Colour) -> Option<(u32,u32)> { self.clear_buffer(); self.buffer[0] = 0xFF_000000; if let Some(ch) = it.next() { self.render_char(colour, ch); while it.peek().map(|c| c.is_combining()).unwrap_or(false) { self.render_int_char(colour, it.next().unwrap()); } Some( (8,16) ) } else { None } } pub fn render_char(&mut self, colour: Colour, ch: char) { if ! ch.is_combining() { self.clear_buffer(); } self.render_int_char(colour, ch); } pub fn get_rendered_dims(&self) -> Option<(u32, u32)> { if &self.buffer[..] == &[0; 8*16][..] { // The buffer is only zero when this hasn't been cleared None } else { Some( (8,16) ) } } pub fn buffer(&self, row: usize, width: usize) -> &[u32] { if row*8 >= self.buffer.len() { &[] } else { &self.buffer[row * 8..][..width] } } fn clear_buffer(&mut self) { self.buffer = [0xFF_000000; 8*16]; } /// Actually does the rendering fn render_int_char(&mut self, colour: Colour, cp: char) { let idx = unicode_to_cp437(cp); let bitmap = &S_FONTDATA[idx as usize]; // Actual render! for row in 0 .. 16 { let byte = &bitmap[row as usize]; let base = row * 8; let r = &mut self.buffer[base .. base + 8]; for col in 0usize .. 8 { if (byte >> 7-col) & 1 != 0 { r[col] = colour.as_argb32(); } } } } } /// Trait to provde 'is_combining', used by render code trait UnicodeCombining { fn is_combining(&self) -> bool; } impl UnicodeCombining for char { fn is_combining(&self) -> bool { match *self as u32 { // Ranges from wikipedia:Combining_Character 0x0300 ..= 0x036F => true, 0x1AB0 ..= 0x1AFF => true, 0x1DC0 ..= 0x1DFF => true, 0x20D0 ..= 0x20FF => true, 0xFE20 ..= 0xFE2F => true, _ => false, } } }
blue
stacked-borrows.rs
// compile-flags: -Zmiri-track-raw-pointers use std::ptr; // Test various stacked-borrows-related things. fn main() { read_does_not_invalidate1(); read_does_not_invalidate2(); mut_raw_then_mut_shr(); mut_shr_then_mut_raw(); mut_raw_mut(); partially_invalidate_mut(); drop_after_sharing(); direct_mut_to_const_raw(); two_raw(); shr_and_raw(); disjoint_mutable_subborrows(); raw_ref_to_part(); } // Make sure that reading from an `&mut` does, like reborrowing to `&`, // NOT invalidate other reborrows. fn
() { fn foo(x: &mut (i32, i32)) -> &i32 { let xraw = x as *mut (i32, i32); let ret = unsafe { &(*xraw).1 }; let _val = x.1; // we just read, this does NOT invalidate the reborrows. ret } assert_eq!(*foo(&mut (1, 2)), 2); } // Same as above, but this time we first create a raw, then read from `&mut` // and then freeze from the raw. fn read_does_not_invalidate2() { fn foo(x: &mut (i32, i32)) -> &i32 { let xraw = x as *mut (i32, i32); let _val = x.1; // we just read, this does NOT invalidate the raw reborrow. let ret = unsafe { &(*xraw).1 }; ret } assert_eq!(*foo(&mut (1, 2)), 2); } // Escape a mut to raw, then share the same mut and use the share, then the raw. // That should work. fn mut_raw_then_mut_shr() { let mut x = 2; let xref = &mut x; let xraw = &mut *xref as *mut _; let xshr = &*xref; assert_eq!(*xshr, 2); unsafe { *xraw = 4; } assert_eq!(x, 4); } // Create first a shared reference and then a raw pointer from a `&mut` // should permit mutation through that raw pointer. fn mut_shr_then_mut_raw() { let xref = &mut 2; let _xshr = &*xref; let xraw = xref as *mut _; unsafe { *xraw = 3; } assert_eq!(*xref, 3); } // Ensure that if we derive from a mut a raw, and then from that a mut, // and then read through the original mut, that does not invalidate the raw. // This shows that the read-exception for `&mut` applies even if the `Shr` item // on the stack is not at the top. fn mut_raw_mut() { let mut x = 2; { let xref1 = &mut x; let xraw = xref1 as *mut _; let _xref2 = unsafe { &mut *xraw }; let _val = *xref1; unsafe { *xraw = 4; } // we can now use both xraw and xref1, for reading assert_eq!(*xref1, 4); assert_eq!(unsafe { *xraw }, 4); assert_eq!(*xref1, 4); assert_eq!(unsafe { *xraw }, 4); // we cannot use xref2; see `compile-fail/stacked-borows/illegal_read4.rs` } assert_eq!(x, 4); } fn partially_invalidate_mut() { let data = &mut (0u8, 0u8); let reborrow = &mut *data as *mut (u8, u8); let shard = unsafe { &mut (*reborrow).0 }; data.1 += 1; // the deref overlaps with `shard`, but that is ok; the access does not overlap. *shard += 1; // so we can still use `shard`. assert_eq!(*data, (1, 1)); } // Make sure that we can handle the situation where a loaction is frozen when being dropped. fn drop_after_sharing() { let x = String::from("hello!"); let _len = x.len(); } // Make sure that coercing &mut T to *const T produces a writeable pointer. fn direct_mut_to_const_raw() { // TODO: This is currently disabled, waiting on a decision on <https://github.com/rust-lang/rust/issues/56604> /*let x = &mut 0; let y: *const i32 = x; unsafe { *(y as *mut i32) = 1; } assert_eq!(*x, 1); */ } // Make sure that we can create two raw pointers from a mutable reference and use them both. fn two_raw() { unsafe { let x = &mut 0; let y1 = x as *mut _; let y2 = x as *mut _; *y1 += 2; *y2 += 1; } } // Make sure that creating a *mut does not invalidate existing shared references. fn shr_and_raw() { unsafe { use std::mem; let x = &mut 0; let y1: &i32 = mem::transmute(&*x); // launder lifetimes let y2 = x as *mut _; let _val = *y1; *y2 += 1; } } fn disjoint_mutable_subborrows() { struct Foo { a: String, b: Vec<u32>, } unsafe fn borrow_field_a<'a>(this:*mut Foo) -> &'a mut String { &mut (*this).a } unsafe fn borrow_field_b<'a>(this:*mut Foo) -> &'a mut Vec<u32> { &mut (*this).b } let mut foo = Foo { a: "hello".into(), b: vec![0,1,2], }; let ptr = &mut foo as *mut Foo; let a = unsafe{ borrow_field_a(ptr) }; let b = unsafe{ borrow_field_b(ptr) }; b.push(4); a.push_str(" world"); eprintln!("{:?} {:?}", a, b); } fn raw_ref_to_part() { struct Part { _lame: i32, } #[repr(C)] struct Whole { part: Part, extra: i32, } let it = Box::new(Whole { part: Part { _lame: 0 }, extra: 42 }); let whole = ptr::addr_of_mut!(*Box::leak(it)); let part = unsafe { ptr::addr_of_mut!((*whole).part) }; let typed = unsafe { &mut *(part as *mut Whole) }; assert!(typed.extra == 42); drop(unsafe { Box::from_raw(whole) }); }
read_does_not_invalidate1