file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
common.rs
use super::{Map, TileType}; use std::cmp::{max, min}; #[derive(PartialEq, Copy, Clone)] #[allow(dead_code)] pub enum Symmetry { None, Horizontal, Vertical, Both } pub fn apply_horizontal_tunnel(map : &mut Map, x1:i32, x2:i32, y:i32) -> Vec<usize>
pub fn apply_vertical_tunnel(map : &mut Map, y1:i32, y2:i32, x:i32) -> Vec<usize> { let mut corridor = Vec::new(); for y in min(y1,y2) ..= max(y1,y2) { let idx = map.xy_idx(x, y); if idx > 0 && idx < map.width as usize * map.height as usize && map.tiles[idx as usize] != TileType::Floor { corridor.push(idx); map.tiles[idx as usize] = TileType::Floor; } } corridor } pub fn draw_corridor(map: &mut Map, x1:i32, y1:i32, x2:i32, y2:i32) -> Vec<usize> { let mut corridor = Vec::new(); let mut x = x1; let mut y = y1; while x != x2 || y != y2 { if x < x2 { x += 1; } else if x > x2 { x -= 1; } else if y < y2 { y += 1; } else if y > y2 { y -= 1; } let idx = map.xy_idx(x, y); if map.tiles[idx] != TileType::Floor { corridor.push(idx); map.tiles[idx] = TileType::Floor; } } corridor } pub fn paint(map: &mut Map, mode: Symmetry, brush_size: i32, x: i32, y:i32) { match mode { Symmetry::None => apply_paint(map, brush_size, x, y), Symmetry::Horizontal => { let center_x = map.width / 2; if x == center_x { apply_paint(map, brush_size, x, y); } else { let dist_x = i32::abs(center_x - x); apply_paint(map, brush_size, center_x + dist_x, y); apply_paint(map, brush_size, center_x - dist_x, y); } } Symmetry::Vertical => { let center_y = map.height / 2; if y == center_y { apply_paint(map, brush_size, x, y); } else { let dist_y = i32::abs(center_y - y); apply_paint(map, brush_size, x, center_y + dist_y); apply_paint(map, brush_size, x, center_y - dist_y); } } Symmetry::Both => { let center_x = map.width / 2; let center_y = map.height / 2; if x == center_x && y == center_y { apply_paint(map, brush_size, x, y); } else { let dist_x = i32::abs(center_x - x); apply_paint(map, brush_size, center_x + dist_x, y); apply_paint(map, brush_size, center_x - dist_x, y); let dist_y = i32::abs(center_y - y); apply_paint(map, brush_size, x, center_y + dist_y); apply_paint(map, brush_size, x, center_y - dist_y); } } } } fn apply_paint(map: &mut Map, brush_size: i32, x: i32, y: i32) { match brush_size { 1 => { let digger_idx = map.xy_idx(x, y); map.tiles[digger_idx] = TileType::Floor; } _ => { let half_brush_size = brush_size / 2; for brush_y in y-half_brush_size .. y+half_brush_size { for brush_x in x-half_brush_size .. x+half_brush_size { if brush_x > 1 && brush_x < map.width-1 && brush_y > 1 && brush_y < map.height-1 { let idx = map.xy_idx(brush_x, brush_y); map.tiles[idx] = TileType::Floor; } } } } } }
{ let mut corridor = Vec::new(); for x in min(x1,x2) ..= max(x1,x2) { let idx = map.xy_idx(x, y); if idx > 0 && idx < map.width as usize * map.height as usize && map.tiles[idx as usize] != TileType::Floor { map.tiles[idx as usize] = TileType::Floor; corridor.push(idx as usize); } } corridor }
readwrite.py
### functions for reading from and writing to input files def read_books(books_file='data/input/books.txt'): # reads the file containing the books # ('books.txt' by default) # and returns the list of tuples: # [(author, title), ...] books = [] try: with open(books_file) as file: for line in file: line = line.strip() if len(line) != 0: line = line book = line.split(',') books.append(tuple(book)) except FileNotFoundError: raise FileNotFoundError(f'Books file at {books_file} not found. FIX: make sure the file exists, is in the correct directory and has the correct name') return books def read_ratings(ratings_file='data/input/ratings.txt'): # reads the file containing the rating vectors # ('ratings.txt' by default) # computes the rating index for every user # and returns the dictionary of tuples: # {user: (rating, ...), ...} ratings = {} try: with open(ratings_file) as file: user_flag = True for line in file: line = line.strip() if len(line) != 0: if user_flag: user = line else: rating = line.split() rating = tuple(int(r) for r in rating) ratings.update({user: rating}) user_flag = not user_flag except FileNotFoundError: raise FileNotFoundError(f'Ratings file at {ratings_file} not found. FIX: make sure the file exists, is in the correct directory and has the correct name') return ratings def write_ratings(user, ratings, ratings_file='data/input/ratings.txt'): # takes the new user and their new ratings: # (rating, ...) # and writes them to the file containing the rating vectors # ('ratings.txt' by default) with open(ratings_file, 'a') as file: print(user, file=file) for elt in ratings: print(str(elt) + ' ', end='', file=file) print('', file=file) def printer(recommendations, user, books, ratings, rating_thr, score_thr): # takes the recommendations: # {(user, score): [(book, rating), ...], ...} # and outputs them both to standard output # and to the main output file # 'output-{name}.txt'
def random_printer(r_recommendations, user, books): # takes the random recommendations: # [book, ...] # and outputs them both to standard output # and to the main output file # 'output-{user}.txt' with open(f'data/output/output-{user}.txt', 'w') as file: s = f'* Random recommendations for: {user} *' stars = '*' * len(s) s = stars + '\n' + s + '\n' + stars print(f'Here are your random recommendations, {user}:') print(s, end='\n\n\n', file=file) for i, n in enumerate(r_recommendations): author, book = books[n] s = f'\t{j}.\t{book}'.ljust(50) + f'\n\t\t\tby {author}' print(s, end='\n') print(s, end='\n\n', file=file) print('') print('', file=file) s = f'''{len(r_recommendations)}\tRandom recommendations: for:\t\t\t\t{user} \tsince your ratings are all 0:\t{ratings[user]}''' print(s, file=file)
with open(f'data/output/output-{user}.txt', 'w') as file: s = f'* Recommendations for: {user} *' stars = '*' * len(s) s = stars + '\n' + s + '\n' + stars print(f'Here are your recommendations based on the similarity algorithm, {user}:') print(s, end='\n\n\n', file=file) j = 0 for key, val in recommendations.items(): r_user, score = key s = f'Recommended from: {r_user}'.ljust(55) + f'({score} similarity)'.rjust(15) s += '\n' + '-' * len(s) print(s, end='\n') print(s, end='\n\n', file=file) for i, elt in enumerate(val): n, rating = elt author, book = books[n] j += 1 s = f'\t{j:2d}.\t{book}'.ljust(51) + f'(rated {rating})'.rjust(10) + f'\n\t\t\tby {author}' print(s, end='\n') print(s, end='\n\n', file=file) print('') print('', file=file) s = f'''{j}\tRecommendations based on the similarity algorithm: for:\t\t\t\t{user} \twith ratings:\t{ratings[user]} with rating threshold of:\t{rating_thr} and similarity threshold of:\t{score_thr}''' print(s, file=file) print(f'Check the output file at /data/output/output-{user}.txt and the algorithm log at logs/recommend-{user}_log.txt for more details.') print(f'Check the recommendation algorithm log at logs/recommend-{user}_log.txt for more details about the recommendation process.', file=file)
__init__.py
# # Copyright 2014 "Igor Feoktistov" <[email protected]> # # 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. # Extras by Steven Scott, Mike Patterson University of Waterloo IST-ISS from .infoblox import InfobloxNotFoundException, InfobloxNoIPavailableException, InfobloxGeneralException, Infoblox
run.go
package check import ( "bufio" "flag" "fmt" "os" "testing" "time" ) // ----------------------------------------------------------------------- // Test suite registry. var allSuites []interface{} // Suite registers the given value as a test suite to be run. Any methods // starting with the Test prefix in the given value will be considered as // a test method. func Suite(suite interface{}) interface{} { allSuites = append(allSuites, suite) return suite } // ----------------------------------------------------------------------- // Public running interface. var ( oldFilterFlag = flag.String("gocheck.f", "", "Regular expression selecting which tests and/or suites to run") oldVerboseFlag = flag.Bool("gocheck.v", false, "Verbose mode") oldStreamFlag = flag.Bool("gocheck.vv", false, "Super verbose mode (disables output caching)") oldBenchFlag = flag.Bool("gocheck.b", false, "Run benchmarks") oldBenchTime = flag.Duration("gocheck.btime", 1*time.Second, "approximate run time for each benchmark") oldListFlag = flag.Bool("gocheck.list", false, "List the names of all tests that will be run") oldWorkFlag = flag.Bool("gocheck.work", false, "Display and do not remove the test working directory") newFilterFlag = flag.String("check.f", "", "Regular expression selecting which tests and/or suites to run") newVerboseFlag = flag.Bool("check.v", false, "Verbose mode") newStreamFlag = flag.Bool("check.vv", false, "Super verbose mode (disables output caching)") newBenchFlag = flag.Bool("check.b", false, "Run benchmarks") newBenchTime = flag.Duration("check.btime", 1*time.Second, "approximate run time for each benchmark") newBenchMem = flag.Bool("check.bmem", false, "Report memory benchmarks") newListFlag = flag.Bool("check.list", false, "List the names of all tests that will be run") newWorkFlag = flag.Bool("check.work", false, "Display and do not remove the test working directory") checkTimeout = flag.String("check.timeout", "", "Panic if test runs longer than specified duration") ) // TestingT runs all test suites registered with the Suite function, // printing results to stdout, and reporting any failures back to // the "testing" package. func TestingT(testingT *testing.T) { benchTime := *newBenchTime if benchTime == 1*time.Second { benchTime = *oldBenchTime } conf := &RunConf{ Filter: *oldFilterFlag + *newFilterFlag, Verbose: *oldVerboseFlag || *newVerboseFlag, Stream: *oldStreamFlag || *newStreamFlag, Benchmark: *oldBenchFlag || *newBenchFlag, BenchmarkTime: benchTime, BenchmarkMem: *newBenchMem, KeepWorkDir: *oldWorkFlag || *newWorkFlag, } if *checkTimeout != "" { timeout, err := time.ParseDuration(*checkTimeout) if err != nil { testingT.Fatalf("error parsing specified timeout flag: %v", err) } conf.CheckTimeout = timeout } if *oldListFlag || *newListFlag { w := bufio.NewWriter(os.Stdout) for _, name := range ListAll(conf) { fmt.Fprintln(w, name) } w.Flush() return } result := RunAll(conf) println(result.String()) if !result.Passed() { testingT.Fail() } } // RunAll runs all test suites registered with the Suite function, using the // provided run configuration. func RunAll(runConf *RunConf) *Result { result := Result{} for _, suite := range allSuites { result.Add(Run(suite, runConf)) } return &result } // Run runs the provided test suite using the provided run configuration. func Run(suite interface{}, runConf *RunConf) *Result { runner := newSuiteRunner(suite, runConf) return runner.run() } // ListAll returns the names of all the test functions registered with the // Suite function that will be run with the provided run configuration. func ListAll(runConf *RunConf) []string { var names []string for _, suite := range allSuites { names = append(names, List(suite, runConf)...) } return names } // List returns the names of the test functions in the given // suite that will be run with the provided run configuration. func
(suite interface{}, runConf *RunConf) []string { var names []string runner := newSuiteRunner(suite, runConf) for _, t := range runner.tests { names = append(names, t.String()) } return names } // ----------------------------------------------------------------------- // Result methods. func (r *Result) Add(other *Result) { r.Succeeded += other.Succeeded r.Skipped += other.Skipped r.Failed += other.Failed r.Panicked += other.Panicked r.FixturePanicked += other.FixturePanicked r.ExpectedFailures += other.ExpectedFailures r.Missed += other.Missed if r.WorkDir != "" && other.WorkDir != "" { r.WorkDir += ":" + other.WorkDir } else if other.WorkDir != "" { r.WorkDir = other.WorkDir } } func (r *Result) Passed() bool { return (r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 && r.Missed == 0 && r.RunError == nil) } func (r *Result) String() string { if r.RunError != nil { return "ERROR: " + r.RunError.Error() } var value string if r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 && r.Missed == 0 { value = "OK: " } else { value = "OOPS: " } value += fmt.Sprintf("%d passed", r.Succeeded) if r.Skipped != 0 { value += fmt.Sprintf(", %d skipped", r.Skipped) } if r.ExpectedFailures != 0 { value += fmt.Sprintf(", %d expected failures", r.ExpectedFailures) } if r.Failed != 0 { value += fmt.Sprintf(", %d FAILED", r.Failed) } if r.Panicked != 0 { value += fmt.Sprintf(", %d PANICKED", r.Panicked) } if r.FixturePanicked != 0 { value += fmt.Sprintf(", %d FIXTURE-PANICKED", r.FixturePanicked) } if r.Missed != 0 { value += fmt.Sprintf(", %d MISSED", r.Missed) } if r.WorkDir != "" { value += "\nWORK=" + r.WorkDir } return value }
List
chunker.rs
// Copyright (c) 2016-2018 The http-serve developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use futures::channel::mpsc; use futures::Stream; use std::io::{self, Write}; use std::mem; /// A `std::io::Write` implementation that makes a chunked hyper response body stream. /// Raw in the sense that it doesn't apply content encoding and isn't particularly user-friendly: /// unflushed data is ignored on drop. /// /// Produces chunks of `Vec<u8>` or a type that implements `From<Vec<u8>>` such as /// `reffers::ARefs<'static, [u8]>`. Currently the chunks are all of the capacity given in the /// constructor. On flush, chunks may satisfy `0 < len < capacity`; otherwise they will satisfy /// `0 < len == capacity`. /// /// The stream is infinitely buffered; calls to `write` and `flush` never block. `flush` thus is a /// hint that data should be sent to the client as soon as possible, but this shouldn't be expected /// to happen before it returns. pub(crate) struct BodyWriter<D, E> where D: From<Vec<u8>> + Send + 'static, E: Send + 'static, { sender: mpsc::UnboundedSender<Result<D, E>>, /// The next buffer to use. Invariant: capacity > len. buf: Vec<u8>, } impl<D, E> BodyWriter<D, E> where D: From<Vec<u8>> + Send + 'static, E: Send + 'static, { pub(crate) fn with_chunk_size( cap: usize, ) -> (Self, Box<dyn Stream<Item = Result<D, E>> + Send>)
/// Causes the HTTP connection to be dropped abruptly with the given error. pub(crate) fn abort(&mut self, error: E) { // hyper drops the connection when the stream contains an error. let _ = self.sender.unbounded_send(Err(error)); } /// Truncates the output buffer (for testing). #[cfg(test)] fn truncate(&mut self) { self.buf.clear() } } impl<D, E> Write for BodyWriter<D, E> where D: From<Vec<u8>> + Send + 'static, E: Send + 'static, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let remaining = self.buf.capacity() - self.buf.len(); let full = remaining <= buf.len(); let bytes = if full { remaining } else { buf.len() }; self.buf.extend_from_slice(&buf[0..bytes]); if full { self.flush()?; } Ok(bytes) } fn flush(&mut self) -> io::Result<()> { if !self.buf.is_empty() { let cap = self.buf.capacity(); let full_buf = mem::replace(&mut self.buf, Vec::with_capacity(cap)); if let Err(_) = self.sender.unbounded_send(Ok(full_buf.into())) { // If this error is returned, no further writes will succeed either. // Therefore, it's acceptable to just drop the full_buf (now e.into_inner()) // rather than put it back as self.buf; it won't cause us to write a stream with // a gap. return Err(io::Error::new( io::ErrorKind::BrokenPipe, "receiver was dropped", )); } } Ok(()) } } impl<D, E> Drop for BodyWriter<D, E> where D: From<Vec<u8>> + Send + 'static, E: Send + 'static, { fn drop(&mut self) { let _ = self.flush(); } } #[cfg(test)] mod tests { use super::BodyWriter; use futures::{stream::StreamExt, stream::TryStreamExt, Stream}; use std::io::Write; use std::pin::Pin; type BoxedError = Box<dyn std::error::Error + 'static + Send + Sync>; type BodyStream = Box<dyn Stream<Item = Result<Vec<u8>, BoxedError>> + Send>; async fn to_vec(s: BodyStream) -> Vec<u8> { Pin::from(s).try_concat().await.unwrap() } // A smaller-than-chunk-size write shouldn't be flushed on write, and there's currently no Drop // implementation to do it either. #[tokio::test] async fn small_no_flush() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); assert_eq!(w.write(b"1").unwrap(), 1); w.truncate(); drop(w); assert_eq!(b"", &to_vec(body).await[..]); } // With a flush, the content should show up. #[tokio::test] async fn small_flush() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); assert_eq!(w.write(b"1").unwrap(), 1); w.flush().unwrap(); drop(w); assert_eq!(b"1", &to_vec(body).await[..]); } // A write of exactly the chunk size should be automatically flushed. #[tokio::test] async fn chunk_write() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); assert_eq!(w.write(b"1234").unwrap(), 4); w.flush().unwrap(); drop(w); assert_eq!(b"1234", &to_vec(body).await[..]); } // ...and everything should be set up for the next write as well. #[tokio::test] async fn chunk_double_write() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); assert_eq!(w.write(b"1234").unwrap(), 4); assert_eq!(w.write(b"5678").unwrap(), 4); w.flush().unwrap(); drop(w); assert_eq!(b"12345678", &to_vec(body).await[..]); } // A larger-than-chunk-size write should be turned into a chunk-size write. #[tokio::test] async fn large_write() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); assert_eq!(w.write(b"123456").unwrap(), 4); drop(w); assert_eq!(b"1234", &to_vec(body).await[..]); } // ...similarly, one that uses all the remaining capacity of the chunk. #[tokio::test] async fn small_large_write() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); assert_eq!(w.write(b"1").unwrap(), 1); assert_eq!(w.write(b"2345").unwrap(), 3); drop(w); assert_eq!(b"1234", &to_vec(body).await[..]); } // Aborting should add an Err element to the stream, ignoring any unflushed bytes. #[tokio::test] async fn abort() { let (mut w, body): (_, BodyStream) = BodyWriter::with_chunk_size(4); w.write_all(b"12345").unwrap(); w.truncate(); w.abort(Box::new(std::io::Error::new( std::io::ErrorKind::Other, "asdf", ))); drop(w); let items = Pin::<_>::from(body) .collect::<Vec<Result<Vec<u8>, BoxedError>>>() .await; assert_eq!(items.len(), 2); assert_eq!(b"1234", &items[0].as_ref().unwrap()[..]); items[1].as_ref().unwrap_err(); } }
{ assert!(cap > 0); let (snd, rcv) = mpsc::unbounded(); let body = Box::new(rcv); ( BodyWriter { sender: snd, buf: Vec::with_capacity(cap), }, body, ) }
ssh_key_batchmode_test.go
package ssh_config import "testing" // BatchMode // If set to “yes”, passphrase/password querying will be disabled. // In addition, the ServerAliveInterval option will be set to 300 // seconds by default. This option is useful in scripts and other // batch jobs where no user is present to supply the password, and // where it is desirable to detect a broken network swiftly. The // argument must be “yes” or “no”. The default is “no”. // func TestBatchModeInitFunc(t *testing.T) { defer func() { if err := recover(); err != nil { t.Errorf("panic in test is not acceptable") } }() f, ok := mapInit[BatchMode] if !ok { t.Errorf("Cannot found init-function") } if f == nil { t.Errorf("Init-function is nil") } if f() == "" { // TODO t.Errorf("Not acceptable empty init value") } } func TestBatchModeValidFunc(t *testing.T) { defer func() { if err := recover(); err != nil { t.Errorf("panic in test is not acceptable") } }() f, ok := mapValid[BatchMode] if !ok { t.Errorf("Cannot found valid-function") } if f == nil { t.Errorf("Valid-function is nil") } if !f("") { // TODO t.Errorf("Not acceptable empty valid-value") } } func TestBatchModePar
defer func() { if err := recover(); err != nil { t.Errorf("panic in test is not acceptable") } }() f, ok := mapParse[BatchMode] if !ok { t.Errorf("Cannot found parse-function") } if f == nil { t.Errorf("Parse-function is nil") } // TODO }
seFunc(t *testing.T) {
stone_game_iv.go
package leetcode import ( "math" ) // Time complexity: O(sqrt(n) * n) // Space complexity: O(n) // Iterative bottom up solution func winnerSquareGame(n int) bool { dp := make([]bool, n+1) for i := 1; i < n+1; i++ { upper := int(math.Sqrt(float64(i))) for j := upper; j > 0; j-- { if dp[i-j*j] == false { dp[i] = true break } } } return dp[len(dp)-1] } // Time complexity: O(sqrt(n) * n) // Space complexity: O(n) // Recursive top down solution func winnerSquareGame2(n int) bool { var solve func(int, map[int]bool) bool solve = func(n int, memo map[int]bool) bool { if n == 0 { return false } if val, ok := memo[n]; ok == true { return val }
memo[n] = true return true } } memo[n] = false return false } return solve(n, make(map[int]bool)) }
upper := int(math.Sqrt(float64(n))) for i := upper; i > 0; i-- { if solve(n-i*i, memo) == false {
test_transaction_service.py
from datetime import timedelta from django.test import TestCase from django.utils import timezone from eth_account import Account from ..models import EthereumTx, ModuleTransaction, MultisigTransaction from ..services.transaction_service import (TransactionService, TransactionServiceProvider) from .factories import (EthereumEventFactory, InternalTxFactory, ModuleTransactionFactory, MultisigTransactionFactory) class TestTransactionService(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.transaction_service: TransactionService = TransactionServiceProvider() cls.transaction_service.redis.flushall() def tearDown(self): super().tearDown() self.transaction_service.redis.flushall() def test_get_all_tx_hashes(self): transaction_service: TransactionService = self.transaction_service safe_address = Account.create().address self.assertFalse(transaction_service.get_all_tx_hashes(safe_address)) # Factories create the models using current datetime, so as the txs are returned sorted they should be # in the reverse order that they were created multisig_transaction = MultisigTransactionFactory(safe=safe_address) multisig_transaction_not_mined = MultisigTransactionFactory(safe=safe_address, nonce=multisig_transaction.nonce, ethereum_tx=None) module_transaction = ModuleTransactionFactory(safe=safe_address) internal_tx_in = InternalTxFactory(to=safe_address, value=4) internal_tx_out = InternalTxFactory(_from=safe_address, value=5) # Should not appear erc20_transfer_in = EthereumEventFactory(to=safe_address) erc20_transfer_out = EthereumEventFactory(from_=safe_address) # Should not appear another_multisig_transaction = MultisigTransactionFactory(safe=safe_address) another_safe_multisig_transaction = MultisigTransactionFactory() # Should not appear, it's for another Safe # Should not appear unless queued=True, nonce > last mined transaction higher_nonce_safe_multisig_transaction = MultisigTransactionFactory(safe=safe_address, ethereum_tx=None) higher_nonce_safe_multisig_transaction_2 = MultisigTransactionFactory(safe=safe_address, ethereum_tx=None) # As there is no multisig tx trusted, just module txs and transfers are returned self.assertEqual(transaction_service.get_all_tx_hashes(safe_address, queued=False, trusted=True).count(), 4) # We change a queued tx, a change was not expected unless we set queued=True higher_nonce_safe_multisig_transaction.trusted = True higher_nonce_safe_multisig_transaction.save() self.assertEqual(transaction_service.get_all_tx_hashes(safe_address, queued=False, trusted=True).count(), 4) self.assertEqual(transaction_service.get_all_tx_hashes(safe_address, queued=True, trusted=True).count(), 5) queryset = transaction_service.get_all_tx_hashes(safe_address, queued=True, trusted=False) self.assertEqual(queryset.count(), 9) queryset = transaction_service.get_all_tx_hashes(safe_address, queued=False, trusted=False) self.assertEqual(queryset.count(), 7) every_execution_date = [element['execution_date'] for element in queryset] expected_times = [ another_multisig_transaction.ethereum_tx.block.timestamp, erc20_transfer_out.ethereum_tx.block.timestamp, erc20_transfer_in.ethereum_tx.block.timestamp, internal_tx_in.ethereum_tx.block.timestamp, module_transaction.internal_tx.ethereum_tx.block.timestamp, multisig_transaction.ethereum_tx.block.timestamp,
all_tx_hashes = [element['safe_tx_hash'] for element in queryset] expected_hashes = [another_multisig_transaction.safe_tx_hash, erc20_transfer_out.ethereum_tx_id, erc20_transfer_in.ethereum_tx_id, internal_tx_in.ethereum_tx_id, module_transaction.internal_tx.ethereum_tx_id, multisig_transaction.safe_tx_hash, # First the mined tx multisig_transaction_not_mined.safe_tx_hash] self.assertEqual(all_tx_hashes, expected_hashes) queryset = transaction_service.get_all_tx_hashes(safe_address, trusted=True, queued=False) self.assertEqual(queryset.count(), 4) def test_get_all_tx_hashes_queued(self): transaction_service: TransactionService = self.transaction_service safe_address = Account.create().address # No mined tx, so nothing is returned MultisigTransactionFactory(safe=safe_address, ethereum_tx=None) MultisigTransactionFactory(safe=safe_address, ethereum_tx=None) self.assertEqual(transaction_service.get_all_tx_hashes(safe_address, queued=False, trusted=False).count(), 0) self.assertEqual(transaction_service.get_all_tx_hashes(safe_address, queued=True, trusted=False).count(), 2) # Mine tx with higher nonce, all should appear MultisigTransactionFactory(safe=safe_address) self.assertEqual(transaction_service.get_all_tx_hashes(safe_address, queued=False, trusted=False).count(), 3) def test_get_all_tx_nonce_sorting(self): transaction_service: TransactionService = self.transaction_service safe_address = Account.create().address # Test edge case of 2 multisig transactions inside the same ethereum transaction m_1 = MultisigTransactionFactory(safe=safe_address, trusted=True, nonce=1) MultisigTransactionFactory(safe=safe_address, trusted=True, ethereum_tx=m_1.ethereum_tx, nonce=0) # Test sorting queryset = transaction_service.get_all_tx_hashes(safe_address) tx_hashes = list([q['safe_tx_hash'] for q in queryset]) transactions = transaction_service.get_all_txs_from_hashes(safe_address, tx_hashes) self.assertEqual(transactions[0].nonce, 1) self.assertEqual(transactions[1].nonce, 0) def test_get_all_txs_from_hashes(self): transaction_service: TransactionService = self.transaction_service safe_address = Account.create().address self.assertFalse(transaction_service.get_all_tx_hashes(safe_address)) # Factories create the models using current datetime, so as the txs are returned sorted they should be # in the reverse order that they were created multisig_transaction = MultisigTransactionFactory(safe=safe_address, ethereum_tx__block__timestamp=timezone.now() - timedelta(days=1)) module_transaction = ModuleTransactionFactory(safe=safe_address) internal_tx_in = InternalTxFactory(to=safe_address, value=4) internal_tx_out = InternalTxFactory(_from=safe_address, value=5) erc20_transfer_in = EthereumEventFactory(to=safe_address) erc20_transfer_out = EthereumEventFactory(from_=safe_address) # Should not appear another_multisig_transaction = MultisigTransactionFactory(safe=safe_address) another_safe_multisig_transaction = MultisigTransactionFactory() # Should not appear, it's for another Safe queryset = transaction_service.get_all_tx_hashes( safe_address, queued=False, trusted=False ) all_tx_hashes = list([q['safe_tx_hash'] for q in queryset]) self.assertEqual(len(self.transaction_service.redis.keys('*')), 0) all_txs = transaction_service.get_all_txs_from_hashes(safe_address, all_tx_hashes) self.assertEqual(len(self.transaction_service.redis.keys('*')), 1) all_txs = transaction_service.get_all_txs_from_hashes(safe_address, all_tx_hashes) # Force caching self.assertEqual(len(self.transaction_service.redis.keys('*')), 1) self.assertEqual(len(all_txs), 6) tx_types = [MultisigTransaction, EthereumTx, EthereumTx, EthereumTx, ModuleTransaction, MultisigTransaction] numbers_of_transfers = [0, 1, 1, 1, 0, 0] for tx, tx_type, number_of_transfers in zip(all_txs, tx_types, numbers_of_transfers): self.assertEqual(type(tx), tx_type) self.assertEqual(len(tx.transfers), number_of_transfers) for transfer in tx.transfers: self.assertIsNone(transfer['token']) # Insert 2 transfers for the MultisigTx and one for the ModuleTx internal_tx_out_2 = InternalTxFactory(_from=safe_address, value=5, ethereum_tx=another_multisig_transaction.ethereum_tx) erc20_transfer_in_2 = EthereumEventFactory(to=safe_address, ethereum_tx=another_multisig_transaction.ethereum_tx) internal_tx_in_2 = InternalTxFactory(to=safe_address, value=4, ethereum_tx=module_transaction.internal_tx.ethereum_tx) queryset_2 = transaction_service.get_all_tx_hashes( safe_address, queued=False, trusted=False ) all_tx_hashes_2 = list([q['safe_tx_hash'] for q in queryset_2]) all_txs_2 = transaction_service.get_all_txs_from_hashes(safe_address, all_tx_hashes_2) self.assertEqual(len(all_txs_2), 6) tx_types = [MultisigTransaction, EthereumTx, EthereumTx, EthereumTx, ModuleTransaction, MultisigTransaction] numbers_of_transfers = [0 + 2, 1, 1, 1, 0 + 1, 0] for tx, tx_type, number_of_transfers in zip(all_txs_2, tx_types, numbers_of_transfers): self.assertEqual(type(tx), tx_type) self.assertEqual(len(tx.transfers), number_of_transfers) for transfer in tx.transfers: self.assertIsNone(transfer['token']) all_txs_serialized = transaction_service.serialize_all_txs(all_txs_2) self.assertEqual(len(all_txs_serialized), len(all_txs_2)) for tx_serialized in all_txs_serialized: self.assertTrue(isinstance(tx_serialized, dict))
multisig_transaction.ethereum_tx.block.timestamp, # Should take timestamp from tx with same nonce and mined ] self.assertEqual(every_execution_date, expected_times)
tri.rs
use crate::math::{Ray, Vec3}; use crate::geom; #[derive(Copy, Clone, Debug)] pub struct Tri<'scene> { vertices: [&'scene Vec3; 3],
pub fn new(vertices: [&'scene Vec3; 3], normals: [&'scene Vec3; 3]) -> Self { Tri { vertices, normals } } } impl<'scene> geom::Surface<'scene> for Tri<'scene> { fn bound(&self) -> geom::Box3 { geom::Box3::new(*self.vertices[0], *self.vertices[1]) .union_v(self.vertices[2]) } fn hit(&self, ray: &mut Ray, hit: &mut geom::Hit<'scene>) -> bool { if cfg!(feature = "stats") { crate::stats::INTERSECTION_TESTS.inc(); crate::stats::TRI_INTERSECTION_TESTS.inc(); } const EPSILON: f32 = 0.0000001; let edge_a = self.vertices[1] - self.vertices[0]; let edge_b = self.vertices[2] - self.vertices[0]; let h = ray.d.cross(&edge_b); let det = edge_a.dot(&h); if det > -EPSILON && det < EPSILON { return false } let inv = 1.0 / det; let s = ray.p - self.vertices[0]; let u = inv * s.dot(&h); if u < 0.0 || u > 1.0 { return false } let q = s.cross(&edge_a); let v = inv * ray.d.dot(&q); if v < 0.0 || u + v > 1.0 { return false } let t = inv * edge_b.dot(&q); if t < ray.min || t > ray.max { return false } let w = 1.0 - u - v; ray.set_max(t); hit.t = t; hit.p = self.vertices[0] * w + self.vertices[1] * u + self.vertices[2] * v; hit.n = ( self.normals[0] * w + self.normals[1] * u + self.normals[2] * v ).normalize(); true } fn hit_any(&self, ray: &Ray) -> bool { if cfg!(feature = "stats") { crate::stats::INTERSECTION_TESTS.inc(); crate::stats::TRI_INTERSECTION_TESTS.inc(); } const EPSILON: f32 = 0.0000001; let edge_a = self.vertices[1] - self.vertices[0]; let edge_b = self.vertices[2] - self.vertices[0]; let h = ray.d.cross(&edge_b); let det = edge_a.dot(&h); if det > -EPSILON && det < EPSILON { return false } let inv = 1.0 / det; let s = ray.p - self.vertices[0]; let u = inv * s.dot(&h); if u < 0.0 || u > 1.0 { return false } let q = s.cross(&edge_a); let v = inv * ray.d.dot(&q); if v < 0.0 || u + v > 1.0 { return false } let t = inv * edge_b.dot(&q); t >= ray.min && t <= ray.max } }
normals: [&'scene Vec3; 3], } impl<'scene> Tri<'scene> {
sess_couchbase.go
// Copyright 2014 beego Author. 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. // Package couchbase for session provider // // depend on github.com/couchbaselabs/go-couchbasee // // go install github.com/couchbaselabs/go-couchbase // // Usage: // import( // _ "github.com/ie310mu/ie310go/session/couchbase" // "github.com/ie310mu/ie310go/session" // ) // // func init() { // globalSessions, _ = session.NewManager("couchbase", ``{"cookieName":"gosessionid","gclifetime":3600,"ProviderConfig":"http://host:port/, Pool, Bucket"}``) // go globalSessions.GC() // } // // more docs: http://beego.me/docs/module/session.md package couchbase import ( "net/http" "strings" "sync" "github.com/ie310mu/ie310go/session" couchbase "github.com/couchbase/go-couchbase" ) var couchbpder = &Provider{} // SessionStore store each session type SessionStore struct { b *couchbase.Bucket sid string lock sync.RWMutex values map[interface{}]interface{} maxlifetime int64 } // Provider couchabse provided type Provider struct { maxlifetime int64 savePath string pool string bucket string b *couchbase.Bucket } // Set value to couchabse session func (cs *SessionStore) Set(key, value interface{}) error { cs.lock.Lock() defer cs.lock.Unlock() cs.values[key] = value return nil } // Get value from couchabse session func (cs *SessionStore) Get(key interface{}) interface{} { cs.lock.RLock() defer cs.lock.RUnlock() if v, ok := cs.values[key]; ok { return v } return nil } // Delete value in couchbase session by given key func (cs *SessionStore) Delete(key interface{}) error { cs.lock.Lock() defer cs.lock.Unlock() delete(cs.values, key) return nil } // Flush Clean all values in couchbase session func (cs *SessionStore) Flush() error { cs.lock.Lock() defer cs.lock.Unlock() cs.values = make(map[interface{}]interface{}) return nil } // SessionID Get couchbase session store id func (cs *SessionStore) SessionID() string { return cs.sid } // SessionRelease Write couchbase session with Gob string func (cs *SessionStore) SessionRelease(w http.ResponseWriter) { defer cs.b.Close() bo, err := session.EncodeGob(cs.values) if err != nil { return } cs.b.Set(cs.sid, int(cs.maxlifetime), bo) } func (cp *Provider) getBucket() *couchbase.Bucket { c, err := couchbase.Connect(cp.savePath) if err != nil { return nil } pool, err := c.GetPool(cp.pool) if err != nil { return nil } bucket, err := pool.GetBucket(cp.bucket) if err != nil { return nil } return bucket } // SessionInit init couchbase session // savepath like couchbase server REST/JSON URL // e.g. http://host:port/, Pool, Bucket func (cp *Provider) SessionInit(maxlifetime int64, savePath string) error { cp.maxlifetime = maxlifetime configs := strings.Split(savePath, ",") if len(configs) > 0 { cp.savePath = configs[0] } if len(configs) > 1 { cp.pool = configs[1] } if len(configs) > 2 { cp.bucket = configs[2] } return nil } // SessionRead read couchbase session by sid func (cp *Provider) SessionRead(sid string) (session.Store, error) { cp.b = cp.getBucket() var ( kv map[interface{}]interface{} err error doc []byte ) err = cp.b.Get(sid, &doc) if err != nil { return nil, err } else if doc == nil { kv = make(map[interface{}]interface{}) } else { kv, err = session.DecodeGob(doc) if err != nil { return nil, err } } cs := &SessionStore{b: cp.b, sid: sid, values: kv, maxlifetime: cp.maxlifetime} return cs, nil } // SessionExist Check couchbase session exist. // it checkes sid exist or not. func (cp *Provider) SessionExist(sid string) bool { cp.b = cp.getBucket() defer cp.b.Close() var doc []byte if err := cp.b.Get(sid, &doc); err != nil || doc == nil { return false } return true } // SessionRegenerate remove oldsid and use sid to generate new session func (cp *Provider) SessionRegenerate(oldsid, sid string) (session.Store, error) { cp.b = cp.getBucket() var doc []byte if err := cp.b.Get(oldsid, &doc); err != nil || doc == nil { cp.b.Set(sid, int(cp.maxlifetime), "") } else { err := cp.b.Delete(oldsid) if err != nil { return nil, err } _, _ = cp.b.Add(sid, int(cp.maxlifetime), doc) } err := cp.b.Get(sid, &doc) if err != nil { return nil, err } var kv map[interface{}]interface{} if doc == nil { kv = make(map[interface{}]interface{}) } else { kv, err = session.DecodeGob(doc) if err != nil { return nil, err } } cs := &SessionStore{b: cp.b, sid: sid, values: kv, maxlifetime: cp.maxlifetime} return cs, nil } // SessionDestroy Remove bucket in this couchbase func (cp *Provider) SessionDestroy(sid string) error { cp.b = cp.getBucket() defer cp.b.Close() cp.b.Delete(sid) return nil } // SessionGC Recycle func (cp *Provider) SessionGC() { } // SessionAll return all active session func (cp *Provider) SessionAll() int {
func init() { session.Register("couchbase", couchbpder) }
return 0 }
chandata.go
package proto import ( "bytes" "errors" "io" ) // ChannelData represents The ChannelData Message. // // See RFC 5766 Section 11.4 type ChannelData struct { Data []byte // can be subslice of Raw Length int // ignored while encoding, len(Data) is used Number ChannelNumber Raw []byte } // Equal returns true if b == c. func (c *ChannelData) Equal(b *ChannelData) bool { if c == nil && b == nil { return true } if c == nil || b == nil { return false } if c.Number != b.Number { return false } if len(c.Data) != len(b.Data) { return false } return bytes.Equal(c.Data, b.Data) } // grow ensures that internal buffer will fit v more bytes and // increases it capacity if necessary. // // Similar to stun.Message.grow method. func (c *ChannelData) grow(v int) { n := len(c.Raw) + v for cap(c.Raw) < n { c.Raw = append(c.Raw, 0) } c.Raw = c.Raw[:n] } // Reset resets Length, Data and Raw length. func (c *ChannelData) Reset() { c.Raw = c.Raw[:0] c.Length = 0 c.Data = c.Data[:0] } // Encode encodes ChannelData Message to Raw. func (c *ChannelData) Encode() { c.Raw = c.Raw[:0] c.WriteHeader() c.Raw = append(c.Raw, c.Data...) padded := nearestPaddedValueLength(len(c.Raw)) if bytesToAdd := padded - len(c.Raw); bytesToAdd > 0 { for i := 0; i < bytesToAdd; i++ { c.Raw = append(c.Raw, 0) } } } const padding = 4 func nearestPaddedValueLength(l int) int { n := padding * (l / padding) if n < l { n += padding } return n } // WriteHeader writes channel number and length. func (c *ChannelData) WriteHeader() { if len(c.Raw) < channelDataHeaderSize { // Making WriteHeader call valid even when c.Raw // is nil or len(c.Raw) is less than needed for header. c.grow(channelDataHeaderSize) } // Early bounds check to guarantee safety of writes below. _ = c.Raw[:channelDataHeaderSize] bin.PutUint16(c.Raw[:channelDataNumberSize], uint16(c.Number)) bin.PutUint16(c.Raw[channelDataNumberSize:channelDataHeaderSize], uint16(len(c.Data)), ) } // ErrBadChannelDataLength means that channel data length is not equal // to actual data length. var ErrBadChannelDataLength = errors.New("channelData length != len(Data)") // Decode decodes The ChannelData Message from Raw. func (c *ChannelData) Decode() error { buf := c.Raw if len(buf) < channelDataHeaderSize { return io.ErrUnexpectedEOF } num := bin.Uint16(buf[:channelDataNumberSize]) c.Number = ChannelNumber(num) l := bin.Uint16(buf[channelDataNumberSize:channelDataHeaderSize]) c.Data = buf[channelDataHeaderSize:] c.Length = int(l) if !c.Number.Valid() { return ErrInvalidChannelNumber } if int(l) < len(c.Data) { c.Data = c.Data[:int(l)] } if int(l) > len(buf[channelDataHeaderSize:]) { return ErrBadChannelDataLength } return nil } const ( channelDataLengthSize = 2 channelDataNumberSize = channelDataLengthSize channelDataHeaderSize = channelDataLengthSize + channelDataNumberSize ) // IsChannelData returns true if buf looks like the ChannelData Message. func
(buf []byte) bool { if len(buf) < channelDataHeaderSize { return false } // Quick check for channel number. num := bin.Uint16(buf[0:channelNumberSize]) return isChannelNumberValid(num) }
IsChannelData
check.rs
use std::fmt::{self, Write}; use glob::glob; use support::install::exe; use support::paths::CargoPathExt; use support::registry::Package; use support::{basic_manifest, project}; #[test] fn check_success() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", "extern crate bar; fn main() { ::bar::baz(); }", ).build(); let _bar = project() .at("bar") .file("Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("src/lib.rs", "pub fn baz() {}") .build(); foo.cargo("check").run(); } #[test] fn check_fail() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", "extern crate bar; fn main() { ::bar::baz(42); }", ).build(); let _bar = project() .at("bar") .file("Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("src/lib.rs", "pub fn baz() {}") .build(); foo.cargo("check").with_status(101).run(); } #[test] fn custom_derive() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", r#" #[macro_use] extern crate bar; trait B { fn b(&self); } #[derive(B)] struct A; fn main() { let a = A; a.b(); } "#, ).build(); let _bar = project()
.at("bar") .file( "Cargo.toml", r#" [package] name = "bar" version = "0.1.0" authors = [] [lib] proc-macro = true "#, ).file( "src/lib.rs", r#" extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(B)] pub fn derive(_input: TokenStream) -> TokenStream { format!("impl B for A {{ fn b(&self) {{}} }}").parse().unwrap() } "#, ).build(); foo.cargo("check").run(); } #[test] fn check_build() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", "extern crate bar; fn main() { ::bar::baz(); }", ).build(); let _bar = project() .at("bar") .file("Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("src/lib.rs", "pub fn baz() {}") .build(); foo.cargo("check").run(); foo.cargo("build").run(); } #[test] fn build_check() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", "extern crate bar; fn main() { ::bar::baz(); }", ).build(); let _bar = project() .at("bar") .file("Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("src/lib.rs", "pub fn baz() {}") .build(); foo.cargo("build").run(); foo.cargo("check").run(); } // Checks that where a project has both a lib and a bin, the lib is only checked // not built. #[test] fn issue_3418() { let foo = project() .file("src/lib.rs", "") .file("src/main.rs", "fn main() {}") .build(); foo.cargo("check -v") .with_stderr_contains("[..] --emit=dep-info,metadata [..]") .run(); } // Some weirdness that seems to be caused by a crate being built as well as // checked, but in this case with a proc macro too. #[test] fn issue_3419() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies] rustc-serialize = "*" "#, ).file( "src/lib.rs", r#" extern crate rustc_serialize; use rustc_serialize::Decodable; pub fn take<T: Decodable>() {} "#, ).file( "src/main.rs", r#" extern crate rustc_serialize; extern crate foo; #[derive(RustcDecodable)] pub struct Foo; fn main() { foo::take::<Foo>(); } "#, ).build(); Package::new("rustc-serialize", "1.0.0") .file( "src/lib.rs", r#"pub trait Decodable: Sized { fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error>; } pub trait Decoder { type Error; fn read_struct<T, F>(&mut self, s_name: &str, len: usize, f: F) -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error>; } "#, ).publish(); p.cargo("check").run(); } // Check on a dylib should have a different metadata hash than build. #[test] fn dylib_check_preserves_build_cache() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" authors = [] [lib] crate-type = ["dylib"] [dependencies] "#, ).file("src/lib.rs", "") .build(); p.cargo("build") .with_stderr( "\ [..]Compiling foo v0.1.0 ([..]) [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ", ).run(); p.cargo("check").run(); p.cargo("build") .with_stderr("[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]") .run(); } // test `cargo rustc --profile check` #[test] fn rustc_check() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", "extern crate bar; fn main() { ::bar::baz(); }", ).build(); let _bar = project() .at("bar") .file("Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("src/lib.rs", "pub fn baz() {}") .build(); foo.cargo("rustc --profile check -- --emit=metadata").run(); } #[test] fn rustc_check_err() { let foo = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [dependencies.bar] path = "../bar" "#, ).file( "src/main.rs", "extern crate bar; fn main() { ::bar::qux(); }", ).build(); let _bar = project() .at("bar") .file("Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("src/lib.rs", "pub fn baz() {}") .build(); foo.cargo("rustc --profile check -- --emit=metadata") .with_status(101) .run(); } #[test] fn check_all() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [workspace] [dependencies] b = { path = "b" } "#, ).file("src/main.rs", "fn main() {}") .file("examples/a.rs", "fn main() {}") .file("tests/a.rs", "") .file("src/lib.rs", "") .file("b/Cargo.toml", &basic_manifest("b", "0.0.1")) .file("b/src/main.rs", "fn main() {}") .file("b/src/lib.rs", "") .build(); p.cargo("check --all -v") .with_stderr_contains("[..] --crate-name foo src/lib.rs [..]") .with_stderr_contains("[..] --crate-name foo src/main.rs [..]") .with_stderr_contains("[..] --crate-name b b/src/lib.rs [..]") .with_stderr_contains("[..] --crate-name b b/src/main.rs [..]") .run(); } #[test] fn check_virtual_all_implied() { let p = project() .file( "Cargo.toml", r#" [workspace] members = ["bar", "baz"] "#, ).file("bar/Cargo.toml", &basic_manifest("bar", "0.1.0")) .file("bar/src/lib.rs", "pub fn bar() {}") .file("baz/Cargo.toml", &basic_manifest("baz", "0.1.0")) .file("baz/src/lib.rs", "pub fn baz() {}") .build(); p.cargo("check -v") .with_stderr_contains("[..] --crate-name bar bar/src/lib.rs [..]") .with_stderr_contains("[..] --crate-name baz baz/src/lib.rs [..]") .run(); } #[test] fn targets_selected_default() { let foo = project() .file("src/main.rs", "fn main() {}") .file("src/lib.rs", "pub fn smth() {}") .file("examples/example1.rs", "fn main() {}") .file("tests/test2.rs", "#[test] fn t() {}") .file("benches/bench3.rs", "") .build(); foo.cargo("check -v") .with_stderr_contains("[..] --crate-name foo src/lib.rs [..]") .with_stderr_contains("[..] --crate-name foo src/main.rs [..]") .with_stderr_does_not_contain("[..] --crate-name example1 examples/example1.rs [..]") .with_stderr_does_not_contain("[..] --crate-name test2 tests/test2.rs [..]") .with_stderr_does_not_contain("[..] --crate-name bench3 benches/bench3.rs [..]") .run(); } #[test] fn targets_selected_all() { let foo = project() .file("src/main.rs", "fn main() {}") .file("src/lib.rs", "pub fn smth() {}") .file("examples/example1.rs", "fn main() {}") .file("tests/test2.rs", "#[test] fn t() {}") .file("benches/bench3.rs", "") .build(); foo.cargo("check --all-targets -v") .with_stderr_contains("[..] --crate-name foo src/lib.rs [..]") .with_stderr_contains("[..] --crate-name foo src/main.rs [..]") .with_stderr_contains("[..] --crate-name example1 examples/example1.rs [..]") .with_stderr_contains("[..] --crate-name test2 tests/test2.rs [..]") .with_stderr_contains("[..] --crate-name bench3 benches/bench3.rs [..]") .run(); } #[test] fn check_unit_test_profile() { let foo = project() .file( "src/lib.rs", r#" #[cfg(test)] mod tests { #[test] fn it_works() { badtext } } "#, ).build(); foo.cargo("check").run(); foo.cargo("check --profile test") .with_status(101) .with_stderr_contains("[..]badtext[..]") .run(); } // Verify what is checked with various command-line filters. #[test] fn check_filters() { let p = project() .file( "src/lib.rs", r#" fn unused_normal_lib() {} #[cfg(test)] mod tests { fn unused_unit_lib() {} } "#, ).file( "src/main.rs", r#" fn main() {} fn unused_normal_bin() {} #[cfg(test)] mod tests { fn unused_unit_bin() {} } "#, ).file( "tests/t1.rs", r#" fn unused_normal_t1() {} #[cfg(test)] mod tests { fn unused_unit_t1() {} } "#, ).file( "examples/ex1.rs", r#" fn main() {} fn unused_normal_ex1() {} #[cfg(test)] mod tests { fn unused_unit_ex1() {} } "#, ).file( "benches/b1.rs", r#" fn unused_normal_b1() {} #[cfg(test)] mod tests { fn unused_unit_b1() {} } "#, ).build(); p.cargo("check") .with_stderr_contains("[..]unused_normal_lib[..]") .with_stderr_contains("[..]unused_normal_bin[..]") .with_stderr_does_not_contain("[..]unused_normal_t1[..]") .with_stderr_does_not_contain("[..]unused_normal_ex1[..]") .with_stderr_does_not_contain("[..]unused_normal_b1[..]") .with_stderr_does_not_contain("[..]unused_unit_[..]") .run(); p.root().join("target").rm_rf(); p.cargo("check --tests -v") .with_stderr_contains("[..] --crate-name foo src/lib.rs [..] --test [..]") .with_stderr_contains("[..] --crate-name foo src/lib.rs [..] --crate-type lib [..]") .with_stderr_contains("[..] --crate-name foo src/main.rs [..] --test [..]") .with_stderr_contains("[..]unused_unit_lib[..]") .with_stderr_contains("[..]unused_unit_bin[..]") .with_stderr_contains("[..]unused_normal_lib[..]") .with_stderr_contains("[..]unused_normal_bin[..]") .with_stderr_contains("[..]unused_unit_t1[..]") .with_stderr_does_not_contain("[..]unused_normal_ex1[..]") .with_stderr_does_not_contain("[..]unused_unit_ex1[..]") .with_stderr_does_not_contain("[..]unused_normal_b1[..]") .with_stderr_does_not_contain("[..]unused_unit_b1[..]") .with_stderr_does_not_contain("[..]--crate-type bin[..]") .run(); p.root().join("target").rm_rf(); p.cargo("check --test t1 -v") .with_stderr_contains("[..]unused_normal_lib[..]") .with_stderr_contains("[..]unused_unit_t1[..]") .with_stderr_does_not_contain("[..]unused_unit_lib[..]") .with_stderr_does_not_contain("[..]unused_normal_bin[..]") .with_stderr_does_not_contain("[..]unused_unit_bin[..]") .with_stderr_does_not_contain("[..]unused_normal_ex1[..]") .with_stderr_does_not_contain("[..]unused_normal_b1[..]") .with_stderr_does_not_contain("[..]unused_unit_ex1[..]") .with_stderr_does_not_contain("[..]unused_unit_b1[..]") .run(); p.root().join("target").rm_rf(); p.cargo("check --all-targets -v") .with_stderr_contains("[..]unused_normal_lib[..]") .with_stderr_contains("[..]unused_normal_bin[..]") .with_stderr_contains("[..]unused_normal_t1[..]") .with_stderr_contains("[..]unused_normal_ex1[..]") .with_stderr_contains("[..]unused_normal_b1[..]") .with_stderr_contains("[..]unused_unit_b1[..]") .with_stderr_contains("[..]unused_unit_t1[..]") .with_stderr_contains("[..]unused_unit_lib[..]") .with_stderr_contains("[..]unused_unit_bin[..]") .with_stderr_does_not_contain("[..]unused_unit_ex1[..]") .run(); } #[test] fn check_artifacts() { // Verify which artifacts are created when running check (#4059). let p = project() .file("src/lib.rs", "") .file("src/main.rs", "fn main() {}") .file("tests/t1.rs", "") .file("examples/ex1.rs", "fn main() {}") .file("benches/b1.rs", "") .build(); let assert_glob = |path: &str, count: usize| { assert_eq!( glob(&p.root().join(path).to_str().unwrap()) .unwrap() .count(), count ); }; p.cargo("check").run(); assert!(!p.root().join("target/debug/libfoo.rmeta").is_file()); assert!(!p.root().join("target/debug/libfoo.rlib").is_file()); assert!(!p.root().join("target/debug").join(exe("foo")).is_file()); assert_glob("target/debug/deps/libfoo-*.rmeta", 2); p.root().join("target").rm_rf(); p.cargo("check --lib").run(); assert!(!p.root().join("target/debug/libfoo.rmeta").is_file()); assert!(!p.root().join("target/debug/libfoo.rlib").is_file()); assert!(!p.root().join("target/debug").join(exe("foo")).is_file()); assert_glob("target/debug/deps/libfoo-*.rmeta", 1); p.root().join("target").rm_rf(); p.cargo("check --bin foo").run(); assert!(!p.root().join("target/debug/libfoo.rmeta").is_file()); assert!(!p.root().join("target/debug/libfoo.rlib").is_file()); assert!(!p.root().join("target/debug").join(exe("foo")).is_file()); assert_glob("target/debug/deps/libfoo-*.rmeta", 2); p.root().join("target").rm_rf(); p.cargo("check --test t1").run(); assert!(!p.root().join("target/debug/libfoo.rmeta").is_file()); assert!(!p.root().join("target/debug/libfoo.rlib").is_file()); assert!(!p.root().join("target/debug").join(exe("foo")).is_file()); assert_glob("target/debug/t1-*", 0); assert_glob("target/debug/deps/libfoo-*.rmeta", 1); assert_glob("target/debug/deps/libt1-*.rmeta", 1); p.root().join("target").rm_rf(); p.cargo("check --example ex1").run(); assert!(!p.root().join("target/debug/libfoo.rmeta").is_file()); assert!(!p.root().join("target/debug/libfoo.rlib").is_file()); assert!( !p.root() .join("target/debug/examples") .join(exe("ex1")) .is_file() ); assert_glob("target/debug/deps/libfoo-*.rmeta", 1); assert_glob("target/debug/examples/libex1-*.rmeta", 1); p.root().join("target").rm_rf(); p.cargo("check --bench b1").run(); assert!(!p.root().join("target/debug/libfoo.rmeta").is_file()); assert!(!p.root().join("target/debug/libfoo.rlib").is_file()); assert!(!p.root().join("target/debug").join(exe("foo")).is_file()); assert_glob("target/debug/b1-*", 0); assert_glob("target/debug/deps/libfoo-*.rmeta", 1); assert_glob("target/debug/deps/libb1-*.rmeta", 1); } #[test] fn short_message_format() { let foo = project() .file("src/lib.rs", "fn foo() { let _x: bool = 'a'; }") .build(); foo.cargo("check --message-format=short") .with_status(101) .with_stderr_contains( "\ src/lib.rs:1:27: error[E0308]: mismatched types error: aborting due to previous error error: Could not compile `foo`. ", ).run(); } #[test] fn proc_macro() { let p = project() .file( "Cargo.toml", r#" [package] name = "demo" version = "0.0.1" [lib] proc-macro = true "#, ).file( "src/lib.rs", r#" extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(Foo)] pub fn demo(_input: TokenStream) -> TokenStream { "".parse().unwrap() } "#, ).file( "src/main.rs", r#" #[macro_use] extern crate demo; #[derive(Foo)] struct A; fn main() {} "#, ).build(); p.cargo("check -v").env("RUST_LOG", "cargo=trace").run(); } #[test] fn does_not_use_empty_rustc_wrapper() { let p = project().file("src/lib.rs", "").build(); p.cargo("check").env("RUSTC_WRAPPER", "").run(); } #[test] fn error_from_deep_recursion() -> Result<(), fmt::Error> { let mut big_macro = String::new(); writeln!(big_macro, "macro_rules! m {{")?; for i in 0..130 { writeln!(big_macro, "({}) => {{ m!({}); }};", i, i + 1)?; } writeln!(big_macro, "}}")?; writeln!(big_macro, "m!(0);")?; let p = project().file("src/lib.rs", &big_macro).build(); p.cargo("check --message-format=json") .with_status(101) .with_stdout_contains( "[..]\"message\":\"recursion limit reached while expanding the macro `m`\"[..]", ) .run(); Ok(()) }
dom.ts
export function
(node: any): node is Element | Text { return node.nodeType && (node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.TEXT_NODE); } export function isElement(node: any): node is Element { return node.nodeType === Node.ELEMENT_NODE; } // a range for test TextNode clientRect const cycleRange = document.createRange(); export function getClientRects(node: Element | Text) { if (isElement(node)) { return [node.getBoundingClientRect()]; } cycleRange.selectNode(node); return Array.from(cycleRange.getClientRects()); }
isDOMNode
data.rs
use crate::map::{Degree, MapCoord}; use ahash::RandomState; use csv::Reader; use indexmap::IndexMap; use std::{ collections::{HashMap, HashSet}, fmt::Display, }; #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub struct StationId(pub u32); // Corresponds to entries in stations.csv #[derive(Debug, Clone)] pub struct Station { pub id: StationId, pub name: String, pub coord: MapCoord, } // Corresponds to entries in join.csv pub struct Connection { station_id_1: StationId, station_id_2: StationId, } impl Display for Station { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {} {}", self.id.0, self.name, self.coord) } } pub fn load_stations() -> IndexMap<StationId, Station, RandomState>
pub fn load_connections() -> HashMap<StationId, HashSet<StationId, RandomState>, RandomState> { let bytes: &[u8] = include_bytes!("../data/join.csv"); let mut reader = Reader::from_reader(bytes); let vec: Vec<Connection> = reader .records() .map(|record| { let record = record.unwrap(); let station_id_1: StationId = StationId(record.get(0).unwrap().parse().unwrap()); let station_id_2: StationId = StationId(record.get(1).unwrap().parse().unwrap()); Connection { station_id_1, station_id_2, } }) .collect(); let mut result: HashMap<StationId, HashSet<StationId, RandomState>, RandomState> = HashMap::with_hasher(RandomState::new()); for record in vec { result .entry(record.station_id_1) .or_default() .insert(record.station_id_2); result .entry(record.station_id_2) .or_default() .insert(record.station_id_1); } result }
{ let bytes: &[u8] = include_bytes!("../data/stations.csv"); let mut reader = Reader::from_reader(bytes); let mut result: IndexMap<StationId, Station, RandomState> = IndexMap::with_hasher(RandomState::new()); for record in reader.records() { let record = record.unwrap(); let long: Degree = record.get(2).unwrap().parse().unwrap(); let lat: Degree = record.get(3).unwrap().parse().unwrap(); let station = Station { id: StationId(record.get(0).unwrap().parse().unwrap()), name: record.get(1).unwrap().to_owned(), coord: MapCoord { long, lat }, }; result.insert(station.id, station); } result }
search_3227b17f70d3cb3a5f2b296d6943848a_test.go
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V. licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // Code generated, DO NOT EDIT package elasticsearch_test import ( "fmt" "os" "strings" "testing" "github.com/elastic/go-elasticsearch/v8" ) var ( _ = fmt.Printf _ = os.Stdout _ = elasticsearch.NewDefaultClient ) // <https://github.com/elastic/elasticsearch/blob/master/docs/reference/search.asciidoc#L72> // // -------------------------------------------------------------------------------- // PUT /_cluster/settings // { // "transient": { // "cluster.routing.use_adaptive_replica_selection": false // } // } // -------------------------------------------------------------------------------- func
(t *testing.T) { es, _ := elasticsearch.NewDefaultClient() // tag:3227b17f70d3cb3a5f2b296d6943848a[] res, err := es.Cluster.PutSettings( strings.NewReader(`{ "transient": { "cluster.routing.use_adaptive_replica_selection": false } }`)) fmt.Println(res, err) if err != nil { // SKIP t.Fatalf("Error getting the response: %s", err) // SKIP } // SKIP defer res.Body.Close() // SKIP // end:3227b17f70d3cb3a5f2b296d6943848a[] }
Test_search_3227b17f70d3cb3a5f2b296d6943848a
digest.go
package builds import ( "fmt" g "github.com/onsi/ginkgo" o "github.com/onsi/gomega" exutil "github.com/openshift/origin/test/extended/util" "k8s.io/apimachinery/pkg/apis/meta/v1" ) var _ = g.Describe("[Feature:Builds][Slow] completed builds should have digest of the image in their status", func() { defer g.GinkgoRecover() var ( imageStreamFixture = exutil.FixturePath("..", "integration", "testdata", "test-image-stream.json") stiBuildFixture = exutil.FixturePath("testdata", "builds", "test-s2i-build.json") dockerBuildFixture = exutil.FixturePath("testdata", "builds", "test-docker-build.json") oc = exutil.NewCLI("build-sti-labels", exutil.KubeConfigPath()) ) g.Context("", func() { g.BeforeEach(func() { exutil.DumpDockerInfo() g.By("waiting for default service account") err := exutil.WaitForServiceAccount(oc.KubeClient().Core().ServiceAccounts(oc.Namespace()), "default") o.Expect(err).NotTo(o.HaveOccurred()) g.By("waiting for builder service account") err = exutil.WaitForServiceAccount(oc.KubeClient().Core().ServiceAccounts(oc.Namespace()), "builder") o.Expect(err).NotTo(o.HaveOccurred()) g.By("creating test imagestream") err = oc.Run("create").Args("-f", imageStreamFixture).Execute() o.Expect(err).NotTo(o.HaveOccurred()) }) g.AfterEach(func() { if g.CurrentGinkgoTestDescription().Failed { exutil.DumpPodStates(oc) exutil.DumpPodLogsStartingWith("", oc) } }) g.Describe("S2I build", func() { g.Describe("started with normal log level", func() { testBuildDigest(oc, stiBuildFixture, 0) }) g.Describe("started with log level >5", func() { testBuildDigest(oc, stiBuildFixture, 7) }) }) g.Describe("Docker build", func() { g.Describe("started with normal log level", func() { testBuildDigest(oc, dockerBuildFixture, 0) }) g.Describe("started with log level >5", func() { testBuildDigest(oc, dockerBuildFixture, 7) }) }) }) }) func
(oc *exutil.CLI, buildFixture string, buildLogLevel uint) { g.It(fmt.Sprintf("should save the image digest when finished"), func() { g.Skip("TODO: find the digest from the pushImage call and ensure it is set") g.By("creating test build") err := oc.Run("create").Args("-f", buildFixture).Execute() o.Expect(err).NotTo(o.HaveOccurred()) logLevelArg := fmt.Sprintf("--build-loglevel=%d", buildLogLevel) g.By("starting a test build") br, err := exutil.StartBuildAndWait(oc, "test", logLevelArg) o.Expect(err).NotTo(o.HaveOccurred()) br.AssertSuccess() g.By("checking that the image digest has been saved to the build status") o.Expect(br.Build.Status.Output.To).NotTo(o.BeNil()) ist, err := oc.ImageClient().Image().ImageStreamTags(oc.Namespace()).Get("test:latest", v1.GetOptions{}) o.Expect(err).NotTo(o.HaveOccurred()) o.Expect(br.Build.Status.Output.To.ImageDigest).To(o.Equal(ist.Image.Name)) }) }
testBuildDigest
TCPclient.py
#-------------------SOCKET PROGRAMMING------------------- #Krijimi i klient aplikacionit import socket #Importojme librarine per socket komunikim ne mes te klientit dhe serverit import sys #Importojme librarine sys import time #Importojme librarine time serverName = '127.0.0.1' #IP serverPort = 14000 #Porti address=(serverName,serverPort) #Adresa eshte qift i hostit dhe portit #Krijimi i soketit. Argumentet e pasuara në socket () specifikojne familjen e adresave dhe llojin e soketit #AF_INET eshte familja e adresave per IPv4. SOCK_STREAM eshte lloji i soketit per TCP protokollin try: clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as err: #Nese ndodh gabim, shfaqet gabimi dhe mbyllet sistemi print("Soketi nuk ka mundur te krijohet!") print(str(err)) time.sleep(1) sys.exit() #Kerkojme nga klienti te jep pergjigjie nese deshiron apo jo ta ndrorroj adresen e serverit print("-------Mire se erdhet ne FIEK Protokollin!-------\n\nAdresa e serverit eshte:"+str(serverName)+", "+str(serverPort)) answer=input("\nDeshironi ta nderroni adresen e serverit? Shtyp PO ose JO: ") if answer=="PO" or answer=="po": serverName=str(input("\nIP? ")) #IP serverPort=int(input("\nPORTI? ")) #Porti elif answer=="JO" or answer=="jo": serverName = '127.0.0.1' #IP serverPort = 14000 #Porti else: print("\nNuk keni shtypur as PO as JO,prandaj po vazhdojme me vlera default! ") time.sleep(1) serverName = '127.0.0.1' #IP serverPort = 14000 #Porti address=(serverName,serverPort) #Adresa eshte qift i hostit dhe portit try: clientSocket.connect(address) #Klienti tenton te lidhet me serverin permes metodes connect(), #ku si parameter e merr adresen(hosti,porti) except socket.error as err: #Nese ndodh gabim gjate lidhjes me serverin, shfaqet gabimi dhe sistemi behet exit print("\nKa ndodhur nje gabim gjate lidhjes me serverin!\n") print(str(err)) time.sleep(2) sys.exit() line="--------------------------------------------------------------------------------"
+"2.NRPORTIT - per ta zgjedhur shtypni NRPORTIT\n"+line +"3.NUMERO- per ta zgjedhur shtypni NUMERO{Hapesire}Teksi Juaj\n"+line +"4.ANASJELLTAS- per ta zgjedhur shtypni ANASJELLTAS{Hapesire}Teksi Juaj\n"+line +"5.PALINDROM - per ta zgjedhur shtypni PALINDROM{Hapesire}Teksi Juaj\n"+line +"6.KOHA - per ta zgjedhur shtypni KOHA\n"+line +"7.LOJA - per ta zgjedhur shtypni LOJA\n"+line +"8.GCF - per ta zgjedhur shtypni GCF{Hapesire}Numri1{Hapesire}Numri2\n"+line +"9.KONVERTO - per ta zgjedhur shtypni {Hapesire}{Modi}{Hapesire}{Numri}\n"+line +"10.THENJA - per ta zgjedhur shtypni THENJA\n"+line +"11.FIBONACCI - per ta zgjedhur shtypni FIBONACCI{Hapesire}Numri i termave\n"+line +"Shtypni PERFUNDO ose vetem tastin ENTER per ta mbyllur programin.\n"+line) message=" " while True: #Unaze e pafundme request = input("Kerkesa juaj? ") #Kerkojme nga klienti te shkruaj kerkesen try: #Tentojme te dergojme kerkesen tek serveri permes sendall, ku kerkesa duhet te enkodohet (default ne formatin utf-8) clientSocket.sendall(str.encode(request)) except socket.error as err: #Nese ndodh gabim, shfaqet gabimi dhe mbyllet soketi print("Ka ndodhur nje gabim gjate dergimit te kerkeses ne server!\n") print(str(err)) break if not request: #Nese klienti nuk jep ndonje kerkese por vetem shtyp enter, soketi mbyllet print("\nNuk keni dhene asnje kerkese prandaj programi po mbyllet...\n") time.sleep(1) break try: # Tentojme ta marrim pergjigjien nga serveri permes recv receivedResponse=clientSocket.recv(1024) except socket.error as err: #Nese ndodh gabim, shfaqet gabimi dhe mbyllet soketi print("Ka ndodhur nje gabim gjate pranimit te pergjigjies nga serveri!\n") print(str(err)) break if len(receivedResponse) <= 0: break message=receivedResponse.decode('utf-8') #Dekodimi i pergjigjies se serverit print("\nPërgjigjia nga serveri --> ",str(message) ,"\n") #Paraqitja ne ekran e pergjigjies se serverit print("-------------------------------------------------------------------------------") clientSocket.close() #Mbyllja e soketit permes close
print("\nJeni lidhur me serverin, mund të zgjedhni njerin nga operacionet e meposhtme!\n\n" +"Operacionet:\n\n"+line +"1.IP - per ta zgjedhur shtypni IP\n"+line
describe_security_group_attribute.go
package ens //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 Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // DescribeSecurityGroupAttribute invokes the ens.DescribeSecurityGroupAttribute API synchronously func (client *Client) DescribeSecurityGroupAttribute(request *DescribeSecurityGroupAttributeRequest) (response *DescribeSecurityGroupAttributeResponse, err error) { response = CreateDescribeSecurityGroupAttributeResponse() err = client.DoAction(request, response) return } // DescribeSecurityGroupAttributeWithChan invokes the ens.DescribeSecurityGroupAttribute API asynchronously func (client *Client) DescribeSecurityGroupAttributeWithChan(request *DescribeSecurityGroupAttributeRequest) (<-chan *DescribeSecurityGroupAttributeResponse, <-chan error) { responseChan := make(chan *DescribeSecurityGroupAttributeResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.DescribeSecurityGroupAttribute(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // DescribeSecurityGroupAttributeWithCallback invokes the ens.DescribeSecurityGroupAttribute API asynchronously func (client *Client) DescribeSecurityGroupAttributeWithCallback(request *DescribeSecurityGroupAttributeRequest, callback func(response *DescribeSecurityGroupAttributeResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DescribeSecurityGroupAttributeResponse var err error defer close(result) response, err = client.DescribeSecurityGroupAttribute(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // DescribeSecurityGroupAttributeRequest is the request struct for api DescribeSecurityGroupAttribute type DescribeSecurityGroupAttributeRequest struct { *requests.RpcRequest SecurityGroupId string `position:"Query" name:"SecurityGroupId"` Version string `position:"Query" name:"Version"` } // DescribeSecurityGroupAttributeResponse is the response struct for api DescribeSecurityGroupAttribute type DescribeSecurityGroupAttributeResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` SecurityGroupId string `json:"SecurityGroupId" xml:"SecurityGroupId"` Permissions Permissions `json:"Permissions" xml:"Permissions"` } // CreateDescribeSecurityGroupAttributeRequest creates a request to invoke DescribeSecurityGroupAttribute API func CreateDescribeSecurityGroupAttributeRequest() (request *DescribeSecurityGroupAttributeRequest) { request = &DescribeSecurityGroupAttributeRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Ens", "2017-11-10", "DescribeSecurityGroupAttribute", "ens", "openAPI") request.Method = requests.POST return } // CreateDescribeSecurityGroupAttributeResponse creates a response to parse from DescribeSecurityGroupAttribute response func CreateDescribeSecurityGroupAttributeResponse() (response *DescribeSecurityGroupAttributeResponse)
{ response = &DescribeSecurityGroupAttributeResponse{ BaseResponse: &responses.BaseResponse{}, } return }
utils.rs
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::ops::Deref; use common_arrow::arrow::bitmap::Bitmap; pub struct Wrap<T>(pub T); impl<T> Deref for Wrap<T> { type Target = T; fn deref(&self) -> &Self::Target
} unsafe fn index_of_unchecked<T>(slice: &[T], item: &T) -> usize { (item as *const _ as usize - slice.as_ptr() as usize) / std::mem::size_of::<T>() } #[allow(dead_code)] fn index_of<T>(slice: &[T], item: &T) -> Option<usize> { debug_assert!(std::mem::size_of::<T>() > 0); let ptr = item as *const T; unsafe { if slice.as_ptr() < ptr && slice.as_ptr().add(slice.len()) > ptr { Some(index_of_unchecked(slice, item)) } else { None } } } pub fn get_iter_capacity<T, I: Iterator<Item = T>>(iter: &I) -> usize { match iter.size_hint() { (_lower, Some(upper)) => upper, (0, None) => 1024, (lower, None) => lower, } } pub fn combine_validities(lhs: Option<&Bitmap>, rhs: Option<&Bitmap>) -> Option<Bitmap> { match (lhs, rhs) { (Some(lhs), None) => Some(lhs.clone()), (None, Some(rhs)) => Some(rhs.clone()), (None, None) => None, (Some(lhs), Some(rhs)) => Some(lhs & rhs), } } pub fn combine_validities_2(lhs: Option<Bitmap>, rhs: Option<Bitmap>) -> Option<Bitmap> { match (lhs, rhs) { (Some(lhs), None) => Some(lhs), (None, Some(rhs)) => Some(rhs), (None, None) => None, (Some(lhs), Some(rhs)) => Some((&lhs) & (&rhs)), } } /// Forked from Arrow until their API stabilizes. /// /// Note that the bound checks are optimized away. /// #[cfg(feature = "simd")] use packed_simd::u8x64; const BIT_MASK: [u8; 8] = [1, 2, 4, 8, 16, 32, 64, 128]; /// Returns the nearest number that is `>=` than `num` and is a multiple of 64 #[inline] pub fn round_upto_multiple_of_64(num: usize) -> usize { round_upto_power_of_2(num, 64) } /// Returns the nearest multiple of `factor` that is `>=` than `num`. Here `factor` must /// be a power of 2. pub fn round_upto_power_of_2(num: usize, factor: usize) -> usize { debug_assert!(factor > 0 && (factor & (factor - 1)) == 0); (num + (factor - 1)) & !(factor - 1) } /// Returns whether bit at position `i` in `data` is set or not #[inline] pub fn get_bit(data: &[u8], i: usize) -> bool { (data[i >> 3] & BIT_MASK[i & 7]) != 0 } /// Returns whether bit at position `i` in `data` is set or not. /// /// # Safety /// /// Note this doesn't do any bound checking, for performance reason. The caller is /// responsible to guarantee that `i` is within bounds. #[inline] pub unsafe fn get_bit_raw(data: *const u8, i: usize) -> bool { (*data.add(i >> 3) & BIT_MASK[i & 7]) != 0 } /// Sets bit at position `i` for `data` #[inline] pub fn set_bit(data: &mut [u8], i: usize) { data[i >> 3] |= BIT_MASK[i & 7]; } /// Sets bit at position `i` for `data` /// /// # Safety /// /// Note this doesn't do any bound checking, for performance reason. The caller is /// responsible to guarantee that `i` is within bounds. #[inline] pub unsafe fn set_bit_raw(data: *mut u8, i: usize) { *data.add(i >> 3) |= BIT_MASK[i & 7]; } /// Sets bit at position `i` for `data` to 0 #[inline] pub fn unset_bit(data: &mut [u8], i: usize) { data[i >> 3] ^= BIT_MASK[i & 7]; } /// Sets bit at position `i` for `data` to 0 /// /// # Safety /// /// Note this doesn't do any bound checking, for performance reason. The caller is /// responsible to guarantee that `i` is within bounds. #[inline] pub unsafe fn unset_bit_raw(data: *mut u8, i: usize) { *data.add(i >> 3) ^= BIT_MASK[i & 7]; } /// Returns the ceil of `value`/`divisor` #[inline] pub fn ceil(value: usize, divisor: usize) -> usize { let (quot, rem) = (value / divisor, value % divisor); if rem > 0 && divisor > 0 { quot + 1 } else { quot } } /// Performs SIMD bitwise binary operations. /// /// # Safety /// /// Note that each slice should be 64 bytes and it is the callers responsibility to ensure /// that this is the case. If passed slices larger than 64 bytes the operation will only /// be performed on the first 64 bytes. Slices less than 64 bytes will panic. #[cfg(simd)] pub unsafe fn bitwise_bin_op_simd<F>(left: &[u8], right: &[u8], result: &mut [u8], op: F) where F: Fn(u8x64, u8x64) -> u8x64 { let left_simd = u8x64::from_slice_unaligned_unchecked(left); let right_simd = u8x64::from_slice_unaligned_unchecked(right); let simd_result = op(left_simd, right_simd); simd_result.write_to_slice_unaligned_unchecked(result); }
{ &self.0 }
regex.go
package regex import ( "regexp" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/processors" ) type Regex struct { Tags []converter Fields []converter regexCache map[string]*regexp.Regexp } type converter struct { Key string Pattern string Replacement string ResultKey string } const sampleConfig = ` ## Tag and field conversions defined in a separate sub-tables # [[processors.regex.tags]] # ## Tag to change # key = "resp_code" # ## Regular expression to match on a tag value # pattern = "^(\\d)\\d\\d$" # ## Pattern for constructing a new value (${1} represents first subgroup) # replacement = "${1}xx" # [[processors.regex.fields]] # key = "request" # ## All the power of the Go regular expressions available here # ## For example, named subgroups # pattern = "^/api(?P<method>/[\\w/]+)\\S*" # replacement = "${method}" # ## If result_key is present, a new field will be created # ## instead of changing existing field # result_key = "method" ## Multiple conversions may be applied for one field sequentially ## Let's extract one more value # [[processors.regex.fields]] # key = "request" # pattern = ".*category=(\\w+).*" # replacement = "${1}" # result_key = "search_category" ` func NewRegex() *Regex
func (r *Regex) SampleConfig() string { return sampleConfig } func (r *Regex) Description() string { return "Transforms tag and field values with regex pattern" } func (r *Regex) Apply(in ...telegraf.Metric) []telegraf.Metric { for _, metric := range in { for _, converter := range r.Tags { if value, ok := metric.GetTag(converter.Key); ok { if key, newValue := r.convert(converter, value); newValue != "" { metric.AddTag(key, newValue) } } } for _, converter := range r.Fields { if value, ok := metric.GetField(converter.Key); ok { switch value := value.(type) { case string: if key, newValue := r.convert(converter, value); newValue != "" { metric.AddField(key, newValue) } } } } } return in } func (r *Regex) convert(c converter, src string) (string, string) { regex, compiled := r.regexCache[c.Pattern] if !compiled { regex = regexp.MustCompile(c.Pattern) r.regexCache[c.Pattern] = regex } value := "" if c.ResultKey == "" || regex.MatchString(src) { value = regex.ReplaceAllString(src, c.Replacement) } if c.ResultKey != "" { return c.ResultKey, value } return c.Key, value } func init() { processors.Add("regex", func() telegraf.Processor { return NewRegex() }) }
{ return &Regex{ regexCache: make(map[string]*regexp.Regexp), } }
rosmsg.rs
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use ros_message::{Duration, Time}; use std::collections::HashMap; use std::io; pub trait RosMsg: std::marker::Sized { fn encode<W: io::Write>(&self, w: W) -> io::Result<()>; fn decode<R: io::Read>(r: R) -> io::Result<Self>; #[inline] fn encode_vec(&self) -> io::Result<Vec<u8>> { let mut writer = io::Cursor::new(Vec::with_capacity(128)); // skip the first 4 bytes that will contain the message length writer.set_position(4); self.encode(&mut writer)?; // write the message length to the start of the header let message_length = (writer.position() - 4) as u32; writer.set_position(0); message_length.encode(&mut writer)?; Ok(writer.into_inner()) } #[inline] fn decode_slice(bytes: &[u8]) -> io::Result<Self> { let mut reader = io::Cursor::new(bytes); // skip the first 4 bytes that contain the message length reader.set_position(4); Self::decode(&mut reader) } } impl RosMsg for bool { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_u8(*self as u8) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_u8().map(|u| u > 0) } } impl RosMsg for u8 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_u8(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_u8() } } impl RosMsg for i8 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_i8(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_i8() } } impl RosMsg for u16 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_u16::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_u16::<LittleEndian>() } } impl RosMsg for i16 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_i16::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_i16::<LittleEndian>() } } impl RosMsg for u32 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_u32::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_u32::<LittleEndian>() } } impl RosMsg for i32 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_i32::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_i32::<LittleEndian>() } } impl RosMsg for u64 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_u64::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_u64::<LittleEndian>() } } impl RosMsg for i64 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_i64::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_i64::<LittleEndian>() } } impl RosMsg for f32 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_f32::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_f32::<LittleEndian>() } } impl RosMsg for f64 { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { w.write_f64::<LittleEndian>(*self) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { r.read_f64::<LittleEndian>() } } #[inline] pub fn encode_fixed_slice<W: io::Write, T: RosMsg>(data: &[T], mut w: W) -> io::Result<()> { data.iter().try_for_each(|v| v.encode(w.by_ref())) } #[inline] pub fn decode_fixed_vec<R: io::Read, T: RosMsg>(len: u32, mut r: R) -> io::Result<Vec<T>> { (0..len).map(move |_| T::decode(r.by_ref())).collect() } #[inline] pub fn encode_variable_slice<W: io::Write, T: RosMsg>(data: &[T], mut w: W) -> io::Result<()> { (data.len() as u32).encode(w.by_ref())?; encode_fixed_slice(data, w) } #[inline] pub fn decode_variable_vec<R: io::Read, T: RosMsg>(mut r: R) -> io::Result<Vec<T>> { decode_fixed_vec(u32::decode(r.by_ref())?, r) } /// Fast vector encoding when platform endiannes matches wire /// endiannes (little). #[inline] #[cfg(target_endian = "little")] pub fn encode_variable_primitive_slice<W: io::Write, T: RosMsg>( data: &[T], mut w: W, ) -> io::Result<()> { (data.len() as u32).encode(w.by_ref())?; let ptr = data.as_ptr() as *const u8; // Because both wire and system are little endian, we simply copy // the in-memory slice to the buffer directly. w.write(unsafe { std::slice::from_raw_parts(ptr, data.len() * std::mem::size_of::<T>()) }) .map(|_| ()) } #[inline] #[cfg(target_endian = "big")] pub fn encode_variable_primitive_slice<W: io::Write, T: RosMsg>( data: &[T], mut w: W, ) -> io::Result<()> { encode_variable_slice(data, w) } /// Fast vector decoding when platform endiannes matches wire /// endiannes (little). #[inline] #[cfg(target_endian = "little")] pub fn decode_variable_primitive_vec<R: io::Read, T: RosMsg>(mut r: R) -> io::Result<Vec<T>> { let num_elements = u32::decode(r.by_ref())? as usize; let num_bytes = num_elements * std::mem::size_of::<T>(); // Allocate the memory w/o initializing because we will later fill // all the memory. let mut buf = Vec::<T>::with_capacity(num_elements); let buf_ptr = buf.as_mut_ptr(); // Fill the Vec to full capacity with the stream data. let mut read_buf = unsafe { std::slice::from_raw_parts_mut(buf_ptr as *mut u8, num_bytes) }; r.read_exact(&mut read_buf)?; // Do not drop the memory std::mem::forget(buf); // Return a new, completely full Vec using the now initialized memory. Ok(unsafe { Vec::from_raw_parts(buf_ptr, num_elements, num_elements) }) } #[inline] #[cfg(target_endian = "big")] pub fn decode_variable_primitive_vec<R: io::Read, T: RosMsg>(mut r: R) -> io::Result<Vec<T>> { decode_variable_vec(r) } #[inline] pub fn encode_str<W: io::Write>(value: &str, w: W) -> io::Result<()> { encode_variable_slice(value.as_bytes(), w) } impl RosMsg for String { #[inline] fn encode<W: io::Write>(&self, w: W) -> io::Result<()> { encode_str(self, w) } #[inline] fn decode<R: io::Read>(r: R) -> io::Result<Self> { decode_variable_vec::<R, u8>(r).and_then(|v| { String::from_utf8(v).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) }) } } impl<Hasher> RosMsg for HashMap<String, String, Hasher> where Hasher: std::hash::BuildHasher, HashMap<String, String, Hasher>: Default, { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> {
let rows = self .iter() .map(|(key, value)| format!("{}={}", key, value)) .collect::<Vec<String>>(); let data_size: usize = rows.iter().map(|item| item.len() + 4).sum(); write_data_size(data_size as u32, w.by_ref())?; rows.into_iter() .try_for_each(|item| item.encode(w.by_ref())) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { let data_size = u64::from(read_data_size(r.by_ref())?); let mut limited_r = r.take(data_size); let mut output = HashMap::<String, String, Hasher>::default(); // TODO: ensure we break only on EOF while let Ok(item) = String::decode(&mut limited_r) { let parts = item.splitn(2, '=').collect::<Vec<&str>>(); match *parts.as_slice() { [key, value] => output.insert(key.into(), value.into()), _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, "Map rows need to have a format of key=value", )); } }; } Ok(output) } } impl RosMsg for Time { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { self.sec.encode(w.by_ref())?; self.nsec.encode(w)?; Ok(()) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { Ok(Self { sec: RosMsg::decode(r.by_ref())?, nsec: RosMsg::decode(r)?, }) } } impl RosMsg for Duration { #[inline] fn encode<W: io::Write>(&self, mut w: W) -> io::Result<()> { self.sec.encode(w.by_ref())?; self.nsec.encode(w)?; Ok(()) } #[inline] fn decode<R: io::Read>(mut r: R) -> io::Result<Self> { Ok(Self { sec: RosMsg::decode(r.by_ref())?, nsec: RosMsg::decode(r)?, }) } } #[inline] fn read_data_size<R: io::Read>(r: R) -> io::Result<u32> { u32::decode(r) } #[inline] fn write_data_size<W: io::Write>(value: u32, w: W) -> io::Result<()> { value.encode(w) }
form_parsers.py
import pandas as pd import bs4 as bs import untangle as ut import requests import urllib.request as rq from collections import OrderedDict from secmmf.mmf_data_loader.utils import get_edgar_url class N_MFP2: def __init__(self): self.select_cols() def born(self, tag): # if tag is a single-node tag contains a navigable string, return a list with that string # if tag has multiple element, needs to further born them childs = [] for x in tag: if (x != '\n') & (type(x) != bs.element.Comment): childs.append(x) return childs def
(self, root, surname=''): name = surname + root.name sons = [] for son in self.born(root): if type(son) == bs.element.NavigableString: text = ': '.join([name, son]) sons.append(text) elif type(son) == bs.element.Tag: sons.extend(self.dive(son, surname=name + '_')) return sons def teach(self, root): sons = [] for son in self.born(root): if len(self.born(son)) == 1: sons.append((son.name, son.get_text().replace('\n', ''))) elif len(self.born(son)) > 1: for grandson in self.born(son): sons.append((son.name + '_' + grandson.name, grandson.get_text().replace('\n', ''))) return sons def teach_rec(self, root): sons = [] for son in self.born(root): if len(self.born(son)) == 1: sons.append((son.name, son.get_text().replace('\n', ''))) elif len(self.born(son)) > 1: sons.append(teach_rec(son)) return sons def parse(self, url='https://www.sec.gov/Archives/edgar/data/759667/000070217219000020/primary_doc.xml'): stubs = self.stubs #_tonum = self._tonum #series_level_names = self.series_level_names #class_level_names = self.class_level_names source = rq.urlopen(url).read() soup = bs.BeautifulSoup(source, 'xml') # parse XML info into a list of dictionaries mmf = [] for tag in self.born(soup.formData): if tag.name in ['classLevelInfo', 'generalInfo', 'seriesLevelInfo']: mmf.append((tag.name, self.teach(tag))) general_series_class = [] general_series = mmf[0][1] + mmf[1][1] for i, x in enumerate(general_series): if x[0] == 'numberOfSharesOutstanding': y = list(x) y[0] = 'series_numberOfSharesOutstanding' general_series[i] = tuple(y) for x in mmf[2:]: general_series_class.append(OrderedDict(general_series + x[1])) df = pd.DataFrame(general_series_class) if 'nameOfPersonDescExpensePay' in df.columns: df.drop(columns='nameOfPersonDescExpensePay', inplace=True) # rename those columns that have reversed patterns namemap = [] for x in ['weeklyGrossRedemptions', 'weeklyGrossSubscriptions']: namemap.append(dict([('fridayWeek' + str(i + 1) + '_' + x, x + '_' + 'fridayWeek' + str(i + 1)) for i in range(5)])) for x in ['totalValueDailyLiquidAssets', 'percentageDailyLiquidAssets']: namemap.append(dict([(x + '_' + 'fridayDay' + str(i + 1), x + '_' + 'fridayWeek' + str(i + 1)) for i in range(5)])) for i in range(4): df = df.rename(columns=namemap[i]) # make data wide to long on weekly holding statistics df = pd.wide_to_long(df, stubnames=self.stubs, i='classesId', j='week', sep='_', suffix='\w+') df.reset_index(inplace=True) df['week'] = df['week'].apply( lambda x: int(x.replace('fridayWeek', ''))) #df = df[['week']+series_level_names+class_level_names] # change the type of numeric data to float #df[_tonum] = df[_tonum].astype(dtype = float) return df def parse_csv(self, url): source = get_edgar_url(url).content soup = bs.BeautifulSoup(source, 'xml') return self.dive(soup.formData) def select_cols(self): self.stubs = ['totalValueDailyLiquidAssets', 'percentageDailyLiquidAssets', 'totalValueWeeklyLiquidAssets', 'percentageWeeklyLiquidAssets', 'netAssetValue', 'netAssetPerShare', 'weeklyGrossRedemptions', 'weeklyGrossSubscriptions'] self._tonum = ['totalShareClassesInSeries', 'averagePortfolioMaturity', 'averageLifeMaturity', 'cash', 'totalValuePortfolioSecurities', 'amortizedCostPortfolioSecurities', 'totalValueOtherAssets', 'totalValueLiabilities', 'netAssetOfSeries', 'numberOfSharesOutstanding', 'stablePricePerShare', 'sevenDayGrossYield', 'minInitialInvestment', 'netAssetsOfClass', 'totalForTheMonthReported_weeklyGrossSubscriptions', 'totalForTheMonthReported_weeklyGrossRedemptions', 'sevenDayNetYield'] + self.stubs self.series_level_names = ['reportDate', 'cik', 'seriesId', 'totalShareClassesInSeries', 'finalFilingFlag', 'fundAcqrdOrMrgdWthAnthrFlag', 'securitiesActFileNumber', 'adviser_adviserName', 'adviser_adviserFileNumber', 'indpPubAccountant_name', 'indpPubAccountant_city', 'indpPubAccountant_stateCountry', 'administrator', 'transferAgent_name', 'transferAgent_cik', 'transferAgent_fileNumber', 'feederFundFlag', 'masterFundFlag', 'seriesFundInsuCmpnySepAccntFlag', 'moneyMarketFundCategory', 'fundExemptRetailFlag', 'averagePortfolioMaturity', 'averageLifeMaturity', 'totalValueDailyLiquidAssets', 'totalValueWeeklyLiquidAssets', 'percentageDailyLiquidAssets', 'percentageWeeklyLiquidAssets', 'cash', 'totalValuePortfolioSecurities', 'amortizedCostPortfolioSecurities', 'totalValueOtherAssets', 'totalValueLiabilities', 'netAssetOfSeries', 'series_numberOfSharesOutstanding', 'stablePricePerShare', 'sevenDayGrossYield', 'netAssetValue'] self.class_level_names = ['classesId', 'minInitialInvestment', 'netAssetsOfClass', 'numberOfSharesOutstanding', 'netAssetPerShare', 'weeklyGrossSubscriptions', 'weeklyGrossRedemptions', 'totalForTheMonthReported_weeklyGrossSubscriptions', 'totalForTheMonthReported_weeklyGrossRedemptions', 'sevenDayNetYield', 'personPayForFundFlag']
dive
ExpectedOutputLibrary.py
from os.path import abspath, dirname, join from fnmatch import fnmatchcase from operator import eq from robot.api import logger CURDIR = dirname(abspath(__file__)) def output_should_be(actual, expected, **replaced):
def _read_file(path, title, replaced=None): with open(path) as file: content = file.read() if replaced: for item in replaced: content = content.replace(item, replaced[item]) logger.debug('%s:\n%s' % (title, content)) return content.splitlines()
actual = _read_file(actual, 'Actual') expected = _read_file(join(CURDIR, expected), 'Expected', replaced) if len(expected) != len(actual): raise AssertionError('Lengths differ. Expected %d lines but got %d' % (len(expected), len(actual))) for exp, act in zip(expected, actual): tester = fnmatchcase if '*' in exp else eq if not tester(act.rstrip(), exp.rstrip()): raise AssertionError('Lines differ.\nExpected: %s\nActual: %s' % (exp, act))
cluster.go
package upgrade import ( "context" "time" "github.com/weaveworks/eksctl/pkg/actions/cluster" "github.com/kris-nova/logger" "github.com/spf13/cobra" "github.com/spf13/pflag" api "github.com/weaveworks/eksctl/pkg/apis/eksctl.io/v1alpha5" "github.com/weaveworks/eksctl/pkg/ctl/cmdutils" ) // updating from 1.15 to 1.16 has been observed to take longer than the default value of 25 minutes // increased to 50 for flex fleet changes const upgradeClusterTimeout = 65 * time.Minute func upgradeCluster(cmd *cmdutils.Cmd) { upgradeClusterWithRunFunc(cmd, DoUpgradeCluster) } func upgradeClusterWithRunFunc(cmd *cmdutils.Cmd, runFunc func(cmd *cmdutils.Cmd) error) { cfg := api.NewClusterConfig() // Reset version cfg.Metadata.Version = "" cmd.ClusterConfig = cfg cmd.SetDescription("cluster", "Upgrade control plane to the next version",
cmdutils.AddCommonFlagsForAWS(cmd.FlagSetGroup, &cmd.ProviderConfig, false) cmd.FlagSetGroup.InFlagSet("General", func(fs *pflag.FlagSet) { fs.StringVarP(&cfg.Metadata.Name, "name", "n", "", "EKS cluster name") cmdutils.AddRegionFlag(fs, &cmd.ProviderConfig) cmdutils.AddVersionFlag(fs, cfg.Metadata, "") cmdutils.AddConfigFileFlag(fs, &cmd.ClusterConfigFile) // cmdutils.AddVersionFlag(fs, cfg.Metadata, `"next" and "latest" can be used to automatically increment version by one, or force latest`) cmdutils.AddApproveFlag(fs, cmd) cmdutils.AddTimeoutFlagWithValue(fs, &cmd.ProviderConfig.WaitTimeout, upgradeClusterTimeout) }) cmd.CobraCommand.RunE = func(_ *cobra.Command, args []string) error { cmd.NameArg = cmdutils.GetNameArg(args) if err := cmdutils.NewMetadataLoader(cmd).Load(); err != nil { return err } return runFunc(cmd) } } // DoUpgradeCluster made public so that it can be shared with update/cluster.go until this is deprecated // TODO Once `eksctl update cluster` is officially deprecated this can be made package private again func DoUpgradeCluster(cmd *cmdutils.Cmd) error { ctx := context.Background() ctl, err := cmd.NewProviderForExistingCluster(ctx) if err != nil { return err } cfg := cmd.ClusterConfig if ok, err := ctl.CanUpdate(cfg); !ok { return err } if cmd.ClusterConfigFile != "" { logger.Warning("NOTE: cluster VPC (subnets, routing & NAT Gateway) configuration changes are not yet implemented") } c, err := cluster.New(ctx, cfg, ctl) if err != nil { return err } return c.Upgrade(ctx, cmd.Plan) }
"Upgrade control plane to the next Kubernetes version if available. Will also perform any updates needed in the cluster stack if resources are missing.")
data_provider.py
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/07_gbe.sst.data_provider.ipynb (unless otherwise specified). __all__ = ['SSTDataProvider'] # Cell from fastcore.foundation import patch from ..data_provider import GBEProvider from ...data_provider import get_efficiently import numpy as np # Cell class SSTDataProvider(GBEProvider): '''This class builds upon GBEProvider to get the working memory task data.''' def __init__(self, data_folder_path): GBEProvider.__init__(self, data_folder_path) # Cell @patch def decode_sst_strings(self:SSTDataProvider, gbe_data): df = self.decode_gbe_strings(gbe_data, 'FruitTapGame') # Removing left/right distinctions df['rt'] = df.lefttime.astype(int) + df.righttime.astype(int) df['is_stop'] = (df.stop.astype(int) > 0).astype(float) df.loc[df.rt==0,'rt'] = np.nan # Setting 0 RTs to nan df['responded'] = (df.rt.isna()==False).astype(float) # Calculating SSD crw = 650 # ToDo: I'll have to double check this is correct; in Smittenaar it's reported as 500ms, but Ying used 650ms (it's correct as we use the center of response window) df['ssd'] = crw - df.gobaddelay.astype(int) df.loc[df.is_stop==False,'ssd'] = np.nan # Error analysis df['omission'] = ((df.is_stop==0) & ((df.rt.isna()) | (df.rt >= 800))).astype(float) df['comission'] = ((df.is_stop==1) & (df.rt.isna()==False)).astype(float) df['premature'] = (df.rt <= 500).astype(float) # Creating convenience variables and restructuring df['accuracy'] = df.success.astype(int) df = df[[ 'gbe_index', 'trial_number', 'anticipation', 'is_stop','gobaddelay','ssd', 'responded', 'rt', 'accuracy', 'omission', 'comission', 'premature']] return df # Cell @patch @get_efficiently def
(self:SSTDataProvider): gbe_data = self.get_gbe_data() df = self.decode_sst_strings(gbe_data) return df
get_sst_data
deployment.py
# Copyright 2014-2015 Canonical Limited. # # 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 logging import re import sys import six from collections import OrderedDict from charmhelpers.contrib.amulet.deployment import ( AmuletDeployment ) DEBUG = logging.DEBUG ERROR = logging.ERROR class OpenStackAmuletDeployment(AmuletDeployment): """OpenStack amulet deployment. This class inherits from AmuletDeployment and has additional support that is specifically for use by OpenStack charms. """ def __init__(self, series=None, openstack=None, source=None, stable=True, log_level=DEBUG): """Initialize the deployment environment.""" super(OpenStackAmuletDeployment, self).__init__(series) self.log = self.get_logger(level=log_level) self.log.info('OpenStackAmuletDeployment: init') self.openstack = openstack self.source = source self.stable = stable def get_logger(self, name="deployment-logger", level=logging.DEBUG): """Get a logger object that will log to stdout.""" log = logging logger = log.getLogger(name) fmt = log.Formatter("%(asctime)s %(funcName)s " "%(levelname)s: %(message)s") handler = log.StreamHandler(stream=sys.stdout) handler.setLevel(level) handler.setFormatter(fmt) logger.addHandler(handler) logger.setLevel(level) return logger def _determine_branch_locations(self, other_services): """Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the other_services.""" self.log.info('OpenStackAmuletDeployment: determine branch locations') # Charms outside the ~openstack-charmers base_charms = { 'mysql': ['precise', 'trusty'], 'mongodb': ['precise', 'trusty'], 'nrpe': ['precise', 'trusty'], } for svc in other_services: # If a location has been explicitly set, use it if svc.get('location'): continue if svc['name'] in base_charms: # NOTE: not all charms have support for all series we # want/need to test against, so fix to most recent # that each base charm supports target_series = self.series if self.series not in base_charms[svc['name']]: target_series = base_charms[svc['name']][-1] svc['location'] = 'cs:{}/{}'.format(target_series, svc['name']) elif self.stable: svc['location'] = 'cs:{}/{}'.format(self.series, svc['name']) else: svc['location'] = 'cs:~openstack-charmers-next/{}/{}'.format( self.series, svc['name'] ) return other_services def _add_services(self, this_service, other_services): """Add services to the deployment and set openstack-origin/source.""" self.log.info('OpenStackAmuletDeployment: adding services') other_services = self._determine_branch_locations(other_services) super(OpenStackAmuletDeployment, self)._add_services(this_service, other_services) services = other_services services.append(this_service) # Charms which should use the source config option use_source = ['mysql', 'mongodb', 'rabbitmq-server', 'ceph', 'ceph-osd', 'ceph-radosgw', 'ceph-mon'] # Charms which can not use openstack-origin, ie. many subordinates no_origin = ['cinder-ceph', 'hacluster', 'neutron-openvswitch', 'nrpe', 'openvswitch-odl', 'neutron-api-odl', 'odl-controller', 'cinder-backup', 'nexentaedge-data', 'nexentaedge-iscsi-gw', 'nexentaedge-swift-gw', 'cinder-nexentaedge', 'nexentaedge-mgmt'] if self.openstack: for svc in services: if svc['name'] not in use_source + no_origin: config = {'openstack-origin': self.openstack} self.d.configure(svc['name'], config) if self.source: for svc in services: if svc['name'] in use_source and svc['name'] not in no_origin: config = {'source': self.source} self.d.configure(svc['name'], config) def _configure_services(self, configs): """Configure all of the services.""" self.log.info('OpenStackAmuletDeployment: configure services') for service, config in six.iteritems(configs): self.d.configure(service, config) def _auto_wait_for_status(self, message=None, exclude_services=None, include_only=None, timeout=1800):
def _get_openstack_release(self): """Get openstack release. Return an integer representing the enum value of the openstack release. """ # Must be ordered by OpenStack release (not by Ubuntu release): (self.precise_essex, self.precise_folsom, self.precise_grizzly, self.precise_havana, self.precise_icehouse, self.trusty_icehouse, self.trusty_juno, self.utopic_juno, self.trusty_kilo, self.vivid_kilo, self.trusty_liberty, self.wily_liberty, self.trusty_mitaka, self.xenial_mitaka) = range(14) releases = { ('precise', None): self.precise_essex, ('precise', 'cloud:precise-folsom'): self.precise_folsom, ('precise', 'cloud:precise-grizzly'): self.precise_grizzly, ('precise', 'cloud:precise-havana'): self.precise_havana, ('precise', 'cloud:precise-icehouse'): self.precise_icehouse, ('trusty', None): self.trusty_icehouse, ('trusty', 'cloud:trusty-juno'): self.trusty_juno, ('trusty', 'cloud:trusty-kilo'): self.trusty_kilo, ('trusty', 'cloud:trusty-liberty'): self.trusty_liberty, ('trusty', 'cloud:trusty-mitaka'): self.trusty_mitaka, ('utopic', None): self.utopic_juno, ('vivid', None): self.vivid_kilo, ('wily', None): self.wily_liberty, ('xenial', None): self.xenial_mitaka} return releases[(self.series, self.openstack)] def _get_openstack_release_string(self): """Get openstack release string. Return a string representing the openstack release. """ releases = OrderedDict([ ('precise', 'essex'), ('quantal', 'folsom'), ('raring', 'grizzly'), ('saucy', 'havana'), ('trusty', 'icehouse'), ('utopic', 'juno'), ('vivid', 'kilo'), ('wily', 'liberty'), ('xenial', 'mitaka'), ]) if self.openstack: os_origin = self.openstack.split(':')[1] return os_origin.split('%s-' % self.series)[1].split('/')[0] else: return releases[self.series] def get_ceph_expected_pools(self, radosgw=False): """Return a list of expected ceph pools in a ceph + cinder + glance test scenario, based on OpenStack release and whether ceph radosgw is flagged as present or not.""" if self._get_openstack_release() >= self.trusty_kilo: # Kilo or later pools = [ 'rbd', 'cinder', 'glance' ] else: # Juno or earlier pools = [ 'data', 'metadata', 'rbd', 'cinder', 'glance' ] if radosgw: pools.extend([ '.rgw.root', '.rgw.control', '.rgw', '.rgw.gc', '.users.uid' ]) return pools
"""Wait for all units to have a specific extended status, except for any defined as excluded. Unless specified via message, any status containing any case of 'ready' will be considered a match. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit. """ self.log.info('Waiting for extended status on units...') all_services = self.d.services.keys() if exclude_services and include_only: raise ValueError('exclude_services can not be used ' 'with include_only') if message: if isinstance(message, re._pattern_type): match = message.pattern else: match = message self.log.debug('Custom extended status wait match: ' '{}'.format(match)) else: self.log.debug('Default extended status wait match: contains ' 'READY (case-insensitive)') message = re.compile('.*ready.*', re.IGNORECASE) if exclude_services: self.log.debug('Excluding services from extended status match: ' '{}'.format(exclude_services)) else: exclude_services = [] if include_only: services = include_only else: services = list(set(all_services) - set(exclude_services)) self.log.debug('Waiting up to {}s for extended status on services: ' '{}'.format(timeout, services)) service_messages = {service: message for service in services} self.d.sentry.wait_for_messages(service_messages, timeout=timeout) self.log.info('OK')
hello-world.py
#!/usr/bin/env python import time import signal from gfxhat import touch, lcd, backlight, fonts from PIL import Image, ImageFont, ImageDraw print("""hello-world.py This basic example prints the text "Hello World" in the middle of the LCD Press any button to see its corresponding LED toggle on/off. Press Ctrl+C to exit. """) led_states = [False for _ in range(6)] width, height = lcd.dimensions() image = Image.new('P', (width, height)) draw = ImageDraw.Draw(image) font = ImageFont.truetype(fonts.AmaticSCBold, 38) text = "Hello World" w, h = font.getsize(text) x = (width - w) // 2 y = (height - h) // 2 draw.text((x, y), text, 1, font) def
(ch, event): if event == 'press': led_states[ch] = not led_states[ch] touch.set_led(ch, led_states[ch]) if led_states[ch]: backlight.set_pixel(ch, 0, 255, 255) else: backlight.set_pixel(ch, 0, 255, 0) backlight.show() for x in range(6): touch.set_led(x, 1) time.sleep(0.1) touch.set_led(x, 0) for x in range(6): backlight.set_pixel(x, 0, 255, 0) touch.on(x, handler) backlight.show() for x in range(128): for y in range(64): pixel = image.getpixel((x, y)) lcd.set_pixel(x, y, pixel) lcd.show() try: signal.pause() except KeyboardInterrupt: for x in range(6): backlight.set_pixel(x, 0, 0, 0) touch.set_led(x, 0) backlight.show() lcd.clear() lcd.show()
handler
index.js
import { Component } from 'preact'; export default class Sound extends Component { play = () => { this.audio.play(); } handleRef = (audio) => { this.audio = audio; } handlePlayProp = () => { const { play } = this.props; if (play) { this.audio.play();
} componentDidMount() { this.handlePlayProp(); } componentDidUpdate() { this.handlePlayProp(); } render = ({ src, onStart, onStop }) => ( <audio ref={this.handleRef} src={src} onPlay={onStart} onEnded={onStop} type="audio/mpeg" /> ) }
} else if (!this.audio.ended) { this.audio.pause(); this.audio.currentTime = 0; }
cache.py
""" This class is used to cache return value of functions on disk for a specified number of days. This is used by lakshmi.assets module to cache name/ asset value (i.e the slow functions). For examples on how to use this class, please see the tests (tests/test_cache.py file). Currently, this module can only be used on functions which are class members and the function itself must take no arguments. These restrictions can be easily relaxed, but so far that all usecases don't need anything more than what is currently implemented. In addition to caching values, this class also allows one to optionally call a user-specified function on cache-misses (currently used to show a progress bar to the user via the lak CLI). """ import functools import pickle from abc import ABC, abstractmethod from datetime import datetime from hashlib import md5 from pathlib import Path # Inspired by https://pypi.org/project/cache-to-disk/. I tried using other # options such as requests-cache, but it was too slow compared to the solution # implemented here. class Cacheable(ABC): """Interface that declares that a particular class's method return values could be cached. The methods should not take a parameter, and cache_key() + method name should uniquely imply the return value of that class.""" @abstractmethod def cache_key(self): """Unique string value used as key for caching.""" pass def get_file_age(file): """Returns the age of file. Args: file: A PosixPath object representing a file. Returns: An int represeting the age in days. """ return (datetime.today() - datetime.fromtimestamp(file.stat().st_mtime)).days # Constants # Default cache directory if none is specified. _DEFAULT_DIR = Path.home() / '.lakshmicache' _CACHE_STR = 'cache_dir' _FORCE_STR = 'force_refresh' _FORCED_FILES_STR = 'forced_files' _MISS_FUNC_STR = 'miss_func' # Dict (string -> object) to keep cache context. # Description of keys to what is stored: # _CACHE_STR: # The pathlib.Path object specifying cache directory. If set to None, # caching is disabled. Default: _DEFAULT_DIR # _FORCE_STR: # If set to True, new values are re-generated once even if a cached one is # available. This is meant for data that is cached for < month (stock prices # and Treasury Bond value). Values that are cached for > 40 days ignore this # flag. Default: False # _FORCED_FILES_STR: # A set of files which are already refreshed once due to _ctx[_FORCE_STR] # being set to True. this is used to ensure we don't re-fetch same values # multiple times in a session. # _MISS_FUNC_STR: # If set, this function is called for every cache miss. _ctx = {_FORCE_STR: False} def set_force_refresh(v): """Sets whether cached values should be refreshed. Args: v: Boolean representing if cached values should be re-generated. """ global _ctx _ctx[_FORCE_STR] = v _ctx[_FORCED_FILES_STR] = set() def set_cache_miss_func(f): """Sets the function to call for cache-misses. Args: f: The function to call whenever a cache-miss happens (i.e. whenever the underlying function is called instead of using a cached value). """ global _ctx if f: _ctx[_MISS_FUNC_STR] = f else: # Clear out previously set function, if any. _ctx.pop(_MISS_FUNC_STR, None) def set_cache_dir(cache_dir): """Sets the cache directory. If the cache directory is not specified, default ~/.lakshmicache is used. Args: cache_dir: The pathlib.Path object specifying cache directory. If set to None, caching is disabled. """ global _ctx _ctx[_CACHE_STR] = cache_dir if cache_dir is None: return cache_dir.mkdir(exist_ok=True) # Create cache dir if one doesn't exist. # Delete old files whose cache values are invalid already. for file in cache_dir.glob('*_*.lkc'): days = int(file.name.split('_')[0]) if get_file_age(file) >= days: file.unlink() def
(file, days): """Helper function to check if the cached value from file is valid. Args: file: The Path object representing a file potentially containing previously cached value. days: Number of days after which the cached value becomes invalid. Returns: True iff the cached value in file is valid. """ MAX_DAYS_TO_FORCE_REFRESH = 40 if ( _ctx[_FORCE_STR] and days < MAX_DAYS_TO_FORCE_REFRESH and file.name not in _ctx[_FORCED_FILES_STR] ): # Ignore cached value. _ctx[_FORCED_FILES_STR].add(file.name) return False return (file.exists() and get_file_age(file) < days) def _call_func(class_obj, func): """Helper function to return value of class_obj.func(). In addition to calling function, this helper also calls the cache_miss function if one is set in the context. Args: class_obj: The object of a particular class implementing Cacheable interface. func: The function whose return values has to be cached. Assumed to take no parameters. Returns: The return value of the func. """ global _ctx if _MISS_FUNC_STR in _ctx: _ctx[_MISS_FUNC_STR]() return func(class_obj) def cache(days): """Returns decorator that caches functions return value on disk for specified number of days. Args: days: Number of days for which to cache the return value of the function. Returns: The decorator. """ def decorator(func): @functools.wraps(func) def new_func(class_obj): global _ctx if _CACHE_STR not in _ctx: # Cache dir not set. Set to default. set_cache_dir(_DEFAULT_DIR) cache_dir = _ctx[_CACHE_STR] if not cache_dir: return _call_func(class_obj, func) key = f'{func.__qualname__}_{class_obj.cache_key()}' filename = f'{days}_{md5(key.encode("utf8")).hexdigest()}.lkc' file = cache_dir / filename if _valid_cached_value(file, days): return pickle.loads(file.read_bytes()) value = _call_func(class_obj, func) file.write_bytes(pickle.dumps(value)) return value return new_func return decorator
_valid_cached_value
model_tam_security_advisory.go
/* Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document. API version: 1.0.9-5517 Contact: [email protected] */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package intersight import ( "encoding/json" "time" "reflect" "strings" ) // TamSecurityAdvisory Intersight representation of a Cisco PSIRT (https://tools.cisco.com/security/center/publicationListing.x) advisory definition. It includes the description of the security advisory and a corresponding reference to the published advisory. It also includes the Intersight data sources needed to evaluate the applicability of this advisory for relevant Intersight managed objects. A PSIRT definition is evaluated against all managed object referenced using the included data sources. Only Cisco TAC and Intersight devops engineers have the ability to create PSIRT definitions in Intersight. type TamSecurityAdvisory struct { TamBaseAdvisory // The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data. ClassId string `json:"ClassId"` // The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property. ObjectType string `json:"ObjectType"` Actions []TamAction `json:"Actions,omitempty"` // Cisco generated identifier for the published security advisory. AdvisoryId *string `json:"AdvisoryId,omitempty"` ApiDataSources []TamApiDataSource `json:"ApiDataSources,omitempty"` // CVSS version 3 base score for the security Advisory. BaseScore *float32 `json:"BaseScore,omitempty"` CveIds []string `json:"CveIds,omitempty"` // Date when the security advisory was first published by Cisco. DatePublished *time.Time `json:"DatePublished,omitempty"` // Date when the security advisory was last updated by Cisco. DateUpdated *time.Time `json:"DateUpdated,omitempty"` // CVSS version 3 environmental score for the security Advisory. EnvironmentalScore *float32 `json:"EnvironmentalScore,omitempty"` // A link to an external URL describing security Advisory in more details. ExternalUrl *string `json:"ExternalUrl,omitempty"` // Recommended action to resolve the security advisory. Recommendation *string `json:"Recommendation,omitempty"` // Cisco assigned status of the published advisory based on whether the investigation is complete or on-going. * `interim` - The Cisco investigation for the advisory is ongoing. Cisco will issue revisions to the advisory when additional information, including fixed software release data, becomes available. * `final` - Cisco has completed its evaluation of the vulnerability described in the advisory. There will be no further updates unless there is a material change in the nature of the vulnerability. Status *string `json:"Status,omitempty"` // CVSS version 3 temporal score for the security Advisory. TemporalScore *float32 `json:"TemporalScore,omitempty"` // Cisco assigned advisory version after latest revision. Version *string `json:"Version,omitempty"` // Workarounds available for the advisory. Workaround *string `json:"Workaround,omitempty"` Organization *OrganizationOrganizationRelationship `json:"Organization,omitempty"` AdditionalProperties map[string]interface{} } type _TamSecurityAdvisory TamSecurityAdvisory // NewTamSecurityAdvisory instantiates a new TamSecurityAdvisory object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTamSecurityAdvisory(classId string, objectType string) *TamSecurityAdvisory { this := TamSecurityAdvisory{} this.ClassId = classId this.ObjectType = objectType var state string = "ready" this.State = &state var status string = "interim" this.Status = &status return &this } // NewTamSecurityAdvisoryWithDefaults instantiates a new TamSecurityAdvisory object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTamSecurityAdvisoryWithDefaults() *TamSecurityAdvisory { this := TamSecurityAdvisory{} var classId string = "tam.SecurityAdvisory" this.ClassId = classId var objectType string = "tam.SecurityAdvisory" this.ObjectType = objectType var status string = "interim" this.Status = &status return &this } // GetClassId returns the ClassId field value func (o *TamSecurityAdvisory) GetClassId() string { if o == nil { var ret string return ret } return o.ClassId } // GetClassIdOk returns a tuple with the ClassId field value // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetClassIdOk() (*string, bool) { if o == nil { return nil, false } return &o.ClassId, true } // SetClassId sets field value func (o *TamSecurityAdvisory) SetClassId(v string) { o.ClassId = v } // GetObjectType returns the ObjectType field value func (o *TamSecurityAdvisory) GetObjectType() string { if o == nil { var ret string return ret } return o.ObjectType } // GetObjectTypeOk returns a tuple with the ObjectType field value // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetObjectTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.ObjectType, true } // SetObjectType sets field value func (o *TamSecurityAdvisory) SetObjectType(v string) { o.ObjectType = v } // GetActions returns the Actions field value if set, zero value otherwise (both if not set or set to explicit null). func (o *TamSecurityAdvisory) GetActions() []TamAction { if o == nil { var ret []TamAction return ret } return o.Actions } // GetActionsOk returns a tuple with the Actions field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *TamSecurityAdvisory) GetActionsOk() (*[]TamAction, bool) { if o == nil || o.Actions == nil { return nil, false } return &o.Actions, true } // HasActions returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasActions() bool { if o != nil && o.Actions != nil { return true } return false } // SetActions gets a reference to the given []TamAction and assigns it to the Actions field. func (o *TamSecurityAdvisory) SetActions(v []TamAction) { o.Actions = v } // GetAdvisoryId returns the AdvisoryId field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetAdvisoryId() string { if o == nil || o.AdvisoryId == nil { var ret string return ret } return *o.AdvisoryId } // GetAdvisoryIdOk returns a tuple with the AdvisoryId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetAdvisoryIdOk() (*string, bool) { if o == nil || o.AdvisoryId == nil { return nil, false } return o.AdvisoryId, true } // HasAdvisoryId returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasAdvisoryId() bool { if o != nil && o.AdvisoryId != nil { return true } return false } // SetAdvisoryId gets a reference to the given string and assigns it to the AdvisoryId field. func (o *TamSecurityAdvisory) SetAdvisoryId(v string) { o.AdvisoryId = &v } // GetApiDataSources returns the ApiDataSources field value if set, zero value otherwise (both if not set or set to explicit null). func (o *TamSecurityAdvisory) GetApiDataSources() []TamApiDataSource { if o == nil { var ret []TamApiDataSource return ret } return o.ApiDataSources } // GetApiDataSourcesOk returns a tuple with the ApiDataSources field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *TamSecurityAdvisory) GetApiDataSourcesOk() (*[]TamApiDataSource, bool) { if o == nil || o.ApiDataSources == nil { return nil, false } return &o.ApiDataSources, true } // HasApiDataSources returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasApiDataSources() bool { if o != nil && o.ApiDataSources != nil { return true } return false } // SetApiDataSources gets a reference to the given []TamApiDataSource and assigns it to the ApiDataSources field. func (o *TamSecurityAdvisory) SetApiDataSources(v []TamApiDataSource) { o.ApiDataSources = v } // GetBaseScore returns the BaseScore field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetBaseScore() float32 { if o == nil || o.BaseScore == nil { var ret float32 return ret } return *o.BaseScore } // GetBaseScoreOk returns a tuple with the BaseScore field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetBaseScoreOk() (*float32, bool) { if o == nil || o.BaseScore == nil { return nil, false } return o.BaseScore, true } // HasBaseScore returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasBaseScore() bool { if o != nil && o.BaseScore != nil { return true } return false } // SetBaseScore gets a reference to the given float32 and assigns it to the BaseScore field. func (o *TamSecurityAdvisory) SetBaseScore(v float32) { o.BaseScore = &v } // GetCveIds returns the CveIds field value if set, zero value otherwise (both if not set or set to explicit null). func (o *TamSecurityAdvisory) GetCveIds() []string { if o == nil { var ret []string return ret } return o.CveIds } // GetCveIdsOk returns a tuple with the CveIds field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *TamSecurityAdvisory) GetCveIdsOk() (*[]string, bool) { if o == nil || o.CveIds == nil { return nil, false } return &o.CveIds, true } // HasCveIds returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasCveIds() bool { if o != nil && o.CveIds != nil { return true } return false } // SetCveIds gets a reference to the given []string and assigns it to the CveIds field. func (o *TamSecurityAdvisory) SetCveIds(v []string) { o.CveIds = v } // GetDatePublished returns the DatePublished field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetDatePublished() time.Time { if o == nil || o.DatePublished == nil { var ret time.Time return ret } return *o.DatePublished } // GetDatePublishedOk returns a tuple with the DatePublished field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetDatePublishedOk() (*time.Time, bool) { if o == nil || o.DatePublished == nil { return nil, false } return o.DatePublished, true } // HasDatePublished returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasDatePublished() bool { if o != nil && o.DatePublished != nil { return true } return false } // SetDatePublished gets a reference to the given time.Time and assigns it to the DatePublished field. func (o *TamSecurityAdvisory) SetDatePublished(v time.Time) { o.DatePublished = &v } // GetDateUpdated returns the DateUpdated field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetDateUpdated() time.Time { if o == nil || o.DateUpdated == nil { var ret time.Time return ret } return *o.DateUpdated } // GetDateUpdatedOk returns a tuple with the DateUpdated field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetDateUpdatedOk() (*time.Time, bool) { if o == nil || o.DateUpdated == nil { return nil, false } return o.DateUpdated, true } // HasDateUpdated returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasDateUpdated() bool { if o != nil && o.DateUpdated != nil { return true } return false } // SetDateUpdated gets a reference to the given time.Time and assigns it to the DateUpdated field. func (o *TamSecurityAdvisory) SetDateUpdated(v time.Time) { o.DateUpdated = &v } // GetEnvironmentalScore returns the EnvironmentalScore field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetEnvironmentalScore() float32 { if o == nil || o.EnvironmentalScore == nil { var ret float32 return ret } return *o.EnvironmentalScore } // GetEnvironmentalScoreOk returns a tuple with the EnvironmentalScore field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetEnvironmentalScoreOk() (*float32, bool) { if o == nil || o.EnvironmentalScore == nil { return nil, false } return o.EnvironmentalScore, true } // HasEnvironmentalScore returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasEnvironmentalScore() bool { if o != nil && o.EnvironmentalScore != nil { return true } return false } // SetEnvironmentalScore gets a reference to the given float32 and assigns it to the EnvironmentalScore field. func (o *TamSecurityAdvisory) SetEnvironmentalScore(v float32) { o.EnvironmentalScore = &v } // GetExternalUrl returns the ExternalUrl field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetExternalUrl() string { if o == nil || o.ExternalUrl == nil { var ret string return ret } return *o.ExternalUrl } // GetExternalUrlOk returns a tuple with the ExternalUrl field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetExternalUrlOk() (*string, bool) { if o == nil || o.ExternalUrl == nil { return nil, false } return o.ExternalUrl, true } // HasExternalUrl returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasExternalUrl() bool { if o != nil && o.ExternalUrl != nil { return true } return false } // SetExternalUrl gets a reference to the given string and assigns it to the ExternalUrl field. func (o *TamSecurityAdvisory) SetExternalUrl(v string) { o.ExternalUrl = &v } // GetRecommendation returns the Recommendation field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetRecommendation() string { if o == nil || o.Recommendation == nil { var ret string return ret } return *o.Recommendation } // GetRecommendationOk returns a tuple with the Recommendation field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetRecommendationOk() (*string, bool) { if o == nil || o.Recommendation == nil { return nil, false } return o.Recommendation, true } // HasRecommendation returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasRecommendation() bool { if o != nil && o.Recommendation != nil { return true } return false } // SetRecommendation gets a reference to the given string and assigns it to the Recommendation field. func (o *TamSecurityAdvisory) SetRecommendation(v string) { o.Recommendation = &v } // GetStatus returns the Status field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetStatus() string { if o == nil || o.Status == nil { var ret string return ret } return *o.Status } // GetStatusOk returns a tuple with the Status field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetStatusOk() (*string, bool) { if o == nil || o.Status == nil { return nil, false } return o.Status, true } // HasStatus returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasStatus() bool { if o != nil && o.Status != nil { return true } return false } // SetStatus gets a reference to the given string and assigns it to the Status field. func (o *TamSecurityAdvisory) SetStatus(v string) { o.Status = &v } // GetTemporalScore returns the TemporalScore field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetTemporalScore() float32 { if o == nil || o.TemporalScore == nil { var ret float32 return ret } return *o.TemporalScore } // GetTemporalScoreOk returns a tuple with the TemporalScore field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetTemporalScoreOk() (*float32, bool) { if o == nil || o.TemporalScore == nil { return nil, false } return o.TemporalScore, true } // HasTemporalScore returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasTemporalScore() bool { if o != nil && o.TemporalScore != nil { return true } return false } // SetTemporalScore gets a reference to the given float32 and assigns it to the TemporalScore field. func (o *TamSecurityAdvisory) SetTemporalScore(v float32) { o.TemporalScore = &v } // GetVersion returns the Version field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetVersion() string { if o == nil || o.Version == nil { var ret string return ret } return *o.Version } // GetVersionOk returns a tuple with the Version field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetVersionOk() (*string, bool) { if o == nil || o.Version == nil { return nil, false } return o.Version, true } // HasVersion returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasVersion() bool { if o != nil && o.Version != nil { return true } return false } // SetVersion gets a reference to the given string and assigns it to the Version field. func (o *TamSecurityAdvisory) SetVersion(v string) { o.Version = &v } // GetWorkaround returns the Workaround field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetWorkaround() string { if o == nil || o.Workaround == nil { var ret string return ret } return *o.Workaround } // GetWorkaroundOk returns a tuple with the Workaround field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetWorkaroundOk() (*string, bool) { if o == nil || o.Workaround == nil { return nil, false } return o.Workaround, true } // HasWorkaround returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasWorkaround() bool { if o != nil && o.Workaround != nil { return true } return false } // SetWorkaround gets a reference to the given string and assigns it to the Workaround field. func (o *TamSecurityAdvisory) SetWorkaround(v string) { o.Workaround = &v } // GetOrganization returns the Organization field value if set, zero value otherwise. func (o *TamSecurityAdvisory) GetOrganization() OrganizationOrganizationRelationship { if o == nil || o.Organization == nil { var ret OrganizationOrganizationRelationship return ret } return *o.Organization } // GetOrganizationOk returns a tuple with the Organization field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TamSecurityAdvisory) GetOrganizationOk() (*OrganizationOrganizationRelationship, bool) { if o == nil || o.Organization == nil { return nil, false } return o.Organization, true } // HasOrganization returns a boolean if a field has been set. func (o *TamSecurityAdvisory) HasOrganization() bool { if o != nil && o.Organization != nil { return true } return false } // SetOrganization gets a reference to the given OrganizationOrganizationRelationship and assigns it to the Organization field. func (o *TamSecurityAdvisory) SetOrganization(v OrganizationOrganizationRelationship) { o.Organization = &v } func (o TamSecurityAdvisory) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} serializedTamBaseAdvisory, errTamBaseAdvisory := json.Marshal(o.TamBaseAdvisory) if errTamBaseAdvisory != nil { return []byte{}, errTamBaseAdvisory } errTamBaseAdvisory = json.Unmarshal([]byte(serializedTamBaseAdvisory), &toSerialize) if errTamBaseAdvisory != nil { return []byte{}, errTamBaseAdvisory } if true { toSerialize["ClassId"] = o.ClassId } if true { toSerialize["ObjectType"] = o.ObjectType } if o.Actions != nil { toSerialize["Actions"] = o.Actions } if o.AdvisoryId != nil { toSerialize["AdvisoryId"] = o.AdvisoryId } if o.ApiDataSources != nil { toSerialize["ApiDataSources"] = o.ApiDataSources } if o.BaseScore != nil { toSerialize["BaseScore"] = o.BaseScore } if o.CveIds != nil { toSerialize["CveIds"] = o.CveIds } if o.DatePublished != nil { toSerialize["DatePublished"] = o.DatePublished } if o.DateUpdated != nil { toSerialize["DateUpdated"] = o.DateUpdated } if o.EnvironmentalScore != nil { toSerialize["EnvironmentalScore"] = o.EnvironmentalScore } if o.ExternalUrl != nil { toSerialize["ExternalUrl"] = o.ExternalUrl } if o.Recommendation != nil { toSerialize["Recommendation"] = o.Recommendation } if o.Status != nil
if o.TemporalScore != nil { toSerialize["TemporalScore"] = o.TemporalScore } if o.Version != nil { toSerialize["Version"] = o.Version } if o.Workaround != nil { toSerialize["Workaround"] = o.Workaround } if o.Organization != nil { toSerialize["Organization"] = o.Organization } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *TamSecurityAdvisory) UnmarshalJSON(bytes []byte) (err error) { type TamSecurityAdvisoryWithoutEmbeddedStruct struct { // The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data. ClassId string `json:"ClassId"` // The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property. ObjectType string `json:"ObjectType"` Actions []TamAction `json:"Actions,omitempty"` // Cisco generated identifier for the published security advisory. AdvisoryId *string `json:"AdvisoryId,omitempty"` ApiDataSources []TamApiDataSource `json:"ApiDataSources,omitempty"` // CVSS version 3 base score for the security Advisory. BaseScore *float32 `json:"BaseScore,omitempty"` CveIds []string `json:"CveIds,omitempty"` // Date when the security advisory was first published by Cisco. DatePublished *time.Time `json:"DatePublished,omitempty"` // Date when the security advisory was last updated by Cisco. DateUpdated *time.Time `json:"DateUpdated,omitempty"` // CVSS version 3 environmental score for the security Advisory. EnvironmentalScore *float32 `json:"EnvironmentalScore,omitempty"` // A link to an external URL describing security Advisory in more details. ExternalUrl *string `json:"ExternalUrl,omitempty"` // Recommended action to resolve the security advisory. Recommendation *string `json:"Recommendation,omitempty"` // Cisco assigned status of the published advisory based on whether the investigation is complete or on-going. * `interim` - The Cisco investigation for the advisory is ongoing. Cisco will issue revisions to the advisory when additional information, including fixed software release data, becomes available. * `final` - Cisco has completed its evaluation of the vulnerability described in the advisory. There will be no further updates unless there is a material change in the nature of the vulnerability. Status *string `json:"Status,omitempty"` // CVSS version 3 temporal score for the security Advisory. TemporalScore *float32 `json:"TemporalScore,omitempty"` // Cisco assigned advisory version after latest revision. Version *string `json:"Version,omitempty"` // Workarounds available for the advisory. Workaround *string `json:"Workaround,omitempty"` Organization *OrganizationOrganizationRelationship `json:"Organization,omitempty"` } varTamSecurityAdvisoryWithoutEmbeddedStruct := TamSecurityAdvisoryWithoutEmbeddedStruct{} err = json.Unmarshal(bytes, &varTamSecurityAdvisoryWithoutEmbeddedStruct) if err == nil { varTamSecurityAdvisory := _TamSecurityAdvisory{} varTamSecurityAdvisory.ClassId = varTamSecurityAdvisoryWithoutEmbeddedStruct.ClassId varTamSecurityAdvisory.ObjectType = varTamSecurityAdvisoryWithoutEmbeddedStruct.ObjectType varTamSecurityAdvisory.Actions = varTamSecurityAdvisoryWithoutEmbeddedStruct.Actions varTamSecurityAdvisory.AdvisoryId = varTamSecurityAdvisoryWithoutEmbeddedStruct.AdvisoryId varTamSecurityAdvisory.ApiDataSources = varTamSecurityAdvisoryWithoutEmbeddedStruct.ApiDataSources varTamSecurityAdvisory.BaseScore = varTamSecurityAdvisoryWithoutEmbeddedStruct.BaseScore varTamSecurityAdvisory.CveIds = varTamSecurityAdvisoryWithoutEmbeddedStruct.CveIds varTamSecurityAdvisory.DatePublished = varTamSecurityAdvisoryWithoutEmbeddedStruct.DatePublished varTamSecurityAdvisory.DateUpdated = varTamSecurityAdvisoryWithoutEmbeddedStruct.DateUpdated varTamSecurityAdvisory.EnvironmentalScore = varTamSecurityAdvisoryWithoutEmbeddedStruct.EnvironmentalScore varTamSecurityAdvisory.ExternalUrl = varTamSecurityAdvisoryWithoutEmbeddedStruct.ExternalUrl varTamSecurityAdvisory.Recommendation = varTamSecurityAdvisoryWithoutEmbeddedStruct.Recommendation varTamSecurityAdvisory.Status = varTamSecurityAdvisoryWithoutEmbeddedStruct.Status varTamSecurityAdvisory.TemporalScore = varTamSecurityAdvisoryWithoutEmbeddedStruct.TemporalScore varTamSecurityAdvisory.Version = varTamSecurityAdvisoryWithoutEmbeddedStruct.Version varTamSecurityAdvisory.Workaround = varTamSecurityAdvisoryWithoutEmbeddedStruct.Workaround varTamSecurityAdvisory.Organization = varTamSecurityAdvisoryWithoutEmbeddedStruct.Organization *o = TamSecurityAdvisory(varTamSecurityAdvisory) } else { return err } varTamSecurityAdvisory := _TamSecurityAdvisory{} err = json.Unmarshal(bytes, &varTamSecurityAdvisory) if err == nil { o.TamBaseAdvisory = varTamSecurityAdvisory.TamBaseAdvisory } else { return err } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "ClassId") delete(additionalProperties, "ObjectType") delete(additionalProperties, "Actions") delete(additionalProperties, "AdvisoryId") delete(additionalProperties, "ApiDataSources") delete(additionalProperties, "BaseScore") delete(additionalProperties, "CveIds") delete(additionalProperties, "DatePublished") delete(additionalProperties, "DateUpdated") delete(additionalProperties, "EnvironmentalScore") delete(additionalProperties, "ExternalUrl") delete(additionalProperties, "Recommendation") delete(additionalProperties, "Status") delete(additionalProperties, "TemporalScore") delete(additionalProperties, "Version") delete(additionalProperties, "Workaround") delete(additionalProperties, "Organization") // remove fields from embedded structs reflectTamBaseAdvisory := reflect.ValueOf(o.TamBaseAdvisory) for i := 0; i < reflectTamBaseAdvisory.Type().NumField(); i++ { t := reflectTamBaseAdvisory.Type().Field(i) if jsonTag := t.Tag.Get("json"); jsonTag != "" { fieldName := "" if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 { fieldName = jsonTag[:commaIdx] } else { fieldName = jsonTag } if fieldName != "AdditionalProperties" { delete(additionalProperties, fieldName) } } } o.AdditionalProperties = additionalProperties } return err } type NullableTamSecurityAdvisory struct { value *TamSecurityAdvisory isSet bool } func (v NullableTamSecurityAdvisory) Get() *TamSecurityAdvisory { return v.value } func (v *NullableTamSecurityAdvisory) Set(val *TamSecurityAdvisory) { v.value = val v.isSet = true } func (v NullableTamSecurityAdvisory) IsSet() bool { return v.isSet } func (v *NullableTamSecurityAdvisory) Unset() { v.value = nil v.isSet = false } func NewNullableTamSecurityAdvisory(val *TamSecurityAdvisory) *NullableTamSecurityAdvisory { return &NullableTamSecurityAdvisory{value: val, isSet: true} } func (v NullableTamSecurityAdvisory) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTamSecurityAdvisory) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
{ toSerialize["Status"] = o.Status }
main.go
package main import ( "time" bx "trader/bexchange" ) func
() { actions := make(chan *bx.Action) done := make(chan bool) go bx.ConsoleActionHandler(actions, done) ob := bx.NewOrderBook(actions) //ob.AddOrder(bx.NewOrder(1, false, 50, 50)) //ob.AddOrder(bx.NewOrder(2, false, 45, 25)) //ob.AddOrder(bx.NewOrder(3, false, 45, 25)) //ob.AddOrder(bx.NewOrder(4, true, 55, 75)) //ob.AddOrder(bx.NewOrder(5, false, 50, 50)) //ob.CancelOrder(1, 50, false) go func() { for { time.Sleep(30 * time.Second) ob.BuyPrice5() ob.SellPrice5() ob.GetFinalPrice() } }() ob.AddOrder(bx.NewOrder(1, true, 2082.34, 1)) ob.AddOrder(bx.NewOrder(2, true, 2087.6, 2)) ob.AddOrder(bx.NewOrder(3, true, 2087.8, 1)) ob.AddOrder(bx.NewOrder(4, true, 2085.01, 5)) ob.AddOrder(bx.NewOrder(5, true, 2088.02, 3)) ob.AddOrder(bx.NewOrder(6, false, 2087.60, 6)) ob.AddOrder(bx.NewOrder(7, true, 2081.77, 7)) ob.AddOrder(bx.NewOrder(8, true, 2086.0, 3)) ob.AddOrder(bx.NewOrder(9, true, 2088.33, 1)) ob.AddOrder(bx.NewOrder(10, false, 2086.54, 2)) ob.AddOrder(bx.NewOrder(11, false, 2086.55, 5)) ob.AddOrder(bx.NewOrder(12, true, 2086.55, 3)) ob.Done() <-done }
main
networks.py
import importlib import logging import os import pkgutil import sys from collections import OrderedDict from inspect import isfunction, getmembers, signature import torch import models.feature_arch as feature_arch logger = logging.getLogger('base') class RegisteredModelNameError(Exception): def
(self, name_error): super().__init__(f'Registered DLAS modules must start with `register_`. Incorrect registration: {name_error}') # Decorator that allows API clients to show DLAS how to build a nn.Module from an opt dict. # Functions with this decorator should have a specific naming format: # `register_<name>` where <name> is the name that will be used in configuration files to reference this model. # Functions with this decorator are expected to take a single argument: # - opt: A dict with the configuration options for building the module. # They should return: # - A torch.nn.Module object for the model being defined. def register_model(func): if func.__name__.startswith("register_"): func._dlas_model_name = func.__name__[9:] assert func._dlas_model_name else: raise RegisteredModelNameError(func.__name__) func._dlas_registered_model = True return func def find_registered_model_fns(base_path='models'): found_fns = {} module_iter = pkgutil.walk_packages([base_path]) for mod in module_iter: if os.name == 'nt': if os.path.join(os.getcwd(), base_path) not in mod.module_finder.path: continue # I have no idea why this is necessary - I think it's a bug in the latest PyWindows release. if mod.ispkg: EXCLUSION_LIST = ['flownet2'] if mod.name not in EXCLUSION_LIST: found_fns.update(find_registered_model_fns(f'{base_path}/{mod.name}')) else: mod_name = f'{base_path}/{mod.name}'.replace('/', '.') importlib.import_module(mod_name) for mod_fn in getmembers(sys.modules[mod_name], isfunction): if hasattr(mod_fn[1], "_dlas_registered_model"): found_fns[mod_fn[1]._dlas_model_name] = mod_fn[1] return found_fns class CreateModelError(Exception): def __init__(self, name, available): super().__init__(f'Could not find the specified model name: {name}. Tip: If your model is in a' f' subdirectory, that directory must contain an __init__.py to be scanned. Available models:' f'{available}') def create_model(opt, opt_net, other_nets=None): which_model = opt_net['which_model'] # For backwards compatibility. if not which_model: which_model = opt_net['which_model_G'] if not which_model: which_model = opt_net['which_model_D'] registered_fns = find_registered_model_fns() if which_model not in registered_fns.keys(): raise CreateModelError(which_model, list(registered_fns.keys())) num_params = len(signature(registered_fns[which_model]).parameters) if num_params == 2: return registered_fns[which_model](opt_net, opt) else: return registered_fns[which_model](opt_net, opt, other_nets)
__init__
photo.js
import styled from '@emotion/styled' import { Box, Card, Text, Image, useColorMode } from 'theme-ui' import theme from '../lib/theme' const Caption = styled(Text)` display: block; font-size: ${theme.fontSizes[1]}px; line-height: ${theme.lineHeights.body}; padding: ${theme.space[2]}px ${theme.space[3]}px; position: absolute; bottom: 0; border-radius: 0 0 ${theme.radii.extra}px ${theme.radii.extra}px; width: 100%; max-width: 100%; z-index: 0; ` const Photo = ({ src, alt, showAlt, dark, ...props }) => { const [colorMode] = useColorMode() const showCaption = showAlt && alt return ( <Card {...props} sx={{ p: [0, 0, 0], boxShadow: 'elevated', borderRadius: 'extra', position: 'relative',
...props.sx }} > <Image src={src} alt={alt} loading="lazy" sx={{ width: '100%', height: '100%', objectFit: 'cover' }} /> {showCaption && ( <Caption variant={dark ? 'cards.translucentDark' : 'cards.translucent'} children={alt} /> )} </Card> ) } export default Photo
maxWidth: '100%', lineHeight: 0,
start_apm_maintenance_mode_responses.go
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. 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. // Code generated by go-swagger; DO NOT EDIT. package clusters_apm // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/elastic/cloud-sdk-go/pkg/models" ) // StartApmMaintenanceModeReader is a Reader for the StartApmMaintenanceMode structure. type StartApmMaintenanceModeReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *StartApmMaintenanceModeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 202: result := NewStartApmMaintenanceModeAccepted() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 403: result := NewStartApmMaintenanceModeForbidden() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewStartApmMaintenanceModeNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 449: result := NewStartApmMaintenanceModeRetryWith() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code()) } } // NewStartApmMaintenanceModeAccepted creates a StartApmMaintenanceModeAccepted with default headers values func NewStartApmMaintenanceModeAccepted() *StartApmMaintenanceModeAccepted { return &StartApmMaintenanceModeAccepted{} } /*StartApmMaintenanceModeAccepted handles this case with default header values. The start maintenance mode command was issued successfully, use the "GET" command on the /{cluster_id} resource to monitor progress */ type StartApmMaintenanceModeAccepted struct { Payload *models.ClusterCommandResponse } func (o *StartApmMaintenanceModeAccepted) Error() string { return fmt.Sprintf("[POST /clusters/apm/{cluster_id}/instances/{instance_ids}/maintenance-mode/_start][%d] startApmMaintenanceModeAccepted %+v", 202, o.Payload) } func (o *StartApmMaintenanceModeAccepted) GetPayload() *models.ClusterCommandResponse { return o.Payload } func (o *StartApmMaintenanceModeAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ClusterCommandResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewStartApmMaintenanceModeForbidden creates a StartApmMaintenanceModeForbidden with default headers values func NewStartApmMaintenanceModeForbidden() *StartApmMaintenanceModeForbidden { return &StartApmMaintenanceModeForbidden{} } /*StartApmMaintenanceModeForbidden handles this case with default header values. The start maintenance mode command was prohibited for the given cluster. (code: `clusters.command_prohibited`) */ type StartApmMaintenanceModeForbidden struct { /*The error codes associated with the response */ XCloudErrorCodes string Payload *models.BasicFailedReply } func (o *StartApmMaintenanceModeForbidden) Error() string { return fmt.Sprintf("[POST /clusters/apm/{cluster_id}/instances/{instance_ids}/maintenance-mode/_start][%d] startApmMaintenanceModeForbidden %+v", 403, o.Payload) } func (o *StartApmMaintenanceModeForbidden) GetPayload() *models.BasicFailedReply { return o.Payload } func (o *StartApmMaintenanceModeForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response header x-cloud-error-codes o.XCloudErrorCodes = response.GetHeader("x-cloud-error-codes") o.Payload = new(models.BasicFailedReply) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewStartApmMaintenanceModeNotFound creates a StartApmMaintenanceModeNotFound with default headers values func NewStartApmMaintenanceModeNotFound() *StartApmMaintenanceModeNotFound { return &StartApmMaintenanceModeNotFound{} } /*StartApmMaintenanceModeNotFound handles this case with default header values. * The cluster specified by {cluster_id} cannot be found. (code: `clusters.cluster_not_found`) * One or more of the instances specified at {instance_ids} could not be found. (code: `clusters.instances_not_found`) */ type StartApmMaintenanceModeNotFound struct { /*The error codes associated with the response */ XCloudErrorCodes string Payload *models.BasicFailedReply } func (o *StartApmMaintenanceModeNotFound) Error() string { return fmt.Sprintf("[POST /clusters/apm/{cluster_id}/instances/{instance_ids}/maintenance-mode/_start][%d] startApmMaintenanceModeNotFound %+v", 404, o.Payload) } func (o *StartApmMaintenanceModeNotFound) GetPayload() *models.BasicFailedReply { return o.Payload } func (o *StartApmMaintenanceModeNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response header x-cloud-error-codes o.XCloudErrorCodes = response.GetHeader("x-cloud-error-codes") o.Payload = new(models.BasicFailedReply) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewStartApmMaintenanceModeRetryWith creates a StartApmMaintenanceModeRetryWith with default headers values func NewStartApmMaintenanceModeRetryWith() *StartApmMaintenanceModeRetryWith
/*StartApmMaintenanceModeRetryWith handles this case with default header values. Elevated permissions are required. (code: `root.unauthorized.rbac.elevated_permissions_required`) */ type StartApmMaintenanceModeRetryWith struct { /*The error codes associated with the response */ XCloudErrorCodes string Payload *models.BasicFailedReply } func (o *StartApmMaintenanceModeRetryWith) Error() string { return fmt.Sprintf("[POST /clusters/apm/{cluster_id}/instances/{instance_ids}/maintenance-mode/_start][%d] startApmMaintenanceModeRetryWith %+v", 449, o.Payload) } func (o *StartApmMaintenanceModeRetryWith) GetPayload() *models.BasicFailedReply { return o.Payload } func (o *StartApmMaintenanceModeRetryWith) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { // response header x-cloud-error-codes o.XCloudErrorCodes = response.GetHeader("x-cloud-error-codes") o.Payload = new(models.BasicFailedReply) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
{ return &StartApmMaintenanceModeRetryWith{} }
orphan.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Orphan checker: every impl either implements a trait defined in this //! crate or pertains to a type defined in this crate. use middle::traits; use middle::ty; use syntax::ast::{Item, ItemImpl}; use syntax::ast; use syntax::ast_util; use syntax::codemap::Span; use syntax::visit; use util::ppaux::Repr; pub fn check(tcx: &ty::ctxt) { let mut orphan = OrphanChecker { tcx: tcx }; visit::walk_crate(&mut orphan, tcx.map.krate()); } struct OrphanChecker<'cx, 'tcx:'cx> { tcx: &'cx ty::ctxt<'tcx> } impl<'cx, 'tcx> OrphanChecker<'cx, 'tcx> { fn check_def_id(&self, span: Span, def_id: ast::DefId) { if def_id.krate != ast::LOCAL_CRATE { span_err!(self.tcx.sess, span, E0116, "cannot associate methods with a type outside the \ crate the type is defined in; define and implement \ a trait or new type instead"); } } } impl<'cx, 'tcx,'v> visit::Visitor<'v> for OrphanChecker<'cx, 'tcx> { fn visit_item(&mut self, item: &'v ast::Item) { let def_id = ast_util::local_def(item.id); match item.node { ast::ItemImpl(_, _, None, _, _) => { // For inherent impls, self type must be a nominal type // defined in this crate.
let self_ty = ty::lookup_item_type(self.tcx, def_id).ty; match self_ty.sty { ty::ty_enum(def_id, _) | ty::ty_struct(def_id, _) => { self.check_def_id(item.span, def_id); } ty::ty_trait(ref data) => { self.check_def_id(item.span, data.principal_def_id()); } _ => { span_err!(self.tcx.sess, item.span, E0118, "no base type found for inherent implementation; \ implement a trait or new type instead"); } } } ast::ItemImpl(_, _, Some(_), _, _) => { // "Trait" impl debug!("coherence2::orphan check: trait impl {}", item.repr(self.tcx)); if traits::is_orphan_impl(self.tcx, def_id) { span_err!(self.tcx.sess, item.span, E0117, "cannot provide an extension implementation \ where both trait and type are not defined in this crate"); } } _ => { // Not an impl } } visit::walk_item(self, item); } }
debug!("coherence2::orphan check: inherent impl {}", item.repr(self.tcx));
sndfile.rs
// The MIT License (MIT) // // Copyright (c) 2013 Jeremy Letang ([email protected]) // // 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. /*! * Libsndfile is a library designed to allow the reading and writing of many * different sampled sound file formats (such as MS Windows WAV and * the Apple/SGI AIFF format) through one standard library interface. * * During read and write operations, formats are seamlessly converted between the * format the application program has requested or supplied and the file's data * format. The application programmer can remain blissfully unaware of issues * such as file endian-ness and data format */ #![allow(dead_code)] //use std::str::from_utf8; use std::str::*; use std::ptr; use std::ffi::CString; use std::ffi::CStr; use std::ops::BitOr; use std::i32::*; use std::intrinsics::transmute; #[doc(hidden)] mod libsndfile { #[link(name = "sndfile")] extern {} } #[doc(hidden)] #[path = "sndfile_ffi.rs"] mod ffi; /// The SndInfo structure is for passing data between the calling /// function and the library when opening a file for reading or writing. #[repr(C)] #[derive(Clone)] pub struct SndInfo { pub frames : i64, pub samplerate : i32, pub channels : i32, pub format : i32, pub sections : i32, pub seekable : i32 } /// Modes availables for the open function. /// /// * Read - Read only mode /// * Write - Write only mode /// * ReadWrite - Read and Write mode #[derive(Copy, Clone)] pub enum OpenMode { Read = ffi::SFM_READ as isize, Write = ffi::SFM_WRITE as isize, ReadWrite = ffi::SFM_RDWR as isize } /// Type of strings available for method get_string() #[derive(Copy, Clone)] pub enum StringSoundType { Title = ffi::SF_STR_TITLE as isize, Copyright = ffi::SF_STR_COPYRIGHT as isize, Software = ffi::SF_STR_SOFTWARE as isize, Artist = ffi::SF_STR_ARTIST as isize, Comment = ffi::SF_STR_COMMENT as isize, Date = ffi::SF_STR_DATE as isize, Album = ffi::SF_STR_ALBUM as isize, License = ffi::SF_STR_LICENSE as isize, TrackNumber = ffi::SF_STR_TRACKNUMBER as isize, Genre = ffi::SF_STR_GENRE as isize } /// Types of error who can be return by API functions #[repr(C)] #[derive(Copy, Clone)] pub enum Error { NoError = ffi::SF_ERR_NO_ERROR as isize, UnrecognizedFormat = ffi::SF_ERR_UNRECOGNISED_FORMAT as isize, SystemError = ffi::SF_ERR_SYSTEM as isize, MalformedFile = ffi::SF_ERR_MALFORMED_FILE as isize, UnsupportedEncoding = ffi::SF_ERR_UNSUPPORTED_ENCODING as isize, } /// Enum to set the offset with method seek /// /// * SeekSet - The offset is set to the start of the audio data plus offset (multichannel) frames. /// * SeekCur - The offset is set to its current location plus offset (multichannel) frames. /// * SeekEnd - The offset is set to the end of the data plus offset (multichannel) frames. #[derive(Copy, Clone)] pub enum SeekMode { SeekSet = ffi::SEEK_SET as isize, SeekCur = ffi::SEEK_CUR as isize, SeekEnd = ffi::SEEK_END as isize } /// Enum who contains the list of the supported audio format /// /// * FormatWav - Microsoft WAV format (little endian) /// * FormatAiff - Apple/SGI AIFF format (big endian) /// * FormatAu - Sun/NeXT AU format (big endian) /// * FormatRaw - RAW PCM data /// * FormatPaf - Ensoniq PARIS file format /// * FormatSvx - Amiga IFF / SVX8 / SV16 format /// * FormatNist - Sphere NIST format /// * FormatVoc - VOC files /// * FormatIrcam - Berkeley/IRCAM/CARL /// * FormatW64 - Sonic Foundry's 64 bit RIFF/WAV /// * FormatMat4 - Matlab (tm) V4.2 / GNU Octave 2.0 /// * FormatMat5 - Matlab (tm) V5.0 / GNU Octave 2.1 /// * FormatPvf - Portable Voice Format /// * FormatXi - Fasttracker 2 Extended Instrument /// * FormatHtk - HMM Tool Kit format /// * FormatSds - Midi Sample Dump Standard /// * FormatAvr - Audio Visual Research /// * FormatWavex - MS WAVE with WAVEFORMATEX /// * FormatSd2 - Sound Designer 2 /// * FormatFlac - FLAC lossless file format /// * FormatCaf - Core Audio File format /// * FormatWve - Psion WVE format /// * FormatOgg - Xiph OGG container /// * FormatMpc2k - Akai MPC 2000 sampler /// * FormatRf64 - RF64 WAV file /// * FormatPcmS8 - Signed 8 bit data /// * FormatPcm16 - Signed 16 bit data /// * FormatPcm24 - Signed 24 bit data /// * FormatPcm32 - Signed 32 bit data /// * FormatPcmU8 - Unsigned 8 bit data (WAV and RAW only) /// * FormatFloat - 32 bit float data /// * FormatDouble - 64 bit float data /// * FormatUlaw - U-Law encoded /// * FormatAlaw - A-Law encoded /// * FormatImaAdpcm - IMA ADPCM /// * FormatApcm - Microsoft ADPCM /// * FormatGsm610 - GSM 6.10 encoding /// * FormatVoxAdpcm - Oki Dialogic ADPCM encoding /// * FormatG72132 - 32kbs G721 ADPCM encoding /// * FormatG72324 - 24kbs G723 ADPCM encoding /// * FormatG72340 - 40kbs G723 ADPCM encoding /// * FormatDww12 - 12 bit Delta Width Variable Word encoding /// * FormatDww16 - 16 bit Delta Width Variable Word encoding /// * FormatDww24 - 24 bit Delta Width Variable Word encoding /// * FormatDwwN - N bit Delta Width Variable Word encoding /// * FormatDpcm8 - 8 bit differential PCM (XI only) /// * FormatDpcm16 - 16 bit differential PCM (XI only) /// * FormatVorbis - Xiph Vorbis encoding /// * EndianFile - Default file endian-ness /// * EndianLittle - Force little endian-ness /// * EndianBig - Force big endian-ness /// * EndianCpu - Force CPU endian-ness #[repr(C)] #[derive(Debug, Clone, PartialOrd, PartialEq, Copy)] pub enum FormatType { FormatWav = ffi::SF_FORMAT_WAV as isize, FormatAiff = ffi::SF_FORMAT_AIFF as isize, FormatAu = ffi::SF_FORMAT_AU as isize, FormatRaw = ffi::SF_FORMAT_RAW as isize, FormatPaf = ffi::SF_FORMAT_PAF as isize, FormatSvx = ffi::SF_FORMAT_SVX as isize, FormatNist = ffi::SF_FORMAT_NIST as isize, FormatVoc = ffi::SF_FORMAT_VOC as isize, FormatIrcam = ffi::SF_FORMAT_IRCAM as isize, FormatW64 = ffi::SF_FORMAT_W64 as isize, FormatMat4 = ffi::SF_FORMAT_MAT4 as isize, FormatMat5 = ffi::SF_FORMAT_MAT5 as isize, FormatPvf = ffi::SF_FORMAT_PVF as isize, FormatXi = ffi::SF_FORMAT_XI as isize, FormatHtk = ffi::SF_FORMAT_HTK as isize, FormatSds = ffi::SF_FORMAT_SDS as isize, FormatAvr = ffi::SF_FORMAT_AVR as isize, FormatWavex = ffi::SF_FORMAT_WAVEX as isize, FormatSd2 = ffi::SF_FORMAT_SD2 as isize, FormatFlac = ffi::SF_FORMAT_FLAC as isize, FormatCaf = ffi::SF_FORMAT_CAF as isize, FormatWve = ffi::SF_FORMAT_WVE as isize, FormatOgg = ffi::SF_FORMAT_OGG as isize, FormatMpc2k = ffi::SF_FORMAT_MPC2K as isize, FormatRf64 = ffi::SF_FORMAT_RF64 as isize, FormatPcmS8 = ffi::SF_FORMAT_PCM_S8 as isize, FormatPcm16 = ffi::SF_FORMAT_PCM_16 as isize, FormatPcm24 = ffi::SF_FORMAT_PCM_24 as isize, FormatPcm32 = ffi::SF_FORMAT_PCM_32 as isize, FormatPcmU8 = ffi::SF_FORMAT_PCM_U8 as isize, FormatFloat = ffi::SF_FORMAT_FLOAT as isize, FormatDouble = ffi::SF_FORMAT_DOUBLE as isize, FormatUlaw = ffi::SF_FORMAT_ULAW as isize, FormatAlaw = ffi::SF_FORMAT_ALAW as isize, FormatImaAdpcm = ffi::SF_FORMAT_IMA_ADPCM as isize, FormatApcm = ffi::SF_FORMAT_MS_ADPCM as isize, FormatGsm610 = ffi::SF_FORMAT_GSM610 as isize, FormatVoxAdpcm = ffi::SF_FORMAT_VOX_ADPCM as isize, FormatG72132 = ffi::SF_FORMAT_G721_32 as isize, FormatG72324 = ffi::SF_FORMAT_G723_24 as isize, FormatG72340 = ffi::SF_FORMAT_G723_40 as isize, FormatDww12 = ffi::SF_FORMAT_DWVW_12 as isize, FormatDww16 = ffi::SF_FORMAT_DWVW_16 as isize, FormatDww24 = ffi::SF_FORMAT_DWVW_24 as isize, FormatDwwN = ffi::SF_FORMAT_DWVW_N as isize, FormatDpcm8 = ffi::SF_FORMAT_DPCM_8 as isize, FormatDpcm16 = ffi::SF_FORMAT_DPCM_16 as isize, FormatVorbis = ffi::SF_FORMAT_VORBIS as isize, EndianFile = ffi::SF_ENDIAN_FILE as isize, EndianLittle = ffi::SF_ENDIAN_LITTLE as isize, EndianBig = ffi::SF_ENDIAN_BIG as isize, EndianCpu = ffi::SF_ENDIAN_CPU as isize, FormatSubMask = ffi::SF_FORMAT_SUBMASK as isize, FormatTypeMask = ffi::SF_FORMAT_TYPEMASK as isize, } impl BitOr for FormatType { type Output = FormatType; fn bitor(self, _rhs: FormatType) -> Self::Output { unsafe { transmute((self as i32) | (_rhs as i32)) } } //fn bitor(self, rhs: RHS) -> Self::Output; } /// SndFile object, used to load/store sound from a file path or an fd. pub struct SndFile { handle : ffi::SNDFILEhandle, //*const ffi::SNDFILE, info : Box<SndInfo> } impl Clone for SndFile { fn clone(&self) -> SndFile { SndFile { handle : self.handle, info : self.info.clone() } } } impl SndFile { /** * Construct SndFile object with the path to the music and a mode to open it. * * # Arguments * * path - The path to load the music * * mode - The mode to open the music * * Return Ok() containing the SndFile on success, a string representation of * the error otherwise. */ pub fn new(path : &str, mode : OpenMode) -> Result<SndFile, String> { let mut info = Box::new(SndInfo { frames : 0, samplerate : 0, channels : 0, format : 0, sections : 0, seekable : 0 }); let c_path = CString::new(path).unwrap(); let tmp_sndfile = { unsafe {ffi::sf_open(c_path.as_ptr() as *mut _, mode as i32, &mut *info) } }; if tmp_sndfile == 0 { Err(unsafe { from_utf8(CStr::from_ptr(ffi::sf_strerror(0) as *const _).to_bytes()).unwrap().to_owned() }) } else { Ok(SndFile { handle : tmp_sndfile, info : info }) } } /** * Construct SndFile object with the path to the music and a mode to open it. * * # Arguments * * path - The path to load the music * * mode - The mode to open the music * * info - The SndInfo to pass to the file * * Return Ok() containing the SndFile on success, a string representation of * the error otherwise. */ pub fn new_with_info(path : &str, mode : OpenMode, mut info: Box<SndInfo>) -> Result<SndFile, String> { let c_path = CString::new(path).unwrap(); let tmp_sndfile = { unsafe {ffi::sf_open(c_path.as_ptr() as *mut _, mode as i32, &mut *info) } }; if tmp_sndfile == 0 { Err(unsafe { from_utf8(CStr::from_ptr(ffi::sf_strerror(0) as *const _).to_bytes()).unwrap().to_owned() }) } else { Ok(SndFile { handle : tmp_sndfile, info : info }) } } /** * Construct SndFile object with the fd of the file containing the music * and a mode to open it. * * # Arguments * * fd - The fd to load the music * * mode - The mode to open the music * * close_desc - Should SndFile close the fd at exit? * * Return Ok() containing the SndFile on success, a string representation * of the error otherwise. */ pub fn new_with_fd(fd : i32, mode : OpenMode, close_desc : bool) -> Result<SndFile, String> { let mut info = Box::new(SndInfo { frames : 0, samplerate : 0, channels : 0, format : 0, sections : 0, seekable : 0 }); let tmp_sndfile = match close_desc { true => unsafe { ffi::sf_open_fd(fd, mode as i32, &mut *info, ffi::SF_TRUE) }, false => unsafe { ffi::sf_open_fd(fd, mode as i32, &mut *info, ffi::SF_FALSE) } }; if tmp_sndfile == 0 { Err(unsafe { from_utf8(CStr::from_ptr(ffi::sf_strerror(0) as *const _).to_bytes()).unwrap().to_owned() }) } else { Ok(SndFile { handle : tmp_sndfile, info : info }) } } /// Return the SndInfo struct of the current music. pub fn get_sndinfo(&self) -> SndInfo { *self.info.clone() } /** * Retrieve a tag contained by the music. * * # Argument * * string_type - The type of the tag to retrieve * * Return Some(String) if the tag is found, None otherwise. */ pub fn get_string(&self, string_type : StringSoundType) -> Option<String> { let c_string = unsafe { ffi::sf_get_string(self.handle, string_type as i32) }; if c_string == ptr::null_mut() { None } else { Some(unsafe { from_utf8(CStr::from_ptr(c_string as *const _).to_bytes()).unwrap().to_owned() //CString::new(c_string as *const i8, false).as_str().unwrap().to_string() }) } } /** * Set a tag on the music file. * * # Arguments * * string_type - The type of the tag to set * * string - The string to set. * * Return NoError on success, an other error code otherwise */ pub fn set_string(&mut self, string_type : StringSoundType, string : String) -> Error { //let c_string = CString::new(string).unwrap(); unsafe { ffi::sf_set_string(self.handle, string_type as i32, string.as_ptr() as *mut _) } } /** * Check if the format of the SndInfo struct is valid. * * # Argument * * info - The SndInfo struct to test * * Return true if the struct is valid, false otherwise. */ pub fn check_format<'r>(info : &'r mut SndInfo) -> bool { match unsafe {ffi::sf_format_check(info) } { ffi::SF_TRUE => true, ffi::SF_FALSE => false, _ => unreachable!() } } /** * Close the SndFile object. * * This function must be called before the exist of the program to destroy * all the resources. * * Return NoError if destruction success, an other error code otherwise. */ pub fn close(&self) -> Error { unsafe { ffi::sf_close(self.handle) } } /** * If the file is opened Write or ReadWrite, call the operating system's * function to force the writing of all file cache buffers to disk. * If the file is opened Read no action is taken. */ pub fn write_sync(&mut self) -> () { unsafe { ffi::sf_write_sync(self.handle) } } pub fn seek(&mut self, frames : i64, whence : SeekMode) -> i64{ unsafe { ffi::sf_seek(self.handle, frames, whence as i32) } } /** * Read items of type i16 * * # Arguments * * array - The array to fill with the items. * * items - The max capacity of the array. * * Return the count of items. */ pub fn read_i16<'r>(&'r mut self, array : &'r mut [i16], items : i64) -> i64 { unsafe { ffi::sf_read_short(self.handle, array.as_mut_ptr(), items) } } /** * Read items of type i32 * * # Arguments * * array - The array to fill with the items. * * items - The max capacity of the array. * * Return the count of items. */ pub fn read_int<'r>(&'r mut self, array : &'r mut [i32], items : i64) -> i64 { unsafe { ffi::sf_read_int(self.handle, array.as_mut_ptr(), items) } } /** * Read items of type f32 * * # Arguments * * array - The array to fill with the items. * * items - The max capacity of the array. * * Return the count of items. */ pub fn read_f32<'r>(&'r mut self, array : &'r mut [f32], items : i64) -> i64 { unsafe { ffi::sf_read_float(self.handle, array.as_mut_ptr(), items) } } /** * Read items of type f64 * * # Arguments * * array - The array to fill with the items. * * items - The max capacity of the array. * * Return the count of items. */ pub fn read_f64<'r>(&'r mut self, array : &'r mut [f64], items : i64) -> i64 { unsafe { ffi::sf_read_double(self.handle, array.as_mut_ptr(), items) } } /** * Read frames of type i16 * * # Arguments * * array - The array to fill with the frames. * * items - The max capacity of the array. * * Return the count of frames. */ pub fn readf_i16<'r>(&'r mut self, array : &'r mut [i16], frames : i64) -> i64 { unsafe { ffi::sf_readf_short(self.handle, array.as_mut_ptr(), frames) } } /** * Read frames of type i32 * * # Arguments * * array - The array to fill with the frames. * * items - The max capacity of the array. * * Return the count of frames. */ pub fn readf_int<'r>(&'r mut self, array : &'r mut [i32], frames : i64) -> i64 { unsafe { ffi::sf_readf_int(self.handle, array.as_mut_ptr(), frames) } } /** * Read frames of type f32 * * # Arguments * * array - The array to fill with the frames. * * items - The max capacity of the array. * * Return the count of frames. */ pub fn readf_f32<'r>(&'r mut self, array : &'r mut [f32], frames : i64) -> i64 { unsafe { ffi::sf_readf_float(self.handle, array.as_mut_ptr(), frames) } } /** * Read frames of type f64 * * # Arguments * * array - The array to fill with the frames. * * items - The max capacity of the array. * * Return the count of frames. */ pub fn readf_f64<'r>(&'r mut self, array : &'r mut [f64], frames : i64) -> i64 { unsafe { ffi::sf_readf_double(self.handle, array.as_mut_ptr(), frames) } } /** * Write items of type i16 * * # Arguments * * array - The array of items to write. * * items - The number of items to write. * * Return the count of wrote items. */ pub fn write_i16<'r>(&'r mut self, array : &'r mut [i16], items : i64) -> i64 { unsafe { ffi::sf_write_short(self.handle, array.as_mut_ptr(), items) } } /** * Write items of type i32 * * # Arguments * * array - The array of items to write. * * items - The number of items to write. * * Return the count of wrote items. */ pub fn write_int<'r>(&'r mut self, array : &'r mut [i32], items : i64) -> i64 { unsafe { ffi::sf_write_int(self.handle, array.as_mut_ptr(), items) } } /** * Write items of type f32 * * # Arguments * * array - The array of items to write. * * items - The number of items to write. * * Return the count of wrote items. */ pub fn write_f32<'r>(&'r mut self, array : &'r mut [f32], items : i64) -> i64 { unsafe { ffi::sf_write_float(self.handle, array.as_mut_ptr(), items) } } /** * Write items of type f64 * * # Arguments * * array - The array of items to write. * * items - The number of items to write. * * Return the count of wrote items. */ pub fn write_f64<'r>(&'r mut self, array : &'r mut [f64], items : i64) -> i64 { unsafe { ffi::sf_write_double(self.handle, array.as_mut_ptr(), items) } } /** * Write frames of type i16 * * # Arguments * * array - The array of frames to write. * * items - The number of frames to write. * * Return the count of wrote frames. */ pub fn writef_i16<'r>(&'r mut self, array : &'r mut [i16], frames : i64) -> i64 { unsafe { ffi::sf_writef_short(self.handle, array.as_mut_ptr(), frames) } } /** * Write frames of type i32 * * # Arguments * * array - The array of frames to write. * * items - The number of frames to write. * * Return the count of wrote frames. */ pub fn writef_int<'r>(&'r mut self, array : &'r mut [i32], frames : i64) -> i64 { unsafe { ffi::sf_writef_int(self.handle, array.as_mut_ptr(), frames) } } /** * Write frames of type f32 * * # Arguments * * array - The array of frames to write. * * items - The number of frames to write. * * Return the count of wrote frames. */ pub fn writef_f32<'r>(&'r mut self, array : &'r mut [f32], frames : i64) -> i64
/** * Write frames of type f64 * * # Arguments * * array - The array of frames to write. * * items - The number of frames to write. * * Return the count of wrote frames. */ pub fn writef_f64<'r>(&'r mut self, array : &'r mut [f64], frames : i64) -> i64 { unsafe { ffi::sf_writef_double(self.handle, array.as_mut_ptr(), frames) } } /** * Get the last error * * Return the last error as a variant of the enum Error. */ pub fn error(&self) -> Error { unsafe { ffi::sf_error(self.handle) } } /** * Get the last error as a string * * Return an owned str containing the last error. */ pub fn string_error(&self) -> String { unsafe { from_utf8(CStr::from_ptr(ffi::sf_strerror(self.handle) as *const _).to_bytes()).unwrap().to_owned() //CString::new(ffi::sf_strerror(self.handle) as *const i8).as_str().unwrap().to_string() } } /** * Get an error as a string from a variant of enum Error * * Return an owned str containing the error. */ pub fn error_number(error_num : Error) -> String { unsafe { from_utf8(CStr::from_ptr(ffi::sf_error_number(error_num as i32) as *const _).to_bytes()).unwrap().to_owned() //CString::new(ffi::sf_error_number(error_num as i32) as *const i8, false).as_str().unwrap().to_string() } } }
{ unsafe { ffi::sf_writef_float(self.handle, array.as_mut_ptr(), frames) } }
__init__.py
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # Copyright (c) 2008-2021 pyglet contributors # All rights reserved. # # 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 pyglet 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 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. # ---------------------------------------------------------------------------- import unicodedata import urllib.parse from ctypes import * from functools import lru_cache import pyglet from pyglet.window import WindowException, MouseCursorException from pyglet.window import MouseCursor, DefaultMouseCursor, ImageMouseCursor from pyglet.window import BaseWindow, _PlatformEventHandler, _ViewEventHandler from pyglet.window import key from pyglet.window import mouse from pyglet.event import EventDispatcher from pyglet.canvas.xlib import XlibCanvas from pyglet.libs.x11 import xlib from pyglet.libs.x11 import cursorfont from pyglet.util import asbytes try: from pyglet.libs.x11 import xsync _have_xsync = True except ImportError: _have_xsync = False class mwmhints_t(Structure): _fields_ = [ ('flags', c_uint32), ('functions', c_uint32), ('decorations', c_uint32), ('input_mode', c_int32), ('status', c_uint32) ] # XXX: wraptypes can't parse the header this function is in yet XkbSetDetectableAutoRepeat = xlib._lib.XkbSetDetectableAutoRepeat XkbSetDetectableAutoRepeat.restype = c_int XkbSetDetectableAutoRepeat.argtypes = [POINTER(xlib.Display), c_int, POINTER(c_int)] _can_detect_autorepeat = None XA_CARDINAL = 6 # Xatom.h:14 XA_ATOM = 4 XDND_VERSION = 5 # Do we have the November 2000 UTF8 extension? _have_utf8 = hasattr(xlib._lib, 'Xutf8TextListToTextProperty') # symbol,ctrl -> motion mapping _motion_map = { (key.UP, False): key.MOTION_UP, (key.RIGHT, False): key.MOTION_RIGHT, (key.DOWN, False): key.MOTION_DOWN, (key.LEFT, False): key.MOTION_LEFT, (key.RIGHT, True): key.MOTION_NEXT_WORD, (key.LEFT, True): key.MOTION_PREVIOUS_WORD, (key.HOME, False): key.MOTION_BEGINNING_OF_LINE, (key.END, False): key.MOTION_END_OF_LINE, (key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE, (key.PAGEDOWN, False): key.MOTION_NEXT_PAGE, (key.HOME, True): key.MOTION_BEGINNING_OF_FILE, (key.END, True): key.MOTION_END_OF_FILE, (key.BACKSPACE, False): key.MOTION_BACKSPACE, (key.DELETE, False): key.MOTION_DELETE, } class XlibException(WindowException): """An X11-specific exception. This exception is probably a programming error in pyglet.""" pass class XlibMouseCursor(MouseCursor): gl_drawable = False hw_drawable = True def __init__(self, cursor): self.cursor = cursor # Platform event data is single item, so use platform event handler directly. XlibEventHandler = _PlatformEventHandler ViewEventHandler = _ViewEventHandler class XlibWindow(BaseWindow): _x_display = None # X display connection _x_screen_id = None # X screen index _x_ic = None # X input context _window = None # Xlib window handle _override_redirect = False _x = 0 _y = 0 # Last known window position _mouse_exclusive_client = None # x,y of "real" mouse during exclusive _mouse_buttons = [False] * 6 # State of each xlib button _active = True _applied_mouse_exclusive = False _applied_keyboard_exclusive = False _mapped = False _lost_context = False _lost_context_state = False _enable_xsync = False _current_sync_value = None _current_sync_valid = False _default_event_mask = (0x1ffffff & ~xlib.PointerMotionHintMask & ~xlib.ResizeRedirectMask & ~xlib.SubstructureNotifyMask) def __init__(self, *args, **kwargs): # Bind event handlers self._event_handlers = {} self._view_event_handlers = {} for name in self._platform_event_names: if not hasattr(self, name): continue func = getattr(self, name) for message in func._platform_event_data: if hasattr(func, '_view'): self._view_event_handlers[message] = func else: self._event_handlers[message] = func super(XlibWindow, self).__init__(*args, **kwargs) global _can_detect_autorepeat if _can_detect_autorepeat is None: supported_rtrn = c_int() _can_detect_autorepeat = XkbSetDetectableAutoRepeat(self.display._display, c_int(1), byref(supported_rtrn)) if _can_detect_autorepeat: self.pressed_keys = set() def _recreate(self, changes): # If flipping to/from fullscreen, need to recreate the window. (This # is the case with both override_redirect method and # _NET_WM_STATE_FULLSCREEN). # # A possible improvement could be to just hide the top window, # destroy the GLX window, and reshow it again when leaving fullscreen. # This would prevent the floating window from being moved by the # WM. if 'fullscreen' in changes or 'resizable' in changes: # clear out the GLX context self.context.detach() xlib.XDestroyWindow(self._x_display, self._window) del self.display._window_map[self._window] del self.display._window_map[self._view] self._window = None self._mapped = False # TODO: detect state loss only by examining context share. if 'context' in changes: self._lost_context = True self._lost_context_state = True self._create() def _create_xdnd_atoms(self, display): self._xdnd_atoms = { 'XdndAware' : xlib.XInternAtom(display, asbytes('XdndAware'), False), 'XdndEnter' : xlib.XInternAtom(display, asbytes('XdndEnter'), False), 'XdndTypeList' : xlib.XInternAtom(display, asbytes('XdndTypeList'), False), 'XdndDrop' : xlib.XInternAtom(display, asbytes('XdndDrop'), False), 'XdndFinished' : xlib.XInternAtom(display, asbytes('XdndFinished'), False), 'XdndSelection' : xlib.XInternAtom(display, asbytes('XdndSelection'), False), 'XdndPosition' : xlib.XInternAtom(display, asbytes('XdndPosition'), False), 'XdndStatus' : xlib.XInternAtom(display, asbytes('XdndStatus'), False), 'XdndActionCopy' : xlib.XInternAtom(display, asbytes('XdndActionCopy'), False), 'text/uri-list' : xlib.XInternAtom(display, asbytes("text/uri-list"), False) } def _create(self): # Unmap existing window if necessary while we fiddle with it. if self._window and self._mapped: self._unmap() self._x_display = self.display._display self._x_screen_id = self.display.x_screen # Create X window if not already existing. if not self._window: root = xlib.XRootWindow(self._x_display, self._x_screen_id) visual_info = self.config.get_visual_info() visual = visual_info.visual visual_id = xlib.XVisualIDFromVisual(visual) default_visual = xlib.XDefaultVisual(self._x_display, self._x_screen_id) default_visual_id = xlib.XVisualIDFromVisual(default_visual) window_attributes = xlib.XSetWindowAttributes() if visual_id != default_visual_id: window_attributes.colormap = xlib.XCreateColormap(self._x_display, root, visual, xlib.AllocNone) else: window_attributes.colormap = xlib.XDefaultColormap(self._x_display, self._x_screen_id) window_attributes.bit_gravity = xlib.StaticGravity # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration # unless CWBackPixel is given in mask. Should have # no effect on other systems, so it's set # unconditionally. mask = xlib.CWColormap | xlib.CWBitGravity | xlib.CWBackPixel if self._fullscreen: width, height = self.screen.width, self.screen.height self._view_x = (width - self._width) // 2 self._view_y = (height - self._height) // 2 else: width, height = self._width, self._height self._view_x = self._view_y = 0 self._window = xlib.XCreateWindow(self._x_display, root, 0, 0, width, height, 0, visual_info.depth, xlib.InputOutput, visual, mask, byref(window_attributes)) self._view = xlib.XCreateWindow(self._x_display, self._window, self._view_x, self._view_y, self._width, self._height, 0, visual_info.depth, xlib.InputOutput, visual, mask, byref(window_attributes)) xlib.XMapWindow(self._x_display, self._view) xlib.XSelectInput(self._x_display, self._view, self._default_event_mask) self.display._window_map[self._window] = self.dispatch_platform_event self.display._window_map[self._view] = self.dispatch_platform_event_view self.canvas = XlibCanvas(self.display, self._view) self.context.attach(self.canvas) self.context.set_vsync(self._vsync) # XXX ? # Setting null background pixmap disables drawing the background, # preventing flicker while resizing (in theory). # # Issue 287: Compiz on Intel/Mesa doesn't draw window decoration if # this is called. As it doesn't seem to have any # effect anyway, it's just commented out. # xlib.XSetWindowBackgroundPixmap(self._x_display, self._window, 0) self._enable_xsync = (pyglet.options['xsync'] and self.display._enable_xsync and self.config.double_buffer) # Set supported protocols protocols = [] protocols.append(xlib.XInternAtom(self._x_display, asbytes('WM_DELETE_WINDOW'), False)) if self._enable_xsync: protocols.append(xlib.XInternAtom(self._x_display, asbytes('_NET_WM_SYNC_REQUEST'), False)) protocols = (c_ulong * len(protocols))(*protocols) xlib.XSetWMProtocols(self._x_display, self._window, protocols, len(protocols)) # Create window resize sync counter if self._enable_xsync: value = xsync.XSyncValue() self._sync_counter = xlib.XID(xsync.XSyncCreateCounter(self._x_display, value)) atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_SYNC_REQUEST_COUNTER'), False) ptr = pointer(self._sync_counter) xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL, 32, xlib.PropModeReplace, cast(ptr, POINTER(c_ubyte)), 1) # Atoms required for Xdnd self._create_xdnd_atoms(self._x_display) # Support for drag and dropping files needs to be enabled. if self._file_drops: # Some variables set because there are 4 different drop events that need shared data. self._xdnd_source = None self._xdnd_version = None self._xdnd_format = None self._xdnd_position = (0, 0) # For position callback. VERSION = c_ulong(int(XDND_VERSION)) ptr = pointer(VERSION) xlib.XChangeProperty(self._x_display, self._window, self._xdnd_atoms['XdndAware'], XA_ATOM, 32, xlib.PropModeReplace, cast(ptr, POINTER(c_ubyte)), 1) # Set window attributes attributes = xlib.XSetWindowAttributes() attributes_mask = 0 self._override_redirect = False if self._fullscreen: if pyglet.options['xlib_fullscreen_override_redirect']: # Try not to use this any more, it causes problems; disabled # by default in favour of _NET_WM_STATE_FULLSCREEN. attributes.override_redirect = self._fullscreen attributes_mask |= xlib.CWOverrideRedirect self._override_redirect = True else: self._set_wm_state('_NET_WM_STATE_FULLSCREEN') if self._fullscreen: xlib.XMoveResizeWindow(self._x_display, self._window, self.screen.x, self.screen.y, self.screen.width, self.screen.height) else: xlib.XResizeWindow(self._x_display, self._window, self._width, self._height) xlib.XChangeWindowAttributes(self._x_display, self._window, attributes_mask, byref(attributes)) # Set style styles = { self.WINDOW_STYLE_DEFAULT: '_NET_WM_WINDOW_TYPE_NORMAL', self.WINDOW_STYLE_DIALOG: '_NET_WM_WINDOW_TYPE_DIALOG', self.WINDOW_STYLE_TOOL: '_NET_WM_WINDOW_TYPE_UTILITY', } if self._style in styles: self._set_atoms_property('_NET_WM_WINDOW_TYPE', (styles[self._style],)) elif self._style == self.WINDOW_STYLE_BORDERLESS: MWM_HINTS_DECORATIONS = 1 << 1 PROP_MWM_HINTS_ELEMENTS = 5 mwmhints = mwmhints_t() mwmhints.flags = MWM_HINTS_DECORATIONS mwmhints.decorations = 0 name = xlib.XInternAtom(self._x_display, asbytes('_MOTIF_WM_HINTS'), False) xlib.XChangeProperty(self._x_display, self._window, name, name, 32, xlib.PropModeReplace, cast(pointer(mwmhints), POINTER(c_ubyte)), PROP_MWM_HINTS_ELEMENTS) # Set resizeable if not self._resizable and not self._fullscreen: self.set_minimum_size(self._width, self._height) self.set_maximum_size(self._width, self._height) # Set caption self.set_caption(self._caption) # Set WM_CLASS for modern desktop environments self.set_wm_class(self._caption) # this is supported by some compositors (ie gnome-shell), and more to come # see: http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#idp6357888 _NET_WM_BYPASS_COMPOSITOR_HINT_ON = c_ulong(int(self._fullscreen)) name = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_BYPASS_COMPOSITOR'), False) ptr = pointer(_NET_WM_BYPASS_COMPOSITOR_HINT_ON) xlib.XChangeProperty(self._x_display, self._window, name, XA_CARDINAL, 32, xlib.PropModeReplace, cast(ptr, POINTER(c_ubyte)), 1) # Create input context. A good but very outdated reference for this # is http://www.sbin.org/doc/Xlib/chapt_11.html if _have_utf8 and not self._x_ic: if not self.display._x_im: xlib.XSetLocaleModifiers(asbytes('@im=none')) self.display._x_im = xlib.XOpenIM(self._x_display, None, None, None) xlib.XFlush(self._x_display) # Need to set argtypes on this function because it's vararg, # and ctypes guesses wrong. xlib.XCreateIC.argtypes = [xlib.XIM, c_char_p, c_int, c_char_p, xlib.Window, c_char_p, xlib.Window, c_void_p] self._x_ic = xlib.XCreateIC(self.display._x_im, asbytes('inputStyle'), xlib.XIMPreeditNothing | xlib.XIMStatusNothing, asbytes('clientWindow'), self._window, asbytes('focusWindow'), self._window, None) filter_events = c_ulong() xlib.XGetICValues(self._x_ic, 'filterEvents', byref(filter_events), None) self._default_event_mask |= filter_events.value xlib.XSetICFocus(self._x_ic) self.switch_to() if self._visible: self.set_visible(True) self.set_mouse_platform_visible() self._applied_mouse_exclusive = None self._update_exclusivity() def _map(self): if self._mapped: return # Map the window, wait for map event before continuing. xlib.XSelectInput(self._x_display, self._window, xlib.StructureNotifyMask) xlib.XMapRaised(self._x_display, self._window) e = xlib.XEvent() while True: xlib.XNextEvent(self._x_display, e) if e.type == xlib.ConfigureNotify: self._width = e.xconfigure.width self._height = e.xconfigure.height elif e.type == xlib.MapNotify: break xlib.XSelectInput(self._x_display, self._window, self._default_event_mask) self._mapped = True if self._override_redirect: # Possibly an override_redirect issue. self.activate() self._update_view_size() self.dispatch_event('on_resize', self._width, self._height) self.dispatch_event('on_show') self.dispatch_event('on_expose') def _unmap(self): if not self._mapped: return xlib.XSelectInput(self._x_display, self._window, xlib.StructureNotifyMask) xlib.XUnmapWindow(self._x_display, self._window) e = xlib.XEvent() while True: xlib.XNextEvent(self._x_display, e) if e.type == xlib.UnmapNotify: break xlib.XSelectInput(self._x_display, self._window, self._default_event_mask) self._mapped = False def _get_root(self): attributes = xlib.XWindowAttributes() xlib.XGetWindowAttributes(self._x_display, self._window, byref(attributes)) return attributes.root def _is_reparented(self): root = c_ulong() parent = c_ulong() children = pointer(c_ulong()) n_children = c_uint() xlib.XQueryTree(self._x_display, self._window, byref(root), byref(parent), byref(children), byref(n_children)) return root.value != parent.value def close(self): if not self._window: return self.context.destroy() self._unmap() if self._window: xlib.XDestroyWindow(self._x_display, self._window) del self.display._window_map[self._window] del self.display._window_map[self._view] self._window = None self._view_event_handlers.clear() self._event_handlers.clear() if _have_utf8: xlib.XDestroyIC(self._x_ic) self._x_ic = None super(XlibWindow, self).close() def switch_to(self): if self.context: self.context.set_current() def flip(self): self.draw_mouse_cursor() # TODO canvas.flip? if self.context: self.context.flip() self._sync_resize() def set_vsync(self, vsync: bool) -> None: if pyglet.options['vsync'] is not None: vsync = pyglet.options['vsync'] super().set_vsync(vsync) self.context.set_vsync(vsync) def set_caption(self, caption): if caption is None: caption = '' self._caption = caption self._set_text_property('WM_NAME', caption, allow_utf8=False) self._set_text_property('WM_ICON_NAME', caption, allow_utf8=False) self._set_text_property('_NET_WM_NAME', caption) self._set_text_property('_NET_WM_ICON_NAME', caption) def set_wm_class(self, name): # WM_CLASS can only contain Ascii characters try: name = name.encode('ascii') except UnicodeEncodeError: name = "pyglet" hint = xlib.XAllocClassHint() hint.contents.res_class = asbytes(name) hint.contents.res_name = asbytes(name.lower()) xlib.XSetClassHint(self._x_display, self._window, hint.contents) xlib.XFree(hint) def get_caption(self): return self._caption def set_size(self, width: int, height: int) -> None: super().set_size(width, height) if not self._resizable: self.set_minimum_size(width, height) self.set_maximum_size(width, height) xlib.XResizeWindow(self._x_display, self._window, width, height) self._update_view_size() self.dispatch_event('on_resize', width, height) def _update_view_size(self): xlib.XResizeWindow(self._x_display, self._view, self._width, self._height) def set_location(self, x, y): if self._is_reparented(): # Assume the window manager has reparented our top-level window # only once, in which case attributes.x/y give the offset from # the frame to the content window. Better solution would be # to use _NET_FRAME_EXTENTS, where supported. attributes = xlib.XWindowAttributes() xlib.XGetWindowAttributes(self._x_display, self._window, byref(attributes)) # XXX at least under KDE's WM these attrs are both 0 x -= attributes.x y -= attributes.y xlib.XMoveWindow(self._x_display, self._window, x, y) def get_location(self): child = xlib.Window() x = c_int() y = c_int() xlib.XTranslateCoordinates(self._x_display, self._window, self._get_root(), 0, 0, byref(x), byref(y), byref(child)) return x.value, y.value def activate(self): # Issue 218 if self._x_display and self._window: xlib.XSetInputFocus(self._x_display, self._window, xlib.RevertToParent, xlib.CurrentTime) def set_visible(self, visible: bool = True) -> None: super().set_visible(visible) if visible: self._map() else: self._unmap() def set_minimum_size(self, width: int, height: int) -> None: super().set_minimum_size(width, height) self._set_wm_normal_hints() def set_maximum_size(self, width: int, height: int) -> None: super().set_maximum_size(width, height) self._set_wm_normal_hints() def minimize(self): xlib.XIconifyWindow(self._x_display, self._window, self._x_screen_id) def maximize(self): self._set_wm_state('_NET_WM_STATE_MAXIMIZED_HORZ', '_NET_WM_STATE_MAXIMIZED_VERT') @staticmethod def _downsample_1bit(pixelarray): byte_list = [] value = 0 for i, pixel in enumerate(pixelarray): index = i % 8 if pixel: value |= 1 << index if index == 7: byte_list.append(value) value = 0 return bytes(byte_list) @lru_cache() def _create_cursor_from_image(self, cursor): """Creates platform cursor from an ImageCursor instance.""" texture = cursor.texture width = texture.width height = texture.height alpha_luma_bytes = texture.get_image_data().get_data('AL', -width * 2) mask_data = self._downsample_1bit(alpha_luma_bytes[0::2]) bmp_data = self._downsample_1bit(alpha_luma_bytes[1::2]) bitmap = xlib.XCreateBitmapFromData(self._x_display, self._window, bmp_data, width, height) mask = xlib.XCreateBitmapFromData(self._x_display, self._window, mask_data, width, height) white = xlib.XColor(red=65535, green=65535, blue=65535) # background color black = xlib.XColor() # foreground color # hot_x/y must be within the image dimension, or the cursor will not display: hot_x = min(max(0, int(self._mouse_cursor.hot_x)), width) hot_y = min(max(0, int(height - self._mouse_cursor.hot_y)), height) cursor = xlib.XCreatePixmapCursor(self._x_display, bitmap, mask, white, black, hot_x, hot_y) xlib.XFreePixmap(self._x_display, bitmap) xlib.XFreePixmap(self._x_display, mask) return cursor def set_mouse_platform_visible(self, platform_visible=None): if not self._window: return if platform_visible is None: platform_visible = self._mouse_visible and not self._mouse_cursor.gl_drawable if platform_visible is False: # Hide pointer by creating an empty cursor: black = xlib.XColor() bitmap = xlib.XCreateBitmapFromData(self._x_display, self._window, bytes(8), 8, 8) cursor = xlib.XCreatePixmapCursor(self._x_display, bitmap, bitmap, black, black, 0, 0) xlib.XDefineCursor(self._x_display, self._window, cursor) xlib.XFreeCursor(self._x_display, cursor) xlib.XFreePixmap(self._x_display, bitmap) elif isinstance(self._mouse_cursor, ImageMouseCursor) and self._mouse_cursor.hw_drawable: # Create a custom hardware cursor: cursor = self._create_cursor_from_image(self._mouse_cursor) xlib.XDefineCursor(self._x_display, self._window, cursor) else: # Restore standard hardware cursor: if isinstance(self._mouse_cursor, XlibMouseCursor): xlib.XDefineCursor(self._x_display, self._window, self._mouse_cursor.cursor) else: xlib.XUndefineCursor(self._x_display, self._window) def set_mouse_position(self, x, y): xlib.XWarpPointer(self._x_display, 0, # src window self._window, # dst window 0, 0, # src x, y 0, 0, # src w, h x, self._height - y) def _update_exclusivity(self): mouse_exclusive = self._active and self._mouse_exclusive keyboard_exclusive = self._active and self._keyboard_exclusive if mouse_exclusive != self._applied_mouse_exclusive: if mouse_exclusive: self.set_mouse_platform_visible(False) # Restrict to client area xlib.XGrabPointer(self._x_display, self._window, True, 0, xlib.GrabModeAsync, xlib.GrabModeAsync, self._window, 0, xlib.CurrentTime) # Move pointer to center of window x = self._width // 2 y = self._height // 2 self._mouse_exclusive_client = x, y self.set_mouse_position(x, y) elif self._fullscreen and not self.screen._xinerama: # Restrict to fullscreen area (prevent viewport scrolling) self.set_mouse_position(0, 0) r = xlib.XGrabPointer(self._x_display, self._view, True, 0, xlib.GrabModeAsync, xlib.GrabModeAsync, self._view, 0, xlib.CurrentTime) if r: # Failed to grab, try again later self._applied_mouse_exclusive = None return self.set_mouse_platform_visible() else: # Unclip xlib.XUngrabPointer(self._x_display, xlib.CurrentTime) self.set_mouse_platform_visible() self._applied_mouse_exclusive = mouse_exclusive if keyboard_exclusive != self._applied_keyboard_exclusive: if keyboard_exclusive: xlib.XGrabKeyboard(self._x_display, self._window, False, xlib.GrabModeAsync, xlib.GrabModeAsync, xlib.CurrentTime) else: xlib.XUngrabKeyboard(self._x_display, xlib.CurrentTime) self._applied_keyboard_exclusive = keyboard_exclusive def set_exclusive_mouse(self, exclusive=True): if exclusive == self._mouse_exclusive: return super().set_exclusive_mouse(exclusive) self._update_exclusivity() def set_exclusive_keyboard(self, exclusive=True): if exclusive == self._keyboard_exclusive: return super().set_exclusive_keyboard(exclusive) self._update_exclusivity() def get_system_mouse_cursor(self, name): if name == self.CURSOR_DEFAULT: return DefaultMouseCursor() # NQR means default shape is not pretty... surely there is another # cursor font? cursor_shapes = { self.CURSOR_CROSSHAIR: cursorfont.XC_crosshair, self.CURSOR_HAND: cursorfont.XC_hand2, self.CURSOR_HELP: cursorfont.XC_question_arrow, # NQR self.CURSOR_NO: cursorfont.XC_pirate, # NQR self.CURSOR_SIZE: cursorfont.XC_fleur, self.CURSOR_SIZE_UP: cursorfont.XC_top_side, self.CURSOR_SIZE_UP_RIGHT: cursorfont.XC_top_right_corner, self.CURSOR_SIZE_RIGHT: cursorfont.XC_right_side, self.CURSOR_SIZE_DOWN_RIGHT: cursorfont.XC_bottom_right_corner, self.CURSOR_SIZE_DOWN: cursorfont.XC_bottom_side, self.CURSOR_SIZE_DOWN_LEFT: cursorfont.XC_bottom_left_corner, self.CURSOR_SIZE_LEFT: cursorfont.XC_left_side, self.CURSOR_SIZE_UP_LEFT: cursorfont.XC_top_left_corner, self.CURSOR_SIZE_UP_DOWN: cursorfont.XC_sb_v_double_arrow, self.CURSOR_SIZE_LEFT_RIGHT: cursorfont.XC_sb_h_double_arrow, self.CURSOR_TEXT: cursorfont.XC_xterm, self.CURSOR_WAIT: cursorfont.XC_watch, self.CURSOR_WAIT_ARROW: cursorfont.XC_watch, # NQR } if name not in cursor_shapes: raise MouseCursorException('Unknown cursor name "%s"' % name) cursor = xlib.XCreateFontCursor(self._x_display, cursor_shapes[name]) return XlibMouseCursor(cursor) def set_icon(self, *images): # Careful! XChangeProperty takes an array of long when data type # is 32-bit (but long can be 64 bit!), so pad high bytes of format if # necessary. import sys fmt = {('little', 4): 'BGRA', ('little', 8): 'BGRAAAAA', ('big', 4): 'ARGB', ('big', 8): 'AAAAARGB'}[(sys.byteorder, sizeof(c_ulong))] data = asbytes('') for image in images: image = image.get_image_data() pitch = -(image.width * len(fmt)) s = c_buffer(sizeof(c_ulong) * 2) memmove(s, cast((c_ulong * 2)(image.width, image.height), POINTER(c_ubyte)), len(s)) data += s.raw + image.get_data(fmt, pitch) buffer = (c_ubyte * len(data))() memmove(buffer, data, len(data)) atom = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_ICON'), False) xlib.XChangeProperty(self._x_display, self._window, atom, XA_CARDINAL, 32, xlib.PropModeReplace, buffer, len(data)//sizeof(c_ulong)) # Private utility def _set_wm_normal_hints(self): hints = xlib.XAllocSizeHints().contents if self._minimum_size: hints.flags |= xlib.PMinSize hints.min_width, hints.min_height = self._minimum_size if self._maximum_size: hints.flags |= xlib.PMaxSize hints.max_width, hints.max_height = self._maximum_size xlib.XSetWMNormalHints(self._x_display, self._window, byref(hints)) def _set_text_property(self, name, value, allow_utf8=True): atom = xlib.XInternAtom(self._x_display, asbytes(name), False) if not atom: raise XlibException('Undefined atom "%s"' % name) text_property = xlib.XTextProperty() if _have_utf8 and allow_utf8: buf = create_string_buffer(value.encode('utf8')) result = xlib.Xutf8TextListToTextProperty(self._x_display, cast(pointer(buf), c_char_p), 1, xlib.XUTF8StringStyle, byref(text_property)) if result < 0: raise XlibException('Could not create UTF8 text property') else: buf = create_string_buffer(value.encode('ascii', 'ignore')) result = xlib.XStringListToTextProperty( cast(pointer(buf), c_char_p), 1, byref(text_property)) if result < 0: raise XlibException('Could not create text property') xlib.XSetTextProperty(self._x_display, self._window, byref(text_property), atom) # XXX <rj> Xlib doesn't like us freeing this # xlib.XFree(text_property.value) def _set_atoms_property(self, name, values, mode=xlib.PropModeReplace): name_atom = xlib.XInternAtom(self._x_display, asbytes(name), False) atoms = [] for value in values: atoms.append(xlib.XInternAtom(self._x_display, asbytes(value), False)) atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False) if len(atoms): atoms_ar = (xlib.Atom * len(atoms))(*atoms) xlib.XChangeProperty(self._x_display, self._window, name_atom, atom_type, 32, mode, cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms)) else: net_wm_state = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_STATE'), False) if net_wm_state: xlib.XDeleteProperty(self._x_display, self._window, net_wm_state) def _set_wm_state(self, *states): # Set property net_wm_state = xlib.XInternAtom(self._x_display, asbytes('_NET_WM_STATE'), False) atoms = [] for state in states: atoms.append(xlib.XInternAtom(self._x_display, asbytes(state), False)) atom_type = xlib.XInternAtom(self._x_display, asbytes('ATOM'), False) if len(atoms): atoms_ar = (xlib.Atom * len(atoms))(*atoms) xlib.XChangeProperty(self._x_display, self._window, net_wm_state, atom_type, 32, xlib.PropModePrepend, cast(pointer(atoms_ar), POINTER(c_ubyte)), len(atoms)) else: xlib.XDeleteProperty(self._x_display, self._window, net_wm_state) # Nudge the WM e = xlib.XEvent() e.xclient.type = xlib.ClientMessage e.xclient.message_type = net_wm_state e.xclient.display = cast(self._x_display, POINTER(xlib.Display)) e.xclient.window = self._window e.xclient.format = 32 e.xclient.data.l[0] = xlib.PropModePrepend for i, atom in enumerate(atoms): e.xclient.data.l[i + 1] = atom xlib.XSendEvent(self._x_display, self._get_root(), False, xlib.SubstructureRedirectMask, byref(e)) # Event handling def dispatch_events(self): self.dispatch_pending_events() self._allow_dispatch_event = True e = xlib.XEvent() # Cache these in case window is closed from an event handler _x_display = self._x_display _window = self._window _view = self._view # Check for the events specific to this window while xlib.XCheckWindowEvent(_x_display, _window, 0x1ffffff, byref(e)): # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, 0): continue self.dispatch_platform_event(e) # Check for the events specific to this view while xlib.XCheckWindowEvent(_x_display, _view, 0x1ffffff, byref(e)): # Key events are filtered by the xlib window event # handler so they get a shot at the prefiltered event. if e.xany.type not in (xlib.KeyPress, xlib.KeyRelease): if xlib.XFilterEvent(e, 0): continue self.dispatch_platform_event_view(e) # Generic events for this window (the window close event). while xlib.XCheckTypedWindowEvent(_x_display, _window, xlib.ClientMessage, byref(e)): self.dispatch_platform_event(e) self._allow_dispatch_event = False def dispatch_pending_events(self): while self._event_queue: EventDispatcher.dispatch_event(self, *self._event_queue.pop(0)) # Dispatch any context-related events if self._lost_context: self._lost_context = False EventDispatcher.dispatch_event(self, 'on_context_lost') if self._lost_context_state: self._lost_context_state = False EventDispatcher.dispatch_event(self, 'on_context_state_lost') def dispatch_platform_event(self, e): if self._applied_mouse_exclusive is None: self._update_exclusivity() event_handler = self._event_handlers.get(e.type) if event_handler: event_handler(e) def dispatch_platform_event_view(self, e): event_handler = self._view_event_handlers.get(e.type) if event_handler: event_handler(e) @staticmethod def _translate_modifiers(state): modifiers = 0 if state & xlib.ShiftMask: modifiers |= key.MOD_SHIFT if state & xlib.ControlMask: modifiers |= key.MOD_CTRL if state & xlib.LockMask: modifiers |= key.MOD_CAPSLOCK if state & xlib.Mod1Mask: modifiers |= key.MOD_ALT if state & xlib.Mod2Mask: modifiers |= key.MOD_NUMLOCK if state & xlib.Mod4Mask: modifiers |= key.MOD_WINDOWS if state & xlib.Mod5Mask:
return modifiers # Event handlers """ def _event_symbol(self, event): # pyglet.self.key keysymbols are identical to X11 keysymbols, no # need to map the keysymbol. symbol = xlib.XKeycodeToKeysym(self._x_display, event.xkey.keycode, 0) if symbol == 0: # XIM event return None elif symbol not in key._key_names.keys(): symbol = key.user_key(event.xkey.keycode) return symbol """ def _event_text_symbol(self, ev): text = None symbol = xlib.KeySym() buffer = create_string_buffer(128) # Look up raw keysym before XIM filters it (default for keypress and # keyrelease) count = xlib.XLookupString(ev.xkey, buffer, len(buffer) - 1, byref(symbol), None) # Give XIM a shot filtered = xlib.XFilterEvent(ev, ev.xany.window) if ev.type == xlib.KeyPress and not filtered: status = c_int() if _have_utf8: encoding = 'utf8' count = xlib.Xutf8LookupString(self._x_ic, ev.xkey, buffer, len(buffer) - 1, byref(symbol), byref(status)) if status.value == xlib.XBufferOverflow: raise NotImplementedError('TODO: XIM buffer resize') else: encoding = 'ascii' count = xlib.XLookupString(ev.xkey, buffer, len(buffer) - 1, byref(symbol), None) if count: status.value = xlib.XLookupBoth if status.value & (xlib.XLookupChars | xlib.XLookupBoth): text = buffer.value[:count].decode(encoding) # Don't treat Unicode command codepoints as text, except Return. if text and unicodedata.category(text) == 'Cc' and text != '\r': text = None symbol = symbol.value # If the event is a XIM filtered event, the keysym will be virtual # (e.g., aacute instead of A after a dead key). Drop it, we don't # want these kind of key events. if ev.xkey.keycode == 0 and not filtered: symbol = None # pyglet.self.key keysymbols are identical to X11 keysymbols, no # need to map the keysymbol. For keysyms outside the pyglet set, map # raw key code to a user key. if symbol and symbol not in key._key_names and ev.xkey.keycode: # Issue 353: Symbol is uppercase when shift key held down. try: symbol = ord(chr(symbol).lower()) except ValueError: # Not a valid unichr, use the keycode symbol = key.user_key(ev.xkey.keycode) else: # If still not recognised, use the keycode if symbol not in key._key_names: symbol = key.user_key(ev.xkey.keycode) if filtered: # The event was filtered, text must be ignored, but the symbol is # still good. return None, symbol return text, symbol @staticmethod def _event_text_motion(symbol, modifiers): if modifiers & key.MOD_ALT: return None ctrl = modifiers & key.MOD_CTRL != 0 return _motion_map.get((symbol, ctrl), None) @ViewEventHandler @XlibEventHandler(xlib.KeyPress) @XlibEventHandler(xlib.KeyRelease) def _event_key_view(self, ev): # Try to detect autorepeat ourselves if the server doesn't support it # XXX: Doesn't always work, better off letting the server do it global _can_detect_autorepeat if not _can_detect_autorepeat and ev.type == xlib.KeyRelease: # Look in the queue for a matching KeyPress with same timestamp, # indicating an auto-repeat rather than actual key event. saved = [] while True: auto_event = xlib.XEvent() result = xlib.XCheckWindowEvent(self._x_display, self._window, xlib.KeyPress|xlib.KeyRelease, byref(auto_event)) if not result: break saved.append(auto_event) if auto_event.type == xlib.KeyRelease: # just save this off for restoration back to the queue continue if ev.xkey.keycode == auto_event.xkey.keycode: # Found a key repeat: dispatch EVENT_TEXT* event text, symbol = self._event_text_symbol(auto_event) modifiers = self._translate_modifiers(ev.xkey.state) modifiers_ctrl = modifiers & (key.MOD_CTRL | key.MOD_ALT) motion = self._event_text_motion(symbol, modifiers) if motion: if modifiers & key.MOD_SHIFT: self.dispatch_event( 'on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif text and not modifiers_ctrl: self.dispatch_event('on_text', text) ditched = saved.pop() for auto_event in reversed(saved): xlib.XPutBackEvent(self._x_display, byref(auto_event)) return else: # Key code of press did not match, therefore no repeating # is going on, stop searching. break # Whoops, put the events back, it's for real. for auto_event in reversed(saved): xlib.XPutBackEvent(self._x_display, byref(auto_event)) text, symbol = self._event_text_symbol(ev) modifiers = self._translate_modifiers(ev.xkey.state) modifiers_ctrl = modifiers & (key.MOD_CTRL | key.MOD_ALT) motion = self._event_text_motion(symbol, modifiers) if ev.type == xlib.KeyPress: if symbol and (not _can_detect_autorepeat or symbol not in self.pressed_keys): self.dispatch_event('on_key_press', symbol, modifiers) if _can_detect_autorepeat: self.pressed_keys.add(symbol) if motion: if modifiers & key.MOD_SHIFT: self.dispatch_event('on_text_motion_select', motion) else: self.dispatch_event('on_text_motion', motion) elif text and not modifiers_ctrl: self.dispatch_event('on_text', text) elif ev.type == xlib.KeyRelease: if symbol: self.dispatch_event('on_key_release', symbol, modifiers) if _can_detect_autorepeat and symbol in self.pressed_keys: self.pressed_keys.remove(symbol) @XlibEventHandler(xlib.KeyPress) @XlibEventHandler(xlib.KeyRelease) def _event_key(self, ev): return self._event_key_view(ev) @ViewEventHandler @XlibEventHandler(xlib.MotionNotify) def _event_motionnotify_view(self, ev): x = ev.xmotion.x y = self.height - ev.xmotion.y if self._mouse_in_window: dx = x - self._mouse_x dy = y - self._mouse_y else: dx = dy = 0 if self._applied_mouse_exclusive \ and (ev.xmotion.x, ev.xmotion.y) == self._mouse_exclusive_client: # Ignore events caused by XWarpPointer self._mouse_x = x self._mouse_y = y return if self._applied_mouse_exclusive: # Reset pointer position ex, ey = self._mouse_exclusive_client xlib.XWarpPointer(self._x_display, 0, self._window, 0, 0, 0, 0, ex, ey) self._mouse_x = x self._mouse_y = y self._mouse_in_window = True buttons = 0 if ev.xmotion.state & xlib.Button1MotionMask: buttons |= mouse.LEFT if ev.xmotion.state & xlib.Button2MotionMask: buttons |= mouse.MIDDLE if ev.xmotion.state & xlib.Button3MotionMask: buttons |= mouse.RIGHT if buttons: # Drag event modifiers = self._translate_modifiers(ev.xmotion.state) self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) else: # Motion event self.dispatch_event('on_mouse_motion', x, y, dx, dy) @XlibEventHandler(xlib.MotionNotify) def _event_motionnotify(self, ev): # Window motion looks for drags that are outside the view but within # the window. buttons = 0 if ev.xmotion.state & xlib.Button1MotionMask: buttons |= mouse.LEFT if ev.xmotion.state & xlib.Button2MotionMask: buttons |= mouse.MIDDLE if ev.xmotion.state & xlib.Button3MotionMask: buttons |= mouse.RIGHT if buttons: # Drag event x = ev.xmotion.x - self._view_x y = self._height - (ev.xmotion.y - self._view_y) if self._mouse_in_window: dx = x - self._mouse_x dy = y - self._mouse_y else: dx = dy = 0 self._mouse_x = x self._mouse_y = y modifiers = self._translate_modifiers(ev.xmotion.state) self.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers) @XlibEventHandler(xlib.ClientMessage) def _event_clientmessage(self, ev): atom = ev.xclient.data.l[0] if atom == xlib.XInternAtom(ev.xclient.display, asbytes('WM_DELETE_WINDOW'), False): self.dispatch_event('on_close') elif (self._enable_xsync and atom == xlib.XInternAtom(ev.xclient.display, asbytes('_NET_WM_SYNC_REQUEST'), False)): lo = ev.xclient.data.l[2] hi = ev.xclient.data.l[3] self._current_sync_value = xsync.XSyncValue(hi, lo) elif ev.xclient.message_type == self._xdnd_atoms['XdndPosition']: self._event_drag_position(ev) elif ev.xclient.message_type == self._xdnd_atoms['XdndDrop']: self._event_drag_drop(ev) elif ev.xclient.message_type == self._xdnd_atoms['XdndEnter']: self._event_drag_enter(ev) def _event_drag_drop(self, ev): if self._xdnd_version > XDND_VERSION: return time = xlib.CurrentTime if self._xdnd_format: if self._xdnd_version >= 1: time = ev.xclient.data.l[2] # Convert to selection notification. xlib.XConvertSelection(self._x_display, self._xdnd_atoms['XdndSelection'], self._xdnd_format, self._xdnd_atoms['XdndSelection'], self._window, time) xlib.XFlush(self._x_display) elif self._xdnd_version >= 2: # If no format send finished with no data. e = xlib.XEvent() e.xclient.type = xlib.ClientMessage e.xclient.message_type = self._xdnd_atoms['XdndFinished'] e.xclient.display = cast(self._x_display, POINTER(xlib.Display)) e.xclient.window = self._window e.xclient.format = 32 e.xclient.data.l[0] = self._window e.xclient.data.l[1] = 0 e.xclient.data.l[2] = None xlib.XSendEvent(self._x_display, self._xdnd_source, False, xlib.NoEventMask, byref(e)) xlib.XFlush(self._x_display) def _event_drag_position(self, ev): if self._xdnd_version > XDND_VERSION: return xoff = (ev.xclient.data.l[2] >> 16) & 0xffff yoff = (ev.xclient.data.l[2]) & 0xffff # Need to convert the position to actual window coordinates with the screen offset child = xlib.Window() x = c_int() y = c_int() xlib.XTranslateCoordinates(self._x_display, self._get_root(), self._window, xoff, yoff, byref(x), byref(y), byref(child)) self._xdnd_position = (x.value, y.value) e = xlib.XEvent() e.xclient.type = xlib.ClientMessage e.xclient.message_type = self._xdnd_atoms['XdndStatus'] e.xclient.display = cast(self._x_display, POINTER(xlib.Display)) e.xclient.window = ev.xclient.data.l[0] e.xclient.format = 32 e.xclient.data.l[0] = self._window e.xclient.data.l[2] = 0 e.xclient.data.l[3] = 0 if self._xdnd_format: e.xclient.data.l[1] = 1 if self._xdnd_version >= 2: e.xclient.data.l[4] = self._xdnd_atoms['XdndActionCopy'] xlib.XSendEvent(self._x_display, self._xdnd_source, False, xlib.NoEventMask, byref(e)) xlib.XFlush(self._x_display) def _event_drag_enter(self, ev): self._xdnd_source = ev.xclient.data.l[0] self._xdnd_version = ev.xclient.data.l[1] >> 24 self._xdnd_format = None if self._xdnd_version > XDND_VERSION: return three_or_more = ev.xclient.data.l[1] & 1 # Search all of them (usually 8) if three_or_more: data, count = self.get_single_property(self._xdnd_source, self._xdnd_atoms['XdndTypeList'], XA_ATOM) data = cast(data, POINTER(xlib.Atom)) else: # Some old versions may only have 3? Needs testing. count = 3 data = ev.xclient.data.l + 2 # Check all of the properties we received from the dropped item and verify it support URI. for i in range(count): if data[i] == self._xdnd_atoms['text/uri-list']: self._xdnd_format = self._xdnd_atoms['text/uri-list'] break if data: xlib.XFree(data) def get_single_property(self, window, atom_property, atom_type): """ Returns the length and data of a window property. """ actualAtom = xlib.Atom() actualFormat = c_int() itemCount = c_ulong() bytesAfter = c_ulong() data = POINTER(c_ubyte)() xlib.XGetWindowProperty(self._x_display, window, atom_property, 0, 2147483647, False, atom_type, byref(actualAtom), byref(actualFormat), byref(itemCount), byref(bytesAfter), data) return data, itemCount.value @XlibEventHandler(xlib.SelectionNotify) def _event_selection_notification(self, ev): if ev.xselection.property != 0 and ev.xselection.selection == self._xdnd_atoms['XdndSelection']: if self._xdnd_format: # This will get the data data, count = self.get_single_property(ev.xselection.requestor, ev.xselection.property, ev.xselection.target) buffer = create_string_buffer(count) memmove(buffer, data, count) formatted_paths = self.parse_filenames(buffer.value.decode()) e = xlib.XEvent() e.xclient.type = xlib.ClientMessage e.xclient.message_type = self._xdnd_atoms['XdndFinished'] e.xclient.display = cast(self._x_display, POINTER(xlib.Display)) e.xclient.window = self._window e.xclient.format = 32 e.xclient.data.l[0] = self._xdnd_source e.xclient.data.l[1] = 1 e.xclient.data.l[2] = self._xdnd_atoms['XdndActionCopy'] xlib.XSendEvent(self._x_display, self._get_root(), False, xlib.NoEventMask, byref(e)) xlib.XFlush(self._x_display) xlib.XFree(data) self.dispatch_event('on_file_drop', self._xdnd_position[0], self._height - self._xdnd_position[1], formatted_paths) @staticmethod def parse_filenames(decoded_string): """All of the filenames from file drops come as one big string with some special characters (%20), this will parse them out. """ import sys different_files = decoded_string.splitlines() parsed = [] for filename in different_files: if filename: filename = urllib.parse.urlsplit(filename).path encoding = sys.getfilesystemencoding() parsed.append(urllib.parse.unquote(filename, encoding)) return parsed def _sync_resize(self): if self._enable_xsync and self._current_sync_valid: if xsync.XSyncValueIsZero(self._current_sync_value): self._current_sync_valid = False return xsync.XSyncSetCounter(self._x_display, self._sync_counter, self._current_sync_value) self._current_sync_value = None self._current_sync_valid = False @ViewEventHandler @XlibEventHandler(xlib.ButtonPress) @XlibEventHandler(xlib.ButtonRelease) def _event_button(self, ev): x = ev.xbutton.x y = self.height - ev.xbutton.y button = 1 << (ev.xbutton.button - 1) # 1, 2, 3 -> 1, 2, 4 modifiers = self._translate_modifiers(ev.xbutton.state) if ev.type == xlib.ButtonPress: # override_redirect issue: manually activate this window if # fullscreen. if self._override_redirect and not self._active: self.activate() if ev.xbutton.button == 4: self.dispatch_event('on_mouse_scroll', x, y, 0, 1) elif ev.xbutton.button == 5: self.dispatch_event('on_mouse_scroll', x, y, 0, -1) elif ev.xbutton.button == 6: self.dispatch_event('on_mouse_scroll', x, y, -1, 0) elif ev.xbutton.button == 7: self.dispatch_event('on_mouse_scroll', x, y, 1, 0) elif ev.xbutton.button < len(self._mouse_buttons): self._mouse_buttons[ev.xbutton.button] = True self.dispatch_event('on_mouse_press', x, y, button, modifiers) else: if ev.xbutton.button < 4: self._mouse_buttons[ev.xbutton.button] = False self.dispatch_event('on_mouse_release', x, y, button, modifiers) @ViewEventHandler @XlibEventHandler(xlib.Expose) def _event_expose(self, ev): # Ignore all expose events except the last one. We could be told # about exposure rects - but I don't see the point since we're # working with OpenGL and we'll just redraw the whole scene. if ev.xexpose.count > 0: return self.dispatch_event('on_expose') @ViewEventHandler @XlibEventHandler(xlib.EnterNotify) def _event_enternotify(self, ev): # figure active mouse buttons # XXX ignore modifier state? state = ev.xcrossing.state self._mouse_buttons[1] = state & xlib.Button1Mask self._mouse_buttons[2] = state & xlib.Button2Mask self._mouse_buttons[3] = state & xlib.Button3Mask self._mouse_buttons[4] = state & xlib.Button4Mask self._mouse_buttons[5] = state & xlib.Button5Mask # mouse position x = self._mouse_x = ev.xcrossing.x y = self._mouse_y = self.height - ev.xcrossing.y self._mouse_in_window = True # XXX there may be more we could do here self.dispatch_event('on_mouse_enter', x, y) @ViewEventHandler @XlibEventHandler(xlib.LeaveNotify) def _event_leavenotify(self, ev): x = self._mouse_x = ev.xcrossing.x y = self._mouse_y = self.height - ev.xcrossing.y self._mouse_in_window = False self.dispatch_event('on_mouse_leave', x, y) @XlibEventHandler(xlib.ConfigureNotify) def _event_configurenotify(self, ev): if self._enable_xsync and self._current_sync_value: self._current_sync_valid = True if self._fullscreen: return self.switch_to() w, h = ev.xconfigure.width, ev.xconfigure.height x, y = ev.xconfigure.x, ev.xconfigure.y if self._width != w or self._height != h: self._width = w self._height = h self._update_view_size() self.dispatch_event('on_resize', self._width, self._height) if self._x != x or self._y != y: self.dispatch_event('on_move', x, y) self._x = x self._y = y @XlibEventHandler(xlib.FocusIn) def _event_focusin(self, ev): self._active = True self._update_exclusivity() self.dispatch_event('on_activate') xlib.XSetICFocus(self._x_ic) @XlibEventHandler(xlib.FocusOut) def _event_focusout(self, ev): self._active = False self._update_exclusivity() self.dispatch_event('on_deactivate') xlib.XUnsetICFocus(self._x_ic) @XlibEventHandler(xlib.MapNotify) def _event_mapnotify(self, ev): self._mapped = True self.dispatch_event('on_show') self._update_exclusivity() @XlibEventHandler(xlib.UnmapNotify) def _event_unmapnotify(self, ev): self._mapped = False self.dispatch_event('on_hide')
modifiers |= key.MOD_SCROLLLOCK
collapse-expand-section.module.ts
/* * Copyright (c) 2018-2019 Porsche Informatik. All Rights Reserved. * This software is released under MIT license. * The full license information can be found in LICENSE in the root directory of this project. */ import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { ClarityModule } from '@clr/angular'; import { ClrCollapseExpandSection } from './collapse-expand-section'; @NgModule({ imports: [CommonModule, ClarityModule, FormsModule], declarations: [ClrCollapseExpandSection], exports: [ClrCollapseExpandSection], }) export class
{}
ClrCollapseExpandSectionModule
register_ref.rs
use {Type,Register}; use util; #[derive(Clone,Debug,PartialEq,Eq)] pub struct RegisterRef { pub register_id: util::Id, pub ty: Type, } impl RegisterRef { pub fn new(register_id: util::Id, ty: Type) -> Self { RegisterRef { register_id: register_id, ty: ty, } } pub fn reference(register: &Register) -> Self { use util::Identifiable; RegisterRef { register_id: register.get_id(), ty: register.ty().clone(), } } pub fn register_id(&self) -> util::Id { self.register_id } pub fn ty(&self) -> Type { self.ty.clone() } }
impl_expression!(RegisterRef);
sanityMonogram.d.ts
import React from 'react'; /** * @public */
fg: string; } /** * @public */ export interface SanityMonogramProps { color?: SanityMonogramColor; } /** * @public */ export declare const SanityMonogram: React.ForwardRefExoticComponent<Pick<SanityMonogramProps & Omit<React.SVGProps<SVGSVGElement>, "color">, "string" | "color" | "className" | "height" | "id" | "lang" | "max" | "media" | "method" | "min" | "name" | "style" | "target" | "type" | "width" | "role" | "tabIndex" | "crossOrigin" | "accentHeight" | "accumulate" | "additive" | "alignmentBaseline" | "allowReorder" | "alphabetic" | "amplitude" | "arabicForm" | "ascent" | "attributeName" | "attributeType" | "autoReverse" | "azimuth" | "baseFrequency" | "baselineShift" | "baseProfile" | "bbox" | "begin" | "bias" | "by" | "calcMode" | "capHeight" | "clip" | "clipPath" | "clipPathUnits" | "clipRule" | "colorInterpolation" | "colorInterpolationFilters" | "colorProfile" | "colorRendering" | "contentScriptType" | "contentStyleType" | "cursor" | "cx" | "cy" | "d" | "decelerate" | "descent" | "diffuseConstant" | "direction" | "display" | "divisor" | "dominantBaseline" | "dur" | "dx" | "dy" | "edgeMode" | "elevation" | "enableBackground" | "end" | "exponent" | "externalResourcesRequired" | "fill" | "fillOpacity" | "fillRule" | "filter" | "filterRes" | "filterUnits" | "floodColor" | "floodOpacity" | "focusable" | "fontFamily" | "fontSize" | "fontSizeAdjust" | "fontStretch" | "fontStyle" | "fontVariant" | "fontWeight" | "format" | "fr" | "from" | "fx" | "fy" | "g1" | "g2" | "glyphName" | "glyphOrientationHorizontal" | "glyphOrientationVertical" | "glyphRef" | "gradientTransform" | "gradientUnits" | "hanging" | "horizAdvX" | "horizOriginX" | "href" | "ideographic" | "imageRendering" | "in2" | "in" | "intercept" | "k1" | "k2" | "k3" | "k4" | "k" | "kernelMatrix" | "kernelUnitLength" | "kerning" | "keyPoints" | "keySplines" | "keyTimes" | "lengthAdjust" | "letterSpacing" | "lightingColor" | "limitingConeAngle" | "local" | "markerEnd" | "markerHeight" | "markerMid" | "markerStart" | "markerUnits" | "markerWidth" | "mask" | "maskContentUnits" | "maskUnits" | "mathematical" | "mode" | "numOctaves" | "offset" | "opacity" | "operator" | "order" | "orient" | "orientation" | "origin" | "overflow" | "overlinePosition" | "overlineThickness" | "paintOrder" | "panose1" | "path" | "pathLength" | "patternContentUnits" | "patternTransform" | "patternUnits" | "pointerEvents" | "points" | "pointsAtX" | "pointsAtY" | "pointsAtZ" | "preserveAlpha" | "preserveAspectRatio" | "primitiveUnits" | "r" | "radius" | "refX" | "refY" | "renderingIntent" | "repeatCount" | "repeatDur" | "requiredExtensions" | "requiredFeatures" | "restart" | "result" | "rotate" | "rx" | "ry" | "scale" | "seed" | "shapeRendering" | "slope" | "spacing" | "specularConstant" | "specularExponent" | "speed" | "spreadMethod" | "startOffset" | "stdDeviation" | "stemh" | "stemv" | "stitchTiles" | "stopColor" | "stopOpacity" | "strikethroughPosition" | "strikethroughThickness" | "stroke" | "strokeDasharray" | "strokeDashoffset" | "strokeLinecap" | "strokeLinejoin" | "strokeMiterlimit" | "strokeOpacity" | "strokeWidth" | "surfaceScale" | "systemLanguage" | "tableValues" | "targetX" | "targetY" | "textAnchor" | "textDecoration" | "textLength" | "textRendering" | "to" | "transform" | "u1" | "u2" | "underlinePosition" | "underlineThickness" | "unicode" | "unicodeBidi" | "unicodeRange" | "unitsPerEm" | "vAlphabetic" | "values" | "vectorEffect" | "version" | "vertAdvY" | "vertOriginX" | "vertOriginY" | "vHanging" | "vIdeographic" | "viewBox" | "viewTarget" | "visibility" | "vMathematical" | "widths" | "wordSpacing" | "writingMode" | "x1" | "x2" | "x" | "xChannelSelector" | "xHeight" | "xlinkActuate" | "xlinkArcrole" | "xlinkHref" | "xlinkRole" | "xlinkShow" | "xlinkTitle" | "xlinkType" | "xmlBase" | "xmlLang" | "xmlns" | "xmlnsXlink" | "xmlSpace" | "y1" | "y2" | "y" | "yChannelSelector" | "z" | "zoomAndPan" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "children" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture" | "key"> & React.RefAttributes<SVGSVGElement>>; //# sourceMappingURL=sanityMonogram.d.ts.map
export interface SanityMonogramColor { bg1: string; bg2: string;
urls.py
from django.conf.urls import include
from django.urls import path from django.contrib import admin urlpatterns = [ path('', include('chat.urls')), path('admin/', admin.site.urls), ]
line.rs
use crate::unit_tests::assert_line_segments_approx_equal; use fenris_geometry::{Disk, LineSegment2d}; use nalgebra::point; #[test] fn test_line_segment_disk_intersection() { let a = point![1.0, 2.0];
// Radius r = 1, empty intersection { let disk = Disk::from_center_and_radius(c, 1.0); assert!(segment.intersect_disk(&disk).is_none()); } // Radius r = 2, cuts the segment in half { let disk = Disk::from_center_and_radius(c, 2.0); let intersection_point = point![3.069693845669907, 1.310102051443365]; let expected_intersection = LineSegment2d::new(a, intersection_point); let intersection = segment.intersect_disk(&disk).unwrap(); assert_line_segments_approx_equal!(intersection, expected_intersection, abstol = 1e-14); } // Radius r = 3, completely contains the line segment { let disk = Disk::from_center_and_radius(c, 3.0); let intersection = segment.intersect_disk(&disk).unwrap(); assert_line_segments_approx_equal!(intersection, segment, abstol = 1e-14); } // Test when the disk is on the other side of the line segment { let c2 = point![2.0, 1.0]; let disk = Disk::from_center_and_radius(c2, 1.0); let expected_intersection = LineSegment2d::new( point![1.465153077165047, 1.844948974278318], point![2.934846922834954, 1.355051025721682], ); let intersection = segment.intersect_disk(&disk).unwrap(); assert_line_segments_approx_equal!(intersection, expected_intersection, abstol = 1e-14); } }
let b = point![4.0, 1.0]; let c = point![2.0, 3.0]; let segment = LineSegment2d::new(a, b);
test_background_swap.py
import os from torch.utils.data import DataLoader from continuum.datasets import CIFAR10, InMemoryDataset from continuum.datasets import MNIST import torchvision from continuum.scenarios import TransformationIncremental import pytest import numpy as np from continuum.transforms.bg_swap import BackgroundSwap DATA_PATH = os.environ.get("CONTINUUM_DATA_PATH") # Uncomment for debugging via image output # import matplotlib.pyplot as plt def test_bg_swap_fast(): """ Fast test for background swap. """ bg_x = np.ones(shape=[2, 5, 5, 3]) * -1 bg_y = np.random.rand(2) fg = np.random.normal(loc=.5, scale=.1, size=[5, 5]) bg = InMemoryDataset(bg_x, bg_y) bg_swap = BackgroundSwap(bg, input_dim=(5, 5), normalize_bg=None) spliced_1_channel = bg_swap(fg)[:, :, 0] assert np.array_equal((spliced_1_channel <= -1), (fg <= .5)) @pytest.mark.slow def test_background_swap_numpy(): """ Test background swap on a single ndarray input. """ mnist = MNIST(DATA_PATH, download=True, train=True) cifar = CIFAR10(DATA_PATH, download=True, train=True) bg_swap = BackgroundSwap(cifar, input_dim=(28, 28)) im = mnist.get_data()[0][0] im = bg_swap(im) # Uncomment for debugging # plt.imshow(im, interpolation='nearest') # plt.show() @pytest.mark.slow def test_background_swap_torch(): """ Test background swap on a single tensor input. """ cifar = CIFAR10(DATA_PATH, download=True, train=True) mnist = torchvision.datasets.MNIST(DATA_PATH, train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor() ])) bg_swap = BackgroundSwap(cifar, input_dim=(28, 28)) im = mnist[0][0] im = bg_swap(im) # Uncomment for debugging # plt.imshow(im.permute(1, 2, 0), interpolation='nearest') # plt.show() @pytest.mark.slow def test_background_tranformation():
""" Example code using TransformationIncremental to create a setting with 3 tasks. """ cifar = CIFAR10(DATA_PATH, train=True) mnist = MNIST(DATA_PATH, download=False, train=True) nb_task = 3 list_trsf = [] for i in range(nb_task): list_trsf.append([torchvision.transforms.ToTensor(), BackgroundSwap(cifar, bg_label=i, input_dim=(28, 28)), torchvision.transforms.ToPILImage()]) scenario = TransformationIncremental(mnist, base_transformations=[torchvision.transforms.ToTensor()], incremental_transformations=list_trsf) folder = "tests/samples/background_trsf/" if not os.path.exists(folder): os.makedirs(folder) for task_id, task_data in enumerate(scenario): task_data.plot(path=folder, title=f"background_{task_id}.jpg", nb_samples=100, shape=[28, 28, 3]) loader = DataLoader(task_data) _, _, _ = next(iter(loader))
platform-server.js
/** * @license Angular v6.1.2 * (c) 2010-2018 Google, Inc. https://angular.io/ * License: MIT */ import { ɵBrowserDomAdapter, ɵsetRootDomAdapter, DOCUMENT, ɵgetDOM, EventManager, ɵNAMESPACE_URIS, ɵSharedStylesHost, ɵflattenStyles, ɵshimContentAttribute, ɵshimHostAttribute, ɵTRANSITION_ID, BrowserModule, EVENT_MANAGER_PLUGINS, TransferState, ɵescapeHtml } from '@angular/platform-browser'; import { Inject, Injectable, Injector, InjectionToken, Optional, NgZone, ViewEncapsulation, NgModule, PLATFORM_ID, PLATFORM_INITIALIZER, RendererFactory2, Testability, createPlatformFactory, platformCore, ɵALLOW_MULTIPLE_PLATFORMS, APP_ID, ApplicationRef, Version } from '@angular/core'; import { BrowserXhr, Http, ReadyState, RequestOptions, XHRBackend, XSRFStrategy, HttpModule } from '@angular/http'; import { HttpHandler, HttpBackend, XhrFactory, ɵHttpInterceptingHandler, HttpClientModule } from '@angular/common/http'; import { Observable, Subject } from 'rxjs'; import { parse } from 'url'; import { DomElementSchemaRegistry } from '@angular/compiler'; import { ɵAnimationEngine } from '@angular/animations/browser'; import { PlatformLocation, ViewportScroller, ɵNullViewportScroller, ɵPLATFORM_SERVER_ID } from '@angular/common'; import { ɵplatformCoreDynamic } from '@angular/platform-browser-dynamic'; import { NoopAnimationsModule, ɵAnimationRendererFactory } from '@angular/platform-browser/animations'; import { first } from 'rxjs/operators'; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license @type {?} */ const domino = require('domino'); /** * @param {?} methodName * @return {?} */ function _notImplemented(methodName) { return new Error('This method is not implemented in DominoAdapter: ' + methodName); } /** * @return {?} */ function setDomTypes() { // Make all Domino types available as types in the global env. Object.assign(global, domino.impl); (/** @type {?} */ (global))['KeyboardEvent'] = domino.impl.Event; } /** * Parses a document string to a Document object. * @param {?} html * @param {?=} url * @return {?} */ function parseDocument(html, url = '/') { /** @type {?} */ let window = domino.createWindow(html, url); /** @type {?} */ let doc = window.document; return doc; } /** * Serializes a document to string. * @param {?} doc * @return {?} */ function serializeDocument(doc) { return (/** @type {?} */ (doc)).serialize(); } /** * DOM Adapter for the server platform based on https://github.com/fgnass/domino. */ class DominoAdapter extends ɵBrowserDomAdapter { /** * @return {?} */ static makeCurrent() { setDomTypes(); ɵsetRootDomAdapter(new DominoAdapter()); } /** * @param {?} error * @return {?} */ logError(error) { console.error(error); } /** * @param {?} error * @return {?} */ log(error) { // tslint:disable-next-line:no-console console.log(error); } /** * @param {?} error * @return {?} */ logGroup(error) { console.error(error); } /** * @return {?} */ logGroupEnd() { } /** * @return {?} */ supportsDOMEvents() { return false; } /** * @return {?} */ supportsNativeShadowDOM() { return false; } /** * @param {?} nodeA * @param {?} nodeB * @return {?} */ contains(nodeA, nodeB) { /** @type {?} */ let inner = nodeB; while (inner) { if (inner === nodeA) return true; inner = inner.parent; } return false; } /** * @return {?} */ createHtmlDocument() { return parseDocument('<html><head><title>fakeTitle</title></head><body></body></html>'); } /** * @return {?} */ getDefaultDocument() { if (!DominoAdapter.defaultDoc) { DominoAdapter.defaultDoc = domino.createDocument(); } return DominoAdapter.defaultDoc; } /** * @param {?} el * @param {?=} doc * @return {?} */ createShadowRoot(el, doc = document) { el.shadowRoot = doc.createDocumentFragment(); el.shadowRoot.parent = el; return el.shadowRoot; } /** * @param {?} el * @return {?} */ getShadowRoot(el) { return el.shadowRoot; } /** * @param {?} node * @return {?} */ isTextNode(node) { return node.nodeType === DominoAdapter.defaultDoc.TEXT_NODE; } /** * @param {?} node * @return {?} */ isCommentNode(node) { return node.nodeType === DominoAdapter.defaultDoc.COMMENT_NODE; } /** * @param {?} node * @return {?} */ isElementNode(node) { return node ? node.nodeType === DominoAdapter.defaultDoc.ELEMENT_NODE : false; } /** * @param {?} node * @return {?} */ hasShadowRoot(node) { return node.shadowRoot != null; } /** * @param {?} node * @return {?} */ isShadowRoot(node) { return this.getShadowRoot(node) == node; } /** * @param {?} el * @param {?} name * @return {?} */ getProperty(el, name) { if (name === 'href') { // Domino tries tp resolve href-s which we do not want. Just return the // attribute value. return this.getAttribute(el, 'href'); } else if (name === 'innerText') { // Domino does not support innerText. Just map it to textContent. return el.textContent; } return (/** @type {?} */ (el))[name]; } /** * @param {?} el * @param {?} name * @param {?} value * @return {?} */ setProperty(el, name, value) { if (name === 'href') { // Even though the server renderer reflects any properties to attributes // map 'href' to attribute just to handle when setProperty is directly called. this.setAttribute(el, 'href', value); } else if (name === 'innerText') { // Domino does not support innerText. Just map it to textContent. el.textContent = value; } (/** @type {?} */ (el))[name] = value; } /** * @param {?} doc * @param {?} target * @return {?} */ getGlobalEventTarget(doc, target) { if (target === 'window') { return doc.defaultView; } if (target === 'document') { return doc; } if (target === 'body') { return doc.body; } return null; } /** * @param {?} doc * @return {?} */ getBaseHref(doc) { /** @type {?} */ const base = this.querySelector(doc.documentElement, 'base'); /** @type {?} */ let href = ''; if (base) { href = this.getHref(base); } // TODO(alxhub): Need relative path logic from BrowserDomAdapter here? return href; } /** * \@internal * @param {?} element * @return {?} */ _readStyleAttribute(element) { /** @type {?} */ const styleMap = {}; /** @type {?} */ const styleAttribute = element.getAttribute('style'); if (styleAttribute) { /** @type {?} */ const styleList = styleAttribute.split(/;+/g); for (let i = 0; i < styleList.length; i++) { /** @type {?} */ const style = styleList[i].trim(); if (style.length > 0) { /** @type {?} */ const colonIndex = style.indexOf(':'); if (colonIndex === -1) { throw new Error(`Invalid CSS style: ${style}`); } /** @type {?} */ const name = style.substr(0, colonIndex).trim(); styleMap[name] = style.substr(colonIndex + 1).trim(); } } } return styleMap; } /** * \@internal * @param {?} element * @param {?} styleMap * @return {?} */ _writeStyleAttribute(element, styleMap) { /** @type {?} */ let styleAttrValue = ''; for (const key in styleMap) { /** @type {?} */ const newValue = styleMap[key]; if (newValue) { styleAttrValue += key + ':' + styleMap[key] + ';'; } } element.setAttribute('style', styleAttrValue); } /** * @param {?} element * @param {?} styleName * @param {?=} styleValue * @return {?} */ setStyle(element, styleName, styleValue) { styleName = styleName.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); /** @type {?} */ const styleMap = this._readStyleAttribute(element); styleMap[styleName] = styleValue || ''; this._writeStyleAttribute(element, styleMap); } /** * @param {?} element * @param {?} styleName * @return {?} */ removeStyle(element, styleName) { // IE requires '' instead of null // see https://github.com/angular/angular/issues/7916 this.setStyle(element, styleName, ''); } /** * @param {?} element * @param {?} styleName * @return {?} */ getStyle(element, styleName) { /** @type {?} */ const styleMap = this._readStyleAttribute(element); return styleMap[styleName] || ''; } /** * @param {?} element * @param {?} styleName * @param {?=} styleValue * @return {?} */ hasStyle(element, styleName, styleValue) { /** @type {?} */ const value = this.getStyle(element, styleName); return styleValue ? value == styleValue : value.length > 0; } /** * @param {?} el * @param {?} evt * @return {?} */ dispatchEvent(el, evt) { el.dispatchEvent(evt); /** @type {?} */ const doc = el.ownerDocument || el; /** @type {?} */ const win = (/** @type {?} */ (doc)).defaultView; if (win) { win.dispatchEvent(evt); } } /** * @return {?} */ getHistory() { throw _notImplemented('getHistory'); } /** * @return {?} */ getLocation() { throw _notImplemented('getLocation'); } /** * @return {?} */ getUserAgent() { return 'Fake user agent'; } /** * @return {?} */ supportsWebAnimation() { return false; } /** * @return {?} */ performanceNow() { return Date.now(); } /** * @return {?} */ getAnimationPrefix() { return ''; } /** * @return {?} */ getTransitionEnd() { return 'transitionend'; } /** * @return {?} */ supportsAnimation() { return true; } /** * @param {?} el * @return {?} */ getDistributedNodes(el) { throw _notImplemented('getDistributedNodes'); } /** * @return {?} */ supportsCookies() { return false; } /** * @param {?} name * @return {?} */ getCookie(name) { throw _notImplemented('getCookie'); } /** * @param {?} name * @param {?} value * @return {?} */ setCookie(name, value) { throw _notImplemented('setCookie'); } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * Representation of the current platform state. * * \@experimental */ class PlatformState { /** * @param {?} _doc */ constructor(_doc) { this._doc = _doc; } /** * Renders the current state of the platform to string. * @return {?} */ renderToString() { return serializeDocument(this._doc); } /** * Returns the current DOM state. * @return {?} */ getDocument() { return this._doc; } } PlatformState.decorators = [ { type: Injectable } ]; /** @nocollapse */ PlatformState.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** @type {?} */ const xhr2 = require('xhr2'); /** @type {?} */ const isAbsoluteUrl = /^[a-zA-Z\-\+.]+:\/\//; /** * @param {?} url * @return {?} */ function validateRequestUrl(url) { if (!isAbsoluteUrl.test(url)) { throw new Error(`URLs requested via Http on the server must be absolute. URL: ${url}`); } } class ServerXhr { /** * @return {?} */ build() { return new xhr2.XMLHttpRequest(); } } ServerXhr.decorators = [ { type: Injectable } ]; class ServerXsrfStrategy { /** * @param {?} req * @return {?} */ configureRequest(req) { } } ServerXsrfStrategy.decorators = [ { type: Injectable } ]; /** * @abstract * @template S, R */ class ZoneMacroTaskWrapper { /** * @param {?} request * @return {?} */ wrap(request) { return new Observable((observer) => { /** @type {?} */ let task = /** @type {?} */ ((null)); /** @type {?} */ let scheduled = false; /** @type {?} */ let sub = null; /** @type {?} */ let savedResult = null; /** @type {?} */ let savedError = null; /** @type {?} */ const scheduleTask = (_task) => { task = _task; scheduled = true; /** @type {?} */ const delegate = this.delegate(request); sub = delegate.subscribe(res => savedResult = res, err => { if (!scheduled) { throw new Error('An http observable was completed twice. This shouldn\'t happen, please file a bug.'); } savedError = err; scheduled = false; task.invoke(); }, () => { if (!scheduled) { throw new Error('An http observable was completed twice. This shouldn\'t happen, please file a bug.'); } scheduled = false; task.invoke(); }); }; /** @type {?} */ const cancelTask = (_task) => { if (!scheduled) { return; } scheduled = false; if (sub) { sub.unsubscribe(); sub = null; } }; /** @type {?} */ const onComplete = () => { if (savedError !== null) { observer.error(savedError); } else { observer.next(savedResult); observer.complete(); } }; /** @type {?} */ const _task = Zone.current.scheduleMacroTask('ZoneMacroTaskWrapper.subscribe', onComplete, {}, () => null, cancelTask); scheduleTask(_task); return () => { if (scheduled && task) { task.zone.cancelTask(task); scheduled = false; } if (sub) { sub.unsubscribe(); sub = null; } }; }); } } class ZoneMacroTaskConnection extends ZoneMacroTaskWrapper { /** * @param {?} request * @param {?} backend */ constructor(request, backend) { super(); this.request = request; this.backend = backend; validateRequestUrl(request.url); this.response = this.wrap(request); } /** * @param {?} request * @return {?} */ delegate(request) { this.lastConnection = this.backend.createConnection(request); return /** @type {?} */ (this.lastConnection.response); } /** * @return {?} */ get readyState() { return !!this.lastConnection ? this.lastConnection.readyState : ReadyState.Unsent; } } class ZoneMacroTaskBackend { /** * @param {?} backend */ constructor(backend) { this.backend = backend; } /** * @param {?} request * @return {?} */ createConnection(request) { return new ZoneMacroTaskConnection(request, this.backend); } } class ZoneClientBackend extends ZoneMacroTaskWrapper { /** * @param {?} backend */ constructor(backend) { super(); this.backend = backend; } /** * @param {?} request * @return {?} */ handle(request) { return this.wrap(request); } /** * @param {?} request * @return {?} */ delegate(request) { return this.backend.handle(request); } } /** * @param {?} xhrBackend * @param {?} options * @return {?} */ function httpFactory(xhrBackend, options) { /** @type {?} */ const macroBackend = new ZoneMacroTaskBackend(xhrBackend); return new Http(macroBackend, options); } /** * @param {?} backend * @param {?} injector * @return {?} */ function zoneWrappedInterceptingHandler(backend, injector) { /** @type {?} */ const realBackend = new ɵHttpInterceptingHandler(backend, injector); return new ZoneClientBackend(realBackend); } /** @type {?} */ const SERVER_HTTP_PROVIDERS = [ { provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions] }, { provide: BrowserXhr, useClass: ServerXhr }, { provide: XSRFStrategy, useClass: ServerXsrfStrategy }, { provide: XhrFactory, useClass: ServerXhr }, { provide: HttpHandler, useFactory: zoneWrappedInterceptingHandler, deps: [HttpBackend, Injector] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * * The DI token for setting the initial config for the platform. * * \@experimental @type {?} */ const INITIAL_CONFIG = new InjectionToken('Server.INITIAL_CONFIG'); /** * * A function that will be executed when calling `renderModuleFactory` or `renderModule` just * before current platform state is rendered to string. * * \@experimental @type {?} */ const BEFORE_APP_SERIALIZED = new InjectionToken('Server.RENDER_MODULE_HOOK'); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @param {?} urlStr * @return {?} */ function parseUrl(urlStr) { /** @type {?} */ const parsedUrl = parse(urlStr); return { pathname: parsedUrl.pathname || '', search: parsedUrl.search || '', hash: parsedUrl.hash || '', }; } /** * Server-side implementation of URL state. Implements `pathname`, `search`, and `hash` * but not the state stack. */ class ServerPlatformLocation { /** * @param {?} _doc * @param {?} _config */ constructor(_doc, _config) { this._doc = _doc; this.pathname = '/'; this.search = ''; this.hash = ''; this._hashUpdate = new Subject(); /** @type {?} */ const config = /** @type {?} */ (_config); if (!!config && !!config.url) { /** @type {?} */ const parsedUrl = parseUrl(config.url); this.pathname = parsedUrl.pathname; this.search = parsedUrl.search; this.hash = parsedUrl.hash; } } /** * @return {?} */ getBaseHrefFromDOM() { return /** @type {?} */ ((ɵgetDOM().getBaseHref(this._doc))); } /** * @param {?} fn * @return {?} */ onPopState(fn) { // No-op: a state stack is not implemented, so // no events will ever come. } /** * @param {?} fn * @return {?} */ onHashChange(fn) { this._hashUpdate.subscribe(fn); } /** * @return {?} */ get url() { return `${this.pathname}${this.search}${this.hash}`; } /** * @param {?} value * @param {?} oldUrl * @return {?} */ setHash(value, oldUrl) { if (this.hash === value) { // Don't fire events if the hash has not changed. return; } (/** @type {?} */ (this)).hash = value; /** @type {?} */ const newUrl = this.url; scheduleMicroTask(() => this._hashUpdate.next(/** @type {?} */ ({ type: 'hashchange', state: null, oldUrl, newUrl }))); } /** * @param {?} state * @param {?} title * @param {?} newUrl * @return {?} */ replaceState(state, title, newUrl) { /** @type {?} */ const oldUrl = this.url; /** @type {?} */ const parsedUrl = parseUrl(newUrl); (/** @type {?} */ (this)).pathname = parsedUrl.pathname; (/** @type {?} */ (this)).search = parsedUrl.search; this.setHash(parsedUrl.hash, oldUrl); } /** * @param {?} state * @param {?} title * @param {?} newUrl * @return {?} */ pushState(state, title, newUrl) { this.replaceState(state, title, newUrl); } /** * @return {?} */ forward() { throw new Error('Not implemented'); } /** * @return {?} */ back() { throw new Error('Not implemented'); } } ServerPlatformLocation.decorators = [ { type: Injectable } ]; /** @nocollapse */ ServerPlatformLocation.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [INITIAL_CONFIG,] }] } ]; /** * @param {?} fn * @return {?} */ function scheduleMicroTask(fn) { Zone.current.scheduleMicroTask('scheduleMicrotask', fn); } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ class ServerEventManagerPlugin { /** * @param {?} doc */ constructor(doc) { this.doc = doc; } /** * @param {?} eventName * @return {?} */ supports(eventName) { return true; } /** * @param {?} element * @param {?} eventName * @param {?} handler * @return {?} */ addEventListener(element, eventName, handler) { return ɵgetDOM().onAndCancel(element, eventName, handler); } /** * @param {?} element * @param {?} eventName * @param {?} handler * @return {?} */ addGlobalEventListener(element, eventName, handler) { /** @type {?} */ const target = ɵgetDOM().getGlobalEventTarget(this.doc, element); if (!target) { throw new Error(`Unsupported event target ${target} for event ${eventName}`); } return this.addEventListener(target, eventName, handler); } } ServerEventManagerPlugin.decorators = [ { type: Injectable } ]; /** @nocollapse */ ServerEventManagerPlugin.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** @type {?} */ const EMPTY_ARRAY = []; class ServerRendererFactory2 { /** * @param {?} eventManager * @param {?} ngZone * @param {?} document * @param {?} sharedStylesHost */ constructor(eventManager, ngZone, document, sharedStylesHost) { this.eventManager = eventManager; this.ngZone = ngZone; this.document = document; this.sharedStylesHost = sharedStylesHost; this.rendererByCompId = new Map(); this.schema = new DomElementSchemaRegistry(); this.defaultRenderer = new DefaultServerRenderer2(eventManager, document, ngZone, this.schema); } /** * @param {?} element * @param {?} type * @return {?} */ createRenderer(element, type) { if (!element || !type) { return this.defaultRenderer; } switch (type.encapsulation) { case ViewEncapsulation.Native: case ViewEncapsulation.Emulated: { /** @type {?} */ let renderer = this.rendererByCompId.get(type.id); if (!renderer) { renderer = new EmulatedEncapsulationServerRenderer2(this.eventManager, this.document, this.ngZone, this.sharedStylesHost, this.schema, type); this.rendererByCompId.set(type.id, renderer); } (/** @type {?} */ (renderer)).applyToHost(element); return renderer; } case ViewEncapsulation.Native: throw new Error('Native encapsulation is not supported on the server!'); default: { if (!this.rendererByCompId.has(type.id)) { /** @type {?} */ const styles = ɵflattenStyles(type.id, type.styles, []); this.sharedStylesHost.addStyles(styles); this.rendererByCompId.set(type.id, this.defaultRenderer); } return this.defaultRenderer; } } } /** * @return {?} */ begin() { } /** * @return {?} */ end() { } } ServerRendererFactory2.decorators = [ { type: Injectable } ]; /** @nocollapse */ ServerRendererFactory2.ctorParameters = () => [ { type: EventManager }, { type: NgZone }, { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }, { type: ɵSharedStylesHost } ]; class DefaultServerRenderer2 { /** * @param {?} eventManager * @param {?} document * @param {?} ngZone * @param {?} schema */ constructor(eventManager, document, ngZone, schema) { this.eventManager = eventManager; this.document = document; this.ngZone = ngZone; this.schema = schema; this.data = Object.create(null); } /** * @return {?} */ destroy() { } /** * @param {?} name * @param {?=} namespace * @param {?=} debugInfo * @return {?} */ createElement(name, namespace, debugInfo) { if (namespace) { return ɵgetDOM().createElementNS(ɵNAMESPACE_URIS[namespace], name, this.document); } return ɵgetDOM().createElement(name, this.document); } /** * @param {?} value * @param {?=} debugInfo * @return {?} */ createComment(value, debugInfo) { return ɵgetDOM().createComment(value); } /** * @param {?} value * @param {?=} debugInfo * @return {?} */ createText(value, debugInfo) { return ɵgetDOM().createTextNode(value); } /** * @param {?} parent * @param {?} newChild * @return {?} */ appendChild(parent, newChild) { ɵgetDOM().appendChild(parent, newChild); } /** * @param {?} parent * @param {?} newChild * @param {?} refChild * @return {?} */ insertBefore(parent, newChild, refChild) { if (parent) { ɵgetDOM().insertBefore(parent, refChild, newChild); } } /** * @param {?} parent * @param {?} oldChild * @return {?} */ removeChild(parent, oldChild) { if (parent) { ɵgetDOM().removeChild(parent, oldChild); } } /** * @param {?} selectorOrNode * @param {?=} debugInfo * @return {?} */ selectRootElement(selectorOrNode, debugInfo) { /** @type {?} */ let el; if (typeof selectorOrNode === 'string') { el = ɵgetDOM().querySelector(this.document, selectorOrNode); if (!el) { throw new Error(`The selector "${selectorOrNode}" did not match any elements`); } } else { el = selectorOrNode; } ɵgetDOM().clearNodes(el); return el; } /** * @param {?} node * @return {?} */ parentNode(node) { return ɵgetDOM().parentElement(node); } /** * @param {?} node * @return {?} */ nextSibling(node) { return ɵgetDOM().nextSibling(node); } /** * @param {?} el * @param {?} name * @param {?} value * @param {?=} namespace * @return {?} */ setAttribute(el, name, value, namespace) { if (namespace) { ɵgetDOM().setAttributeNS(el, ɵNAMESPACE_URIS[namespace], namespace + ':' + name, value); } else { ɵgetDOM().setAttribute(el, name, value); } } /** * @param {?} el * @param {?} name * @param {?=} namespace * @return {?} */ removeAttribute(el, name, namespace) { if (namespace) { ɵgetDOM().removeAttributeNS(el, ɵNAMESPACE_URIS[namespace], name); } else { ɵgetDOM().removeAttribute(el, name); } } /** * @param {?} el * @param {?} name * @return {?} */ addClass(el, name) { ɵgetDOM().addClass(el, name); } /** * @param {?} el * @param {?} name * @return {?} */ removeClass(el, name) { ɵgetDOM().removeClass(el, name); } /** * @param {?} el * @param {?} style * @param {?} value * @param {?} flags * @return {?} */ setStyle(el, style, value, flags) { ɵgetDOM().setStyle(el, style, value); } /** * @param {?} el * @param {?} style * @param {?} flags * @return {?} */ removeStyle(el, style, flags) { ɵgetDOM().removeStyle(el, style); } /** * @param {?} tagName * @param {?} propertyName * @return {?} */ _isSafeToReflectProperty(tagName, propertyName) { return this.schema.securityContext(tagName, propertyName, true) === this.schema.securityContext(tagName, propertyName, false); } /** * @param {?} el * @param {?} name * @param {?} value * @return {?} */ setProperty(el, name, value) { checkNoSyntheticProp(name, 'property'); ɵgetDOM().setProperty(el, name, value); /** @type {?} */ const tagName = (/** @type {?} */ (el.tagName)).toLowerCase(); if (value != null && (typeof value === 'number' || typeof value == 'string') && name.toLowerCase() !== 'innerhtml' && this.schema.hasElement(tagName, EMPTY_ARRAY) && this.schema.hasProperty(tagName, name, EMPTY_ARRAY) && this._isSafeToReflectProperty(tagName, name)) { this.setAttribute(el, name, value.toString()); } } /** * @param {?} node * @param {?} value * @return {?} */ setValue(node, value) { ɵgetDOM().setText(node, value); } /** * @param {?} target * @param {?} eventName * @param {?} callback * @return {?} */ listen(target, eventName, callback) { checkNoSyntheticProp(eventName, 'listener'); if (typeof target === 'string') { return /** @type {?} */ (this.eventManager.addGlobalEventListener(target, eventName, this.decoratePreventDefault(callback))); } return /** @type {?} */ ((this.eventManager.addEventListener(target, eventName, this.decoratePreventDefault(callback)))); } /** * @param {?} eventHandler * @return {?} */ decoratePreventDefault(eventHandler) { return (event) => { /** @type {?} */ const allowDefaultBehavior = this.ngZone.runGuarded(() => eventHandler(event)); if (allowDefaultBehavior === false) { event.preventDefault(); event.returnValue = false; } }; } } /** @type {?} */ const AT_CHARCODE = '@'.charCodeAt(0); /** * @param {?} name * @param {?} nameKind * @return {?} */ function checkNoSyntheticProp(name, nameKind) { if (name.charCodeAt(0) === AT_CHARCODE) { throw new Error(`Found the synthetic ${nameKind} ${name}. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.`); } } class EmulatedEncapsulationServerRenderer2 extends DefaultServerRenderer2 { /** * @param {?} eventManager * @param {?} document * @param {?} ngZone * @param {?} sharedStylesHost * @param {?} schema * @param {?} component */ constructor(eventManager, document, ngZone, sharedStylesHost, schema, component) { super(eventManager, document, ngZone, schema); this.component = component; /** @type {?} */ const componentId = 's' + component.id; /** @type {?} */ const styles = ɵflattenStyles(componentId, component.styles, []); sharedStylesHost.addStyles(styles); this.contentAttr = ɵshimContentAttribute(componentId); this.hostAttr = ɵshimHostAttribute(componentId); } /** * @param {?} element * @return {?} */ applyToHost(element) { super.setAttribute(element, this.hostAttr, ''); } /** * @param {?} parent * @param {?} name * @return {?} */ createElement(parent, name) { /** @type {?} */ const el = super.createElement(parent, name, this.document); super.setAttribute(el, this.contentAttr, ''); return el; } } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ class ServerStylesHost extends ɵSharedStylesHost { /** * @param {?} doc * @param {?} transitionId */ constructor(doc, transitionId) { super(); this.doc = doc; this.transitionId = transitionId; this.head = null; this.head = ɵgetDOM().getElementsByTagName(doc, 'head')[0]; } /** * @param {?} style * @return {?} */ _addStyle(style) { /** @type {?} */ let adapter = ɵgetDOM(); /** @type {?} */ const el = adapter.createElement('style'); adapter.setText(el, style); if (!!this.transitionId) { adapter.setAttribute(el, 'ng-transition', this.transitionId); } adapter.appendChild(this.head, el); } /** * @param {?} additions * @return {?} */ onStylesAdded(additions) { additions.forEach(style => this._addStyle(style)); } } ServerStylesHost.decorators = [ { type: Injectable } ]; /** @nocollapse */ ServerStylesHost.ctorParameters = () => [ { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }, { type: String, decorators: [{ type: Optional }, { type: Inject, args: [ɵTRANSITION_ID,] }] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** @type {?} */ const INTERNAL_SERVER_PLATFORM_PROVIDERS = [ { provide: DOCUMENT, useFactory: _document, deps: [Injector] }, { provide: PLATFORM_ID, useValue: ɵPLATFORM_SERVER_ID }, { provide: PLATFORM_INITIALIZER, useFactory: initDominoAdapter, multi: true, deps: [Injector] }, { provide: PlatformLocation, useClass: ServerPlatformLocation, deps: [DOCUMENT, [Optional, INITIAL_CONFIG]] }, { provide: PlatformState, deps: [DOCUMENT] }, // Add special provider that allows multiple instances of platformServer* to be created. { provide: ɵALLOW_MULTIPLE_PLATFORMS, useValue: true } ]; /** * @param {?} injector * @return {?} */ function initDominoAdapter(injector) { return () => { DominoAdapter.makeCurrent(); }; } /** * @param {?} renderer * @param {?} engine * @param {?} zone * @return {?} */ function instantiateServerRendererFactory(renderer, engine, zone) { return new ɵAnimationRendererFactory(renderer, engine, zone); } /** @type {?} */ const SERVER_RENDER_PROVIDERS = [ ServerRendererFactory2, { provide: RendererFactory2, useFactory: instantiateServerRendererFactory, deps: [ServerRendererFactory2, ɵAnimationEngine, NgZone] }, ServerStylesHost, { provide: ɵSharedStylesHost, useExisting: ServerStylesHost }, { provide: EVENT_MANAGER_PLUGINS, multi: true, useClass: ServerEventManagerPlugin }, ]; /** * The ng module for the server. * * \@experimental */ class ServerModule { }
imports: [HttpModule, HttpClientModule, NoopAnimationsModule], providers: [ SERVER_RENDER_PROVIDERS, SERVER_HTTP_PROVIDERS, { provide: Testability, useValue: null }, { provide: ViewportScroller, useClass: ɵNullViewportScroller }, ], },] } ]; /** * @param {?} injector * @return {?} */ function _document(injector) { /** @type {?} */ let config = injector.get(INITIAL_CONFIG, null); if (config && config.document) { return parseDocument(config.document, config.url); } else { return ɵgetDOM().createHtmlDocument(); } } /** * * \@experimental @type {?} */ const platformServer = createPlatformFactory(platformCore, 'server', INTERNAL_SERVER_PLATFORM_PROVIDERS); /** * * The server platform that supports the runtime compiler. * * \@experimental @type {?} */ const platformDynamicServer = createPlatformFactory(ɵplatformCoreDynamic, 'serverDynamic', INTERNAL_SERVER_PLATFORM_PROVIDERS); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @param {?} doc * @param {?} appId * @param {?} transferStore * @return {?} */ function serializeTransferStateFactory(doc, appId, transferStore) { return () => { /** @type {?} */ const script = doc.createElement('script'); script.id = appId + '-state'; script.setAttribute('type', 'application/json'); script.textContent = ɵescapeHtml(transferStore.toJson()); doc.body.appendChild(script); }; } /** * NgModule to install on the server side while using the `TransferState` to transfer state from * server to client. * * \@experimental */ class ServerTransferStateModule { } ServerTransferStateModule.decorators = [ { type: NgModule, args: [{ providers: [ TransferState, { provide: BEFORE_APP_SERIALIZED, useFactory: serializeTransferStateFactory, deps: [DOCUMENT, APP_ID, TransferState], multi: true, } ] },] } ]; /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @param {?} platformFactory * @param {?} options * @return {?} */ function _getPlatform(platformFactory, options) { /** @type {?} */ const extraProviders = options.extraProviders ? options.extraProviders : []; return platformFactory([ { provide: INITIAL_CONFIG, useValue: { document: options.document, url: options.url } }, extraProviders ]); } /** * @template T * @param {?} platform * @param {?} moduleRefPromise * @return {?} */ function _render(platform, moduleRefPromise) { return moduleRefPromise.then((moduleRef) => { /** @type {?} */ const transitionId = moduleRef.injector.get(ɵTRANSITION_ID, null); if (!transitionId) { throw new Error(`renderModule[Factory]() requires the use of BrowserModule.withServerTransition() to ensure the server-rendered app can be properly bootstrapped into a client app.`); } /** @type {?} */ const applicationRef = moduleRef.injector.get(ApplicationRef); return applicationRef.isStable.pipe((first((isStable) => isStable))) .toPromise() .then(() => { /** @type {?} */ const platformState = platform.injector.get(PlatformState); /** @type {?} */ const callbacks = moduleRef.injector.get(BEFORE_APP_SERIALIZED, null); if (callbacks) { for (const callback of callbacks) { try { callback(); } catch (e) { // Ignore exceptions. console.warn('Ignoring BEFORE_APP_SERIALIZED Exception: ', e); } } } /** @type {?} */ const output = platformState.renderToString(); platform.destroy(); return output; }); }); } /** * Renders a Module to string. * * `document` is the full document HTML of the page to render, as a string. * `url` is the URL for the current render request. * `extraProviders` are the platform level providers for the current render request. * * Do not use this in a production server environment. Use pre-compiled {\@link NgModuleFactory} with * {\@link renderModuleFactory} instead. * * \@experimental * @template T * @param {?} module * @param {?} options * @return {?} */ function renderModule(module, options) { /** @type {?} */ const platform = _getPlatform(platformDynamicServer, options); return _render(platform, platform.bootstrapModule(module)); } /** * Renders a {\@link NgModuleFactory} to string. * * `document` is the full document HTML of the page to render, as a string. * `url` is the URL for the current render request. * `extraProviders` are the platform level providers for the current render request. * * \@experimental * @template T * @param {?} moduleFactory * @param {?} options * @return {?} */ function renderModuleFactory(moduleFactory, options) { /** @type {?} */ const platform = _getPlatform(platformServer, options); return _render(platform, platform.bootstrapModuleFactory(moduleFactory)); } /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** @type {?} */ const VERSION = new Version('6.1.2'); /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ // This file only reexports content of the `src` folder. Keep it that way. /** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { SERVER_HTTP_PROVIDERS as ɵangular_packages_platform_server_platform_server_i, ServerXhr as ɵangular_packages_platform_server_platform_server_e, ServerXsrfStrategy as ɵangular_packages_platform_server_platform_server_f, httpFactory as ɵangular_packages_platform_server_platform_server_g, zoneWrappedInterceptingHandler as ɵangular_packages_platform_server_platform_server_h, instantiateServerRendererFactory as ɵangular_packages_platform_server_platform_server_a, ServerEventManagerPlugin as ɵangular_packages_platform_server_platform_server_d, ServerStylesHost as ɵangular_packages_platform_server_platform_server_c, serializeTransferStateFactory as ɵangular_packages_platform_server_platform_server_b, PlatformState, ServerModule, platformDynamicServer, platformServer, BEFORE_APP_SERIALIZED, INITIAL_CONFIG, ServerTransferStateModule, renderModule, renderModuleFactory, VERSION, INTERNAL_SERVER_PLATFORM_PROVIDERS as ɵINTERNAL_SERVER_PLATFORM_PROVIDERS, SERVER_RENDER_PROVIDERS as ɵSERVER_RENDER_PROVIDERS, ServerRendererFactory2 as ɵServerRendererFactory2 }; //# sourceMappingURL=platform-server.js.map
ServerModule.decorators = [ { type: NgModule, args: [{ exports: [BrowserModule],
resources.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; const rootUri = vscode.Uri.parse(vscode.env.webviewResourceRoot); export function
(uri: vscode.Uri): vscode.Uri { return rootUri.with({ path: rootUri.path + uri.path, query: uri.query, fragment: uri.fragment, }); }
toResoruceUri
pb3server.py
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor class One(pb.Root): def remote_takeTwo(self, two): print "received a Two called", two
reactor.listenTCP(8800, pb.PBServerFactory(One())) reactor.run()
print "telling it to print(12)" two.callRemote("print", 12)
alternating_characters.py
def minimum_deletions(string: str) -> int: current_character = string[0] count = 0 deletions = 0 for character in string: if character == current_character: count += 1 else: current_character = character
test_cases = int(input()) for _ in range(test_cases): string = input() print(minimum_deletions(string))
deletions += count - 1 count = 1 return deletions + count - 1
event.rs
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::sync::Mutex; use rustc_serialize::{Encoder, Encodable}; #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)] pub enum Event { Intern(u64), Insert(u64, String), Remove(u64), } lazy_static! { pub static ref LOG: Mutex<Vec<Event>> = Mutex::new(Vec::with_capacity(50_000)); } pub fn log(e: Event)
macro_rules! log (($e:expr) => (::event::log($e))); // Serialize by converting to this private struct, // which produces more convenient output. #[derive(RustcEncodable)] struct SerializeEvent<'a> { event: &'static str, id: u64, string: Option<&'a String>, } impl Encodable for Event { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { let (event, id, string) = match *self { Event::Intern(id) => ("intern", id, None), Event::Insert(id, ref s) => ("insert", id, Some(s)), Event::Remove(id) => ("remove", id, None), }; SerializeEvent { event: event, id: id, string: string }.encode(s) } }
{ LOG.lock().unwrap().push(e); }
attrs.go
// Copyright 2020 CUE 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 internal import ( "fmt" "strconv" "strings" "unicode" "github.com/solo-io/cue/cue/errors" "github.com/solo-io/cue/cue/literal" "github.com/solo-io/cue/cue/token" ) // AttrKind indicates the location of an attribute within CUE source. type AttrKind uint8 const ( // FieldAttr indicates an attribute is a field attribute. // foo: bar @attr() FieldAttr AttrKind = 1 << iota // DeclAttr indicates an attribute was specified at a declaration position. // foo: { // @attr() // } DeclAttr // TODO: Possible future attr kinds // ElemAttr // FileAttr // ValueAttr = FieldAttr|DeclAttr|ElemAttr ) // Attr holds positional information for a single Attr. type Attr struct { Name string // e.g. "json" or "protobuf" Body string Kind AttrKind Fields []KeyValue Err error } // NewNonExisting creates a non-existing attribute. func NewNonExisting(key string) Attr { const msgNotExist = "attribute %q does not exist" return Attr{Err: errors.Newf(token.NoPos, msgNotExist, key)} } type KeyValue struct { data string equal int // index of equal sign or 0 if non-existing } func (kv *KeyValue) Text() string { return kv.data } func (kv *KeyValue) Key() string { if kv.equal == 0 { return kv.data } s := kv.data[:kv.equal] s = strings.TrimSpace(s) return s } func (kv *KeyValue) Value() string { if kv.equal == 0 { return "" } return strings.TrimSpace(kv.data[kv.equal+1:]) } func (a *Attr) hasPos(p int) error { if a.Err != nil { return a.Err } if p >= len(a.Fields)
return nil } // String reports the possibly empty string value at the given position or // an error the attribute is invalid or if the position does not exist. func (a *Attr) String(pos int) (string, error) { if err := a.hasPos(pos); err != nil { return "", err } return a.Fields[pos].Text(), nil } // Int reports the integer at the given position or an error if the attribute is // invalid, the position does not exist, or the value at the given position is // not an integer. func (a *Attr) Int(pos int) (int64, error) { if err := a.hasPos(pos); err != nil { return 0, err } // TODO: use CUE's literal parser once it exists, allowing any of CUE's // number types. return strconv.ParseInt(a.Fields[pos].Text(), 10, 64) } // Flag reports whether an entry with the given name exists at position pos or // onwards or an error if the attribute is invalid or if the first pos-1 entries // are not defined. func (a *Attr) Flag(pos int, key string) (bool, error) { if err := a.hasPos(pos - 1); err != nil { return false, err } for _, kv := range a.Fields[pos:] { if kv.Text() == key { return true, nil } } return false, nil } // Lookup searches for an entry of the form key=value from position pos onwards // and reports the value if found. It reports an error if the attribute is // invalid or if the first pos-1 entries are not defined. func (a *Attr) Lookup(pos int, key string) (val string, found bool, err error) { if err := a.hasPos(pos - 1); err != nil { return "", false, err } for _, kv := range a.Fields[pos:] { if kv.Key() == key { return kv.Value(), true, nil } } return "", false, nil } func ParseAttrBody(pos token.Pos, s string) (a Attr) { a.Body = s i := 0 for { i += skipSpace(s[i:]) // always scan at least one, possibly empty element. n, err := scanAttributeElem(pos, s[i:], &a) if err != nil { return Attr{Err: err} } if i += n; i >= len(s) { break } i += skipSpace(s[i:]) if s[i] != ',' { return Attr{Err: errors.Newf(pos, "invalid attribute: expected comma")} } i++ } return a } func skipSpace(s string) int { for n, r := range s { if !unicode.IsSpace(r) { return n } } return 0 } func scanAttributeElem(pos token.Pos, s string, a *Attr) (n int, err errors.Error) { // try CUE string kv := KeyValue{} if n, kv.data, err = scanAttributeString(pos, s); n == 0 { // try key-value pair p := strings.IndexAny(s, ",=") // ) is assumed to be stripped. switch { case p < 0: kv.data = strings.TrimSpace(s) n = len(s) default: // ',' n = p kv.data = strings.TrimSpace(s[:n]) case s[p] == '=': kv.equal = p offset := p + 1 offset += skipSpace(s[offset:]) var str string if p, str, err = scanAttributeString(pos, s[offset:]); p > 0 { n = offset + p kv.data = s[:offset] + str } else { n = len(s) if p = strings.IndexByte(s[offset:], ','); p >= 0 { n = offset + p } kv.data = strings.TrimSpace(s[:n]) } } } if a != nil { a.Fields = append(a.Fields, kv) } return n, err } func scanAttributeString(pos token.Pos, s string) (n int, str string, err errors.Error) { if s == "" || (s[0] != '#' && s[0] != '"' && s[0] != '\'') { return 0, "", nil } nHash := 0 for { if nHash < len(s) { if s[nHash] == '#' { nHash++ continue } if s[nHash] == '\'' || s[nHash] == '"' { break } } return nHash, s[:nHash], errors.Newf(pos, "invalid attribute string") } // Determine closing quote. nQuote := 1 if c := s[nHash]; nHash+6 < len(s) && s[nHash+1] == c && s[nHash+2] == c { nQuote = 3 } close := s[nHash:nHash+nQuote] + s[:nHash] // Search for closing quote. index := strings.Index(s[len(close):], close) if index == -1 { return len(s), "", errors.Newf(pos, "attribute string not terminated") } index += 2 * len(close) s, err2 := literal.Unquote(s[:index]) if err2 != nil { return index, "", errors.Newf(pos, "invalid attribute string: %v", err2) } return index, s, nil }
{ return fmt.Errorf("field does not exist") }
Guard.ts
import Entity from '@src/entities/Entity'; import Sprite from '@src/sprites/Sprite'; import Vector from '@src/utils/math/Vector'; import Player from '@src/Player'; import Enemy from '@src/entities/Enemy'; import {spriteTextures} from '@src/sprites/SpriteTexture'; import Raycaster from '@src/utils/math/Raycaster'; import {calcDist} from '@src/utils/math/distance'; class Guard implements Entity, Enemy { public sprites: Sprite[] = []; public collision = true; public direction = Math.PI/-2; public health = 30; public moving = false; private time = 0; private lastShot = 0; public dead = false; private lastDeath = 0; private lastSeenPlayer = 0; private lastFired = 0; private readyToShoot = false; private shootTimeout:NodeJS.Timeout|null = null; private lastVector:Vector|null = null; constructor(public x:number, public y:number,public path:Vector[] = []){ this.sprites = [new Sprite(x, y, spriteTextures.guardS)]; if(this.path.length > 0){ this.lastVector = path[0]; } } tick():void { // } tickEnemy(delta:number, player:Player, raycaster:Raycaster):boolean { this.readyToShoot = false; if(this.dead){ const sinceDeath = Date.now()/1000 - this.lastDeath; if(sinceDeath < 0.2){ this.sprites[0].texture = spriteTextures.guardD1; }else if(sinceDeath >= 0.2 && sinceDeath < 0.4){ this.sprites[0].texture = spriteTextures.guardD2; }else if(sinceDeath >= 0.4 && sinceDeath < 0.6){ this.sprites[0].texture = spriteTextures.guardD3; }else if(sinceDeath >= 0.6 && sinceDeath < 0.8){ this.sprites[0].texture = spriteTextures.guardD4; }else{ this.sprites[0].texture = spriteTextures.guardD5; } return false; } this.sprites[0].x = this.x; this.sprites[0].y = this.y; let angle = Math.atan2(this.y - player.y, this.x - player.x) + Math.PI; angle = angle + this.direction + 2 * Math.PI; angle = angle % (2*Math.PI); angle = angle - Math.PI; angle = angle / Math.PI; let tex = ''; this.time += delta*2; if(this.moving){ tex = (Math.floor(this.time)%4+1).toString(); } if(angle < -7/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'N']; }else if(angle >= -7/8 && angle < -5/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'NW']; }else if(angle >= -5/8 && angle < -3/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'W']; }else if(angle >= -3/8 && angle < -1/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'SW']; }else if(angle >= -1/8 && angle < 1/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'S']; }else if(angle >= 1/8 && angle < 3/8){
}else if(angle >= 5/8 && angle < 7/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'NE']; }else{ this.sprites[0].texture = spriteTextures['guard'+tex+'N']; } const dist = calcDist(this.x, this.y, player.x, player.y); const raycastPlayer = raycaster.raycast( new Vector(player.x - this.x, player.y - this.y), new Vector(this.x, this.y) ); const seeingPlayer = (angle > -1/2 && angle < 1/2) && raycastPlayer.distance > dist; if(seeingPlayer){ this.moving = false; this.sprites[0].texture = spriteTextures.guardF2; this.lookAtPlayer(angle); } if(Date.now()/1000 - this.lastShot < 0.3){ this.sprites[0].texture = spriteTextures.guardShot; } if(Date.now()/1000 - this.lastFired < 0.3){ this.sprites[0].texture = spriteTextures.guardF3; } if(player.firing){ const aimed = this.checkPlayerAim(player); if(aimed && this.lastShot != player.lastFire){ this.lastShot = player.lastFire; this.lookAtPlayer(angle); if(player.weapon.range > dist && raycastPlayer.distance > dist){ this.health = this.health - player.weapon.damage; if(this.health < 0){ player.score += 100; this.dead = true; this.collision = false; this.lastDeath = Date.now()/1000; return true; } } } } if(this.readyToShoot && Date.now()/1000 - this.lastFired > 0.5){ if(!this.shootTimeout){ this.shootTimeout = setTimeout(() => { this.fire(player); this.shootTimeout = null; }, 500); } }else{ if(this.shootTimeout){ clearTimeout(this.shootTimeout); this.shootTimeout = null; } } if(Date.now()/1000 - this.lastSeenPlayer > 5 && this.path.length > 0){ this.moving = true; } if(this.moving){ this.move(delta); } return false; } lookAtPlayer(angle: number) { this.direction = (this.direction - angle * Math.PI + 2*Math.PI) % (2*Math.PI); this.lastSeenPlayer = Date.now()/1000; this.readyToShoot = angle < 0.001; } checkPlayerAim(player:Player):boolean { const dist = calcDist(this.x, this.y, player.x, player.y); let angle = Math.atan2(player.y - this.y, player.x - this.x); angle = angle - player.dir + 2 * Math.PI; angle = angle % (2*Math.PI); angle = angle - Math.PI; angle = angle / Math.PI; return angle >= -0.2/dist && angle <= 0.2/dist; } fire(player:Player){ if(!this.readyToShoot) return; this.lastFired = Date.now()/1000; player.health -= Math.floor(Math.random()*10+5); } move(delta:number){ if(this.path.length < 1){ return; } const nextVectorIndex = (this.path.findIndex(v => v===this.lastVector) + 1) % this.path.length; const nextVector = this.path[nextVectorIndex]; if(Math.abs(nextVector.x - this.x) < 0.1 && Math.abs(nextVector.y - this.y) < 0.1){ this.lastVector = nextVector; return; } this.x += Math.sign(nextVector.x - this.x) * delta; this.y += Math.sign(nextVector.y - this.y) * delta; this.direction = Math.atan2( Math.sign(nextVector.y - this.y), Math.sign(this.x - nextVector.x) ); } activate() { // } } export default Guard;
this.sprites[0].texture = spriteTextures['guard'+tex+'SE']; }else if(angle >= 3/8 && angle < 5/8){ this.sprites[0].texture = spriteTextures['guard'+tex+'E'];
carbrandbase.ts
// Generated by github.com/davyxu/tabtoy // Version: 2.8.10 module table { export var TCarBrand : table.ITCarBrandDefine[] = [ { Id : 1000, Brand : "奔驰" }, { Id : 2000, Brand : "本田" },
{ Id : 5000, Brand : "奥迪" }, { Id : 6000, Brand : "宝马" }, { Id : 7000, Brand : "雪佛莱" }, { Id : 8000, Brand : "保时捷" }, { Id : 9000, Brand : "奔驰" }, { Id : 10000, Brand : "劳斯劳斯" } ] // Id export var TCarBrandById : game.Dictionary<table.ITCarBrandDefine> = {} function readTCarBrandById(){ for(let rec of TCarBrand) { TCarBrandById[rec.Id] = rec; } } readTCarBrandById(); }
{ Id : 3000, Brand : "大众" }, { Id : 4000, Brand : "丰田" },
IoTDBRpcDataSet.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from IoTDBConstants import * from thrift.transport import TTransport from iotdb.rpc.TSIService import TSFetchResultsReq, TSCloseOperationReq class IoTDBRpcDataSet(object): TIMESTAMP_STR = "Time" # VALUE_IS_NULL = "The value got by %s (column name) is NULL." START_INDEX = 2 FLAG = 0x80 def __init__(self, sql, column_name_list, column_type_list, column_name_index, ignore_timestamp, query_id, client, session_id, query_data_set, fetch_size): self.__session_id = session_id self.__ignore_timestamp = ignore_timestamp self.__sql = sql self.__query_id = query_id self.__client = client self.__fetch_size = fetch_size self.__column_size = len(column_name_list) self.__column_name_list = [] self.__column_type_list = [] self.__column_ordinal_dict = {} if not ignore_timestamp: self.__column_name_list.append(IoTDBRpcDataSet.TIMESTAMP_STR) self.__column_type_list.append(TSDataType.INT64) self.__column_ordinal_dict[IoTDBRpcDataSet.TIMESTAMP_STR] = 1 if column_name_index is not None: self.__column_type_deduplicated_list = [None for _ in range(len(column_name_index))] for i in range(len(column_name_list)): name = column_name_list[i] self.__column_name_list.append(name) self.__column_type_list.append(TSDataType[column_type_list[i]]) if name not in self.__column_ordinal_dict: index = column_name_index[name] self.__column_ordinal_dict[name] = index + IoTDBRpcDataSet.START_INDEX self.__column_type_deduplicated_list[index] = TSDataType[column_type_list[i]] else: index = IoTDBRpcDataSet.START_INDEX self.__column_type_deduplicated_list = [] for i in range(len(column_name_list)): name = column_name_list[i] self.__column_name_list.append(name) self.__column_type_list.append(TSDataType[column_type_list[i]]) if name not in self.__column_ordinal_dict: self.__column_ordinal_dict[name] = index index += 1 self.__column_type_deduplicated_list.append(TSDataType[column_type_list[i]]) self.__time_bytes = bytes(0) self.__current_bitmap = [bytes(0) for _ in range(len(self.__column_type_deduplicated_list))] self.__value = [None for _ in range(len(self.__column_type_deduplicated_list))] self.__query_data_set = query_data_set self.__is_closed = False self.__empty_resultSet = False self.__has_cached_record = False self.__rows_index = 0 def close(self): if self.__is_closed: return if self.__client is not None: try: status = self.__client.closeOperation(TSCloseOperationReq(self.__session_id, self.__query_id)) print("close session {}, message: {}".format(self.__session_id, status.message)) except TTransport.TException as e: print("close session {} failed because: ".format(self.__session_id), e) raise Exception self.__is_closed = True self.__client = None def next(self): if self.has_cached_result(): self.construct_one_row() return True if self.__empty_resultSet: return False if self.fetch_results(): self.construct_one_row() return True return False def has_cached_result(self): return (self.__query_data_set is not None) and (len(self.__query_data_set.time) != 0) def construct_one_row(self): # simulating buffer, read 8 bytes from data set and discard first 8 bytes which have been read. self.__time_bytes = self.__query_data_set.time[:8] self.__query_data_set.time = self.__query_data_set.time[8:] for i in range(len(self.__query_data_set.bitmapList)): bitmap_buffer = self.__query_data_set.bitmapList[i] # another 8 new rows, should move the bitmap buffer position to next byte if self.__rows_index % 8 == 0: self.__current_bitmap[i] = bitmap_buffer[0] self.__query_data_set.bitmapList[i] = bitmap_buffer[1:] if not self.is_null(i, self.__rows_index): value_buffer = self.__query_data_set.valueList[i] data_type = self.__column_type_deduplicated_list[i] # simulating buffer if data_type == TSDataType.BOOLEAN: self.__value[i] = value_buffer[:1] self.__query_data_set.valueList[i] = value_buffer[1:] elif data_type == TSDataType.INT32: self.__value[i] = value_buffer[:4] self.__query_data_set.valueList[i] = value_buffer[4:] elif data_type == TSDataType.INT64: self.__value[i] = value_buffer[:8] self.__query_data_set.valueList[i] = value_buffer[8:] elif data_type == TSDataType.FLOAT: self.__value[i] = value_buffer[:4] self.__query_data_set.valueList[i] = value_buffer[4:] elif data_type == TSDataType.DOUBLE: self.__value[i] = value_buffer[:8] self.__query_data_set.valueList[i] = value_buffer[8:] elif data_type == TSDataType.TEXT: length = int.from_bytes(value_buffer[:4], byteorder="big", signed=False) self.__value[i] = value_buffer[4: 4 + length] self.__query_data_set.valueList[i] = value_buffer[4 + length:] else:
self.__rows_index += 1 self.__has_cached_record = True def fetch_results(self): self.__rows_index = 0 request = TSFetchResultsReq(self.__session_id, self.__sql, self.__fetch_size, self.__query_id, True) try: resp = self.__client.fetchResults(request) if not resp.hasResultSet: self.__empty_resultSet = True else: self.__query_data_set = resp.queryDataSet return resp.hasResultSet except TTransport.TException as e: print("Cannot fetch result from server, because of network connection: ", e) def is_null(self, index, row_num): bitmap = self.__current_bitmap[index] shift = row_num % 8 return ((IoTDBRpcDataSet.FLAG >> shift) & (bitmap & 0xff)) == 0 def is_null_by_index(self, column_index): index = self.__column_ordinal_dict[self.find_column_name_by_index(column_index)] - IoTDBRpcDataSet.START_INDEX # time column will never be None if index < 0: return True return self.is_null(index, self.__rows_index - 1) def is_null_by_name(self, column_name): index = self.__column_ordinal_dict[column_name] - IoTDBRpcDataSet.START_INDEX # time column will never be None if index < 0: return True return self.is_null(index, self.__rows_index - 1) def find_column_name_by_index(self, column_index): if column_index <= 0: raise Exception("Column index should start from 1") if column_index > len(self.__column_name_list): raise Exception("column index {} out of range {}".format(column_index, self.__column_size)) return self.__column_name_list[column_index - 1] def get_fetch_size(self): return self.__fetch_size def set_fetch_size(self, fetch_size): self.__fetch_size = fetch_size def get_column_names(self): return self.__column_name_list def get_column_types(self): return self.__column_type_list def get_column_size(self): return self.__column_size def get_ignore_timestamp(self): return self.__ignore_timestamp def get_column_ordinal_dict(self): return self.__column_ordinal_dict def get_column_type_deduplicated_list(self): return self.__column_type_deduplicated_list def get_values(self): return self.__value def get_time_bytes(self): return self.__time_bytes def get_has_cached_record(self): return self.__has_cached_record
print("unsupported data type {}.".format(data_type)) # could raise exception here
types.rs
#[derive(Clone, Debug, Eq, PartialEq)] pub enum Instruction { Aaload, Aastore, Aconstnull, Aload(u8), AloadWide(u16), Aload0, Aload1, Aload2, Aload3, Anewarray(u16), Areturn, Arraylength, Astore(u8), AstoreWide(u16), Astore0, Astore1, Astore2, Astore3, Athrow, Baload, Bastore, Bipush(i8), Caload, Castore, Checkcast(u16), D2f, D2i, D2l, Dadd, Daload, Dastore, Dcmpg, Dcmpl, Dconst0, Dconst1, Ddiv, Dload(u8), DloadWide(u16), Dload0, Dload1, Dload2, Dload3, Dmul, Dneg, Drem, Dreturn, Dstore(u8), DstoreWide(u16), Dstore0, Dstore1, Dstore2, Dstore3, Dsub, Dup, Dupx1, Dupx2, Dup2, Dup2x1, Dup2x2, F2d, F2i, F2l, Fadd, Faload, Fastore, Fcmpg, Fcmpl, Fconst0, Fconst1, Fconst2, Fdiv, Fload(u8), FloadWide(u16), Fload0, Fload1, Fload2, Fload3, Fmul, Fneg, Frem, Freturn, Fstore(u8), FstoreWide(u16), Fstore0, Fstore1, Fstore2, Fstore3, Fsub, Getfield(u16), Getstatic(u16), Goto(i16), GotoW(i32), I2b, I2c, I2d, I2f, I2l, I2s, Iadd, Iaload, Iand, Iastore, Iconstm1, Iconst0, Iconst1, Iconst2, Iconst3, Iconst4, Iconst5, Idiv, IfAcmpeq(i16), IfAcmpne(i16), IfIcmpeq(i16), IfIcmpne(i16), IfIcmplt(i16), IfIcmpge(i16), IfIcmpgt(i16), IfIcmple(i16), Ifeq(i16), Ifne(i16), Iflt(i16), Ifge(i16), Ifgt(i16), Ifle(i16), Ifnonnull(i16), Ifnull(i16), Iinc { index: u8, value: i8, }, IincWide { index: u16, value: i16, }, Iload(u8), IloadWide(u16), Iload0, Iload1, Iload2, Iload3, Imul, Ineg, Instanceof(u16), Invokedynamic(u16), Invokeinterface { index: u16, count: u8, }, Invokespecial(u16), Invokestatic(u16), Invokevirtual(u16), Ior, Irem, Ireturn, Ishl, Ishr, Istore(u8), IstoreWide(u16), Istore0, Istore1, Istore2, Istore3, Isub, Iushr, Ixor, Jsr(i16), JsrW(i32), L2d, L2f, L2i, Ladd, Laload, Land, Lastore, Lcmp, Lconst0, Lconst1, Ldc(u8), LdcW(u16), Ldc2W(u16), Ldiv, Lload(u8), LloadWide(u16), Lload0, Lload1, Lload2, Lload3, Lmul, Lneg, Lookupswitch { default: i32, pairs: Vec<(i32, i32)>, }, Lor, Lrem, Lreturn, Lshl, Lshr, Lstore(u8), LstoreWide(u16), Lstore0, Lstore1, Lstore2, Lstore3, Lsub, Lushr, Lxor, Monitorenter, Monitorexit,
Multianewarray { index: u16, dimensions: u8, }, New(u16), Newarray(u8), Nop, Pop, Pop2, Putfield(u16), Putstatic(u16), Ret(u8), RetWide(u16), Return, Saload, Sastore, Sipush(i16), Swap, Tableswitch { default: i32, low: i32, high: i32, offsets: Vec<i32>, }, }
TbsHandshakeAcc-encr-mode-non-aead.ta.ts
/* eslint-disable */ import { ASN1Element as _Element, ASN1TagClass as _TagClass, OPTIONAL, } from "asn1-ts"; import * as $ from "asn1-ts/dist/node/functional"; import { AlgorithmIdentifier, _decode_AlgorithmIdentifier, _encode_AlgorithmIdentifier,
_encode_AlgorithmIdentifier, } from "../PKI-Stub/AlgorithmIdentifier.ta"; /* START_OF_SYMBOL_DEFINITION TbsHandshakeAcc_encr_mode_non_aead */ /** * @summary TbsHandshakeAcc_encr_mode_non_aead * @description * * ### ASN.1 Definition: * * ```asn1 * TbsHandshakeAcc-encr-mode-non-aead ::= SEQUENCE { -- REMOVED_FROM_UNNESTING -- } * ``` * * @class */ export class TbsHandshakeAcc_encr_mode_non_aead { constructor( /** * @summary `encr`. * @public * @readonly */ readonly encr: OPTIONAL<AlgorithmIdentifier>, /** * @summary `icvAlgID`. * @public * @readonly */ readonly icvAlgID: AlgorithmIdentifier ) {} /** * @summary Restructures an object into a TbsHandshakeAcc_encr_mode_non_aead * @description * * This takes an `object` and converts it to a `TbsHandshakeAcc_encr_mode_non_aead`. * * @public * @static * @method * @param {Object} _o An object having all of the keys and values of a `TbsHandshakeAcc_encr_mode_non_aead`. * @returns {TbsHandshakeAcc_encr_mode_non_aead} */ public static _from_object( _o: Partial< { [_K in keyof TbsHandshakeAcc_encr_mode_non_aead]: TbsHandshakeAcc_encr_mode_non_aead[_K]; } > ): TbsHandshakeAcc_encr_mode_non_aead { return new TbsHandshakeAcc_encr_mode_non_aead(_o.encr, _o.icvAlgID); } } /* END_OF_SYMBOL_DEFINITION TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _root_component_type_list_1_spec_for_TbsHandshakeAcc_encr_mode_non_aead */ /** * @summary The Leading Root Component Types of TbsHandshakeAcc_encr_mode_non_aead * @description * * This is an array of `ComponentSpec`s that define how to decode the leading root component type list of a SET or SEQUENCE. * * @constant */ export const _root_component_type_list_1_spec_for_TbsHandshakeAcc_encr_mode_non_aead: $.ComponentSpec[] = [ new $.ComponentSpec( "encr", true, $.hasTag(_TagClass.context, 0), undefined, undefined ), new $.ComponentSpec( "icvAlgID", false, $.hasTag(_TagClass.context, 1), undefined, undefined ), ]; /* END_OF_SYMBOL_DEFINITION _root_component_type_list_1_spec_for_TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _root_component_type_list_2_spec_for_TbsHandshakeAcc_encr_mode_non_aead */ /** * @summary The Trailing Root Component Types of TbsHandshakeAcc_encr_mode_non_aead * @description * * This is an array of `ComponentSpec`s that define how to decode the trailing root component type list of a SET or SEQUENCE. * * @constant */ export const _root_component_type_list_2_spec_for_TbsHandshakeAcc_encr_mode_non_aead: $.ComponentSpec[] = []; /* END_OF_SYMBOL_DEFINITION _root_component_type_list_2_spec_for_TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _extension_additions_list_spec_for_TbsHandshakeAcc_encr_mode_non_aead */ /** * @summary The Extension Addition Component Types of TbsHandshakeAcc_encr_mode_non_aead * @description * * This is an array of `ComponentSpec`s that define how to decode the extension addition component type list of a SET or SEQUENCE. * * @constant */ export const _extension_additions_list_spec_for_TbsHandshakeAcc_encr_mode_non_aead: $.ComponentSpec[] = []; /* END_OF_SYMBOL_DEFINITION _extension_additions_list_spec_for_TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _cached_decoder_for_TbsHandshakeAcc_encr_mode_non_aead */ let _cached_decoder_for_TbsHandshakeAcc_encr_mode_non_aead: $.ASN1Decoder<TbsHandshakeAcc_encr_mode_non_aead> | null = null; /* END_OF_SYMBOL_DEFINITION _cached_decoder_for_TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _decode_TbsHandshakeAcc_encr_mode_non_aead */ /** * @summary Decodes an ASN.1 element into a(n) TbsHandshakeAcc_encr_mode_non_aead * @function * @param {_Element} el The element being decoded. * @returns {TbsHandshakeAcc_encr_mode_non_aead} The decoded data structure. */ export function _decode_TbsHandshakeAcc_encr_mode_non_aead(el: _Element) { if (!_cached_decoder_for_TbsHandshakeAcc_encr_mode_non_aead) { _cached_decoder_for_TbsHandshakeAcc_encr_mode_non_aead = function ( el: _Element ): TbsHandshakeAcc_encr_mode_non_aead { /* START_OF_SEQUENCE_COMPONENT_DECLARATIONS */ let encr: OPTIONAL<AlgorithmIdentifier>; let icvAlgID!: AlgorithmIdentifier; /* END_OF_SEQUENCE_COMPONENT_DECLARATIONS */ /* START_OF_CALLBACKS_MAP */ const callbacks: $.DecodingMap = { encr: (_el: _Element): void => { encr = $._decode_implicit<AlgorithmIdentifier>( () => _decode_AlgorithmIdentifier )(_el); }, icvAlgID: (_el: _Element): void => { icvAlgID = $._decode_implicit<AlgorithmIdentifier>( () => _decode_AlgorithmIdentifier )(_el); }, }; /* END_OF_CALLBACKS_MAP */ $._parse_sequence( el, callbacks, _root_component_type_list_1_spec_for_TbsHandshakeAcc_encr_mode_non_aead, _extension_additions_list_spec_for_TbsHandshakeAcc_encr_mode_non_aead, _root_component_type_list_2_spec_for_TbsHandshakeAcc_encr_mode_non_aead, undefined ); return new TbsHandshakeAcc_encr_mode_non_aead( /* SEQUENCE_CONSTRUCTOR_CALL */ encr, icvAlgID ); }; } return _cached_decoder_for_TbsHandshakeAcc_encr_mode_non_aead(el); } /* END_OF_SYMBOL_DEFINITION _decode_TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _cached_encoder_for_TbsHandshakeAcc_encr_mode_non_aead */ let _cached_encoder_for_TbsHandshakeAcc_encr_mode_non_aead: $.ASN1Encoder<TbsHandshakeAcc_encr_mode_non_aead> | null = null; /* END_OF_SYMBOL_DEFINITION _cached_encoder_for_TbsHandshakeAcc_encr_mode_non_aead */ /* START_OF_SYMBOL_DEFINITION _encode_TbsHandshakeAcc_encr_mode_non_aead */ /** * @summary Encodes a(n) TbsHandshakeAcc_encr_mode_non_aead into an ASN.1 Element. * @function * @param {value} el The element being decoded. * @param elGetter A function that can be used to get new ASN.1 elements. * @returns {_Element} The TbsHandshakeAcc_encr_mode_non_aead, encoded as an ASN.1 Element. */ export function _encode_TbsHandshakeAcc_encr_mode_non_aead( value: TbsHandshakeAcc_encr_mode_non_aead, elGetter: $.ASN1Encoder<TbsHandshakeAcc_encr_mode_non_aead> ) { if (!_cached_encoder_for_TbsHandshakeAcc_encr_mode_non_aead) { _cached_encoder_for_TbsHandshakeAcc_encr_mode_non_aead = function ( value: TbsHandshakeAcc_encr_mode_non_aead, elGetter: $.ASN1Encoder<TbsHandshakeAcc_encr_mode_non_aead> ): _Element { return $._encodeSequence( ([] as (_Element | undefined)[]) .concat([ /* IF_ABSENT */ value.encr === undefined ? undefined : $._encode_implicit( _TagClass.context, 0, () => _encode_AlgorithmIdentifier, $.BER )(value.encr, $.BER), /* REQUIRED */ $._encode_implicit( _TagClass.context, 1, () => _encode_AlgorithmIdentifier, $.BER )(value.icvAlgID, $.BER), ]) .filter((c: _Element | undefined): c is _Element => !!c), $.BER ); }; } return _cached_encoder_for_TbsHandshakeAcc_encr_mode_non_aead( value, elGetter ); } /* END_OF_SYMBOL_DEFINITION _encode_TbsHandshakeAcc_encr_mode_non_aead */ /* eslint-enable */
} from "../PKI-Stub/AlgorithmIdentifier.ta"; export { AlgorithmIdentifier, _decode_AlgorithmIdentifier,
ring.go
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. 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. package v1 import ( "fmt" "strings" ) // Ring describes secret ring contract. type Ring interface { Level() int Name() string Prefix() string Path(...string) (string, error) } var ( // RingMeta represents R0 secrets RingMeta Ring = &ring{ level: 0, name: "Meta", prefix: ringMeta, pathBuilderFunc: func(ring Ring, values ...string) (string, error) { return csoPath("meta/%s/%s", 2, values...) }, } // RingInfra represents R1 secrets RingInfra = &ring{ level: 1, name: "Infrastructure", prefix: ringInfra, pathBuilderFunc: func(ring Ring, values ...string) (string, error) { return csoPath("infra/%s/%s/%s/%s/%s", 5, values...) }, } // RingPlatform repsents R2 secrets RingPlatform = &ring{ level: 2, name: "Platform", prefix: ringPlatform, pathBuilderFunc: func(ring Ring, values ...string) (string, error) { return csoPath("platform/%s/%s/%s/%s/%s", 5, values...) }, } // RingProduct represents R3 secrets RingProduct = &ring{ level: 3, name: "Product", prefix: ringProduct, pathBuilderFunc: func(ring Ring, values ...string) (string, error) { return csoPath("product/%s/%s/%s/%s", 4, values...) }, } // RingApplication represents R4 secrets RingApplication = &ring{ level: 4, name: "Application", prefix: ringApp, pathBuilderFunc: func(ring Ring, values ...string) (string, error) { return csoPath("app/%s/%s/%s/%s/%s/%s", 6, values...) }, } // RingArtifact represents R5 secrets RingArtifact = &ring{ level: 5, name: "Artifact", prefix: ringArtifact, pathBuilderFunc: func(ring Ring, values ...string) (string, error) { return csoPath("artifact/%s/%s/%s", 3, values...) }, } ) // ----------------------------------------------------------------------------- type ring struct { level int name string prefix string pathBuilderFunc func(Ring, ...string) (string, error) } func (r ring) Level() int { return r.level } func (r ring) Name() string { return r.name } func (r ring) Prefix() string { return r.prefix } func (r ring) Path(values ...string) (string, error) { return r.pathBuilderFunc(r, values...) } // ----------------------------------------------------------------------------- // csoPath build and validate a secret path according to CSO specification func csoPath(format string, count int, values ...string) (string, error)
{ // Check values count if len(values) < count { return "", fmt.Errorf("expected (%d) and received (%d) value count doesn't match", count, len(values)) } // Prepare suffix suffix := strings.Join(values[count-1:], "/") // Prepare values var items []interface{} for i := 0; i < count-1; i++ { items = append(items, values[i]) } items = append(items, suffix) // Prepare validation csoPath := fmt.Sprintf(format, items...) // Validate secret path if err := Validate(csoPath); err != nil { return "", fmt.Errorf("'%s' is not a compliant CSO path: %w", csoPath, err) } // No Error return csoPath, nil }
configurator.py
"""Apache Configuration based off of Augeas Configurator.""" # pylint: disable=too-many-lines import filecmp import logging import os import re import shutil import socket import time import zope.interface from acme import challenges from letsencrypt import errors from letsencrypt import interfaces from letsencrypt import le_util from letsencrypt.plugins import common from letsencrypt_apache import augeas_configurator from letsencrypt_apache import constants from letsencrypt_apache import display_ops from letsencrypt_apache import tls_sni_01 from letsencrypt_apache import obj from letsencrypt_apache import parser from collections import defaultdict logger = logging.getLogger(__name__) # TODO: Augeas sections ie. <VirtualHost>, <IfModule> beginning and closing # tags need to be the same case, otherwise Augeas doesn't recognize them. # This is not able to be completely remedied by regular expressions because # Augeas views <VirtualHost> </Virtualhost> as an error. This will just # require another check_parsing_errors() after all files are included... # (after a find_directive search is executed currently). It can be a one # time check however because all of LE's transactions will ensure # only properly formed sections are added. # Note: This protocol works for filenames with spaces in it, the sites are # properly set up and directives are changed appropriately, but Apache won't # recognize names in sites-enabled that have spaces. These are not added to the # Apache configuration. It may be wise to warn the user if they are trying # to use vhost filenames that contain spaces and offer to change ' ' to '_' # Note: FILEPATHS and changes to files are transactional. They are copied # over before the updates are made to the existing files. NEW_FILES is # transactional due to the use of register_file_creation() # TODO: Verify permissions on configuration root... it is easier than # checking permissions on each of the relative directories and less error # prone. # TODO: Write a server protocol finder. Listen <port> <protocol> or # Protocol <protocol>. This can verify partial setups are correct # TODO: Add directives to sites-enabled... not sites-available. # sites-available doesn't allow immediate find_dir search even with save() # and load() class ApacheConfigurator(augeas_configurator.AugeasConfigurator): # pylint: disable=too-many-instance-attributes,too-many-public-methods """Apache configurator. State of Configurator: This code has been been tested and built for Ubuntu 14.04 Apache 2.4 and it works for Ubuntu 12.04 Apache 2.2 :ivar config: Configuration. :type config: :class:`~letsencrypt.interfaces.IConfig` :ivar parser: Handles low level parsing :type parser: :class:`~letsencrypt_apache.parser` :ivar tup version: version of Apache :ivar list vhosts: All vhosts found in the configuration (:class:`list` of :class:`~letsencrypt_apache.obj.VirtualHost`) :ivar dict assoc: Mapping between domains and vhosts """ zope.interface.implements(interfaces.IAuthenticator, interfaces.IInstaller) zope.interface.classProvides(interfaces.IPluginFactory) description = "Apache Web Server - Alpha" @classmethod def add_parser_arguments(cls, add): add("ctl", default=constants.CLI_DEFAULTS["ctl"], help="Path to the 'apache2ctl' binary, used for 'configtest', " "retrieving the Apache2 version number, and initialization " "parameters.") add("enmod", default=constants.CLI_DEFAULTS["enmod"], help="Path to the Apache 'a2enmod' binary.") add("dismod", default=constants.CLI_DEFAULTS["dismod"], help="Path to the Apache 'a2dismod' binary.") add("le-vhost-ext", default=constants.CLI_DEFAULTS["le_vhost_ext"], help="SSL vhost configuration extension.") add("server-root", default=constants.CLI_DEFAULTS["server_root"], help="Apache server root directory.") le_util.add_deprecated_argument(add, "init-script", 1) def __init__(self, *args, **kwargs): """Initialize an Apache Configurator. :param tup version: version of Apache as a tuple (2, 4, 7) (used mostly for unittesting) """ version = kwargs.pop("version", None) super(ApacheConfigurator, self).__init__(*args, **kwargs) # Add name_server association dict self.assoc = dict() # Outstanding challenges self._chall_out = set() # These will be set in the prepare function self.parser = None self.version = version self.vhosts = None self._enhance_func = {"redirect": self._enable_redirect, "ensure-http-header": self._set_http_header} @property def mod_ssl_conf(self): """Full absolute path to SSL configuration file.""" return os.path.join(self.config.config_dir, constants.MOD_SSL_CONF_DEST) def prepare(self): """Prepare the authenticator/installer. :raises .errors.NoInstallationError: If Apache configs cannot be found :raises .errors.MisconfigurationError: If Apache is misconfigured :raises .errors.NotSupportedError: If Apache version is not supported :raises .errors.PluginError: If there is any other error """ # Verify Apache is installed for exe in (self.conf("ctl"), self.conf("enmod"), self.conf("dismod")): if not le_util.exe_exists(exe): raise errors.NoInstallationError # Make sure configuration is valid self.config_test() self.parser = parser.ApacheParser( self.aug, self.conf("server-root"), self.conf("ctl")) # Check for errors in parsing files with Augeas self.check_parsing_errors("httpd.aug") # Set Version if self.version is None: self.version = self.get_version() if self.version < (2, 2): raise errors.NotSupportedError( "Apache Version %s not supported.", str(self.version)) # Get all of the available vhosts self.vhosts = self.get_virtual_hosts() install_ssl_options_conf(self.mod_ssl_conf) def deploy_cert(self, domain, cert_path, key_path, chain_path=None, fullchain_path=None): # pylint: disable=unused-argument """Deploys certificate to specified virtual host. Currently tries to find the last directives to deploy the cert in the VHost associated with the given domain. If it can't find the directives, it searches the "included" confs. The function verifies that it has located the three directives and finally modifies them to point to the correct destination. After the certificate is installed, the VirtualHost is enabled if it isn't already. .. todo:: Might be nice to remove chain directive if none exists This shouldn't happen within letsencrypt though :raises errors.PluginError: When unable to deploy certificate due to a lack of directives """ vhost = self.choose_vhost(domain) self._clean_vhost(vhost) # This is done first so that ssl module is enabled and cert_path, # cert_key... can all be parsed appropriately self.prepare_server_https("443") path = {"cert_path": self.parser.find_dir("SSLCertificateFile", None, vhost.path), "cert_key": self.parser.find_dir("SSLCertificateKeyFile", None, vhost.path)} # Only include if a certificate chain is specified if chain_path is not None: path["chain_path"] = self.parser.find_dir( "SSLCertificateChainFile", None, vhost.path) if not path["cert_path"] or not path["cert_key"]: # Throw some can't find all of the directives error" logger.warn( "Cannot find a cert or key directive in %s. " "VirtualHost was not modified", vhost.path) # Presumably break here so that the virtualhost is not modified raise errors.PluginError( "Unable to find cert and/or key directives") logger.info("Deploying Certificate to VirtualHost %s", vhost.filep) logger.debug("Apache version is %s", ".".join(str(i) for i in self.version)) if self.version < (2, 4, 8) or (chain_path and not fullchain_path): # install SSLCertificateFile, SSLCertificateKeyFile, # and SSLCertificateChainFile directives set_cert_path = cert_path self.aug.set(path["cert_path"][-1], cert_path) self.aug.set(path["cert_key"][-1], key_path) if chain_path is not None: self.parser.add_dir(vhost.path, "SSLCertificateChainFile", chain_path) else: raise errors.PluginError("--chain-path is required for your version of Apache") else: if not fullchain_path: raise errors.PluginError("Please provide the --fullchain-path\ option pointing to your full chain file") set_cert_path = fullchain_path self.aug.set(path["cert_path"][-1], fullchain_path) self.aug.set(path["cert_key"][-1], key_path) # Save notes about the transaction that took place self.save_notes += ("Changed vhost at %s with addresses of %s\n" "\tSSLCertificateFile %s\n" "\tSSLCertificateKeyFile %s\n" % (vhost.filep, ", ".join(str(addr) for addr in vhost.addrs), set_cert_path, key_path)) if chain_path is not None: self.save_notes += "\tSSLCertificateChainFile %s\n" % chain_path # Make sure vhost is enabled if not vhost.enabled: self.enable_site(vhost) def choose_vhost(self, target_name, temp=False): """Chooses a virtual host based on the given domain name. If there is no clear virtual host to be selected, the user is prompted with all available choices. The returned vhost is guaranteed to have TLS enabled unless temp is True. If temp is True, there is no such guarantee and the result is not cached. :param str target_name: domain name :param bool temp: whether the vhost is only used temporarily :returns: ssl vhost associated with name :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.PluginError: If no vhost is available or chosen """ # Allows for domain names to be associated with a virtual host if target_name in self.assoc: return self.assoc[target_name] # Try to find a reasonable vhost vhost = self._find_best_vhost(target_name) if vhost is not None: if temp: return vhost if not vhost.ssl: vhost = self.make_vhost_ssl(vhost) self.assoc[target_name] = vhost return vhost return self._choose_vhost_from_list(target_name, temp) def _choose_vhost_from_list(self, target_name, temp=False): # Select a vhost from a list vhost = display_ops.select_vhost(target_name, self.vhosts) if vhost is None: logger.error( "No vhost exists with servername or alias of: %s. " "No vhost was selected. Please specify servernames " "in the Apache config", target_name) raise errors.PluginError("No vhost selected") elif temp: return vhost elif not vhost.ssl: addrs = self._get_proposed_addrs(vhost, "443") # TODO: Conflicts is too conservative if not any(vhost.enabled and vhost.conflicts(addrs) for vhost in self.vhosts): vhost = self.make_vhost_ssl(vhost) else: logger.error( "The selected vhost would conflict with other HTTPS " "VirtualHosts within Apache. Please select another " "vhost or add ServerNames to your configuration.") raise errors.PluginError( "VirtualHost not able to be selected.") self.assoc[target_name] = vhost return vhost def _find_best_vhost(self, target_name): """Finds the best vhost for a target_name. This does not upgrade a vhost to HTTPS... it only finds the most appropriate vhost for the given target_name. :returns: VHost or None """ # Points 4 - Servername SSL # Points 3 - Address name with SSL # Points 2 - Servername no SSL # Points 1 - Address name with no SSL best_candidate = None best_points = 0 for vhost in self.vhosts: if vhost.modmacro is True: continue if target_name in vhost.get_names(): points = 2 elif any(addr.get_addr() == target_name for addr in vhost.addrs): points = 1 else: # No points given if names can't be found. # This gets hit but doesn't register continue # pragma: no cover if vhost.ssl: points += 2 if points > best_points: best_points = points best_candidate = vhost # No winners here... is there only one reasonable vhost? if best_candidate is None: # reasonable == Not all _default_ addrs vhosts = self._non_default_vhosts() # remove mod_macro hosts from reasonable vhosts reasonable_vhosts = [vh for vh in vhosts if vh.modmacro is False] if len(reasonable_vhosts) == 1: best_candidate = reasonable_vhosts[0] return best_candidate def _non_default_vhosts(self): """Return all non _default_ only vhosts.""" return [vh for vh in self.vhosts if not all( addr.get_addr() == "_default_" for addr in vh.addrs )] def get_all_names(self): """Returns all names found in the Apache Configuration. :returns: All ServerNames, ServerAliases, and reverse DNS entries for virtual host addresses :rtype: set """ all_names = set() vhost_macro = [] for vhost in self.vhosts: all_names.update(vhost.get_names()) if vhost.modmacro: vhost_macro.append(vhost.filep) for addr in vhost.addrs: if common.hostname_regex.match(addr.get_addr()): all_names.add(addr.get_addr()) else: name = self.get_name_from_ip(addr) if name: all_names.add(name) if len(vhost_macro) > 0: zope.component.getUtility(interfaces.IDisplay).notification( "Apache mod_macro seems to be in use in file(s):\n{0}" "\n\nUnfortunately mod_macro is not yet supported".format( "\n ".join(vhost_macro))) return all_names def get_name_from_ip(self, addr): # pylint: disable=no-self-use """Returns a reverse dns name if available. :param addr: IP Address :type addr: ~.common.Addr :returns: name or empty string if name cannot be determined :rtype: str """ # If it isn't a private IP, do a reverse DNS lookup if not common.private_ips_regex.match(addr.get_addr()): try: socket.inet_aton(addr.get_addr()) return socket.gethostbyaddr(addr.get_addr())[0] except (socket.error, socket.herror, socket.timeout): pass return "" def _add_servernames(self, host): """Helper function for get_virtual_hosts(). :param host: In progress vhost whose names will be added :type host: :class:`~letsencrypt_apache.obj.VirtualHost` """ # Take the final ServerName as each overrides the previous servername_match = self.parser.find_dir( "ServerName", None, start=host.path, exclude=False) serveralias_match = self.parser.find_dir( "ServerAlias", None, start=host.path, exclude=False) for alias in serveralias_match: serveralias = self.parser.get_arg(alias) if not host.modmacro: host.aliases.add(serveralias) if servername_match: # Get last ServerName as each overwrites the previous servername = self.parser.get_arg(servername_match[-1]) if not host.modmacro: host.name = servername def _create_vhost(self, path): """Used by get_virtual_hosts to create vhost objects :param str path: Augeas path to virtual host :returns: newly created vhost :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` """ addrs = set() args = self.aug.match(path + "/arg") for arg in args: addrs.add(obj.Addr.fromstring(self.parser.get_arg(arg))) is_ssl = False if self.parser.find_dir("SSLEngine", "on", start=path, exclude=False): is_ssl = True # "SSLEngine on" might be set outside of <VirtualHost> # Treat vhosts with port 443 as ssl vhosts for addr in addrs: if addr.get_port() == "443": is_ssl = True filename = get_file_path(path) is_enabled = self.is_site_enabled(filename) macro = False if "/macro/" in path.lower(): macro = True vhost = obj.VirtualHost(filename, path, addrs, is_ssl, is_enabled, modmacro=macro) self._add_servernames(vhost) return vhost # TODO: make "sites-available" a configurable directory def get_virtual_hosts(self): """Returns list of virtual hosts found in the Apache configuration. :returns: List of :class:`~letsencrypt_apache.obj.VirtualHost` objects found in configuration :rtype: list """ # Search sites-available, httpd.conf for possible virtual hosts paths = self.aug.match( ("/files%s/sites-available//*[label()=~regexp('%s')]" % (self.parser.root, parser.case_i("VirtualHost")))) vhs = [] for path in paths: vhs.append(self._create_vhost(path)) return vhs def is_name_vhost(self, target_addr): """Returns if vhost is a name based vhost NameVirtualHost was deprecated in Apache 2.4 as all VirtualHosts are now NameVirtualHosts. If version is earlier than 2.4, check if addr has a NameVirtualHost directive in the Apache config :param letsencrypt_apache.obj.Addr target_addr: vhost address :returns: Success :rtype: bool """ # Mixed and matched wildcard NameVirtualHost with VirtualHost # behavior is undefined. Make sure that an exact match exists # search for NameVirtualHost directive for ip_addr # note ip_addr can be FQDN although Apache does not recommend it return (self.version >= (2, 4) or self.parser.find_dir("NameVirtualHost", str(target_addr))) def add_name_vhost(self, addr): """Adds NameVirtualHost directive for given address. :param addr: Address that will be added as NameVirtualHost directive :type addr: :class:`~letsencrypt_apache.obj.Addr` """ loc = parser.get_aug_path(self.parser.loc["name"]) if addr.get_port() == "443": path = self.parser.add_dir_to_ifmodssl( loc, "NameVirtualHost", [str(addr)]) else: path = self.parser.add_dir(loc, "NameVirtualHost", [str(addr)]) msg = ("Setting %s to be NameBasedVirtualHost\n" "\tDirective added to %s\n" % (addr, path)) logger.debug(msg) self.save_notes += msg def prepare_server_https(self, port, temp=False): """Prepare the server for HTTPS. Make sure that the ssl_module is loaded and that the server is appropriately listening on port. :param str port: Port to listen on """ if "ssl_module" not in self.parser.modules: self.enable_mod("ssl", temp=temp) # Check for Listen <port> # Note: This could be made to also look for ip:443 combo listens = [self.parser.get_arg(x).split()[0] for x in self.parser.find_dir("Listen")] # In case no Listens are set (which really is a broken apache config) if not listens: listens = ["80"] for listen in listens: # For any listen statement, check if the machine also listens on Port 443. # If not, add such a listen statement. if len(listen.split(":")) == 1: # Its listening to all interfaces if port not in listens: if port == "443": args = [port] else: # Non-standard ports should specify https protocol args = [port, "https"] self.parser.add_dir_to_ifmodssl( parser.get_aug_path( self.parser.loc["listen"]), "Listen", args) self.save_notes += "Added Listen %s directive to %s\n" % ( port, self.parser.loc["listen"]) listens.append(port) else: # The Listen statement specifies an ip _, ip = listen[::-1].split(":", 1) ip = ip[::-1] if "%s:%s" % (ip, port) not in listens: if port == "443": args = ["%s:%s" % (ip, port)] else: # Non-standard ports should specify https protocol args = ["%s:%s" % (ip, port), "https"] self.parser.add_dir_to_ifmodssl( parser.get_aug_path( self.parser.loc["listen"]), "Listen", args) self.save_notes += "Added Listen %s:%s directive to %s\n" % ( ip, port, self.parser.loc["listen"]) listens.append("%s:%s" % (ip, port)) def make_addrs_sni_ready(self, addrs): """Checks to see if the server is ready for SNI challenges. :param addrs: Addresses to check SNI compatibility :type addrs: :class:`~letsencrypt_apache.obj.Addr` """ # Version 2.4 and later are automatically SNI ready. if self.version >= (2, 4): return for addr in addrs: if not self.is_name_vhost(addr): logger.debug("Setting VirtualHost at %s to be a name " "based virtual host", addr) self.add_name_vhost(addr) def make_vhost_ssl(self, nonssl_vhost): # pylint: disable=too-many-locals """Makes an ssl_vhost version of a nonssl_vhost. Duplicates vhost and adds default ssl options New vhost will reside as (nonssl_vhost.path) + ``letsencrypt_apache.constants.CLI_DEFAULTS["le_vhost_ext"]`` .. note:: This function saves the configuration :param nonssl_vhost: Valid VH that doesn't have SSLEngine on :type nonssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: SSL vhost :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.PluginError: If more than one virtual host is in the file or if plugin is unable to write/read vhost files. """ avail_fp = nonssl_vhost.filep ssl_fp = self._get_ssl_vhost_path(avail_fp) self._copy_create_ssl_vhost_skeleton(avail_fp, ssl_fp) # Reload augeas to take into account the new vhost self.aug.load() # Get Vhost augeas path for new vhost vh_p = self.aug.match("/files%s//* [label()=~regexp('%s')]" % (ssl_fp, parser.case_i("VirtualHost"))) if len(vh_p) != 1: logger.error("Error: should only be one vhost in %s", avail_fp) raise errors.PluginError("Currently, we only support " "configurations with one vhost per file") else: # This simplifies the process vh_p = vh_p[0] # Update Addresses self._update_ssl_vhosts_addrs(vh_p) # Add directives self._add_dummy_ssl_directives(vh_p) # Log actions and create save notes logger.info("Created an SSL vhost at %s", ssl_fp) self.save_notes += "Created ssl vhost at %s\n" % ssl_fp self.save() # We know the length is one because of the assertion above # Create the Vhost object ssl_vhost = self._create_vhost(vh_p) self.vhosts.append(ssl_vhost) # NOTE: Searches through Augeas seem to ruin changes to directives # The configuration must also be saved before being searched # for the new directives; For these reasons... this is tacked # on after fully creating the new vhost # Now check if addresses need to be added as NameBasedVhost addrs # This is for compliance with versions of Apache < 2.4 self._add_name_vhost_if_necessary(ssl_vhost) return ssl_vhost def _get_ssl_vhost_path(self, non_ssl_vh_fp): # Get filepath of new ssl_vhost if non_ssl_vh_fp.endswith(".conf"): return non_ssl_vh_fp[:-(len(".conf"))] + self.conf("le_vhost_ext") else: return non_ssl_vh_fp + self.conf("le_vhost_ext") def _copy_create_ssl_vhost_skeleton(self, avail_fp, ssl_fp): """Copies over existing Vhost with IfModule mod_ssl.c> skeleton. :param str avail_fp: Pointer to the original available non-ssl vhost :param str ssl_fp: Full path where the new ssl_vhost will reside. A new file is created on the filesystem. """ # First register the creation so that it is properly removed if # configuration is rolled back self.reverter.register_file_creation(False, ssl_fp) try: with open(avail_fp, "r") as orig_file: with open(ssl_fp, "w") as new_file: new_file.write("<IfModule mod_ssl.c>\n") for line in orig_file: new_file.write(line) new_file.write("</IfModule>\n") except IOError: logger.fatal("Error writing/reading to file in make_vhost_ssl") raise errors.PluginError("Unable to write/read in make_vhost_ssl") def _update_ssl_vhosts_addrs(self, vh_path): ssl_addrs = set() ssl_addr_p = self.aug.match(vh_path + "/arg") for addr in ssl_addr_p: old_addr = obj.Addr.fromstring( str(self.parser.get_arg(addr))) ssl_addr = old_addr.get_addr_obj("443") self.aug.set(addr, str(ssl_addr)) ssl_addrs.add(ssl_addr) return ssl_addrs def _clean_vhost(self, vhost): # remove duplicated or conflicting ssl directives self._deduplicate_directives(vhost.path, ["SSLCertificateFile", "SSLCertificateKeyFile"]) # remove all problematic directives self._remove_directives(vhost.path, ["SSLCertificateChainFile"]) def _deduplicate_directives(self, vh_path, directives): for directive in directives: while len(self.parser.find_dir(directive, None, vh_path, False)) > 1: directive_path = self.parser.find_dir(directive, None, vh_path, False) self.aug.remove(re.sub(r"/\w*$", "", directive_path[0])) def _remove_directives(self, vh_path, directives): for directive in directives: while len(self.parser.find_dir(directive, None, vh_path, False)) > 0: directive_path = self.parser.find_dir(directive, None, vh_path, False) self.aug.remove(re.sub(r"/\w*$", "", directive_path[0])) def _add_dummy_ssl_directives(self, vh_path): self.parser.add_dir(vh_path, "SSLCertificateFile", "insert_cert_file_path") self.parser.add_dir(vh_path, "SSLCertificateKeyFile", "insert_key_file_path") self.parser.add_dir(vh_path, "Include", self.mod_ssl_conf) def _add_name_vhost_if_necessary(self, vhost): """Add NameVirtualHost Directives if necessary for new vhost. NameVirtualHosts was a directive in Apache < 2.4 https://httpd.apache.org/docs/2.2/mod/core.html#namevirtualhost :param vhost: New virtual host that was recently created. :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` """ need_to_save = False # See if the exact address appears in any other vhost # Remember 1.1.1.1:* == 1.1.1.1 -> hence any() for addr in vhost.addrs: for test_vh in self.vhosts: if (vhost.filep != test_vh.filep and any(test_addr == addr for test_addr in test_vh.addrs) and not self.is_name_vhost(addr)): self.add_name_vhost(addr) logger.info("Enabling NameVirtualHosts on %s", addr) need_to_save = True if need_to_save: self.save() ############################################################################ # Enhancements ############################################################################ def supported_enhancements(self): # pylint: disable=no-self-use """Returns currently supported enhancements.""" return ["redirect", "ensure-http-header"] def enhance(self, domain, enhancement, options=None): """Enhance configuration. :param str domain: domain to enhance :param str enhancement: enhancement type defined in :const:`~letsencrypt.constants.ENHANCEMENTS` :param options: options for the enhancement See :const:`~letsencrypt.constants.ENHANCEMENTS` documentation for appropriate parameter. :raises .errors.PluginError: If Enhancement is not supported, or if there is any other problem with the enhancement. """ try: func = self._enhance_func[enhancement] except KeyError: raise errors.PluginError( "Unsupported enhancement: {0}".format(enhancement)) try: func(self.choose_vhost(domain), options) except errors.PluginError: logger.warn("Failed %s for %s", enhancement, domain) raise def _set_http_header(self, ssl_vhost, header_substring): """Enables header that is identified by header_substring on ssl_vhost. If the header identified by header_substring is not already set, a new Header directive is placed in ssl_vhost's configuration with arguments from: constants.HTTP_HEADER[header_substring] .. note:: This function saves the configuration :param ssl_vhost: Destination of traffic, an ssl enabled vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param header_substring: string that uniquely identifies a header. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests. :type str :returns: Success, general_vhost (HTTP vhost) :rtype: (bool, :class:`~letsencrypt_apache.obj.VirtualHost`) :raises .errors.PluginError: If no viable HTTP host can be created or set with header header_substring. """ if "headers_module" not in self.parser.modules: self.enable_mod("headers") # Check if selected header is already set self._verify_no_matching_http_header(ssl_vhost, header_substring) # Add directives to server self.parser.add_dir(ssl_vhost.path, "Header", constants.HEADER_ARGS[header_substring]) self.save_notes += ("Adding %s header to ssl vhost in %s\n" % (header_substring, ssl_vhost.filep)) self.save() logger.info("Adding %s header to ssl vhost in %s", header_substring, ssl_vhost.filep) def _verify_no_matching_http_header(self, ssl_vhost, header_substring): """Checks to see if an there is an existing Header directive that contains the string header_substring. :param ssl_vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param header_substring: string that uniquely identifies a header. e.g: Strict-Transport-Security, Upgrade-Insecure-Requests. :type str :returns: boolean :rtype: (bool) :raises errors.PluginEnhancementAlreadyPresent When header header_substring exists """ header_path = self.parser.find_dir("Header", None, start=ssl_vhost.path) if header_path: # "Existing Header directive for virtualhost" pat = '(?:[ "]|^)(%s)(?:[ "]|$)' % (header_substring.lower()) for match in header_path: if re.search(pat, self.aug.get(match).lower()): raise errors.PluginEnhancementAlreadyPresent( "Existing %s header" % (header_substring)) def _enable_redirect(self, ssl_vhost, unused_options): """Redirect all equivalent HTTP traffic to ssl_vhost. .. todo:: This enhancement should be rewritten and will unfortunately require lots of debugging by hand. Adds Redirect directive to the port 80 equivalent of ssl_vhost First the function attempts to find the vhost with equivalent ip addresses that serves on non-ssl ports The function then adds the directive .. note:: This function saves the configuration :param ssl_vhost: Destination of traffic, an ssl enabled vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param unused_options: Not currently used :type unused_options: Not Available :returns: Success, general_vhost (HTTP vhost) :rtype: (bool, :class:`~letsencrypt_apache.obj.VirtualHost`) :raises .errors.PluginError: If no viable HTTP host can be created or used for the redirect. """ if "rewrite_module" not in self.parser.modules: self.enable_mod("rewrite") general_vh = self._get_http_vhost(ssl_vhost) if general_vh is None: # Add virtual_server with redirect logger.debug("Did not find http version of ssl virtual host " "attempting to create") redirect_addrs = self._get_proposed_addrs(ssl_vhost) for vhost in self.vhosts: if vhost.enabled and vhost.conflicts(redirect_addrs): raise errors.PluginError( "Unable to find corresponding HTTP vhost; " "Unable to create one as intended addresses conflict; " "Current configuration does not support automated " "redirection") self._create_redirect_vhost(ssl_vhost) else: # Check if LetsEncrypt redirection already exists self._verify_no_letsencrypt_redirect(general_vh) # Note: if code flow gets here it means we didn't find the exact # letsencrypt RewriteRule config for redirection. Finding # another RewriteRule is likely to be fine in most or all cases, # but redirect loops are possible in very obscure cases; see #1620 # for reasoning. if self._is_rewrite_exists(general_vh): logger.warn("Added an HTTP->HTTPS rewrite in addition to " "other RewriteRules; you may wish to check for " "overall consistency.") # Add directives to server # Note: These are not immediately searchable in sites-enabled # even with save() and load() if not self._is_rewrite_engine_on(general_vh): self.parser.add_dir(general_vh.path, "RewriteEngine", "on") if self.get_version() >= (2, 3, 9): self.parser.add_dir(general_vh.path, "RewriteRule", constants.REWRITE_HTTPS_ARGS_WITH_END) else: self.parser.add_dir(general_vh.path, "RewriteRule", constants.REWRITE_HTTPS_ARGS) self.save_notes += ("Redirecting host in %s to ssl vhost in %s\n" % (general_vh.filep, ssl_vhost.filep)) self.save() logger.info("Redirecting vhost in %s to ssl vhost in %s", general_vh.filep, ssl_vhost.filep) def _verify_no_letsencrypt_redirect(self, vhost): """Checks to see if a redirect was already installed by letsencrypt. Checks to see if virtualhost already contains a rewrite rule that is identical to Letsencrypt's redirection rewrite rule. :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :raises errors.PluginEnhancementAlreadyPresent: When the exact letsencrypt redirection WriteRule exists in virtual host. """ rewrite_path = self.parser.find_dir( "RewriteRule", None, start=vhost.path) # There can be other RewriteRule directive lines in vhost config. # rewrite_args_dict keys are directive ids and the corresponding value # for each is a list of arguments to that directive. rewrite_args_dict = defaultdict(list) pat = r'.*(directive\[\d+\]).*' for match in rewrite_path: m = re.match(pat, match) if m: dir_id = m.group(1) rewrite_args_dict[dir_id].append(match) if rewrite_args_dict: redirect_args = [constants.REWRITE_HTTPS_ARGS, constants.REWRITE_HTTPS_ARGS_WITH_END] for matches in rewrite_args_dict.values(): if [self.aug.get(x) for x in matches] in redirect_args: raise errors.PluginEnhancementAlreadyPresent( "Let's Encrypt has already enabled redirection") def _is_rewrite_exists(self, vhost): """Checks if there exists a RewriteRule directive in vhost :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: True if a RewriteRule directive exists. :rtype: bool """ rewrite_path = self.parser.find_dir( "RewriteRule", None, start=vhost.path) return bool(rewrite_path) def _is_rewrite_engine_on(self, vhost): """Checks if a RewriteEngine directive is on :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` """ rewrite_engine_path = self.parser.find_dir("RewriteEngine", "on", start=vhost.path) if rewrite_engine_path: return self.parser.get_arg(rewrite_engine_path[0]) return False def _create_redirect_vhost(self, ssl_vhost): """Creates an http_vhost specifically to redirect for the ssl_vhost. :param ssl_vhost: ssl vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: tuple of the form (`success`, :class:`~letsencrypt_apache.obj.VirtualHost`) :rtype: tuple """ text = self._get_redirect_config_str(ssl_vhost) redirect_filepath = self._write_out_redirect(ssl_vhost, text) self.aug.load() # Make a new vhost data structure and add it to the lists new_vhost = self._create_vhost(parser.get_aug_path(redirect_filepath)) self.vhosts.append(new_vhost) # Finally create documentation for the change self.save_notes += ("Created a port 80 vhost, %s, for redirection to " "ssl vhost %s\n" % (new_vhost.filep, ssl_vhost.filep)) def _get_redirect_config_str(self, ssl_vhost): # get servernames and serveraliases serveralias = "" servername = "" if ssl_vhost.name is not None: servername = "ServerName " + ssl_vhost.name if ssl_vhost.aliases: serveralias = "ServerAlias " + " ".join(ssl_vhost.aliases) rewrite_rule_args = [] if self.get_version() >= (2, 3, 9): rewrite_rule_args = constants.REWRITE_HTTPS_ARGS_WITH_END else: rewrite_rule_args = constants.REWRITE_HTTPS_ARGS return ("<VirtualHost %s>\n" "%s \n" "%s \n" "ServerSignature Off\n" "\n" "RewriteEngine On\n" "RewriteRule %s\n" "\n" "ErrorLog /var/log/apache2/redirect.error.log\n" "LogLevel warn\n" "</VirtualHost>\n" % (" ".join(str(addr) for addr in self._get_proposed_addrs(ssl_vhost)), servername, serveralias, " ".join(rewrite_rule_args))) def _write_out_redirect(self, ssl_vhost, text): # This is the default name redirect_filename = "le-redirect.conf" # See if a more appropriate name can be applied if ssl_vhost.name is not None: # make sure servername doesn't exceed filename length restriction if len(ssl_vhost.name) < (255 - (len(redirect_filename) + 1)): redirect_filename = "le-redirect-%s.conf" % ssl_vhost.name redirect_filepath = os.path.join( self.parser.root, "sites-available", redirect_filename) # Register the new file that will be created # Note: always register the creation before writing to ensure file will # be removed in case of unexpected program exit self.reverter.register_file_creation(False, redirect_filepath) # Write out file with open(redirect_filepath, "w") as redirect_file: redirect_file.write(text) logger.info("Created redirect file: %s", redirect_filename) return redirect_filepath def _get_http_vhost(self, ssl_vhost): """Find appropriate HTTP vhost for ssl_vhost.""" # First candidate vhosts filter candidate_http_vhs = [ vhost for vhost in self.vhosts if not vhost.ssl ] # Second filter - check addresses for http_vh in candidate_http_vhs: if http_vh.same_server(ssl_vhost): return http_vh return None def _get_proposed_addrs(self, vhost, port="80"): # pylint: disable=no-self-use """Return all addrs of vhost with the port replaced with the specified. :param obj.VirtualHost ssl_vhost: Original Vhost :param str port: Desired port for new addresses :returns: `set` of :class:`~obj.Addr` """ redirects = set() for addr in vhost.addrs: redirects.add(addr.get_addr_obj(port)) return redirects def get_all_certs_keys(self): """Find all existing keys, certs from configuration. Retrieve all certs and keys set in VirtualHosts on the Apache server :returns: list of tuples with form [(cert, key, path)] cert - str path to certificate file key - str path to associated key file path - File path to configuration file. :rtype: list """ c_k = set() for vhost in self.vhosts: if vhost.ssl: cert_path = self.parser.find_dir( "SSLCertificateFile", None, start=vhost.path, exclude=False) key_path = self.parser.find_dir( "SSLCertificateKeyFile", None, start=vhost.path, exclude=False) if cert_path and key_path: cert = os.path.abspath(self.parser.get_arg(cert_path[-1])) key = os.path.abspath(self.parser.get_arg(key_path[-1])) c_k.add((cert, key, get_file_path(cert_path[-1]))) else: logger.warning( "Invalid VirtualHost configuration - %s", vhost.filep) return c_k def is_site_enabled(self, avail_fp): """Checks to see if the given site is enabled. .. todo:: fix hardcoded sites-enabled, check os.path.samefile :param str avail_fp: Complete file path of available site :returns: Success :rtype: bool """ enabled_dir = os.path.join(self.parser.root, "sites-enabled") for entry in os.listdir(enabled_dir): try: if filecmp.cmp(avail_fp, os.path.join(enabled_dir, entry)): return True except OSError: pass return False def enable_site(self, vhost): """Enables an available site, Apache reload required. .. note:: Does not make sure that the site correctly works or that all modules are enabled appropriately. .. todo:: This function should number subdomains before the domain vhost .. todo:: Make sure link is not broken... :param vhost: vhost to enable :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.NotSupportedError: If filesystem layout is not supported. """ if self.is_site_enabled(vhost.filep): return if "/sites-available/" in vhost.filep: enabled_path = ("%s/sites-enabled/%s" % (self.parser.root, os.path.basename(vhost.filep))) self.reverter.register_file_creation(False, enabled_path) os.symlink(vhost.filep, enabled_path) vhost.enabled = True logger.info("Enabling available site: %s", vhost.filep) self.save_notes += "Enabled site %s\n" % vhost.filep else: raise errors.NotSupportedError( "Unsupported filesystem layout. " "sites-available/enabled expected.") def enable_mod(self, mod_name, temp=False): """Enables module in Apache. Both enables and reloads Apache so module is active. :param str mod_name: Name of the module to enable. (e.g. 'ssl') :param bool temp: Whether or not this is a temporary action. :raises .errors.NotSupportedError: If the filesystem layout is not supported. :raises .errors.MisconfigurationError: If a2enmod or a2dismod cannot be run. """ # Support Debian specific setup avail_path = os.path.join(self.parser.root, "mods-available") enabled_path = os.path.join(self.parser.root, "mods-enabled") if not os.path.isdir(avail_path) or not os.path.isdir(enabled_path): raise errors.NotSupportedError( "Unsupported directory layout. You may try to enable mod %s " "and try again." % mod_name) deps = _get_mod_deps(mod_name) # Enable all dependencies for dep in deps: if (dep + "_module") not in self.parser.modules: self._enable_mod_debian(dep, temp) self._add_parser_mod(dep) note = "Enabled dependency of %s module - %s" % (mod_name, dep) if not temp: self.save_notes += note + os.linesep logger.debug(note) # Enable actual module self._enable_mod_debian(mod_name, temp) self._add_parser_mod(mod_name) if not temp: self.save_notes += "Enabled %s module in Apache\n" % mod_name logger.info("Enabled Apache %s module", mod_name) # Modules can enable additional config files. Variables may be defined # within these new configuration sections. # Reload is not necessary as DUMP_RUN_CFG uses latest config. self.parser.update_runtime_variables(self.conf("ctl")) def
(self, mod_name): """Shortcut for updating parser modules.""" self.parser.modules.add(mod_name + "_module") self.parser.modules.add("mod_" + mod_name + ".c") def _enable_mod_debian(self, mod_name, temp): """Assumes mods-available, mods-enabled layout.""" # Generate reversal command. # Try to be safe here... check that we can probably reverse before # applying enmod command if not le_util.exe_exists(self.conf("dismod")): raise errors.MisconfigurationError( "Unable to find a2dismod, please make sure a2enmod and " "a2dismod are configured correctly for letsencrypt.") self.reverter.register_undo_command( temp, [self.conf("dismod"), mod_name]) le_util.run_script([self.conf("enmod"), mod_name]) def restart(self): """Runs a config test and reloads the Apache server. :raises .errors.MisconfigurationError: If either the config test or reload fails. """ self.config_test() self._reload() def _reload(self): """Reloads the Apache server. :raises .errors.MisconfigurationError: If reload fails """ try: le_util.run_script([self.conf("ctl"), "-k", "graceful"]) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) def config_test(self): # pylint: disable=no-self-use """Check the configuration of Apache for errors. :raises .errors.MisconfigurationError: If config_test fails """ try: le_util.run_script([self.conf("ctl"), "configtest"]) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) def get_version(self): """Return version of Apache Server. Version is returned as tuple. (ie. 2.4.7 = (2, 4, 7)) :returns: version :rtype: tuple :raises .PluginError: if unable to find Apache version """ try: stdout, _ = le_util.run_script([self.conf("ctl"), "-v"]) except errors.SubprocessError: raise errors.PluginError( "Unable to run %s -v" % self.conf("ctl")) regex = re.compile(r"Apache/([0-9\.]*)", re.IGNORECASE) matches = regex.findall(stdout) if len(matches) != 1: raise errors.PluginError("Unable to find Apache version") return tuple([int(i) for i in matches[0].split(".")]) def more_info(self): """Human-readable string to help understand the module""" return ( "Configures Apache to authenticate and install HTTPS.{0}" "Server root: {root}{0}" "Version: {version}".format( os.linesep, root=self.parser.loc["root"], version=".".join(str(i) for i in self.version)) ) ########################################################################### # Challenges Section ########################################################################### def get_chall_pref(self, unused_domain): # pylint: disable=no-self-use """Return list of challenge preferences.""" return [challenges.TLSSNI01] def perform(self, achalls): """Perform the configuration related challenge. This function currently assumes all challenges will be fulfilled. If this turns out not to be the case in the future. Cleanup and outstanding challenges will have to be designed better. """ self._chall_out.update(achalls) responses = [None] * len(achalls) chall_doer = tls_sni_01.ApacheTlsSni01(self) for i, achall in enumerate(achalls): # Currently also have chall_doer hold associated index of the # challenge. This helps to put all of the responses back together # when they are all complete. chall_doer.add_chall(achall, i) sni_response = chall_doer.perform() if sni_response: # Must reload in order to activate the challenges. # Handled here because we may be able to load up other challenge # types self.restart() # TODO: Remove this dirty hack. We need to determine a reliable way # of identifying when the new configuration is being used. time.sleep(3) # Go through all of the challenges and assign them to the proper # place in the responses return value. All responses must be in the # same order as the original challenges. for i, resp in enumerate(sni_response): responses[chall_doer.indices[i]] = resp return responses def cleanup(self, achalls): """Revert all challenges.""" self._chall_out.difference_update(achalls) # If all of the challenges have been finished, clean up everything if not self._chall_out: self.revert_challenge_config() self.restart() self.parser.init_modules() def _get_mod_deps(mod_name): """Get known module dependencies. .. note:: This does not need to be accurate in order for the client to run. This simply keeps things clean if the user decides to revert changes. .. warning:: If all deps are not included, it may cause incorrect parsing behavior, due to enable_mod's shortcut for updating the parser's currently defined modules (`.ApacheConfigurator._add_parser_mod`) This would only present a major problem in extremely atypical configs that use ifmod for the missing deps. """ deps = { "ssl": ["setenvif", "mime", "socache_shmcb"] } return deps.get(mod_name, []) def get_file_path(vhost_path): """Get file path from augeas_vhost_path. Takes in Augeas path and returns the file name :param str vhost_path: Augeas virtual host path :returns: filename of vhost :rtype: str """ # Strip off /files avail_fp = vhost_path[6:] # This can be optimized... while True: # Cast all to lowercase to be case insensitive find_if = avail_fp.lower().find("/ifmodule") if find_if != -1: avail_fp = avail_fp[:find_if] continue find_vh = avail_fp.lower().find("/virtualhost") if find_vh != -1: avail_fp = avail_fp[:find_vh] continue find_macro = avail_fp.lower().find("/macro") if find_macro != -1: avail_fp = avail_fp[:find_macro] continue break return avail_fp def install_ssl_options_conf(options_ssl): """ Copy Let's Encrypt's SSL options file into the system's config dir if required. """ # XXX if we ever try to enforce a local privilege boundary (eg, running # letsencrypt for unprivileged users via setuid), this function will need # to be modified. # XXX if the user is in security-autoupdate mode, we should be willing to # overwrite the options_ssl file at least if it's unmodified: # https://github.com/letsencrypt/letsencrypt/issues/1123 # Check to make sure options-ssl.conf is installed if not os.path.isfile(options_ssl): shutil.copyfile(constants.MOD_SSL_CONF_SRC, options_ssl)
_add_parser_mod
application_service_client.py
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Accesses the google.cloud.talent.v4beta1 ApplicationService API.""" import functools import pkg_resources import warnings from google.oauth2 import service_account import google.api_core.client_options import google.api_core.gapic_v1.client_info import google.api_core.gapic_v1.config import google.api_core.gapic_v1.method import google.api_core.gapic_v1.routing_header import google.api_core.grpc_helpers import google.api_core.page_iterator import google.api_core.path_template import grpc from google.cloud.talent_v4beta1.gapic import application_service_client_config from google.cloud.talent_v4beta1.gapic import enums from google.cloud.talent_v4beta1.gapic.transports import ( application_service_grpc_transport, ) from google.cloud.talent_v4beta1.proto import application_pb2 from google.cloud.talent_v4beta1.proto import application_service_pb2 from google.cloud.talent_v4beta1.proto import application_service_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import field_mask_pb2 _GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-talent").version class ApplicationServiceClient(object): """ A service that handles application management, including CRUD and enumeration. """ SERVICE_ADDRESS = "jobs.googleapis.com:443" """The default address of the service.""" # The name of the interface for this client. This is the key used to # find the method configuration in the client_config dictionary. _INTERFACE_NAME = "google.cloud.talent.v4beta1.ApplicationService" @classmethod def from_service_account_file(cls, filename, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ApplicationServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @classmethod def application_path(cls, project, tenant, profile, application): """Return a fully-qualified application string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}", project=project, tenant=tenant, profile=profile, application=application, ) @classmethod def profile_path(cls, project, tenant, profile): """Return a fully-qualified profile string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}/profiles/{profile}", project=project, tenant=tenant, profile=profile, ) def __init__( self, transport=None, channel=None, credentials=None, client_config=None, client_info=None, client_options=None, ): """Constructor. Args: transport (Union[~.ApplicationServiceGrpcTransport, Callable[[~.Credentials, type], ~.ApplicationServiceGrpcTransport]): A transport instance, responsible for actually making the API calls. The default transport uses the gRPC protocol. This argument may also be a callable which returns a transport instance. Callables will be sent the credentials as the first argument and the default transport class as the second argument. channel (grpc.Channel): DEPRECATED. A ``Channel`` instance through which to make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. This argument is mutually exclusive with providing a transport instance to ``transport``; doing so will raise an exception. client_config (dict): DEPRECATED. A dictionary of call options for each method. If not specified, the default configuration is used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. client_options (Union[dict, google.api_core.client_options.ClientOptions]): Client options used to set user options on the client. API Endpoint should be set through client_options. """ # Raise deprecation warnings for things we want to go away. if client_config is not None: warnings.warn( "The `client_config` argument is deprecated.", PendingDeprecationWarning, stacklevel=2, ) else: client_config = application_service_client_config.config if channel: warnings.warn( "The `channel` argument is deprecated; use " "`transport` instead.", PendingDeprecationWarning, stacklevel=2, ) api_endpoint = self.SERVICE_ADDRESS if client_options: if type(client_options) == dict: client_options = google.api_core.client_options.from_dict( client_options ) if client_options.api_endpoint: api_endpoint = client_options.api_endpoint # Instantiate the transport. # The transport is responsible for handling serialization and # deserialization and actually sending data to the service. if transport: if callable(transport): self.transport = transport( credentials=credentials, default_class=application_service_grpc_transport.ApplicationServiceGrpcTransport, address=api_endpoint, ) else: if credentials: raise ValueError( "Received both a transport instance and " "credentials; these are mutually exclusive." ) self.transport = transport else: self.transport = application_service_grpc_transport.ApplicationServiceGrpcTransport( address=api_endpoint, channel=channel, credentials=credentials ) if client_info is None: client_info = google.api_core.gapic_v1.client_info.ClientInfo( gapic_version=_GAPIC_LIBRARY_VERSION ) else: client_info.gapic_version = _GAPIC_LIBRARY_VERSION self._client_info = client_info # Parse out the default settings for retry and timeout for each RPC # from the client configuration. # (Ordinarily, these are the defaults specified in the `*_config.py` # file next to this one.) self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( client_config["interfaces"][self._INTERFACE_NAME] ) # Save a dictionary of cached API call functions. # These are the actual callables which invoke the proper # transport methods, wrapped with `wrap_method` to add retry, # timeout, and the like. self._inner_api_calls = {} # Service calls def create_application( self, parent, application, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new application entity. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ApplicationServiceClient() >>> >>> parent = client.profile_path('[PROJECT]', '[TENANT]', '[PROFILE]') >>> >>> # TODO: Initialize `application`: >>> application = {} >>> >>> response = client.create_application(parent, application) Args: parent (str): Required. Resource name of the profile under which the application is created. The format is "projects/{project\_id}/tenants/{tenant\_id}/profiles/{profile\_id}", for example, "projects/test-project/tenants/test-tenant/profiles/test-profile". application (Union[dict, ~google.cloud.talent_v4beta1.types.Application]): Required. The application to be created. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Application` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.talent_v4beta1.types.Application` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_application" not in self._inner_api_calls: self._inner_api_calls[ "create_application" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_application, default_retry=self._method_configs["CreateApplication"].retry, default_timeout=self._method_configs["CreateApplication"].timeout, client_info=self._client_info, ) request = application_service_pb2.CreateApplicationRequest( parent=parent, application=application ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["create_application"]( request, retry=retry, timeout=timeout, metadata=metadata ) def get_application( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves specified application. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ApplicationServiceClient() >>> >>> name = client.application_path('[PROJECT]', '[TENANT]', '[PROFILE]', '[APPLICATION]') >>> >>> response = client.get_application(name) Args: name (str): Required. The resource name of the application to be retrieved. The format is "projects/{project\_id}/tenants/{tenant\_id}/profiles/{profile\_id}/applications/{application\_id}", for example, "projects/test-project/tenants/test-tenant/profiles/test-profile/applications/test-application". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.talent_v4beta1.types.Application` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_application" not in self._inner_api_calls: self._inner_api_calls[ "get_application" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_application, default_retry=self._method_configs["GetApplication"].retry, default_timeout=self._method_configs["GetApplication"].timeout, client_info=self._client_info, ) request = application_service_pb2.GetApplicationRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_application"]( request, retry=retry, timeout=timeout, metadata=metadata ) def update_application( self, application, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates specified application. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ApplicationServiceClient() >>> >>> # TODO: Initialize `application`: >>> application = {} >>> >>> response = client.update_application(application) Args: application (Union[dict, ~google.cloud.talent_v4beta1.types.Application]): Required. The application resource to replace the current resource in the system. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.Application` update_mask (Union[dict, ~google.cloud.talent_v4beta1.types.FieldMask]): Optional but strongly recommended for the best service experience. If ``update_mask`` is provided, only the specified fields in ``application`` are updated. Otherwise all the fields are updated. A field mask to specify the application fields to be updated. Only top level fields of ``Application`` are supported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.talent_v4beta1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.talent_v4beta1.types.Application` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_application" not in self._inner_api_calls: self._inner_api_calls[ "update_application" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_application, default_retry=self._method_configs["UpdateApplication"].retry, default_timeout=self._method_configs["UpdateApplication"].timeout, client_info=self._client_info, ) request = application_service_pb2.UpdateApplicationRequest( application=application, update_mask=update_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("application.name", application.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["update_application"]( request, retry=retry, timeout=timeout, metadata=metadata ) def delete_application( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None,
Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ApplicationServiceClient() >>> >>> name = client.application_path('[PROJECT]', '[TENANT]', '[PROFILE]', '[APPLICATION]') >>> >>> client.delete_application(name) Args: name (str): Required. The resource name of the application to be deleted. The format is "projects/{project\_id}/tenants/{tenant\_id}/profiles/{profile\_id}/applications/{application\_id}", for example, "projects/test-project/tenants/test-tenant/profiles/test-profile/applications/test-application". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_application" not in self._inner_api_calls: self._inner_api_calls[ "delete_application" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_application, default_retry=self._method_configs["DeleteApplication"].retry, default_timeout=self._method_configs["DeleteApplication"].timeout, client_info=self._client_info, ) request = application_service_pb2.DeleteApplicationRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_application"]( request, retry=retry, timeout=timeout, metadata=metadata ) def list_applications( self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all applications associated with the profile. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ApplicationServiceClient() >>> >>> parent = client.profile_path('[PROJECT]', '[TENANT]', '[PROFILE]') >>> >>> # Iterate over all results >>> for element in client.list_applications(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_applications(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. Resource name of the profile under which the application is created. The format is "projects/{project\_id}/tenants/{tenant\_id}/profiles/{profile\_id}", for example, "projects/test-project/tenants/test-tenant/profiles/test-profile". page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.talent_v4beta1.types.Application` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_applications" not in self._inner_api_calls: self._inner_api_calls[ "list_applications" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_applications, default_retry=self._method_configs["ListApplications"].retry, default_timeout=self._method_configs["ListApplications"].timeout, client_info=self._client_info, ) request = application_service_pb2.ListApplicationsRequest( parent=parent, page_size=page_size ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_applications"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="applications", request_token_field="page_token", response_token_field="next_page_token", ) return iterator
): """ Deletes specified application.
model_storage_key_setting.go
/* Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advanced ways than the prior generations of tools. Cisco Intersight provides an integrated and intuitive management experience for resources in the traditional data center as well as at the edge. With flexible deployment options to address complex security needs, getting started with Intersight is quick and easy. Cisco Intersight has deep integration with Cisco UCS and HyperFlex systems allowing for remote deployment, configuration, and ongoing maintenance. The model-based deployment works for a single system in a remote location or hundreds of systems in a data center and enables rapid, standardized configuration and deployment. It also streamlines maintaining those systems whether you are working with small or very large configurations. The Intersight OpenAPI document defines the complete set of properties that are returned in the HTTP response. From that perspective, a client can expect that no additional properties are returned, unless these properties are explicitly defined in the OpenAPI document. However, when a client uses an older version of the Intersight OpenAPI document, the server may send additional properties because the software is more recent than the client. In that case, the client may receive properties that it does not know about. Some generated SDKs perform a strict validation of the HTTP response body against the OpenAPI document. API version: 1.0.9-5517 Contact: [email protected] */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package intersight import ( "encoding/json" "reflect" "strings" ) // StorageKeySetting Models the local key configurarion required for disks encryptions. type StorageKeySetting struct { MoBaseComplexType // The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data. ClassId string `json:"ClassId"` // The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property. ObjectType string `json:"ObjectType"` // Method to be used for fetching the encryption key. * `None` - Drive encryption not configured. * `Manual` - Drive encryption using manual key. * `Kmip` - Remote encryption using KMIP. KeyType *string `json:"KeyType,omitempty"` ManualKey NullableStorageLocalKeySetting `json:"ManualKey,omitempty"` RemoteKey NullableStorageRemoteKeySetting `json:"RemoteKey,omitempty"` AdditionalProperties map[string]interface{} } type _StorageKeySetting StorageKeySetting // NewStorageKeySetting instantiates a new StorageKeySetting object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewStorageKeySetting(classId string, objectType string) *StorageKeySetting { this := StorageKeySetting{} this.ClassId = classId this.ObjectType = objectType var keyType string = "None" this.KeyType = &keyType return &this } // NewStorageKeySettingWithDefaults instantiates a new StorageKeySetting object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewStorageKeySettingWithDefaults() *StorageKeySetting { this := StorageKeySetting{} var classId string = "storage.KeySetting" this.ClassId = classId var objectType string = "storage.KeySetting" this.ObjectType = objectType var keyType string = "None" this.KeyType = &keyType return &this } // GetClassId returns the ClassId field value func (o *StorageKeySetting) GetClassId() string { if o == nil { var ret string return ret } return o.ClassId } // GetClassIdOk returns a tuple with the ClassId field value // and a boolean to check if the value has been set. func (o *StorageKeySetting) GetClassIdOk() (*string, bool) { if o == nil { return nil, false } return &o.ClassId, true } // SetClassId sets field value func (o *StorageKeySetting) SetClassId(v string) { o.ClassId = v } // GetObjectType returns the ObjectType field value func (o *StorageKeySetting) GetObjectType() string { if o == nil { var ret string return ret } return o.ObjectType } // GetObjectTypeOk returns a tuple with the ObjectType field value // and a boolean to check if the value has been set. func (o *StorageKeySetting) GetObjectTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.ObjectType, true } // SetObjectType sets field value func (o *StorageKeySetting) SetObjectType(v string) { o.ObjectType = v } // GetKeyType returns the KeyType field value if set, zero value otherwise. func (o *StorageKeySetting) GetKeyType() string { if o == nil || o.KeyType == nil { var ret string return ret } return *o.KeyType } // GetKeyTypeOk returns a tuple with the KeyType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *StorageKeySetting) GetKeyTypeOk() (*string, bool) { if o == nil || o.KeyType == nil { return nil, false } return o.KeyType, true } // HasKeyType returns a boolean if a field has been set. func (o *StorageKeySetting) HasKeyType() bool { if o != nil && o.KeyType != nil { return true } return false } // SetKeyType gets a reference to the given string and assigns it to the KeyType field. func (o *StorageKeySetting) SetKeyType(v string) { o.KeyType = &v } // GetManualKey returns the ManualKey field value if set, zero value otherwise (both if not set or set to explicit null). func (o *StorageKeySetting) GetManualKey() StorageLocalKeySetting { if o == nil || o.ManualKey.Get() == nil { var ret StorageLocalKeySetting return ret } return *o.ManualKey.Get() } // GetManualKeyOk returns a tuple with the ManualKey field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StorageKeySetting) GetManualKeyOk() (*StorageLocalKeySetting, bool) { if o == nil { return nil, false } return o.ManualKey.Get(), o.ManualKey.IsSet() } // HasManualKey returns a boolean if a field has been set. func (o *StorageKeySetting) HasManualKey() bool { if o != nil && o.ManualKey.IsSet() { return true } return false } // SetManualKey gets a reference to the given NullableStorageLocalKeySetting and assigns it to the ManualKey field. func (o *StorageKeySetting) SetManualKey(v StorageLocalKeySetting) { o.ManualKey.Set(&v) } // SetManualKeyNil sets the value for ManualKey to be an explicit nil func (o *StorageKeySetting) SetManualKeyNil() { o.ManualKey.Set(nil) } // UnsetManualKey ensures that no value is present for ManualKey, not even an explicit nil func (o *StorageKeySetting) UnsetManualKey() { o.ManualKey.Unset() } // GetRemoteKey returns the RemoteKey field value if set, zero value otherwise (both if not set or set to explicit null). func (o *StorageKeySetting) GetRemoteKey() StorageRemoteKeySetting { if o == nil || o.RemoteKey.Get() == nil { var ret StorageRemoteKeySetting return ret } return *o.RemoteKey.Get() } // GetRemoteKeyOk returns a tuple with the RemoteKey field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *StorageKeySetting) GetRemoteKeyOk() (*StorageRemoteKeySetting, bool) { if o == nil { return nil, false } return o.RemoteKey.Get(), o.RemoteKey.IsSet() } // HasRemoteKey returns a boolean if a field has been set. func (o *StorageKeySetting) HasRemoteKey() bool { if o != nil && o.RemoteKey.IsSet() { return true } return false } // SetRemoteKey gets a reference to the given NullableStorageRemoteKeySetting and assigns it to the RemoteKey field. func (o *StorageKeySetting) SetRemoteKey(v StorageRemoteKeySetting) { o.RemoteKey.Set(&v) } // SetRemoteKeyNil sets the value for RemoteKey to be an explicit nil func (o *StorageKeySetting) SetRemoteKeyNil() { o.RemoteKey.Set(nil) } // UnsetRemoteKey ensures that no value is present for RemoteKey, not even an explicit nil func (o *StorageKeySetting) UnsetRemoteKey() { o.RemoteKey.Unset() } func (o StorageKeySetting) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} serializedMoBaseComplexType, errMoBaseComplexType := json.Marshal(o.MoBaseComplexType) if errMoBaseComplexType != nil { return []byte{}, errMoBaseComplexType } errMoBaseComplexType = json.Unmarshal([]byte(serializedMoBaseComplexType), &toSerialize) if errMoBaseComplexType != nil { return []byte{}, errMoBaseComplexType } if true { toSerialize["ClassId"] = o.ClassId } if true { toSerialize["ObjectType"] = o.ObjectType } if o.KeyType != nil { toSerialize["KeyType"] = o.KeyType } if o.ManualKey.IsSet() { toSerialize["ManualKey"] = o.ManualKey.Get() } if o.RemoteKey.IsSet() { toSerialize["RemoteKey"] = o.RemoteKey.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *StorageKeySetting) UnmarshalJSON(bytes []byte) (err error) { type StorageKeySettingWithoutEmbeddedStruct struct { // The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data. ClassId string `json:"ClassId"` // The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property. ObjectType string `json:"ObjectType"` // Method to be used for fetching the encryption key. * `None` - Drive encryption not configured. * `Manual` - Drive encryption using manual key. * `Kmip` - Remote encryption using KMIP. KeyType *string `json:"KeyType,omitempty"` ManualKey NullableStorageLocalKeySetting `json:"ManualKey,omitempty"` RemoteKey NullableStorageRemoteKeySetting `json:"RemoteKey,omitempty"` } varStorageKeySettingWithoutEmbeddedStruct := StorageKeySettingWithoutEmbeddedStruct{} err = json.Unmarshal(bytes, &varStorageKeySettingWithoutEmbeddedStruct) if err == nil { varStorageKeySetting := _StorageKeySetting{} varStorageKeySetting.ClassId = varStorageKeySettingWithoutEmbeddedStruct.ClassId varStorageKeySetting.ObjectType = varStorageKeySettingWithoutEmbeddedStruct.ObjectType varStorageKeySetting.KeyType = varStorageKeySettingWithoutEmbeddedStruct.KeyType varStorageKeySetting.ManualKey = varStorageKeySettingWithoutEmbeddedStruct.ManualKey varStorageKeySetting.RemoteKey = varStorageKeySettingWithoutEmbeddedStruct.RemoteKey *o = StorageKeySetting(varStorageKeySetting) } else { return err } varStorageKeySetting := _StorageKeySetting{} err = json.Unmarshal(bytes, &varStorageKeySetting) if err == nil { o.MoBaseComplexType = varStorageKeySetting.MoBaseComplexType } else { return err } additionalProperties := make(map[string]interface{})
delete(additionalProperties, "ObjectType") delete(additionalProperties, "KeyType") delete(additionalProperties, "ManualKey") delete(additionalProperties, "RemoteKey") // remove fields from embedded structs reflectMoBaseComplexType := reflect.ValueOf(o.MoBaseComplexType) for i := 0; i < reflectMoBaseComplexType.Type().NumField(); i++ { t := reflectMoBaseComplexType.Type().Field(i) if jsonTag := t.Tag.Get("json"); jsonTag != "" { fieldName := "" if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 { fieldName = jsonTag[:commaIdx] } else { fieldName = jsonTag } if fieldName != "AdditionalProperties" { delete(additionalProperties, fieldName) } } } o.AdditionalProperties = additionalProperties } return err } type NullableStorageKeySetting struct { value *StorageKeySetting isSet bool } func (v NullableStorageKeySetting) Get() *StorageKeySetting { return v.value } func (v *NullableStorageKeySetting) Set(val *StorageKeySetting) { v.value = val v.isSet = true } func (v NullableStorageKeySetting) IsSet() bool { return v.isSet } func (v *NullableStorageKeySetting) Unset() { v.value = nil v.isSet = false } func NewNullableStorageKeySetting(val *StorageKeySetting) *NullableStorageKeySetting { return &NullableStorageKeySetting{value: val, isSet: true} } func (v NullableStorageKeySetting) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableStorageKeySetting) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "ClassId")
percentiles.go
// Copyright (c) 2019 Uber Technologies, Inc. // // 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. package common import ( "fmt" "math" "sort" "github.com/m3db/m3/src/query/graphite/errors" "github.com/m3db/m3/src/query/graphite/ts" ) const ( // FloatingPointFormat is the floating point format for naming FloatingPointFormat = "%.3f" ) // ErrInvalidPercentile is used when the percentile specified is incorrect func ErrInvalidPercentile(percentile float64) error { return errors.NewInvalidParamsError(fmt.Errorf("invalid percentile, percentile="+FloatingPointFormat, percentile)) } // PercentileNamer formats a string with a percentile type PercentileNamer func(name string, percentile float64) string // ThresholdComparator compares two floats for other comparison // functions such as Percentile checks. type ThresholdComparator func(v, threshold float64) bool // GreaterThan is a ThresholdComparator function for when // a value is greater than a threshold func GreaterThan(v, threshold float64) bool { return v > threshold } // LessThan is a ThresholdComparator function for when // a value is less than a threshold func LessThan(v, threshold float64) bool { return v < threshold } // SafeSort sorts the input slice and returns the number of NaNs in the input. func SafeSort(input []float64) int { nans := 0 for i := 0; i < len(input); i++ { if math.IsNaN(input[i]) { nans++ } } sort.Float64s(input) return nans } // SafeSum returns the sum of the input slice the number of NaNs in the input. func SafeSum(input []float64) (float64, int) { nans := 0 sum := 0.0 for _, v := range input { if !math.IsNaN(v) { sum += v } else { nans += 1 } } return sum, nans } // SafeMax returns the maximum value of the input slice the number of NaNs in the input. func SafeMax(input []float64) (float64, int) { nans := 0 max := -math.MaxFloat64 for _, v := range input { if math.IsNaN(v) { nans++ continue } if v > max { max = v } } return max, nans } // SafeMin returns the minimum value of the input slice the number of NaNs in the input. func SafeMin(input []float64) (float64, int) { nans := 0 min := math.MaxFloat64 for _, v := range input { if math.IsNaN(v) { nans++ continue } if v < min { min = v } } return min, nans } // GetPercentile computes the percentile cut off for an array of floats func GetPercentile(input []float64, percentile float64, interpolate bool) float64 { nans := SafeSort(input) series := input[nans:] if len(series) == 0 { return math.NaN() } fractionalRank := (percentile / 100.0) * (float64(len(series) + 1)) rank := int(fractionalRank) rankFraction := fractionalRank - float64(rank) if interpolate == false { rank = rank + int(math.Ceil(rankFraction)) } var percentileResult float64 if rank == 0 { percentileResult = series[0] } else if rank-1 == len(series) { percentileResult = series[len(series)-1] } else { percentileResult = series[rank-1] } if interpolate && rank != len(series) { nextValue := series[rank] percentileResult = percentileResult + (rankFraction * (nextValue - percentileResult)) } return percentileResult } // NPercentile returns percentile-percent of each series in the seriesList. func NPercentile(ctx *Context, in ts.SeriesList, percentile float64, pn PercentileNamer) (ts.SeriesList, error) { if percentile < 0.0 || percentile > 100.0 { return ts.NewSeriesList(), ErrInvalidPercentile(percentile) } results := make([]*ts.Series, 0, in.Len()) for _, s := range in.Values { safeValues := s.SafeValues() if len(safeValues) == 0 { continue } percentileVal := GetPercentile(safeValues, percentile, false) if !math.IsNaN(percentileVal) { vals := ts.NewConstantValues(ctx, percentileVal, s.Len(), s.MillisPerStep()) percentileSeries := ts.NewSeries(ctx, pn(s.Name(), percentile), s.StartTime(), vals) results = append(results, percentileSeries) } } in.Values = results return in, nil } // RemoveByPercentile removes all series above or below the given percentile, as // determined by the PercentileComparator func RemoveByPercentile( ctx *Context, in ts.SeriesList, percentile float64, pn PercentileNamer, tc ThresholdComparator, ) (ts.SeriesList, error)
{ results := make([]*ts.Series, 0, in.Len()) for _, series := range in.Values { single := ts.SeriesList{ Values: []*ts.Series{series}, Metadata: in.Metadata, } percentileSeries, err := NPercentile(ctx, single, percentile, pn) if err != nil { return ts.NewSeriesList(), err } numSteps := series.Len() vals := ts.NewValues(ctx, series.MillisPerStep(), numSteps) if percentileSeries.Len() == 1 { percentile := percentileSeries.Values[0].ValueAt(0) for i := 0; i < numSteps; i++ { v := series.ValueAt(i) if !tc(v, percentile) { vals.SetValueAt(i, v) } } } name := pn(series.Name(), percentile) newSeries := ts.NewSeries(ctx, name, series.StartTime(), vals) results = append(results, newSeries) } in.Values = results return in, nil }
blockchain.rs
use crate::{ consensus::*, execution::{analysis_cache::AnalysisCache, processor::ExecutionProcessor, tracer::NoopTracer}, models::*, state::*, }; use anyhow::Context; use std::{collections::HashMap, convert::TryFrom}; #[derive(Debug)] pub struct Blockchain<'state> { state: &'state mut InMemoryState, config: ChainSpec, engine: Box<dyn Consensus>, bad_blocks: HashMap<H256, ValidationError>, receipts: Vec<Receipt>, } impl<'state> Blockchain<'state> { pub fn new( state: &'state mut InMemoryState, config: ChainSpec, genesis_block: Block, ) -> anyhow::Result<Blockchain<'state>> { Self::new_with_consensus( state, engine_factory(config.clone())?, config, genesis_block, ) } pub fn new_with_consensus( state: &'state mut InMemoryState, engine: Box<dyn Consensus>, config: ChainSpec, genesis_block: Block, ) -> anyhow::Result<Blockchain<'state>> { let hash = genesis_block.header.hash(); let number = genesis_block.header.number; state.insert_block(genesis_block, hash); state.canonize_block(number, hash); Ok(Self { state, engine, config, bad_blocks: Default::default(), receipts: Default::default(), }) } pub fn insert_block(&mut self, block: Block, check_state_root: bool) -> anyhow::Result<()> { self.engine .validate_block_header(&block.header, &mut self.state, true)?; self.engine.pre_validate_block(&block, &mut self.state)?; let hash = block.header.hash(); if let Some(error) = self.bad_blocks.get(&hash) { return Err(error.clone().into()); } let b = BlockWithSenders::from(block.clone()); let ancestor = self.canonical_ancestor(&b.header, hash)?; let current_canonical_block = self.state.current_canonical_block(); self.unwind_last_changes(ancestor, current_canonical_block)?; let block_number = b.header.number; let mut chain = self.intermediate_chain( BlockNumber(block_number.0 - 1), b.header.parent_hash, ancestor, )?; chain.push(WithHash { inner: b, hash }); let mut num_of_executed_chain_blocks = 0; for x in &chain { if let Err(e) = self .execute_block(&x.inner, check_state_root) .with_context(|| format!("Failed to execute block #{}", block_number)) { if let Some(e) = e.downcast_ref::<ValidationError>() { self.bad_blocks.insert(hash, e.clone()); self.unwind_last_changes(ancestor, ancestor.0 + num_of_executed_chain_blocks)?; self.re_execute_canonical_chain(ancestor, current_canonical_block)?; } return Err(e); } num_of_executed_chain_blocks += 1; } self.state.insert_block(block, hash); let current_total_difficulty = self .state .total_difficulty( current_canonical_block, self.state.canonical_hash(current_canonical_block).unwrap(), )? .unwrap(); if self.state.total_difficulty(block_number, hash)?.unwrap() > current_total_difficulty { // canonize the new chain for i in (ancestor + 1..=current_canonical_block).rev() { self.state.decanonize_block(i); } for x in chain { self.state.canonize_block(x.header.number, x.hash); } } else { self.unwind_last_changes(ancestor, ancestor + num_of_executed_chain_blocks)?; self.re_execute_canonical_chain(ancestor, current_canonical_block)?; } Ok(())
fn execute_block( &mut self, block: &BlockWithSenders, check_state_root: bool, ) -> anyhow::Result<()> { let body = BlockBodyWithSenders { transactions: block.transactions.clone(), ommers: block.ommers.clone(), }; let block_spec = self.config.collect_block_spec(block.header.number); let mut analysis_cache = AnalysisCache::default(); let mut tracer = NoopTracer; let processor = ExecutionProcessor::new( self.state, &mut tracer, &mut analysis_cache, &mut *self.engine, &block.header, &body, &block_spec, ); let _ = processor.execute_and_write_block()?; if check_state_root { let state_root = self.state.state_root_hash(); if state_root != block.header.state_root { self.state.unwind_state_changes(block.header.number); return Err(ValidationError::WrongStateRoot { expected: block.header.state_root, got: state_root, } .into()); } } Ok(()) } fn re_execute_canonical_chain( &mut self, ancestor: impl Into<BlockNumber>, tip: impl Into<BlockNumber>, ) -> anyhow::Result<()> { let ancestor = ancestor.into(); let tip = tip.into(); assert!(ancestor <= tip); for block_number in ancestor + 1..=tip { let hash = self.state.canonical_hash(block_number).unwrap(); let body = self .state .read_body_with_senders(block_number, hash)? .unwrap(); let header = self.state.read_header(block_number, hash)?.unwrap(); let block = BlockWithSenders { header: header.into(), transactions: body.transactions, ommers: body.ommers, }; let _ = self.execute_block(&block, false).unwrap(); } Ok(()) } fn unwind_last_changes( &mut self, ancestor: impl Into<BlockNumber>, tip: impl Into<BlockNumber>, ) -> anyhow::Result<()> { let ancestor = ancestor.into(); let tip = tip.into(); assert!(ancestor <= tip); for block_number in (ancestor + 1..=tip).rev() { self.state.unwind_state_changes(block_number); } Ok(()) } fn intermediate_chain( &self, block_number: impl Into<BlockNumber>, mut hash: H256, canonical_ancestor: impl Into<BlockNumber>, ) -> anyhow::Result<Vec<WithHash<BlockWithSenders>>> { let block_number = block_number.into(); let canonical_ancestor = canonical_ancestor.into(); let mut chain = Vec::with_capacity(usize::try_from(block_number.0 - canonical_ancestor.0).unwrap()); for block_number in (canonical_ancestor + 1..=block_number).rev() { let body = self .state .read_body_with_senders(block_number, hash)? .unwrap(); let header = self.state.read_header(block_number, hash)?.unwrap().into(); let block = WithHash { inner: BlockWithSenders { header, transactions: body.transactions, ommers: body.ommers, }, hash, }; hash = block.header.parent_hash; chain.push(block); } chain.reverse(); Ok(chain) } fn canonical_ancestor( &self, header: &PartialHeader, hash: H256, ) -> anyhow::Result<BlockNumber> { if let Some(canonical_hash) = self.state.canonical_hash(header.number) { if canonical_hash == hash { return Ok(header.number); } } let parent = self .state .read_header(BlockNumber(header.number.0 - 1), header.parent_hash)? .ok_or(ValidationError::UnknownParent)?; self.canonical_ancestor(&parent.into(), header.parent_hash) } }
}
example.py
"""Run an example script to quickly test any MyQ account.""" import asyncio from aiohttp import ClientSession import pymyq from pymyq.errors import MyQError async def main() -> None: """Create the aiohttp session and run the example.""" async with ClientSession() as websession: try: myq = await pymyq.login( '<EMAIL>', '<PASSWORD>', '<BRAND>', websession) devices = await myq.get_devices()
print('Type: {0}'.format(device.type)) print('Serial: {0}'.format(device.serial)) print('Device ID: {0}'.format(device.device_id)) print('Parent ID: {0}'.format(device.parent_id)) print('Current State: {0}'.format(device.state)) print() print('Opening the device...') await device.open() print('Current State: {0}'.format(device.state)) await asyncio.sleep(15) print('Closing the device...') await device.close() print('Current State: {0}'.format(device.state)) except MyQError as err: print(err) asyncio.get_event_loop().run_until_complete(main())
for idx, device in enumerate(devices): print('Device #{0}: {1}'.format(idx + 1, device.name)) print('--------') print('Brand: {0}'.format(device.brand))
tconlcd_clk.rs
#[doc = "Register `TCONLCD_CLK` reader"] pub struct R(crate::R<TCONLCD_CLK_SPEC>); impl core::ops::Deref for R { type Target = crate::R<TCONLCD_CLK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<TCONLCD_CLK_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<TCONLCD_CLK_SPEC>) -> Self { R(reader) } } #[doc = "Register `TCONLCD_CLK` writer"] pub struct W(crate::W<TCONLCD_CLK_SPEC>); impl core::ops::Deref for W { type Target = crate::W<TCONLCD_CLK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<TCONLCD_CLK_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<TCONLCD_CLK_SPEC>) -> Self { W(writer) } } #[doc = "Gating Clock\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CLK_GATING_A { #[doc = "0: `0`"] OFF = 0, #[doc = "1: `1`"] ON = 1, } impl From<CLK_GATING_A> for bool { #[inline(always)] fn from(variant: CLK_GATING_A) -> Self { variant as u8 != 0 } } #[doc = "Field `CLK_GATING` reader - Gating Clock"] pub struct CLK_GATING_R(crate::FieldReader<bool>); impl CLK_GATING_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { CLK_GATING_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CLK_GATING_A { match self.bits { false => CLK_GATING_A::OFF, true => CLK_GATING_A::ON, } } #[doc = "Checks if the value of the field is `OFF`"] #[inline(always)] pub fn is_off(&self) -> bool { **self == CLK_GATING_A::OFF } #[doc = "Checks if the value of the field is `ON`"] #[inline(always)] pub fn is_on(&self) -> bool { **self == CLK_GATING_A::ON } } impl core::ops::Deref for CLK_GATING_R { type Target = crate::FieldReader<bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CLK_GATING` writer - Gating Clock"] pub struct CLK_GATING_W<'a> { w: &'a mut W, } impl<'a> CLK_GATING_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CLK_GATING_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "`0`"] #[inline(always)] pub fn off(self) -> &'a mut W { self.variant(CLK_GATING_A::OFF) } #[doc = "`1`"] #[inline(always)] pub fn on(self) -> &'a mut W { self.variant(CLK_GATING_A::ON) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(1 << 31)) | ((value as u32 & 1) << 31); self.w } } #[doc = "Clock Source Select\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CLK_SRC_SEL_A { #[doc = "0: `0`"] PLL_VIDEO0_1X = 0, #[doc = "1: `1`"] PLL_VIDEO0_4X = 1, #[doc = "2: `10`"] PLL_VIDEO1_1X = 2, #[doc = "3: `11`"] PLL_VIDEO1_4X = 3, #[doc = "4: `100`"] PLL_PERI_2X = 4, #[doc = "5: `101`"] PLL_AUDIO1_DIV2 = 5, } impl From<CLK_SRC_SEL_A> for u8 { #[inline(always)] fn from(variant: CLK_SRC_SEL_A) -> Self { variant as _ } } #[doc = "Field `CLK_SRC_SEL` reader - Clock Source Select"] pub struct CLK_SRC_SEL_R(crate::FieldReader<u8>); impl CLK_SRC_SEL_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { CLK_SRC_SEL_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<CLK_SRC_SEL_A> { match self.bits { 0 => Some(CLK_SRC_SEL_A::PLL_VIDEO0_1X), 1 => Some(CLK_SRC_SEL_A::PLL_VIDEO0_4X), 2 => Some(CLK_SRC_SEL_A::PLL_VIDEO1_1X), 3 => Some(CLK_SRC_SEL_A::PLL_VIDEO1_4X), 4 => Some(CLK_SRC_SEL_A::PLL_PERI_2X), 5 => Some(CLK_SRC_SEL_A::PLL_AUDIO1_DIV2), _ => None, } } #[doc = "Checks if the value of the field is `PLL_VIDEO0_1X`"] #[inline(always)] pub fn is_pll_video0_1x(&self) -> bool { **self == CLK_SRC_SEL_A::PLL_VIDEO0_1X } #[doc = "Checks if the value of the field is `PLL_VIDEO0_4X`"] #[inline(always)] pub fn is_pll_video0_4x(&self) -> bool { **self == CLK_SRC_SEL_A::PLL_VIDEO0_4X } #[doc = "Checks if the value of the field is `PLL_VIDEO1_1X`"] #[inline(always)] pub fn is_pll_video1_1x(&self) -> bool { **self == CLK_SRC_SEL_A::PLL_VIDEO1_1X } #[doc = "Checks if the value of the field is `PLL_VIDEO1_4X`"] #[inline(always)] pub fn is_pll_video1_4x(&self) -> bool { **self == CLK_SRC_SEL_A::PLL_VIDEO1_4X } #[doc = "Checks if the value of the field is `PLL_PERI_2X`"] #[inline(always)] pub fn is_pll_peri_2x(&self) -> bool { **self == CLK_SRC_SEL_A::PLL_PERI_2X } #[doc = "Checks if the value of the field is `PLL_AUDIO1_DIV2`"] #[inline(always)] pub fn is_pll_audio1_div2(&self) -> bool { **self == CLK_SRC_SEL_A::PLL_AUDIO1_DIV2 } } impl core::ops::Deref for CLK_SRC_SEL_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CLK_SRC_SEL` writer - Clock Source Select"] pub struct CLK_SRC_SEL_W<'a> { w: &'a mut W, } impl<'a> CLK_SRC_SEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CLK_SRC_SEL_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "`0`"] #[inline(always)] pub fn pll_video0_1x(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::PLL_VIDEO0_1X) } #[doc = "`1`"] #[inline(always)] pub fn pll_video0_4x(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::PLL_VIDEO0_4X) } #[doc = "`10`"] #[inline(always)] pub fn pll_video1_1x(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::PLL_VIDEO1_1X) } #[doc = "`11`"] #[inline(always)] pub fn pll_video1_4x(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::PLL_VIDEO1_4X) } #[doc = "`100`"] #[inline(always)] pub fn pll_peri_2x(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::PLL_PERI_2X) } #[doc = "`101`"] #[inline(always)] pub fn pll_audio1_div2(self) -> &'a mut W { self.variant(CLK_SRC_SEL_A::PLL_AUDIO1_DIV2) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(7 << 24)) | ((value as u32 & 7) << 24); self.w } } #[doc = "Factor N\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum FACTOR_N_A { #[doc = "0: `0`"] N1 = 0, #[doc = "1: `1`"] N2 = 1, #[doc = "2: `10`"] N4 = 2, #[doc = "3: `11`"] N8 = 3, } impl From<FACTOR_N_A> for u8 { #[inline(always)] fn from(variant: FACTOR_N_A) -> Self
} #[doc = "Field `FACTOR_N` reader - Factor N"] pub struct FACTOR_N_R(crate::FieldReader<u8>); impl FACTOR_N_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { FACTOR_N_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FACTOR_N_A { match self.bits { 0 => FACTOR_N_A::N1, 1 => FACTOR_N_A::N2, 2 => FACTOR_N_A::N4, 3 => FACTOR_N_A::N8, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `N1`"] #[inline(always)] pub fn is_n1(&self) -> bool { **self == FACTOR_N_A::N1 } #[doc = "Checks if the value of the field is `N2`"] #[inline(always)] pub fn is_n2(&self) -> bool { **self == FACTOR_N_A::N2 } #[doc = "Checks if the value of the field is `N4`"] #[inline(always)] pub fn is_n4(&self) -> bool { **self == FACTOR_N_A::N4 } #[doc = "Checks if the value of the field is `N8`"] #[inline(always)] pub fn is_n8(&self) -> bool { **self == FACTOR_N_A::N8 } } impl core::ops::Deref for FACTOR_N_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FACTOR_N` writer - Factor N"] pub struct FACTOR_N_W<'a> { w: &'a mut W, } impl<'a> FACTOR_N_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FACTOR_N_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "`0`"] #[inline(always)] pub fn n1(self) -> &'a mut W { self.variant(FACTOR_N_A::N1) } #[doc = "`1`"] #[inline(always)] pub fn n2(self) -> &'a mut W { self.variant(FACTOR_N_A::N2) } #[doc = "`10`"] #[inline(always)] pub fn n4(self) -> &'a mut W { self.variant(FACTOR_N_A::N4) } #[doc = "`11`"] #[inline(always)] pub fn n8(self) -> &'a mut W { self.variant(FACTOR_N_A::N8) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(3 << 8)) | ((value as u32 & 3) << 8); self.w } } #[doc = "Field `FACTOR_M` reader - Factor M"] pub struct FACTOR_M_R(crate::FieldReader<u8>); impl FACTOR_M_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { FACTOR_M_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FACTOR_M_R { type Target = crate::FieldReader<u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `FACTOR_M` writer - Factor M"] pub struct FACTOR_M_W<'a> { w: &'a mut W, } impl<'a> FACTOR_M_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); self.w } } impl R { #[doc = "Bit 31 - Gating Clock"] #[inline(always)] pub fn clk_gating(&self) -> CLK_GATING_R { CLK_GATING_R::new(((self.bits >> 31) & 1) != 0) } #[doc = "Bits 24:26 - Clock Source Select"] #[inline(always)] pub fn clk_src_sel(&self) -> CLK_SRC_SEL_R { CLK_SRC_SEL_R::new(((self.bits >> 24) & 7) as u8) } #[doc = "Bits 8:9 - Factor N"] #[inline(always)] pub fn factor_n(&self) -> FACTOR_N_R { FACTOR_N_R::new(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 0:3 - Factor M"] #[inline(always)] pub fn factor_m(&self) -> FACTOR_M_R { FACTOR_M_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bit 31 - Gating Clock"] #[inline(always)] pub fn clk_gating(&mut self) -> CLK_GATING_W { CLK_GATING_W { w: self } } #[doc = "Bits 24:26 - Clock Source Select"] #[inline(always)] pub fn clk_src_sel(&mut self) -> CLK_SRC_SEL_W { CLK_SRC_SEL_W { w: self } } #[doc = "Bits 8:9 - Factor N"] #[inline(always)] pub fn factor_n(&mut self) -> FACTOR_N_W { FACTOR_N_W { w: self } } #[doc = "Bits 0:3 - Factor M"] #[inline(always)] pub fn factor_m(&mut self) -> FACTOR_M_W { FACTOR_M_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "TCONLCD Clock Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tconlcd_clk](index.html) module"] pub struct TCONLCD_CLK_SPEC; impl crate::RegisterSpec for TCONLCD_CLK_SPEC { type Ux = u32; } #[doc = "`read()` method returns [tconlcd_clk::R](R) reader structure"] impl crate::Readable for TCONLCD_CLK_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [tconlcd_clk::W](W) writer structure"] impl crate::Writable for TCONLCD_CLK_SPEC { type Writer = W; } #[doc = "`reset()` method sets TCONLCD_CLK to value 0"] impl crate::Resettable for TCONLCD_CLK_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
{ variant as _ }
test_squeezedimd.py
# Copyright 2020 MONAI Consortium # 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 unittest import numpy as np from parameterized import parameterized from monai.transforms import SqueezeDimd TEST_CASE_1 = [ {"keys": ["img", "seg"], "dim": None}, {"img": np.random.rand(1, 2, 1, 3), "seg": np.random.randint(0, 2, size=[1, 2, 1, 3])}, (2, 3), ] TEST_CASE_2 = [ {"keys": ["img", "seg"], "dim": 2}, {"img": np.random.rand(1, 2, 1, 8, 16), "seg": np.random.randint(0, 2, size=[1, 2, 1, 8, 16])}, (1, 2, 8, 16), ] TEST_CASE_3 = [ {"keys": ["img", "seg"], "dim": -1}, {"img": np.random.rand(1, 1, 16, 8, 1), "seg": np.random.randint(0, 2, size=[1, 1, 16, 8, 1])}, (1, 1, 16, 8), ] TEST_CASE_4 = [ {"keys": ["img", "seg"]}, {"img": np.random.rand(1, 2, 1, 3), "seg": np.random.randint(0, 2, size=[1, 2, 1, 3])}, (2, 3), ] TEST_CASE_5 = [ {"keys": ["img", "seg"], "dim": -2}, {"img": np.random.rand(1, 1, 16, 8, 1), "seg": np.random.randint(0, 2, size=[1, 1, 16, 8, 1])}, ] TEST_CASE_6 = [ {"keys": ["img", "seg"], "dim": 0.5}, {"img": np.random.rand(1, 1, 16, 8, 1), "seg": np.random.randint(0, 2, size=[1, 1, 16, 8, 1])}, ] class TestSqueezeDim(unittest.TestCase): @parameterized.expand([TEST_CASE_1, TEST_CASE_2, TEST_CASE_3, TEST_CASE_4]) def
(self, input_param, test_data, expected_shape): result = SqueezeDimd(**input_param)(test_data) self.assertTupleEqual(result["img"].shape, expected_shape) self.assertTupleEqual(result["seg"].shape, expected_shape) @parameterized.expand([TEST_CASE_5, TEST_CASE_6]) def test_invalid_inputs(self, input_param, test_data): with self.assertRaises(AssertionError): result = SqueezeDimd(**input_param)(test_data) if __name__ == "__main__": unittest.main()
test_shape
core.go
package caprice import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) // The actual URL endpoint to hit const endpoint string = "https://api.random.org/json-rpc/1/invoke" // Caprice's core object. Responsible for safekeeping the API key, // as well as managing advisory delays in concurrent implementations. type trueRNG struct { apiKey string } // A helper function that will return a new trueRNG object func TrueRNG(apiKey string) trueRNG { return trueRNG{apiKey: apiKey} } // The outer JSON wrapper we send in our request body. It contains // `params`, which is a JSON object containing all the method parameters. // Typically, a struct implementing RequestShell will be populated for you. type RequestShell struct { Version string `json:"jsonrpc"` Params interface{} `json:"params"` Method string `json:"method"` Id int `json:"id"` } // The outer JSON wrapper we receive in our request body. It contains // `result`, which is a JSON object containing an object containing // all the actual data we care for. // `error` is returned from the API in lieu of `result` in the event of an error. // 'id' and versions are constants supplied and returned by the API. type ResponseShell struct { Version string `json:"jsonrpc"` Result json.RawMessage `json:"result"` Error Error `json:"error"` Id int `json:"id"` } // A nested inner JSON wrapper around Random within ResponseShell.Result. It includes some // basic diagnostic information as well. One of four types implementing Response // interface type Result struct { Random Random `json:"random"` BitsUsed int `json:"bitsUsed"` BitsLeft int `json:"bitsLeft"` RequestsLeft int `json:"requestsLeft"` AdvisoryDelay int `json:"advisoryDelay"` } // A nested inner JSON object within ResponseShell.Result. It includes only // basic diagnostic information. One of four types implementing Response // interface; returned directly as part of the GetUsage method. type Status struct { Status string `json:"status"` CreationTime string `json:"creationTime"` BitsLeft int `json:"bitsLeft"` RequestsLeft int `json:"requestsLeft"` TotalBits int `json:"totalBits"` TotalRequests int `json:"totalRequests"` } // A nested inner JSON object within ResponseShell.Result. It includes only // basic diagnostic information. One of four types implementing Response // interface; returned directly as part of the GetUsage method. type VerifiedSignature struct { Authenticity bool `json:"authenticiity"` } // A nested inner JSON wrapper around Random within ResponseShell.Result. It includes some // basic diagnostic information as well as a signature to verify the source of the data. // One of four types implementing Response interface. Raw is an alias for Random here. type SignedResult struct { Raw json.RawMessage `json:"random"` Signature string `json:"signature"` BitsUsed int `json:"bitsUsed"` BitsLeft int `json:"bitsLeft"` RequestsLeft int `json:"requestsLeft"` AdvisoryDelay int `json:"advisoryDelay"` } // A deeply nested inner JSON object contained inside ResponseShell.Random, which includes // everything we asked for. For basic methods, `Data` and `CompletionTime` are returned. // For signed methods, the values `HashedApiKey` and `SerialNumber` are also returned. type Random struct { Data []interface{} `json:"data"` CompletionTime string `json:"completionTime"` SerialNumber int `json:"serialNumber"` HashedApiKey string `json:"hashedApiKey"` } type SignedIntegerData struct { Raw json.RawMessage HashedApiKey string SerialNumber int Data []int Signature string } type SignedFloatData struct { Raw json.RawMessage HashedApiKey string SerialNumber int Data []float64 Signature string } type SignedStringData struct { Raw json.RawMessage HashedApiKey string Data []string SerialNumber int Signature string } // An interface that all Status, Result and SignedResult implement so that they can be // returned as valid outputs of the Request and SignedRequest functions. The expectation // is that any struct that satisfies this interface has the actual data we would care about. type Response interface { Content() interface{} } func (s Status) Content() interface{} { return s } func (r Result) Content() interface{} { return r.Random.Data } func (sr SignedResult) Content() interface{} { return sr } func (vs VerifiedSignature) Content() interface{} { return vs } // Core error object. Includes error message, the status code returned by the API, // and optional data returned by the upstream API. type Error struct { Code int `json:"code"` Message string `json:"message"` Data []interface{} `json:"data,omitempty"` } type IntegersReq struct { ApiKey string `json:"apiKey"` N int `json:"n"` Min int `json:"min"` Max int `json:"max"` Replacement bool `json:"replacement"` } type DecimalFractionsReq struct { ApiKey string `json:"apiKey"` N int `json:"n"` DecimalPlaces int `json:"decimalPlaces"` Replacement bool `json:"replacement"` } type GaussiansReq struct { ApiKey string `json:"apiKey"` N int `json:"n"` Mean float64 `json:"mean"` StandardDeviation float64 `json:"standardDeviation"` SignificantDigits int `json:"significantDigits"` } type StringsReq struct { ApiKey string `json:"apiKey"` N int `json:"n"` Length int `json:"length"` Characters string `json:"characters"` Replacement bool `json:"replacement"` } type UUIDsReq struct { ApiKey string `json:"apiKey"` N int `json:"n"` } type BlobsReq struct { ApiKey string `json:"apiKey"` N int `json:"n"` Size int `json:"size"` Format string `json:"format"` } type StatusReq struct { ApiKey string `json:"apiKey"` } type VerifySignatureReq struct { Raw map[string]interface{} `json:"random"` Signature string `json:"signature"` } func (e Error) Error() string { return fmt.Sprintf("Code: %d, Error: %s", e.Code, e.Message) } func clientError(message string) (ResponseShell, Error) { return ResponseShell{}, Error{ Code: 409, Message: message, } } // A helper function that makes HTTP calls to RANDOM.org with our request parameters and method name. func _request(method string, params interface{}) (ResponseShell, Error) { // create the JSON body for our request - ID is set to any number, doesn't matter which as API doesn't support batch notifs. body, err := json.Marshal(RequestShell{Version: "2.0", Params: params, Method: method, Id: 1}) fmt.Println(string(body)) if err != nil
// fire off the POST request resp, err := http.Post(endpoint, "application/json-rpc", bytes.NewReader(body)) if err != nil { return clientError(err.Error()) } defer resp.Body.Close() // convert resp.Body into a buffer we can unmarshall from text, err := ioutil.ReadAll(resp.Body) if err != nil { return clientError(err.Error()) } // handle non-successful behaviour if resp.StatusCode != 200 { errorMessage := Error{} json.Unmarshal(text, &errorMessage) return ResponseShell{}, errorMessage } // unmarshall response data response := ResponseShell{} json.Unmarshal(text, &response) if response.Error.Message != "" { return ResponseShell{}, response.Error } return response, Error{} } func Request(method string, params interface{}) (Response, Error) { response, err := _request(method, params) if err.Message != "" { return nil, err } if method == "getUsage" { status := Status{} json.Unmarshal(response.Result, &status) return status, Error{} } result := Result{} json.Unmarshal(response.Result, &result) return result, Error{} } func SignedRequest(method string, params interface{}) (Response, Error) { response, err := _request(method, params) if err.Message != "" { return nil, err } if method == "verifySignature" { verifiedSignature := VerifiedSignature{} json.Unmarshal(response.Result, &verifiedSignature) return verifiedSignature, Error{} } result := SignedResult{} json.Unmarshal(response.Result, &result) return result, Error{} }
{ return clientError(err.Error()) }
CONTAINER.ts
export const CONTAINER: Context = { code: 'container', children: true, repeater: false, sanitizers: [], validators: [], }; export default CONTAINER;
import { Context } from './Types';
control.rs
#[doc = "Reader of register CONTROL"] pub type R = crate::R<u32, super::CONTROL>; #[doc = "Writer for register CONTROL"] pub type W = crate::W<u32, super::CONTROL>; #[doc = "Register CONTROL `reset()`'s with value 0x03"] impl crate::ResetValue for super::CONTROL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x03 } } #[doc = "EMC Enable. Indicates if the EMC is enabled or disabled:\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum E_A { #[doc = "0: Disabled"] DISABLED = 0, #[doc = "1: Enabled\r\n(POR and warm reset value)."] ENABLED = 1, } impl From<E_A> for bool { #[inline(always)] fn from(variant: E_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `E`"] pub type E_R = crate::R<bool, E_A>; impl E_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> E_A { match self.bits { false => E_A::DISABLED, true => E_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == E_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == E_A::ENABLED } } #[doc = "Write proxy for field `E`"] pub struct E_W<'a> { w: &'a mut W, } impl<'a> E_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: E_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(E_A::DISABLED) } #[doc = "Enabled (POR and warm reset value)."] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(E_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Address mirror. Indicates normal or reset memory map:\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum M_A { #[doc = "0: Normal memory map."] NORMAL = 0, #[doc = "1: Reset memory map. Static memory EMC_CS1 is\r\nmirrored onto EMC_CS0 and EMC_DYCS0 (POR reset value)."] RESET = 1, } impl From<M_A> for bool { #[inline(always)] fn from(variant: M_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `M`"] pub type M_R = crate::R<bool, M_A>; impl M_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> M_A { match self.bits { false => M_A::NORMAL, true => M_A::RESET, } } #[doc = "Checks if the value of the field is `NORMAL`"] #[inline(always)] pub fn is_normal(&self) -> bool { *self == M_A::NORMAL } #[doc = "Checks if the value of the field is `RESET`"] #[inline(always)] pub fn is_reset(&self) -> bool { *self == M_A::RESET } } #[doc = "Write proxy for field `M`"] pub struct M_W<'a> { w: &'a mut W, } impl<'a> M_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: M_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Normal memory map."] #[inline(always)] pub fn normal(self) -> &'a mut W { self.variant(M_A::NORMAL) } #[doc = "Reset memory map. Static memory EMC_CS1 is mirrored onto EMC_CS0 and EMC_DYCS0 (POR reset value)."] #[inline(always)] pub fn reset(self) -> &'a mut W
#[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Low-power mode. Indicates normal, or low-power mode:\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum L_A { #[doc = "0: Normal mode (warm\r\nreset value)."] WARMRESET = 0, #[doc = "1: Low-power\r\nmode. Entering low-power mode reduces memory controller power consumption.\r\nDynamic memory is refreshed as necessary. The memory controller\r\nreturns to normal functional mode by clearing the low-power mode\r\nbit (L), or by POR. This bit must only be modified when the EMC\r\nis in idle state.\\[1\\]"] LOWPOWER = 1, } impl From<L_A> for bool { #[inline(always)] fn from(variant: L_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `L`"] pub type L_R = crate::R<bool, L_A>; impl L_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> L_A { match self.bits { false => L_A::WARMRESET, true => L_A::LOWPOWER, } } #[doc = "Checks if the value of the field is `WARMRESET`"] #[inline(always)] pub fn is_warmreset(&self) -> bool { *self == L_A::WARMRESET } #[doc = "Checks if the value of the field is `LOWPOWER`"] #[inline(always)] pub fn is_lowpower(&self) -> bool { *self == L_A::LOWPOWER } } #[doc = "Write proxy for field `L`"] pub struct L_W<'a> { w: &'a mut W, } impl<'a> L_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: L_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Normal mode (warm reset value)."] #[inline(always)] pub fn warmreset(self) -> &'a mut W { self.variant(L_A::WARMRESET) } #[doc = "Low-power mode. Entering low-power mode reduces memory controller power consumption. Dynamic memory is refreshed as necessary. The memory controller returns to normal functional mode by clearing the low-power mode bit (L), or by POR. This bit must only be modified when the EMC is in idle state.\\[1\\]"] #[inline(always)] pub fn lowpower(self) -> &'a mut W { self.variant(L_A::LOWPOWER) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } impl R { #[doc = "Bit 0 - EMC Enable. Indicates if the EMC is enabled or disabled:"] #[inline(always)] pub fn e(&self) -> E_R { E_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Address mirror. Indicates normal or reset memory map:"] #[inline(always)] pub fn m(&self) -> M_R { M_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Low-power mode. Indicates normal, or low-power mode:"] #[inline(always)] pub fn l(&self) -> L_R { L_R::new(((self.bits >> 2) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - EMC Enable. Indicates if the EMC is enabled or disabled:"] #[inline(always)] pub fn e(&mut self) -> E_W { E_W { w: self } } #[doc = "Bit 1 - Address mirror. Indicates normal or reset memory map:"] #[inline(always)] pub fn m(&mut self) -> M_W { M_W { w: self } } #[doc = "Bit 2 - Low-power mode. Indicates normal, or low-power mode:"] #[inline(always)] pub fn l(&mut self) -> L_W { L_W { w: self } } }
{ self.variant(M_A::RESET) }
train_test.py
# coding=utf-8 # Copyright 2019 The TensorFlow GAN 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. """Tests for stargan_estimator.train.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_gan.examples.stargan_estimator import train_lib mock = tf.compat.v1.test.mock def _test_generator(input_images, _): """Simple generator function.""" return input_images * tf.compat.v1.get_variable('dummy_g', initializer=2.0) def _test_discriminator(inputs, num_domains): """Differentiable dummy discriminator for StarGAN.""" hidden = tf.compat.v1.layers.flatten(inputs) output_src = tf.reduce_mean(input_tensor=hidden, axis=1) output_cls = tf.compat.v1.layers.dense(inputs=hidden, units=num_domains) return output_src, output_cls class TrainTest(tf.test.TestCase): @mock.patch.object(train_lib.data_provider, 'provide_data', autospec=True) @mock.patch.object( train_lib.data_provider, 'provide_celeba_test_set', autospec=True) def
(self, mock_provide_celeba_test_set, mock_provide_data): hparams = train_lib.HParams( batch_size=1, patch_size=8, output_dir='/tmp/tfgan_logdir/stargan/', generator_lr=1e-4, discriminator_lr=1e-4, max_number_of_steps=0, steps_per_eval=1, adam_beta1=0.5, adam_beta2=0.999, gen_disc_step_ratio=0.2, master='', ps_tasks=0, task=0) num_domains = 3 # Construct mock inputs. images_shape = [ hparams.batch_size, hparams.patch_size, hparams.patch_size, 3 ] img_list = [np.zeros(images_shape, dtype=np.float32)] * num_domains # Create a list of num_domains arrays of shape [batch_size, num_domains]. # Note: assumes hparams.batch_size <= num_domains. lbl_list = [np.eye(num_domains)[:hparams.batch_size, :]] * num_domains mock_provide_data.return_value = (img_list, lbl_list) mock_provide_celeba_test_set.return_value = np.zeros( [3, hparams.patch_size, hparams.patch_size, 3]) train_lib.train(hparams, _test_generator, _test_discriminator) if __name__ == '__main__': tf.test.main()
test_main
variables_5.js
var searchData=
['eval',['eval',['../structboost_1_1hana_1_1lazy.html#aae2998c08f1f80ed52a6acf57c4eec6c',1,'boost::hana::lazy']]], ['eval_5fif',['eval_if',['../group__group-Logical.html#gab64636f84de983575aac0208f5fa840c',1,'boost::hana']]], ['extend',['extend',['../group__group-Comonad.html#gaf44692351fd9fe4e76815dfef6ff4478',1,'boost::hana']]], ['extract',['extract',['../group__group-Comonad.html#ga307479a91a21b7ab06a2bc746b003dcc',1,'boost::hana']]] ];
[ ['empty',['empty',['../group__group-MonadPlus.html#gaa6be1e83ad72b9d69b43b4bada0f3a75',1,'boost::hana']]], ['equal',['equal',['../group__group-Comparable.html#gacaf1ebea6b3ab96ac9dcb82f0e64e547',1,'boost::hana']]], ['erase_5fkey',['erase_key',['../structboost_1_1hana_1_1map.html#af856f7bf77f69cdf1b8fd4e566eaef9b',1,'boost::hana::map::erase_key()'],['../structboost_1_1hana_1_1set.html#af856f7bf77f69cdf1b8fd4e566eaef9b',1,'boost::hana::set::erase_key()']]],
dsn.go
// Copyright (c) 2017-2018 Snowflake Computing Inc. All right reserved. package gosnowflake import ( "fmt" "net/url" "strconv" "strings" "time" ) const ( defaultLoginTimeout = 60 * time.Second defaultRequestTimeout = 0 * time.Second defaultAuthenticator = "snowflake" defaultDomain = ".snowflakecomputing.com" ) // Config is a set of configuration parameters type Config struct { Account string // Account name User string // Username Password string // Password (requires User) Database string // Database name Schema string // Schema Warehouse string // Warehouse Role string // Role Region string // Region Params map[string]*string // other connection parameters Protocol string // http or https (optional) Host string // hostname (optional) Port int // port (optional) Authenticator string // snowflake, okta URL, oauth or externalbrowser Passcode string PasscodeInPassword bool LoginTimeout time.Duration // Login timeout RequestTimeout time.Duration // request timeout Application string // application name. InsecureMode bool // driver doesn't check certificate revocation status Token string // Token to use for OAuth / JWT / other forms of token based auth } // DSN constructs a DSN for Snowflake db. func DSN(cfg *Config) (dsn string, err error) { hasHost := true if cfg.Host == "" { hasHost = false if cfg.Region == "" { cfg.Host = cfg.Account + defaultDomain } else { cfg.Host = cfg.Account + "." + cfg.Region + defaultDomain } } // in case account includes region posDot := strings.Index(cfg.Account, ".") if posDot > 0 { cfg.Region = cfg.Account[posDot+1:] cfg.Account = cfg.Account[:posDot] } err = fillMissingConfigParameters(cfg) if err != nil { return "", err } params := &url.Values{} if hasHost && cfg.Account != "" { // account may not be included in a Host string params.Add("account", cfg.Account) } if cfg.Database != "" { params.Add("database", cfg.Database) } if cfg.Schema != "" { params.Add("schema", cfg.Schema) } if cfg.Warehouse != "" { params.Add("warehouse", cfg.Warehouse) } if cfg.Role != "" { params.Add("role", cfg.Role) } if cfg.Region != "" { params.Add("region", cfg.Region) } if cfg.Authenticator != defaultAuthenticator { params.Add("authenticator", strings.ToLower(cfg.Authenticator)) } if cfg.Passcode != "" { params.Add("passcode", cfg.Passcode) } if cfg.PasscodeInPassword { params.Add("passcodeInPassword", strconv.FormatBool(cfg.PasscodeInPassword)) } if cfg.LoginTimeout != defaultLoginTimeout { params.Add("loginTimeout", strconv.FormatInt(int64(cfg.LoginTimeout/time.Second), 10)) } if cfg.RequestTimeout != defaultRequestTimeout { params.Add("requestTimeout", strconv.FormatInt(int64(cfg.RequestTimeout/time.Second), 10)) } if cfg.Application != clientType { params.Add("application", cfg.Application) } if cfg.Protocol != "" && cfg.Protocol != "https" { params.Add("protocol", cfg.Protocol) } if cfg.Token != "" { params.Add("token", cfg.Token) } if cfg.Params != nil { for k, v := range cfg.Params { params.Add(k, *v) } } dsn = fmt.Sprintf("%v:%v@%v:%v", url.QueryEscape(cfg.User), url.QueryEscape(cfg.Password), cfg.Host, cfg.Port) if params.Encode() != "" { dsn += "?" + params.Encode() } return } // ParseDSN parses the DSN string to a Config. func ParseDSN(dsn string) (cfg *Config, err error) { // New config with some default values cfg = &Config{ Params: make(map[string]*string), } // user[:password]@account/database/schema[?param1=value1&paramN=valueN] // or // user[:password]@account/database[?param1=value1&paramN=valueN] // or // user[:password]@host:port/database/schema?account=user_account[?param1=value1&paramN=valueN] // or // host:port/database/schema?account=user_account[?param1=value1&paramN=valueN] foundSlash := false secondSlash := false done := false var i int posQuestion := len(dsn) for i = len(dsn) - 1; i >= 0; i-- { switch { case dsn[i] == '/': foundSlash = true // left part is empty if i <= 0 var j int posSecondSlash := i if i > 0 { for j = i - 1; j >= 0; j-- { switch { case dsn[j] == '/': // second slash secondSlash = true posSecondSlash = j case dsn[j] == '@': // username[:password]@... cfg.User, cfg.Password = parseUserPassword(j, dsn) } if dsn[j] == '@' { break } } // account or host:port err = parseAccountHostPort(cfg, j, posSecondSlash, dsn) if err != nil { return nil, err } } // [?param1=value1&...&paramN=valueN] // Find the first '?' in dsn[i+1:] err = parseParams(cfg, i, dsn) if err != nil { return } if secondSlash { cfg.Database = dsn[posSecondSlash+1 : i] cfg.Schema = dsn[i+1 : posQuestion] } else { cfg.Database = dsn[posSecondSlash+1 : posQuestion] } done = true case dsn[i] == '?': posQuestion = i } if done { break } } if !foundSlash { // no db or schema is specified var j int for j = len(dsn) - 1; j >= 0; j-- { switch { case dsn[j] == '@': cfg.User, cfg.Password = parseUserPassword(j, dsn) case dsn[j] == '?': posQuestion = j } if dsn[j] == '@' { break } } err = parseAccountHostPort(cfg, j, posQuestion, dsn) if err != nil { return nil, err } err = parseParams(cfg, posQuestion-1, dsn) if err != nil { return } } if cfg.Account == "" && strings.HasSuffix(cfg.Host, defaultDomain) { posDot := strings.Index(cfg.Host, ".") if posDot > 0 { cfg.Account = cfg.Host[:posDot] } } err = fillMissingConfigParameters(cfg) if err != nil { return nil, err } // unescape parameters var s string s, err = url.QueryUnescape(cfg.User) if err != nil { return nil, err } cfg.User = s s, err = url.QueryUnescape(cfg.Password) if err != nil { return nil, err } cfg.Password = s s, err = url.QueryUnescape(cfg.Database) if err != nil { return nil, err } cfg.Database = s s, err = url.QueryUnescape(cfg.Schema) if err != nil { return nil, err } cfg.Schema = s s, err = url.QueryUnescape(cfg.Role) if err != nil { return nil, err } cfg.Role = s s, err = url.QueryUnescape(cfg.Warehouse) if err != nil { return nil, err } cfg.Warehouse = s return cfg, nil } func fillMissingConfigParameters(cfg *Config) error { if strings.Trim(cfg.Authenticator, " ") == "" { cfg.Authenticator = defaultAuthenticator } if strings.Trim(cfg.Account, " ") == "" { return ErrEmptyAccount } authenticator := strings.ToUpper(cfg.Authenticator) if authenticator != authenticatorOAuth && strings.Trim(cfg.User, " ") == "" { // oauth does not require a username return ErrEmptyUsername } if authenticator != authenticatorExternalBrowser && authenticator != authenticatorOAuth && strings.Trim(cfg.Password, " ") == "" { // no password parameter is required for EXTERNALBROWSER and OAUTH. return ErrEmptyPassword } if strings.Trim(cfg.Protocol, " ") == "" { cfg.Protocol = "https" } if cfg.Port == 0 { cfg.Port = 443 } cfg.Region = strings.Trim(cfg.Region, " ") if cfg.Region != "" { // region is specified but not included in Host i := strings.Index(cfg.Host, defaultDomain) if i >= 1 { hostPrefix := cfg.Host[0:i] if !strings.HasSuffix(hostPrefix, cfg.Region) { cfg.Host = hostPrefix + "." + cfg.Region + defaultDomain } } } if cfg.LoginTimeout == 0 { cfg.LoginTimeout = defaultLoginTimeout } if cfg.RequestTimeout == 0 { cfg.RequestTimeout = defaultRequestTimeout } if strings.Trim(cfg.Application, " ") == "" { cfg.Application = clientType } if strings.HasSuffix(cfg.Host, defaultDomain) && len(cfg.Host) == len(defaultDomain) { return &SnowflakeError{ Number: ErrCodeFailedToParseHost, Message: errMsgFailedToParseHost, MessageArgs: []interface{}{cfg.Host}, } } return nil } // transformAccountToHost transforms host to accout name func transformAccountToHost(cfg *Config) (err error) { if cfg.Port == 0 && !strings.HasSuffix(cfg.Host, defaultDomain) && cfg.Host != "" { // account name is specified instead of host:port cfg.Account = cfg.Host cfg.Host = cfg.Account + defaultDomain cfg.Port = 443 posDot := strings.Index(cfg.Account, ".") if posDot > 0 { cfg.Region = cfg.Account[posDot+1:] cfg.Account = cfg.Account[:posDot] } } return nil } // parseAccountHostPort parses the DSN string to attempt to get account or host and port. func parseAccountHostPort(cfg *Config, posAt, posSlash int, dsn string) (err error) { // account or host:port var k int for k = posAt + 1; k < posSlash; k++ { if dsn[k] == ':' { cfg.Port, err = strconv.Atoi(dsn[k+1 : posSlash]) if err != nil { err = &SnowflakeError{ Number: ErrCodeFailedToParsePort, Message: errMsgFailedToParsePort, MessageArgs: []interface{}{dsn[k+1 : posSlash]}, } return } break } } cfg.Host = dsn[posAt+1 : k] return transformAccountToHost(cfg) } // parseUserPassword parses the DSN string for username and password func parseUserPassword(posAt int, dsn string) (user, password string) { var k int for k = 0; k < posAt; k++ { if dsn[k] == ':'
} user = dsn[:k] return } // parseParams parse parameters func parseParams(cfg *Config, posQuestion int, dsn string) (err error) { for j := posQuestion + 1; j < len(dsn); j++ { if dsn[j] == '?' { if err = parseDSNParams(cfg, dsn[j+1:]); err != nil { return } break } } return } // parseDSNParams parses the DSN "query string". Values must be url.QueryEscape'ed func parseDSNParams(cfg *Config, params string) (err error) { glog.V(2).Infof("Query String: %v\n", params) for _, v := range strings.Split(params, "&") { param := strings.SplitN(v, "=", 2) if len(param) != 2 { continue } var value string value, err = url.QueryUnescape(param[1]) if err != nil { return err } switch param[0] { // Disable INFILE whitelist / enable all files case "account": cfg.Account = value case "warehouse": cfg.Warehouse = value case "database": cfg.Database = value case "schema": cfg.Schema = value case "role": cfg.Role = value case "region": cfg.Region = value case "protocol": cfg.Protocol = value case "passcode": cfg.Passcode = value case "passcodeInPassword": var vv bool vv, err = strconv.ParseBool(value) if err != nil { return } cfg.PasscodeInPassword = vv case "loginTimeout": var vv int64 vv, err = strconv.ParseInt(value, 10, 64) if err != nil { return } cfg.LoginTimeout = time.Duration(vv * int64(time.Second)) case "application": cfg.Application = value case "authenticator": cfg.Authenticator = strings.ToLower(value) case "insecureMode": var vv bool vv, err = strconv.ParseBool(value) if err != nil { return } cfg.InsecureMode = vv case "token": cfg.Token = value default: if cfg.Params == nil { cfg.Params = make(map[string]*string) } cfg.Params[param[0]] = &value } } return }
{ password = dsn[k+1 : posAt] break }
views.py
from captions.models import Caption from captions.serializers import CaptionSerializer, UserSerializer from rest_framework import generics from django.contrib.auth.models import User from rest_framework import permissions from captions.permissions import IsOwnerOrReadOnly class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView):
class CaptionList(generics.ListCreateAPIView): queryset = Caption.objects.all() serializer_class = CaptionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] # def perform_create(self, serializer): # serializer.save(owner=self.request.user) class CaptionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Caption.objects.all() serializer_class = CaptionSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
queryset = User.objects.all() serializer_class = UserSerializer
main.rs
use noise::*; use clap::Clap; use gre::*; use svg::node::element::*; use svg::node::element::path::Data; #[derive(Clap)] #[clap()] struct
{ #[clap(short, long, default_value = "1521.0")] seed: f64, #[clap(short, long, default_value = "1.0")] amp: f64, #[clap(short, long, default_value = "0.8")] freq: f64, } #[derive(Clone, Copy, Debug)] struct VCircle { x: f64, y: f64, r: f64, } impl VCircle { fn new(x: f64, y: f64, r: f64) -> Self { VCircle { x, y, r } } fn includes(self: &Self, p: (f64, f64)) -> bool { euclidian_dist((self.x,self.y), p) < self.r } } fn waves_in_circle( opts: Opts, circle: &VCircle, ) -> (Vec<Vec<Vec<(f64, f64)>>>, Vec<f64>) { let seed = opts.seed; let mut routes_acc = Vec::new(); let mut routes = Vec::new(); let mut base_y = circle.y + 2. * circle.r; let perlin = Perlin::new(); let mut passage = Passage2DCounter::new(0.4, circle.r * 2.0, circle.r * 2.0); let passage_limit = 10; let mut height_map: Vec<f64> = Vec::new(); loop { if base_y < circle.y - circle.r - 10.0 { break; } let precision = 0.2; let mut route = Vec::new(); let mut x = circle.x - circle.r; let mut was_outside = true; let mut i = 0; loop { if x > circle.x + circle.r { break; } let y = base_y + (circle.r - euclidian_dist((circle.x, circle.y), (x, base_y))) * opts.amp * ( 0.6 * perlin.get([ opts.freq * 0.01 * x, opts.freq * 0.01 * base_y, seed + 1.4 * perlin.get([ opts.freq * (0.04 * base_y + 0.03 * perlin.get([ opts.freq * 1.2 * base_y, opts.freq * 0.5 * x, 100. + 7.3 * seed ])), opts.freq * 0.04 * x, 10. + 0.3 * seed ]) ]) + 1.2 * perlin.get([ opts.freq * 0.009 * x, opts.freq * 0.005 * base_y, -7. + 9. * seed ])); let mut collides = false; if i >= height_map.len() { height_map.push(y); } else { if y > height_map[i] { collides = true; } else { height_map[i] = y; } } let inside = !collides && circle.includes((x, y)) && passage.count(( x - circle.x + circle.r, y - circle.y + circle.r )) < passage_limit; if inside { if was_outside { if route.len() > 2 { routes.push(route); } route = Vec::new(); } was_outside = false; route.push((x, y)); } else { was_outside = true; } x += precision; i += 1; } routes.push(route); if routes_acc.len() == 0 && base_y < circle.y { routes_acc.push(routes); routes = Vec::new(); } base_y -= 0.45; } routes_acc.push(routes); (routes_acc, height_map) } type WaveballRes = (Vec<VCircle>, Vec<Vec<Vec<(f64, f64)>>>); fn waveball(opts: Opts, c: &VCircle) -> WaveballRes { let (waves, _height_map) = waves_in_circle(opts, c); (vec![c.clone()], waves) } fn art(opts: Opts) -> Vec<Group> { let width = 300.0; let height = 240.0; let pad = 10.0; let stroke_width = 0.3; let circle = VCircle::new(width/2.0, height/2.0, height / 2.0 - pad); let (circles, routes_acc) = waveball(opts, &circle); let mut layers = Vec::new(); let colors = vec!["darkblue", "red"]; for (ci, &color) in colors.iter().enumerate() { let mut l = layer(color); if ci == 0 { for c in circles.clone() { l = l.add( Circle::new() .set("r", c.r) .set("cx", c.x) .set("cy", c.y) .set("stroke", color) .set( "stroke-width", stroke_width, ) .set("fill", "none") .set("style", "mix-blend-mode: multiply;") ); } l = l.add(signature( 0.8, (185.0, 224.0), color, )); } let mut data = Data::new(); for (i, routes) in routes_acc.iter().enumerate() { if i % colors.len() == ci { for r in routes.clone() { data = render_route(data, r); } } } l = l.add(base_path(color, stroke_width, data)); layers.push(l); } layers } fn main() { let opts: Opts = Opts::parse(); let groups = art(opts); let mut document = base_24x30_landscape("white"); for g in groups { document = document.add(g); } svg::save("image.svg", &document).unwrap(); }
Opts
cpuacct.rs
// Copyright (c) 2018 Levente Kurusa // // SPDX-License-Identifier: Apache-2.0 or MIT // //! This module contains the implementation of the `cpuacct` cgroup subsystem. //! //! See the Kernel's documentation for more information about this subsystem, found at: //! [Documentation/cgroup-v1/cpuacct.txt](https://www.kernel.org/doc/Documentation/cgroup-v1/cpuacct.txt) use std::io::Write; use std::path::PathBuf; use crate::error::ErrorKind::*; use crate::error::*; use crate::{read_string_from, read_u64_from}; use crate::{ControllIdentifier, ControllerInternal, Controllers, Resources, Subsystem}; /// A controller that allows controlling the `cpuacct` subsystem of a Cgroup. /// /// In essence, this control group provides accounting (hence the name `cpuacct`) for CPU usage of /// the tasks in the control group. #[derive(Debug, Clone)] pub struct CpuAcctController { base: PathBuf, path: PathBuf, } /// Represents the statistics retrieved from the control group. pub struct CpuAcct { /// Divides the time used by the tasks into `user` time and `system` time. pub stat: String, /// Total CPU time (in nanoseconds) spent by the tasks. pub usage: u64, /// Total CPU time (in nanoseconds) spent by the tasks, broken down by CPU and by whether the /// time spent is `user` time or `system` time. /// /// An example is as follows: /// ```text /// cpu user system /// 0 8348363768 0 /// 1 8324369100 0 /// 2 8598185449 0 /// 3 8648262473 0 /// ``` pub usage_all: String, /// CPU time (in nanoseconds) spent by the tasks, broken down by each CPU. /// Times spent in each CPU are separated by a space. pub usage_percpu: String, /// As for `usage_percpu`, but the `system` time spent. pub usage_percpu_sys: String, /// As for `usage_percpu`, but the `user` time spent. pub usage_percpu_user: String, /// CPU time (in nanoseconds) spent by the tasks that counted for `system` time. pub usage_sys: u64, /// CPU time (in nanoseconds) spent by the tasks that counted for `user` time. pub usage_user: u64, } impl ControllerInternal for CpuAcctController { fn control_type(&self) -> Controllers { Controllers::CpuAcct } fn get_path(&self) -> &PathBuf { &self.path } fn get_path_mut(&mut self) -> &mut PathBuf { &mut self.path } fn get_base(&self) -> &PathBuf { &self.base } fn apply(&self, _res: &Resources) -> Result<()> { Ok(()) } } impl ControllIdentifier for CpuAcctController { fn controller_type() -> Controllers
} impl<'a> From<&'a Subsystem> for &'a CpuAcctController { fn from(sub: &'a Subsystem) -> &'a CpuAcctController { unsafe { match sub { Subsystem::CpuAcct(c) => c, _ => { assert_eq!(1, 0); let v = std::mem::MaybeUninit::uninit(); v.assume_init() } } } } } impl CpuAcctController { /// Contructs a new `CpuAcctController` with `root` serving as the root of the control group. pub fn new(root: PathBuf) -> Self { Self { base: root.clone(), path: root, } } /// Gathers the statistics that are available in the control group into a `CpuAcct` structure. pub fn cpuacct(&self) -> CpuAcct { CpuAcct { stat: self .open_path("cpuacct.stat", false) .and_then(read_string_from) .unwrap_or_default(), usage: self .open_path("cpuacct.usage", false) .and_then(read_u64_from) .unwrap_or(0), usage_all: self .open_path("cpuacct.usage_all", false) .and_then(read_string_from) .unwrap_or_default(), usage_percpu: self .open_path("cpuacct.usage_percpu", false) .and_then(read_string_from) .unwrap_or_default(), usage_percpu_sys: self .open_path("cpuacct.usage_percpu_sys", false) .and_then(read_string_from) .unwrap_or_default(), usage_percpu_user: self .open_path("cpuacct.usage_percpu_user", false) .and_then(read_string_from) .unwrap_or_default(), usage_sys: self .open_path("cpuacct.usage_sys", false) .and_then(read_u64_from) .unwrap_or(0), usage_user: self .open_path("cpuacct.usage_user", false) .and_then(read_u64_from) .unwrap_or(0), } } /// Reset the statistics the kernel has gathered about the control group. pub fn reset(&self) -> Result<()> { self.open_path("cpuacct.usage", true).and_then(|mut file| { file.write_all(b"0") .map_err(|e| Error::with_cause(WriteFailed, e)) }) } }
{ Controllers::CpuAcct }
test_args.py
from passgen import args def test_num_words(): mock_argv = ['passgen', '-n', '22'] options = args.get_cli_options(mock_argv) assert 22 == options.num_words mock_argv = ['passgen', '--num-words', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.num_words mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_NUM_WORDS == options.num_words def test_count(): mock_argv = ['passgen', '-c', '22'] options = args.get_cli_options(mock_argv) assert 22 == options.count mock_argv = ['passgen', '--count', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.count mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_COUNT == options.count mock_argv = ['passgen', '--count', '-1'] # negative value ignored options = args.get_cli_options(mock_argv) assert args.DEFAULT_COUNT == options.count def test_min_chars():
def test_max_chars(): mock_argv = ['passgen', '--max-chars', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.max_chars mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_MAX_CHARS == options.max_chars def test_conflicting_min_max_chars(): mock_argv = ['passgen', '--min-chars', '9999', '--max-chars', '11'] options = args.get_cli_options(mock_argv) assert 9999 == options.min_chars assert args.DEFAULT_MAX_CHARS == options.max_chars def test_get_defaults(): options = args.get_default_options() assert args.DEFAULT_COUNT == options.count
mock_argv = ['passgen', '--min-chars', '33'] options = args.get_cli_options(mock_argv) assert 33 == options.min_chars mock_argv = ['passgen'] options = args.get_cli_options(mock_argv) assert args.DEFAULT_MIN_CHARS == options.min_chars
app.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # """ Main application """ import logging as _logging import multiprocessing as _mp import fortworth as _fortworth import wheedle.artifact_poller as _apoller import wheedle.commit_poller as _cpoller import wheedle.configuration as _config import wheedle.errors as _errors # pylint: disable=too-few-public-methods class Application: """ Poller application """ def __init__(self, home, data_dir=None, config_file=None): self._home = home self._log = _logging.getLogger(self.__class__.__name__) self._process_list = [] config_file = config_file if config_file is not None else _fortworth.join(home, 'wheedle.conf') self._config = _config.Configuration(config_file, data_dir) try: _logging.basicConfig(level=self._config['Logging']['default_log_level'], format='%(asctime)s %(name)s - %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %Z') except ValueError as err: raise _errors.ConfigFileError(self._config.config_file_name(), 'Logging', err) self._log.info('Data directory: %s', self._config.data_dir()) def run(self): """ Run the application. This starts each of the configured artifact and commit pollers """ try: self._start_pollers(self._config.poller_names()) # Wait for processes to terminate for process in self._process_list: process.join() except _errors.PollerError as err: self._log.error(err) _fortworth.exit(1) except KeyboardInterrupt: print(' KeyboardInterrupt') self._log.info('exit') def _start_pollers(self, poller_name_list): for poller_name in poller_name_list: ap_event = None if self._config.has_commit_poller(poller_name): ap_event = _mp.Event() self._start_commit_poller(poller_name, ap_event) self._start_artifact_poller(poller_name, ap_event) def _start_artifact_poller(self, name, ap_event): """ Start the named artifact poller """ artifact_poller_process = _mp.Process(target=_apoller.ArtifactPoller.run, args=(self._config, name, ap_event), name=name + '-AP') artifact_poller_process.start() self._process_list.append(artifact_poller_process) def _start_commit_poller(self, name, ap_event): """ Start the named commit poller """ commit_poller_process = _mp.Process(target=_cpoller.CommitPoller.run, args=(self._config, name, ap_event), name=name + '-CP') commit_poller_process.start()
self._process_list.append(commit_poller_process) if __name__ == '__main__': try: APP = Application(_fortworth.current_dir()) APP.run() except _errors.PollerError as err: print(err) _fortworth.exit(1)
genericfun.rs
//! Generic Functions mod gen1 { fn sqr<T>(x: T) -> T::Output where T: std::ops::Mul + Copy, { x * x } pub fn gen1_examples() { let x = sqr(3); let y = sqr(3.0); println!("x={}, y={}", x, y); } }
}
pub fn genericfun_examples() { gen1::gen1_examples();
FaGrinSquintTears.d.ts
// THIS FILE IS AUTO GENERATED import { IconTree, IconType } from '../lib' export declare const FaGrinSquintTears: IconType;
mod.rs
//! A multi-producer, single-consumer queue for sending values across //! asynchronous tasks. //! //! Similar to `std`, channel creation provides [`Receiver`] and [`Sender`] //! handles. [`Receiver`] implements `Stream` and allows a task to read values //! out of the channel. If there is no message to read, the current task will be //! notified when a new value is sent. [`Sender`] implements the `Sink` trait //! and allows sending messages into the channel. If the channel is at capacity, //! the send is rejected and the task will be notified when additional capacity //! is available. In other words, the channel provides backpressure. //! //! Unbounded channels are also available using the `unbounded_channel` //! constructor. //! //! # Disconnection //! //! When all [`Sender`] handles have been dropped, it is no longer //! possible to send values into the channel. This is considered the termination //! event of the stream. As such, `Receiver::poll` returns `Ok(Ready(None))`. //! //! If the [`Receiver`] handle is dropped, then messages can no longer //! be read out of the channel. In this case, all further attempts to send will //! result in an error. //! //! # Clean Shutdown //! //! When the [`Receiver`] is dropped, it is possible for unprocessed messages to //! remain in the channel. Instead, it is usually desirable to perform a "clean" //! shutdown. To do this, the receiver first calls `close`, which will prevent //! any further messages to be sent into the channel. Then, the receiver //! consumes the channel to completion, at which point the receiver can be //! dropped. //! //! [`Sender`]: struct.Sender.html //! [`Receiver`]: struct.Receiver.html pub(super) mod block; mod bounded; pub use self::bounded::{channel, Receiver, Sender}; mod chan; pub(super) mod list; mod unbounded; pub use self::unbounded::{unbounded_channel, UnboundedReceiver, UnboundedSender}; pub mod error; /// The number of values a block can contain. /// /// This value must be a power of 2. It also must be smaller than the number of /// bits in `usize`. #[cfg(all(target_pointer_width = "64", not(loom)))]
#[cfg(loom)] const BLOCK_CAP: usize = 2;
const BLOCK_CAP: usize = 32; #[cfg(all(not(target_pointer_width = "64"), not(loom)))] const BLOCK_CAP: usize = 16;
validate.go
// Copyright 2019 Anapaya Systems // // 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 itopo import ( "reflect" "github.com/google/go-cmp/cmp" "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/serrors" "github.com/scionproto/scion/go/lib/topology" "github.com/scionproto/scion/go/proto" ) type dynDropper interface { // MustDropDynamic indicates whether the dynamic topology shall be dropped. MustDropDynamic(topo, oldTopo *topology.RWTopology) bool } // validator is used to validate that the topology update is permissible. type validator interface { dynDropper // Validate checks that the topology update is valid according to the mutability rules. // The validation rules differ between service types. However, at the very least, it // is checked that topo is not nil and the immutable parts do not change. Validate(topo, oldTopo *topology.RWTopology, allowed bool) error } func validatorFactory(id string, svc proto.ServiceType) validator { switch svc { case proto.ServiceType_unset: return &validatorWrap{&generalValidator{}} case proto.ServiceType_br: // FIXME(roosd): add validator for border router. return &validatorWrap{&brValidator{id: id}} default: // FIMXE(roosd): add validator for service. return &validatorWrap{&svcValidator{id: id, svc: svc}} } } // validatorWrap wraps the internalValidator and implements validator. type validatorWrap struct { internalValidator } // Validate checks that the topology update is valid. func (v *validatorWrap) Validate(topo, oldTopo *topology.RWTopology, allowed bool) error { if err := v.General(topo); err != nil { return err } if err := v.Immutable(topo, oldTopo); err != nil { return err } if err := v.SemiMutable(topo, oldTopo, allowed); err != nil { return err } return nil } type internalValidator interface { dynDropper // General checks that the topology is generally valid. The exact check is implementation // specific to the validator. However, at the very least, this check ensures that the // provided topology is non-nil. General(topo *topology.RWTopology) error // Immutable checks that the immutable parts of the topology do not change. Immutable(topo, oldTopo *topology.RWTopology) error // SemiMutable checks that the semi-mutable parts of the topology update are valid. SemiMutable(topo, oldTopo *topology.RWTopology, allowed bool) error } var _ internalValidator = (*generalValidator)(nil) // generalValidator is used to validate updates if no specific element information // is set. It only checks that the topology is non-nil and the immutable fields are // not modified. type generalValidator struct{} func (v *generalValidator) General(topo *topology.RWTopology) error { if topo == nil { return serrors.New("Topo must not be nil") } return nil } func (v *generalValidator) Immutable(topo, oldTopo *topology.RWTopology) error { if oldTopo == nil { return nil } if !topo.IA.Equal(oldTopo.IA) { return common.NewBasicError("IA is immutable", nil, "expected", oldTopo.IA, "actual", topo.IA) } if !topo.Attributes.Equal(oldTopo.Attributes) { return common.NewBasicError("Attributes are immutable", nil, "expected", oldTopo.Attributes, "actual", topo.Attributes) } if topo.MTU != oldTopo.MTU { return common.NewBasicError("MTU is immutable", nil, "expected", oldTopo.MTU, "actual", topo.MTU) } return nil } func (*generalValidator) SemiMutable(_, _ *topology.RWTopology, _ bool) error { return nil } func (*generalValidator) MustDropDynamic(_, _ *topology.RWTopology) bool { return false } var _ internalValidator = (*svcValidator)(nil) // svcValidator is used to validate updates if the element is a infra service. // It checks that the service is present, and only permissible updates are done. type svcValidator struct { generalValidator id string svc proto.ServiceType } func (v *svcValidator) General(topo *topology.RWTopology) error { if err := v.generalValidator.General(topo); err != nil { return err } if _, err := topo.GetTopoAddr(v.id, v.svc); err != nil { return common.NewBasicError("Topo must contain service", nil, "id", v.id, "svc", v.svc) } return nil } func (v *svcValidator) Immutable(topo, oldTopo *topology.RWTopology) error { if oldTopo == nil { return nil } if err := v.generalValidator.Immutable(topo, oldTopo); err != nil { return err } // We already checked that the service is in the map. nAddr, _ := topo.GetTopoAddr(v.id, v.svc) oAddr, _ := oldTopo.GetTopoAddr(v.id, v.svc) // FIXME(scrye): The equality check below is protocol specific. Use reflect.DeepEqual for now, // but it's better to define what "entry must not change" actually means w.r.t. all possible // internal addresses. if !reflect.DeepEqual(nAddr, oAddr) { return common.NewBasicError("Local service entry must not change", nil, "id", v.id, "svc", v.svc, "expected", oAddr, "actual", nAddr) } return nil } var _ internalValidator = (*brValidator)(nil) // brValidator is used to validate updates if the element is a border router. // It checks that the border router is present, and only permissible updates // are done. type brValidator struct { generalValidator id string } func (v *brValidator) General(topo *topology.RWTopology) error { if err := v.generalValidator.General(topo); err != nil
if _, ok := topo.BR[v.id]; !ok { return common.NewBasicError("Topo must contain border router", nil, "id", v.id) } return nil } func (v *brValidator) Immutable(topo, oldTopo *topology.RWTopology) error { if oldTopo == nil { return nil } if err := v.generalValidator.Immutable(topo, oldTopo); err != nil { return err } if topo.BR[v.id].InternalAddr.String() != oldTopo.BR[v.id].InternalAddr.String() { return common.NewBasicError("InternalAddrs is immutable", nil, "expected", oldTopo.BR[v.id].InternalAddr, "actual", topo.BR[v.id].InternalAddr) } if !reflect.DeepEqual(topo.BR[v.id].CtrlAddrs, oldTopo.BR[v.id].CtrlAddrs) { return common.NewBasicError("CtrlAddrs is immutable", nil, "expected", oldTopo.BR[v.id].CtrlAddrs, "actual", topo.BR[v.id].CtrlAddrs) } return nil } func (v *brValidator) SemiMutable(topo, oldTopo *topology.RWTopology, allowed bool) error { if oldTopo == nil { return nil } if !allowed && v.interfacesChanged(topo, oldTopo) { return common.NewBasicError("IFID set changed", nil, "expected", oldTopo.BR[v.id].IFIDs, "actual", topo.BR[v.id].IFIDs) } return nil } func (v *brValidator) MustDropDynamic(topo, oldTopo *topology.RWTopology) bool { if oldTopo == nil { return false } return v.interfacesChanged(topo, oldTopo) } func (v *brValidator) interfacesChanged(topo, oldTopo *topology.RWTopology) bool { if v.interfaceSetChanged(topo, oldTopo) { return true } for _, ifid := range topo.BR[v.id].IFIDs { if !cmp.Equal(topo.IFInfoMap[ifid], oldTopo.IFInfoMap[ifid]) { return true } } return false } func (v *brValidator) interfaceSetChanged(topo, oldTopo *topology.RWTopology) bool { if len(topo.BR[v.id].IFIDs) != len(oldTopo.BR[v.id].IFIDs) { return true } // The interfaces are sorted. for i, ifid := range topo.BR[v.id].IFIDs { if ifid != oldTopo.BR[v.id].IFIDs[i] { return true } } return false }
{ return err }
m_js_controller.js
(function(_){var aa,ga,ha;_.l=function(a){return function(){return aa[a].apply(this,arguments)}};_.n=function(a,b){return aa[a]=b};_.ba=function(a){return"function"===typeof window.encodeURIComponent?(0,window.encodeURIComponent)(a):(0,window.escape)(a)};aa=[];_.p=this;_.q=function(a){return void 0!==a};_.r=function(a,b,c){a=a.split(".");c=c||_.p;a[0]in c||!c.execScript||c.execScript("var "+a[0]);for(var d;a.length&&(d=a.shift());)!a.length&&_.q(b)?c[d]=b:c=c[d]?c[d]:c[d]={}};_.t=function(){};_.ca=function(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";else if("function"==b&&"undefined"==typeof a.call)return"object";return b};_.ea=function(a){return"array"==_.ca(a)};_.v=function(a){return"string"==typeof a};_.w=function(a){return"number"==typeof a};_.x=function(a){return"function"==_.ca(a)};_.fa=function(a){var b=typeof a;return"object"==b&&null!=a||"function"==b};ga=function(a,b,c){return a.call.apply(a.bind,arguments)};ha=function(a,b,c){if(!a)throw Error();if(2<arguments.length){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(c,d);return a.apply(b,c)}}return function(){return a.apply(b,arguments)}};_.y=function(a,b,c){_.y=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ga:ha;return _.y.apply(null,arguments)};_.ia=function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var b=c.slice();b.push.apply(b,arguments);return a.apply(this,b)}};_.A=Date.now||function(){return+new Date};_.B=function(a,b){function
(){}c.prototype=b.prototype;a.I=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.LC=function(a,c,f){for(var h=Array(arguments.length-2),k=2;k<arguments.length;k++)h[k-2]=arguments[k];return b.prototype[c].apply(a,h)}};_.ka=function(a,b){a[b]||(a[b]=[]);return a[b]};_.la=function(a,b){return a[b]?a[b].length:0};_.ma=function(a,b,c){for(var d in a)b.call(c,a[d],d,a)};_.na=function(a){var b=[],c=0,d;for(d in a)b[c++]=a[d];return b};_.oa=function(a){var b=[],c=0,d;for(d in a)b[c++]=d;return b};var pa;var ua,ya;_.qa=function(a,b){var c=a.length-b.length;return 0<=c&&a.indexOf(b,c)==c};_.ra=String.prototype.trim?function(a){return a.trim()}:function(a){return a.replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")};_.sa=function(a,b){return-1!=a.toLowerCase().indexOf(b.toLowerCase())};_.ta=String.prototype.repeat?function(a,b){return a.repeat(b)}:function(a,b){return Array(b+1).join(a)};_.va=function(a,b){for(var c=0,d=(0,_.ra)(String(a)).split("."),e=(0,_.ra)(String(b)).split("."),f=Math.max(d.length,e.length),h=0;0==c&&h<f;h++){var k=d[h]||"",m=e[h]||"",u=RegExp("(\\d*)(\\D*)","g"),z=RegExp("(\\d*)(\\D*)","g");do{var G=u.exec(k)||["","",""],U=z.exec(m)||["","",""];if(0==G[0].length&&0==U[0].length)break;c=ua(0==G[1].length?0:(0,window.parseInt)(G[1],10),0==U[1].length?0:(0,window.parseInt)(U[1],10))||ua(0==G[2].length,0==U[2].length)||ua(G[2],U[2])}while(0==c)}return c};ua=function(a,b){return a<b?-1:a>b?1:0};_.wa=2147483648*Math.random()|0;_.xa=function(a){return String(a).replace(/\-([a-z])/g,function(a,c){return c.toUpperCase()})};ya=function(a){var b=_.v(void 0)?"undefined".replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08"):"\\s";return a.replace(new RegExp("(^"+(b?"|["+b+"]+":"")+")([a-z])","g"),function(a,b,e){return b+e.toUpperCase()})};_.za=function(a){this.g=a||[]};_.za.prototype.$=function(){return this.g};_.za.prototype.im=function(){var a=this.g[8];return null!=a?a:""};_.za.prototype.po=_.l(0);_.Aa=function(a){this.g=a||[]};_.Ba=function(a){this.g=a||[]};_.Ca=new _.Aa;_.Da=new _.Ba;_.Aa.prototype.$=function(){return this.g};_.g=_.Ba.prototype;_.g.$=function(){return this.g};_.g.zm=_.l(1);_.g.getDuration=function(){var a=this.g[0];return null!=a?a:300};_.g.kh=function(){var a=this.g[3];return null!=a?a:1};_.g.mm=function(){var a=this.g[4];return null!=a?a:0};var Fa,Ga,Ka,Ma,Oa,Za,ab,bb,cb,db,eb,jb,kb,wb,xb,yb,zb,Bb,Cb;_.Ea=function(a){this.g=a||[]};Fa=function(a){this.g=a||[]};Ga=function(a){this.g=a||[]};_.Ha=function(a){this.g=a||[]};_.Ia=function(a){this.g=a||[]};_.Ja=function(a){this.g=a||[]};Ka=function(a){this.g=a||[]};_.La=function(a){this.g=a||[]};Ma=function(a){this.g=a||[]};_.Na=function(a){this.g=a||[]};Oa=function(a){this.g=a||[]};_.Pa=function(a){this.g=a||[]};_.Qa=function(a){this.g=a||[]};_.Ra=function(a){this.g=a||[]};_.Sa=function(a){this.g=a||[]};_.Ua=function(a){this.g=a||[]};_.Ea.prototype.$=function(){return this.g};_.Ea.prototype.getWidth=function(){var a=this.g[1];return null!=a?a:0};_.Ea.prototype.getHeight=function(){var a=this.g[2];return null!=a?a:0};_.Va=function(a){a=a.g[3];return null!=a?a:!1};_.Wa=function(a){a=a.g[4];return null!=a?a:!1};_.g=_.Ea.prototype;_.g.getEscapedQemQueryId=function(){var a=this.g[6];return null!=a?a:""};_.g.getEscapedGwsQueryId=function(){var a=this.g[7];return null!=a?a:""};_.g.getWebProperty=function(){var a=this.g[9];return null!=a?a:""};_.g.hh=_.l(3);_.g.gh=_.l(5);var Xa=function(a){a=a.g[12];return null!=a?a:!1};_.Ea.prototype.kf=_.l(7);_.Ea.prototype.jf=_.l(9);_.Ea.prototype.hf=_.l(11);_.Ya=new _.Ha;Za=new _.Na;ab=function(a){return(a=a.g[8])?new _.Na(a):Za};bb=new Oa;cb=function(a){return(a=a.g[15])?new Oa(a):bb};db=new Ga;eb=function(a){return(a=a.g[23])?new Ga(a):db};_.fb=new _.Pa;_.Ea.prototype.fh=_.l(13);_.gb=new _.Qa;_.ib=new _.Ia;jb=new Fa;kb=function(a){return(a=a.g[27])?new Fa(a):jb};_.nb=new _.Sa;_.ob=new _.Ua;_.Ea.prototype.getAds=function(a){return new _.Ja(_.ka(this.g,0)[a])};_.Ea.prototype.fe=_.l(15);Fa.prototype.$=function(){return this.g};var pb=function(a){a=a.g[0];return null!=a?a:!1},qb=function(a){a=a.g[1];return null!=a?a:!1},rb=function(a){a=a.g[2];return null!=a?a:!1},sb=function(a){a=a.g[3];return null!=a?a:!1},ub=function(a){a=a.g[4];return null!=a?a:!1};Ga.prototype.$=function(){return this.g};_.g=_.Ha.prototype;_.g.$=function(){return this.g};_.g.km=function(){var a=this.g[0];return null!=a?a:!1};_.g.lm=function(){var a=this.g[1];return null!=a?a:!1};_.g.jm=function(){var a=this.g[2];return null!=a?a:!1};_.g.nm=function(){var a=this.g[4];return null!=a?a:!1};_.g=_.Ia.prototype;_.g.$=function(){return this.g};_.g.km=function(){var a=this.g[4];return null!=a?a:!1};_.g.lm=function(){var a=this.g[5];return null!=a?a:!1};_.g.jm=function(){var a=this.g[6];return null!=a?a:!1};_.g.nm=function(){var a=this.g[7];return null!=a?a:!1};_.g=_.Ja.prototype;_.g.$=function(){return this.g};_.g.getType=_.l(18);_.g.getIndex=function(){var a=this.g[1];return null!=a?a:0};_.g.getWidth=function(){var a=this.g[2];return null!=a?a:0};_.g.getHeight=function(){var a=this.g[3];return null!=a?a:0};var vb=function(a){a=a.g[4];return null!=a?a:""};_.Ja.prototype.im=function(){var a=this.g[5];return null!=a?a:""};_.Ja.prototype.dj=function(){var a=this.g[7];return null!=a?a:""};wb=function(a){a=a.g[10];return null!=a?a:!1};xb=function(a){a=a.g[14];return null!=a?a:""};yb=function(a){a=a.g[15];return null!=a?a:""};zb=new Ma;_.Ab=function(a){return(a=a.g[8])?new Ma(a):zb};Bb=new Ka;Cb=function(a){return(a=a.g[9])?new Ka(a):Bb};_.Db=new _.La;Ka.prototype.$=function(){return this.g};Ka.prototype.dj=function(){var a=this.g[0];return null!=a?a:""};var Eb=function(a){a=a.g[2];return null!=a?a:""};_.La.prototype.$=function(){return this.g};_.Fb=new _.za;Ma.prototype.$=function(){return this.g};_.Gb=function(a){a=a.g[2];return null!=a?a:""};_.Na.prototype.$=function(){return this.g};_.Na.prototype.ym=_.l(19);_.Na.prototype.hm=function(){var a=this.g[0];return null!=a?a:""};var Hb=function(a){a=a.g[1];return null!=a?a:!1},Ib=function(a){a=a.g[2];return null!=a?a:!1},Jb=function(a){a=a.g[3];return null!=a?a:!1};Oa.prototype.$=function(){return this.g};var Kb=function(a){a=a.g[0];return null!=a?a:!1};_.Pa.prototype.$=function(){return this.g};_.Qa.prototype.$=function(){return this.g};_.Lb=new _.Ra;_.Ra.prototype.$=function(){return this.g};_.Sa.prototype.$=function(){return this.g};_.Ua.prototype.$=function(){return this.g};var Sb,$b;_.Nb=Array.prototype.indexOf?function(a,b,c){return Array.prototype.indexOf.call(a,b,c)}:function(a,b,c){c=null==c?0:0>c?Math.max(0,a.length+c):c;if(_.v(a))return _.v(b)&&1==b.length?a.indexOf(b,c):-1;for(;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1};_.Ob=Array.prototype.lastIndexOf?function(a,b,c){return Array.prototype.lastIndexOf.call(a,b,null==c?a.length-1:c)}:function(a,b,c){c=null==c?a.length-1:c;0>c&&(c=Math.max(0,a.length+c));if(_.v(a))return _.v(b)&&1==b.length?a.lastIndexOf(b,c):-1;for(;0<=c;c--)if(c in a&&a[c]===b)return c;return-1};_.C=Array.prototype.forEach?function(a,b,c){Array.prototype.forEach.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)f in e&&b.call(c,e[f],f,a)};_.Pb=Array.prototype.filter?function(a,b,c){return Array.prototype.filter.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=[],f=0,h=_.v(a)?a.split(""):a,k=0;k<d;k++)if(k in h){var m=h[k];b.call(c,m,k,a)&&(e[f++]=m)}return e};_.Qb=Array.prototype.map?function(a,b,c){return Array.prototype.map.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=Array(d),f=_.v(a)?a.split(""):a,h=0;h<d;h++)h in f&&(e[h]=b.call(c,f[h],h,a));return e};_.Rb=Array.prototype.some?function(a,b,c){return Array.prototype.some.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return!0;return!1};Sb=Array.prototype.every?function(a,b,c){return Array.prototype.every.call(a,b,c)}:function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&!b.call(c,e[f],f,a))return!1;return!0};_.Ub=function(a,b){var c=_.Tb(a,b,void 0);return 0>c?null:_.v(a)?a.charAt(c):a[c]};_.Tb=function(a,b,c){for(var d=a.length,e=_.v(a)?a.split(""):a,f=0;f<d;f++)if(f in e&&b.call(c,e[f],f,a))return f;return-1};_.Vb=function(a,b){return 0<=(0,_.Nb)(a,b)};_.Xb=function(a,b){var c=(0,_.Nb)(a,b),d;(d=0<=c)&&_.Wb(a,c);return d};_.Wb=function(a,b){Array.prototype.splice.call(a,b,1)};_.Yb=function(a){return Array.prototype.concat.apply(Array.prototype,arguments)};_.Zb=function(a){var b=a.length;if(0<b){for(var c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}return[]};$b=function(a,b){return a>b?1:a<b?-1:0};a:{var bc=_.p.navigator;if(bc){var cc=bc.userAgent;if(cc){_.ac=cc;break a}}_.ac=""}_.D=function(a){return-1!=_.ac.indexOf(a)};var dc=function(){return _.D("Opera")||_.D("OPR")},ec=function(){return(_.D("Chrome")||_.D("CriOS"))&&!dc()&&!_.D("Edge")};var fc=function(a){_.p.setTimeout(function(){throw a;},0)},gc,hc=function(){var a=_.p.MessageChannel;"undefined"===typeof a&&"undefined"!==typeof window&&window.postMessage&&window.addEventListener&&!_.D("Presto")&&(a=function(){var a=window.document.createElement("IFRAME");a.style.display="none";a.src="";window.document.documentElement.appendChild(a);var b=a.contentWindow,a=b.document;a.open();a.write("");a.close();var c="callImmediate"+Math.random(),d="file:"==b.location.protocol?"*":b.location.protocol+"//"+b.location.host,a=(0,_.y)(function(a){if(("*"==d||a.origin==d)&&a.data==c)this.port1.onmessage()},this);b.addEventListener("message",a,!1);this.port1={};this.port2={postMessage:function(){b.postMessage(c,d)}}});if("undefined"!==typeof a&&!_.D("Trident")&&!_.D("MSIE")){var b=new a,c={},d=c;b.port1.onmessage=function(){if(_.q(c.next)){c=c.next;var a=c.Tp;c.Tp=null;a()}};return function(a){d.next={Tp:a};d=d.next;b.port2.postMessage(0)}}return"undefined"!==typeof window.document&&"onreadystatechange"in window.document.createElement("SCRIPT")?function(a){var b=window.document.createElement("SCRIPT");b.onreadystatechange=function(){b.onreadystatechange=null;b.parentNode.removeChild(b);b=null;a();a=null};window.document.documentElement.appendChild(b)}:function(a){_.p.setTimeout(a,0)}};var ic=function(a,b,c){this.sy=c;this.Cv=a;this.Gd=b;this.Ij=0;this.kj=null};ic.prototype.get=function(){var a;0<this.Ij?(this.Ij--,a=this.kj,this.kj=a.next,a.next=null):a=this.Cv();return a};ic.prototype.put=function(a){this.Gd(a);this.Ij<this.sy&&(this.Ij++,a.next=this.kj,this.kj=a)};var jc=function(){this.cl=this.gg=null},lc=new ic(function(){return new kc},function(a){a.reset()},100);jc.prototype.add=function(a,b){var c=lc.get();c.set(a,b);this.cl?this.cl.next=c:this.gg=c;this.cl=c};jc.prototype.remove=function(){var a=null;this.gg&&(a=this.gg,this.gg=this.gg.next,this.gg||(this.cl=null),a.next=null);return a};var kc=function(){this.next=this.scope=this.gm=null};kc.prototype.set=function(a,b){this.gm=a;this.scope=b;this.next=null};kc.prototype.reset=function(){this.next=this.scope=this.gm=null};var rc=function(a,b){mc||nc();oc||(mc(),oc=!0);qc.add(a,b)},mc,nc=function(){if(_.p.Promise&&_.p.Promise.resolve){var a=_.p.Promise.resolve(void 0);mc=function(){a.then(sc)}}else mc=function(){var a=sc;!_.x(_.p.setImmediate)||_.p.Window&&_.p.Window.prototype&&!_.D("Edge")&&_.p.Window.prototype.setImmediate==_.p.setImmediate?(gc||(gc=hc()),gc(a)):_.p.setImmediate(a)}},oc=!1,qc=new jc,sc=function(){for(var a=null;a=qc.remove();){try{a.gm.call(a.scope)}catch(b){fc(b)}lc.put(a)}oc=!1};_.E=function(){this.af=this.af;this.xe=this.xe};_.E.prototype.af=!1;_.E.prototype.N=_.l(20);_.E.prototype.D=_.l(22);_.tc=function(a){_.E.call(this);this.tr=1;this.Sj=[];this.fk=0;this.Ra=[];this.jc={};this.cv=Boolean(a)};_.B(_.tc,_.E);_.tc.prototype.subscribe=function(a,b,c){var d=this.jc[a];d||(d=this.jc[a]=[]);var e=this.tr;this.Ra[e]=a;this.Ra[e+1]=b;this.Ra[e+2]=c;this.tr=e+3;d.push(e);return e};_.tc.prototype.unsubscribe=function(a,b,c){if(a=this.jc[a]){var d=this.Ra;if(a=_.Ub(a,function(a){return d[a+1]==b&&d[a+2]==c}))return this.$o(a)}return!1};_.tc.prototype.$o=function(a){var b=this.Ra[a];if(b){var c=this.jc[b];0!=this.fk?(this.Sj.push(a),this.Ra[a+1]=_.t):(c&&_.Xb(c,a),delete this.Ra[a],delete this.Ra[a+1],delete this.Ra[a+2])}return!!b};_.tc.prototype.zs=function(a,b){var c=this.jc[a];if(c){for(var d=Array(arguments.length-1),e=1,f=arguments.length;e<f;e++)d[e-1]=arguments[e];if(this.cv)for(e=0;e<c.length;e++){var h=c[e];uc(this.Ra[h+1],this.Ra[h+2],d)}else{this.fk++;try{for(e=0,f=c.length;e<f;e++)h=c[e],this.Ra[h+1].apply(this.Ra[h+2],d)}finally{if(this.fk--,0<this.Sj.length&&0==this.fk)for(;c=this.Sj.pop();)this.$o(c)}}}};var uc=function(a,b,c){rc(function(){a.apply(b,c)})};_.tc.prototype.clear=_.l(27);_.tc.prototype.ra=_.l(32);_.tc.prototype.D=_.l(21);_.F=function(a,b,c,d){a.addEventListener?a.addEventListener(b,c,d||!1):a.attachEvent&&a.attachEvent("on"+b,c)};_.vc=function(a,b,c){a.removeEventListener?a.removeEventListener(b,c,!1):a.detachEvent&&a.detachEvent("on"+b,c)};_.wc=function(a,b,c){return Math.min(Math.max(a,b),c)};_.H=function(a,b){this.x=_.q(a)?a:0;this.y=_.q(b)?b:0};_.g=_.H.prototype;_.g.clone=function(){return new _.H(this.x,this.y)};_.g.floor=function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this};_.g.round=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this};_.g.translate=_.l(35);_.g.scale=_.l(39);_.xc=function(a){_.xc[" "](a);return a};_.xc[" "]=_.t;_.I=function(a,b){this.width=a;this.height=b};_.g=_.I.prototype;_.g.clone=function(){return new _.I(this.width,this.height)};_.g.uc=_.l(40);_.g.Cb=_.l(44);_.g.floor=function(){this.width=Math.floor(this.width);this.height=Math.floor(this.height);return this};_.g.round=function(){this.width=Math.round(this.width);this.height=Math.round(this.height);return this};_.g.scale=_.l(38);_.yc=function(){return _.D("iPhone")&&!_.D("iPod")&&!_.D("iPad")};var Hc,Ic,Kc,Mc;_.zc=dc();_.J=_.D("Trident")||_.D("MSIE");_.Ac=_.D("Edge");_.Bc=_.D("Gecko")&&!(_.sa(_.ac,"WebKit")&&!_.D("Edge"))&&!(_.D("Trident")||_.D("MSIE"))&&!_.D("Edge");_.Cc=_.sa(_.ac,"WebKit")&&!_.D("Edge");_.Dc=_.D("Macintosh");_.Ec=_.D("Android");_.Fc=_.yc();_.Gc=_.D("iPad");Hc=function(){var a=_.ac;if(_.Bc)return/rv\:([^\);]+)(\)|;)/.exec(a);if(_.Ac)return/Edge\/([\d\.]+)/.exec(a);if(_.J)return/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);if(_.Cc)return/WebKit\/(\S+)/.exec(a)};Ic=function(){var a=_.p.document;return a?a.documentMode:void 0};_.Jc=function(){if(_.zc&&_.p.opera){var a;var b=_.p.opera.version;try{a=b()}catch(c){a=b}return a}a="";(b=Hc())&&(a=b?b[1]:"");return _.J&&(b=Ic(),b>(0,window.parseFloat)(a))?String(b):a}();Kc={};_.Lc=function(a){return Kc[a]||(Kc[a]=0<=_.va(_.Jc,a))};Mc=_.p.document;_.Nc=Mc&&_.J?Ic()||("CSS1Compat"==Mc.compatMode?(0,window.parseInt)(_.Jc,10):5):void 0;_.Oc=!_.J||9<=Number(_.Nc);!_.Bc&&!_.J||_.J&&9<=Number(_.Nc)||_.Bc&&_.Lc("1.9.1");_.Pc=_.J&&!_.Lc("9");_.Vc=function(a){return a?new _.Tc(_.Uc(a)):pa||(pa=new _.Tc)};_.Wc=function(a,b){return _.v(b)?a.getElementById(b):b};_.Xc=function(a,b,c,d){a=d||a;b=b&&"*"!=b?b.toUpperCase():"";if(a.querySelectorAll&&a.querySelector&&(b||c))return a.querySelectorAll(b+(c?"."+c:""));if(c&&a.getElementsByClassName){a=a.getElementsByClassName(c);if(b){d={};for(var e=0,f=0,h;h=a[f];f++)b==h.nodeName&&(d[e++]=h);d.length=e;return d}return a}a=a.getElementsByTagName(b||"*");if(c){d={};for(f=e=0;h=a[f];f++)b=h.className,"function"==typeof b.split&&_.Vb(b.split(/\s+/),c)&&(d[e++]=h);d.length=e;return d}return a};_.Yc=function(a){for(var b;b=a.firstChild;)a.removeChild(b)};_.Zc=function(a,b){if(!a||!b)return!1;if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if("undefined"!=typeof a.compareDocumentPosition)return a==b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a};_.Uc=function(a){return 9==a.nodeType?a:a.ownerDocument||a.document};_.Tc=function(a){this.za=a||_.p.document||window.document};_.g=_.Tc.prototype;_.g.lf=_.Vc;_.g.sa=function(a){return _.Wc(this.za,a)};_.g.Tb=_.l(48);_.g.createElement=function(a){return this.za.createElement(a)};_.g.createTextNode=_.l(45);_.g.appendChild=function(a,b){a.appendChild(b)};_.g.ao=_.Yc;_.g.contains=_.Zc;var ad;_.K=function(a,b,c){if(_.v(b))(b=_.$c(a,b))&&(a.style[b]=c);else for(var d in b){c=a;var e=b[d],f=_.$c(c,d);f&&(c.style[f]=e)}};ad={};_.$c=function(a,b){var c=ad[b];if(!c){var d=_.xa(b),c=d;void 0===a.style[d]&&(d=(_.Cc?"Webkit":_.Bc?"Moz":_.J?"ms":_.zc?"O":null)+ya(d),void 0!==a.style[d]&&(c=d));ad[b]=c}return c};_.bd=function(a,b){var c=_.Uc(a);return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defaultView.getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||"":""};_.cd=function(a,b){return _.bd(a,b)||(a.currentStyle?a.currentStyle[b]:null)||a.style&&a.style[b]};_.dd=function(a){var b;try{b=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:0}}_.J&&a.ownerDocument.body&&(a=a.ownerDocument,b.left-=a.documentElement.clientLeft+a.body.clientLeft,b.top-=a.documentElement.clientTop+a.body.clientTop);return b};_.ed=function(a){a=_.dd(a);return new _.H(a.left,a.top)};var hd;_.fd=function(a,b,c){for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&b.call(c,a[d],d,a)};hd=function(){var a=gd;if(!a)return"";var b=/.*[&#?]google_debug(=[^&]*)?(&.*)?$/;try{var c=b.exec((0,window.decodeURIComponent)(a));if(c)return c[1]&&1<c[1].length?c[1].substring(1):"true"}catch(d){}return""};var kd,id;kd=function(a,b,c,d,e,f){try{if((d?a.pA:Math.random())<(e||a.Jv)){var h=a.fv+b+id(c),h=h.substring(0,2E3);"undefined"===typeof f?_.jd(_.p,h):_.jd(_.p,h,f)}}catch(k){}};id=function(a){var b="";_.fd(a,function(a,d){if(0===a||a)b+="&"+d+"="+(0,window.encodeURIComponent)(String(a))});return b};_.jd=function(a,b,c){a.google_image_requests||(a.google_image_requests=[]);var d=a.document.createElement("img");if(c){var e=function(a){c(a);_.vc(d,"load",e);_.vc(d,"error",e)};_.F(d,"load",e);_.F(d,"error",e)}d.src=b;a.google_image_requests.push(d)};_.L=window.document;_.M=window;var ld,nd;ld=Object.prototype.hasOwnProperty;_.md=function(a,b){for(var c in a)ld.call(a,c)&&b.call(void 0,a[c],c,a)};nd=function(a,b,c,d,e,f){var h;if(!h)a:{if(1===a.nodeType)try{if(1==a.nodeType)h=_.ed(a);else{var k=a.changedTouches?a.changedTouches[0]:a;h=new _.H(k.clientX,k.clientY)}break a}catch(m){}h=new _.H(0,0)}if(window.document.createEvent)k=window.document.createEvent("MouseEvents"),k.initMouseEvent(b,!0,!0,null,0,h.x,h.y,h.x,h.y,d,void 0,e,f,c,null);else if(window.document.createEventObject)k=window.document.createEventObject(),k.Wl="on"+b,k.button=c,k.ctrlKey=d,k.altKey=void 0,k.shiftKey=e,k.metaKey=f,k.clientX=h.x,k.clientY=h.y,k.screenX=h.x,k.screenY=h.y;else return!1;if(a.dispatchEvent)a.dispatchEvent(k);else if(a.fireEvent)a.fireEvent(k.Wl,k);else return!1;return!0};_.od=!!window.google_async_iframe_id;_.pd=_.od&&window.parent||window;_.qd=function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};_.rd=function(a){return a.preventDefault?a.defaultPrevented:!1===a.returnValue};var td=function(a,b){this.Kd=0;this.Js=void 0;this.Fi=this.Pe=this.L=null;this.gj=this.Xl=!1;if(a!=_.t)try{var c=this;a.call(b,function(a){sd(c,2,a)},function(a){sd(c,3,a)})}catch(d){sd(this,3,d)}},ud=function(){this.next=this.context=this.Lf=this.zh=this.Re=null;this.ll=!1};ud.prototype.reset=function(){this.context=this.Lf=this.zh=this.Re=null;this.ll=!1};var vd=new ic(function(){return new ud},function(a){a.reset()},100),wd=function(a,b,c){var d=vd.get();d.zh=a;d.Lf=b;d.context=c;return d},yd=function(a,b,c){xd(a,b,c,null)||rc(_.ia(b,a))},zd=function(a){return new td(function(b,c){a.length||b(void 0);for(var d=0,e;d<a.length;d++)e=a[d],yd(e,b,c)})},Ad=function(a){return new td(function(b,c){var d=a.length,e=[];if(d)for(var f=function(a,c){d--;e[a]=c;0==d&&b(e)},h=function(a){c(a)},k=0,m;k<a.length;k++)m=a[k],yd(m,_.ia(f,k),h);else b(e)})};td.prototype.then=function(a,b,c){return Bd(this,_.x(a)?a:null,_.x(b)?b:null,c)};td.prototype.then=td.prototype.then;td.prototype.$goog_Thenable=!0;var Dd=function(a,b){a.Pe||2!=a.Kd&&3!=a.Kd||Cd(a);a.Fi?a.Fi.next=b:a.Pe=b;a.Fi=b},Bd=function(a,b,c,d){var e=wd(null,null,null);e.Re=new td(function(a,h){e.zh=b?function(c){try{var e=b.call(d,c);a(e)}catch(u){h(u)}}:a;e.Lf=c?function(b){try{var e=c.call(d,b);a(e)}catch(u){h(u)}}:h});e.Re.L=a;Dd(a,e);return e.Re};td.prototype.RA=function(a){this.Kd=0;sd(this,2,a)};td.prototype.SA=function(a){this.Kd=0;sd(this,3,a)};var sd=function(a,b,c){0==a.Kd&&(a==c&&(b=3,c=new TypeError("Promise cannot resolve to itself")),a.Kd=1,xd(c,a.RA,a.SA,a)||(a.Js=c,a.Kd=b,a.L=null,Cd(a),3!=b||Ed(a,c)))},xd=function(a,b,c,d){if(a instanceof td)return Dd(a,wd(b||_.t,c||null,d)),!0;var e;if(a)try{e=!!a.$goog_Thenable}catch(h){e=!1}else e=!1;if(e)return a.then(b,c,d),!0;if(_.fa(a))try{var f=a.then;if(_.x(f))return Fd(a,f,b,c,d),!0}catch(h){return c.call(d,h),!0}return!1},Fd=function(a,b,c,d,e){var f=!1,h=function(a){f||(f=!0,c.call(e,a))},k=function(a){f||(f=!0,d.call(e,a))};try{b.call(a,h,k)}catch(m){k(m)}},Cd=function(a){a.Xl||(a.Xl=!0,rc(a.fw,a))},Gd=function(a){var b=null;a.Pe&&(b=a.Pe,a.Pe=b.next,b.next=null);a.Pe||(a.Fi=null);return b};td.prototype.fw=function(){for(var a=null;a=Gd(this);){var b=this.Kd,c=this.Js;if(3==b&&a.Lf&&!a.ll)for(var d=void 0,d=this;d&&d.gj;d=d.L)d.gj=!1;if(a.Re)a.Re.L=null,Hd(a,b,c);else try{a.ll?a.zh.call(a.context):Hd(a,b,c)}catch(e){Id.call(null,e)}vd.put(a)}this.Xl=!1};var Hd=function(a,b,c){2==b?a.zh.call(a.context,c):a.Lf&&a.Lf.call(a.context,c)},Ed=function(a,b){a.gj=!0;rc(function(){a.gj&&Id.call(null,b)})},Id=fc;var Kd=function(a,b,c){var d="mouseenter_custom"==b,e=Jd(b);return function(f){f||(f=window.event);if(f.type==e){if("mouseenter_custom"==b||"mouseleave_custom"==b){var h;if(h=d?f.relatedTarget||f.fromElement:f.relatedTarget||f.toElement)for(var k=0;k<a.length;k++)if(_.Zc(a[k],h))return}c(f)}}},Jd=function(a){return"mouseenter_custom"==a?"mouseover":"mouseleave_custom"==a?"mouseout":a};var Ld=function(a,b,c,d,e){c="&"+b+"="+c;var f=a.indexOf("&"+d+"=");c=0>f?a+c:a.substring(0,f)+c+a.substring(f);return 2E3<c.length?_.q(e)?Ld(a,b,e,d,void 0):a:c};_.Md="StopIteration"in _.p?_.p.StopIteration:{message:"StopIteration",stack:""};_.Nd=function(){};_.Nd.prototype.next=function(){throw _.Md;};_.Nd.prototype.ng=function(){return this};_.Od=function(a,b){this.Eb={};this.O=[];this.ii=this.X=0;var c=arguments.length;if(1<c){if(c%2)throw Error("Uneven number of arguments");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+1])}else a&&this.addAll(a)};_.g=_.Od.prototype;_.g.ra=_.l(31);_.g.Z=function(){Pd(this);for(var a=[],b=0;b<this.O.length;b++)a.push(this.Eb[this.O[b]]);return a};_.g.zb=function(){Pd(this);return this.O.concat()};_.g.Ua=function(a){return Qd(this.Eb,a)};_.g.Cb=_.l(43);_.g.clear=_.l(26);_.g.remove=function(a){return Qd(this.Eb,a)?(delete this.Eb[a],this.X--,this.ii++,this.O.length>2*this.X&&Pd(this),!0):!1};var Pd=function(a){if(a.X!=a.O.length){for(var b=0,c=0;b<a.O.length;){var d=a.O[b];Qd(a.Eb,d)&&(a.O[c++]=d);b++}a.O.length=c}if(a.X!=a.O.length){for(var e={},c=b=0;b<a.O.length;)d=a.O[b],Qd(e,d)||(a.O[c++]=d,e[d]=1),b++;a.O.length=c}};_.g=_.Od.prototype;_.g.get=function(a,b){return Qd(this.Eb,a)?this.Eb[a]:b};_.g.set=function(a,b){Qd(this.Eb,a)||(this.X++,this.O.push(a),this.ii++);this.Eb[a]=b};_.g.addAll=function(a){var b;a instanceof _.Od?(b=a.zb(),a=a.Z()):(b=_.oa(a),a=_.na(a));for(var c=0;c<b.length;c++)this.set(b[c],a[c])};_.g.forEach=function(a,b){for(var c=this.zb(),d=0;d<c.length;d++){var e=c[d],f=this.get(e);a.call(b,f,e,this)}};_.g.clone=function(){return new _.Od(this)};_.g.ng=function(a){Pd(this);var b=0,c=this.ii,d=this,e=new _.Nd;e.next=function(){if(c!=d.ii)throw Error("The map has changed since the iterator was created");if(b>=d.O.length)throw _.Md;var e=d.O[b++];return a?e:d.Eb[e]};return e};var Qd=function(a,b){return Object.prototype.hasOwnProperty.call(a,b)};var Wd,Yd,Zd,ae,be;_.Rd=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/;_.Sd=function(a){return a?(0,window.decodeURI)(a):a};_.Vd=function(a,b){return b.match(_.Rd)[a]||null};Wd=function(a,b){if(a)for(var c=a.split("&"),d=0;d<c.length;d++){var e=c[d].indexOf("="),f=null,h=null;0<=e?(f=c[d].substring(0,e),h=c[d].substring(e+1)):f=c[d];b(f,h?(0,window.decodeURIComponent)(h.replace(/\+/g," ")):"")}};_.Xd=function(a){if(a[1]){var b=a[0],c=b.indexOf("#");0<=c&&(a.push(b.substr(c)),a[0]=b=b.substr(0,c));c=b.indexOf("?");0>c?a[1]="?":c==b.length-1&&(a[1]=void 0)}return a.join("")};Yd=function(a,b,c,d){for(var e=c.length;0<=(b=a.indexOf(c,b))&&b<d;){var f=a.charCodeAt(b-1);if(38==f||63==f)if(f=a.charCodeAt(b+e),!f||61==f||38==f||35==f)return b;b+=e+1}return-1};Zd=/#|$/;_.$d=function(a,b){var c=a.search(Zd),d=Yd(a,0,b,c);if(0>d)return null;var e=a.indexOf("&",d);if(0>e||e>c)e=c;d+=b.length+1;return(0,window.decodeURIComponent)(a.substr(d,e-d).replace(/\+/g," "))};ae=/[?&]($|#)/;be=function(a,b,c){for(var d=a.search(Zd),e=0,f,h=[];0<=(f=Yd(a,e,b,d));)h.push(a.substring(e,f)),e=Math.min(a.indexOf("&",f)+1||d,d);h.push(a.substr(e));a=[h.join("").replace(ae,"$1"),"&",b];null!=c&&a.push("=",(0,window.encodeURIComponent)(String(c)));return _.Xd(a)};var ee,fe,he,je,pe,ke,me,le,oe,ne;_.N=function(a,b){this.Wa=this.Je=this.Kb="";this.Nf=null;this.rd=this.Mf="";this.nb=this.iy=!1;var c;if(a instanceof _.N)this.nb=_.q(b)?b:a.nb,_.ce(this,a.Kb),c=a.Je,_.de(this),this.Je=c,ee(this,a.Wa),fe(this,a.Nf),c=a.getPath(),_.de(this),this.Mf=c,_.ge(this,a.Ka.clone()),c=a.rd,_.de(this),this.rd=c;else if(a&&(c=String(a).match(_.Rd))){this.nb=!!b;_.ce(this,c[1]||"",!0);var d=c[2]||"";_.de(this);this.Je=he(d);ee(this,c[3]||"",!0);fe(this,c[4]);d=c[5]||"";_.de(this);this.Mf=he(d,!0);_.ge(this,c[6]||"",!0);c=c[7]||"";_.de(this);this.rd=he(c)}else this.nb=!!b,this.Ka=new _.ie(null,0,this.nb)};_.N.prototype.toString=function(){var a=[],b=this.Kb;b&&a.push(je(b,ke,!0),":");var c=this.Wa;if(c||"file"==b)a.push("//"),(b=this.Je)&&a.push(je(b,ke,!0),"@"),a.push((0,window.encodeURIComponent)(String(c)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),c=this.Nf,null!=c&&a.push(":",String(c));if(c=this.getPath())this.Wa&&"/"!=c.charAt(0)&&a.push("/"),a.push(je(c,"/"==c.charAt(0)?le:me,!0));(c=this.Ka.toString())&&a.push("?",c);(c=this.rd)&&a.push("#",je(c,ne));return a.join("")};_.N.prototype.resolve=function(a){var b=this.clone(),c=!!a.Kb;c?_.ce(b,a.Kb):c=!!a.Je;if(c){var d=a.Je;_.de(b);b.Je=d}else c=!!a.Wa;c?ee(b,a.Wa):c=null!=a.Nf;d=a.getPath();if(c)fe(b,a.Nf);else if(c=!!a.Mf){if("/"!=d.charAt(0))if(this.Wa&&!this.Mf)d="/"+d;else{var e=b.getPath().lastIndexOf("/");-1!=e&&(d=b.getPath().substr(0,e+1)+d)}e=d;if(".."==e||"."==e)d="";else if(-1!=e.indexOf("./")||-1!=e.indexOf("/.")){for(var d=0==e.lastIndexOf("/",0),e=e.split("/"),f=[],h=0;h<e.length;){var k=e[h++];"."==k?d&&h==e.length&&f.push(""):".."==k?((1<f.length||1==f.length&&""!=f[0])&&f.pop(),d&&h==e.length&&f.push("")):(f.push(k),d=!0)}d=f.join("/")}else d=e}c?(_.de(b),b.Mf=d):c=""!==a.Ka.toString();c?_.ge(b,he(a.Ka.toString())):c=!!a.rd;c&&(a=a.rd,_.de(b),b.rd=a);return b};_.N.prototype.clone=function(){return new _.N(this)};_.ce=function(a,b,c){_.de(a);a.Kb=c?he(b,!0):b;a.Kb&&(a.Kb=a.Kb.replace(/:$/,""))};ee=function(a,b,c){_.de(a);a.Wa=c?he(b,!0):b};fe=function(a,b){_.de(a);if(b){b=Number(b);if((0,window.isNaN)(b)||0>b)throw Error("Bad port number "+b);a.Nf=b}else a.Nf=null};_.N.prototype.getPath=function(){return this.Mf};_.ge=function(a,b,c){_.de(a);b instanceof _.ie?(a.Ka=b,a.Ka.qo(a.nb)):(c||(b=je(b,oe)),a.Ka=new _.ie(b,0,a.nb))};_.de=function(a){if(a.iy)throw Error("Tried to modify a read-only Uri");};_.N.prototype.qo=function(a){this.nb=a;this.Ka&&this.Ka.qo(a);return this};he=function(a,b){return a?b?(0,window.decodeURI)(a.replace(/%25/g,"%2525")):(0,window.decodeURIComponent)(a):""};je=function(a,b,c){return _.v(a)?(a=(0,window.encodeURI)(a).replace(b,pe),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),a):null};pe=function(a){a=a.charCodeAt(0);return"%"+(a>>4&15).toString(16)+(a&15).toString(16)};ke=/[#\/\?@]/g;me=/[\#\?:]/g;le=/[\#\?]/g;oe=/[\#\?@]/g;ne=/#/g;_.ie=function(a,b,c){this.X=this.ca=null;this.Xa=a||null;this.nb=!!c};_.qe=function(a){a.ca||(a.ca=new _.Od,a.X=0,a.Xa&&Wd(a.Xa,function(b,c){a.add((0,window.decodeURIComponent)(b.replace(/\+/g," ")),c)}))};_.g=_.ie.prototype;_.g.ra=_.l(30);_.g.add=function(a,b){_.qe(this);this.Xa=null;a=re(this,a);var c=this.ca.get(a);c||this.ca.set(a,c=[]);c.push(b);this.X+=1;return this};_.g.remove=function(a){_.qe(this);a=re(this,a);return this.ca.Ua(a)?(this.Xa=null,this.X-=this.ca.get(a).length,this.ca.remove(a)):!1};_.g.clear=_.l(25);_.g.Cb=_.l(42);_.g.Ua=function(a){_.qe(this);a=re(this,a);return this.ca.Ua(a)};_.g.zb=function(){_.qe(this);for(var a=this.ca.Z(),b=this.ca.zb(),c=[],d=0;d<b.length;d++)for(var e=a[d],f=0;f<e.length;f++)c.push(b[d]);return c};_.g.Z=function(a){_.qe(this);var b=[];if(_.v(a))this.Ua(a)&&(b=_.Yb(b,this.ca.get(re(this,a))));else{a=this.ca.Z();for(var c=0;c<a.length;c++)b=_.Yb(b,a[c])}return b};_.g.set=function(a,b){_.qe(this);this.Xa=null;a=re(this,a);this.Ua(a)&&(this.X-=this.ca.get(a).length);this.ca.set(a,[b]);this.X+=1;return this};_.g.get=function(a,b){var c=a?this.Z(a):[];return 0<c.length?String(c[0]):b};_.se=function(a,b,c){a.remove(b);0<c.length&&(a.Xa=null,a.ca.set(re(a,b),_.Zb(c)),a.X+=c.length)};_.ie.prototype.toString=function(){if(this.Xa)return this.Xa;if(!this.ca)return"";for(var a=[],b=this.ca.zb(),c=0;c<b.length;c++)for(var d=b[c],e=(0,window.encodeURIComponent)(String(d)),d=this.Z(d),f=0;f<d.length;f++){var h=e;""!==d[f]&&(h+="="+(0,window.encodeURIComponent)(String(d[f])));a.push(h)}return this.Xa=a.join("&")};_.ie.prototype.clone=function(){var a=new _.ie;a.Xa=this.Xa;this.ca&&(a.ca=this.ca.clone(),a.X=this.X);return a};var re=function(a,b){var c=String(b);a.nb&&(c=c.toLowerCase());return c};_.ie.prototype.qo=function(a){a&&!this.nb&&(_.qe(this),this.Xa=null,this.ca.forEach(function(a,c){var d=c.toLowerCase();c!=d&&(this.remove(c),_.se(this,d,a))},this));this.nb=a};_.ie.prototype.extend=_.l(50);_.te=_.D("Firefox");_.ue=_.yc()||_.D("iPod");_.ve=_.D("iPad");_.we=_.D("Android")&&!(ec()||_.D("Firefox")||dc()||_.D("Silk"));_.xe=ec();_.ye=_.D("Safari")&&!(ec()||_.D("Coast")||dc()||_.D("Edge")||_.D("Silk")||_.D("Android"))&&!(_.yc()||_.D("iPad")||_.D("iPod"));var ze,Ae,Be,Ce,De,Ge,Fe;ze=function(a){return _.we||_.Ec?a.replace(/https?:\/\/(market.android.com|play.google.com\/store\/apps)\//,"market://"):a};Ae=function(a){return a.replace("?","?"+(0,window.encodeURIComponent)("rct")+"="+(0,window.encodeURIComponent)("j")+"&")};Be="doubleclick.net 2mdn.net dartmotif.net doubleclick.net doubleclick.com gstatic.com app-measurement.com google-analytics.com".split(" ");Ce=function(a){var b=_.Sd(_.Vd(3,a));return b?(0,_.Rb)(Be,function(a){return _.qa(b,a)}):!0};De=function(a){if(a.match(/[\?&]sa=L/)){var b;b=_.Vd(1,a);!b&&_.p.self&&_.p.self.location&&(b=_.p.self.location.protocol,b=b.substr(0,b.length-1));b=b?b.toLowerCase():"";var c=a.match(_.Rd);a=c[5];var d=c[6],c=c[7],e="";a&&(e+=a);d&&(e+="?"+d);c&&(e+="#"+c);a=e;c=window.location.toString();d=_.Sd(_.Vd(3,c));c=_.Vd(1,c);"http"!=b&&"https"!=b&&(c=b);a=Ae(c+"://"+d+(a||""));b=new window.XMLHttpRequest;b.open("GET",a,!1);window.jstiming&&_.x(window.jstiming.report)?(a=new window.jstiming.Timer,b.send(),a.tick&&(a.tick("cr_csr"),window.jstiming.report(a))):b.send();var f;b.responseText&&(b=b.responseText.match(/URL=\'([^\']*)\'/),1<b.length&&(f=b[1].replace(/&amp;/g,"&")));return f}};Ge=function(a){if(!a.Se||!a.Bc||a.cg&&Ce(a.cg)||!_.Ee(a.Bc)&&!Fe(a.Bc)||!a.Wj||!a.cs)return!1;var b=a.cs,c=_.Ee(a.Bc),d=Fe(a.Bc),e=a.Bc,f=a.Se,h=a.cg;if(!f||"L"!=_.$d(f,"sa"))return a=new td(_.t),sd(a,2,void 0),!1;if(c){_.Ee(h)&&(e=h,h=void 0);if(void 0==h)return a.Wj(f),b(e),!0;h=(c=De(f))||h;_.Ee(h)&&(e=h,h=void 0);h&&(h=be(h,"urlloadedinbrowser","false"),a.Wj(h));b(e);return!0}if(d){h=(c=De(f))||h;c=_.$d(h,"referrer");d=_.$d(e,"referrer");Fe(h)&&(e=h,h=void 0);f=[];d&&f.push(d);c&&f.push(c);if(c=f.join("&"))e=be(e,"referrer",c),h&&(h=be(h,"referrer",c));e=ze(e);h&&(h=be(h,"urlloadedinbrowser","false"),a.Wj(h));b(e);return!0}return!1};Fe=function(a){if(!a)return!1;var b=_.Sd(_.Vd(3,a));a=_.Sd(_.Vd(5,a));return"market.android.com"==b||"play.google.com"==b&&"/store/apps/details"==a};_.Ee=function(a){return a?"itunes.apple.com"==_.Sd(_.Vd(3,a)):!1};var He;He={yB:0,mg:1,URL:2,kg:3,jg:4,Hu:5,Du:7,FAVICON:8,mi:9,lg:6,ku:10,tu:11,ru:12,uu:34,cu:13,Wt:14,MB:15,ni:16,Mu:29,au:30,yu:17,Zt:18,bu:19,xB:20,Xt:21,Bu:22,ri:23,li:24,pi:25,oi:26,Yt:27,Au:28,Ju:31,$t:32,fl:33,hu:35,hl:36,dl:37,gl:38,FB:1E3,lu:1001,mu:1002};_.Ie=[11,12,16,18,27,28];var Je=function(a,b,c,d){b=c(d,b);if(!(b instanceof Array))return a;(0,_.C)(b,function(b){if(2!==b.length&&3!==b.length)return a;a=Ld(a,b[0],b[1],"adurl",b[2])});return a},Ke=function(a,b,c){if(_.M.ona){_.qd(a);a=b.href||c.Se;_.M.agss&&(a=_.M.agss(a));if(b=window.u2hgmob){b=a;var d=c.cg,e=c.Bc;if(window.ona&&window.onc){var f=window.ona;window.asogmob&&window.osto&&(f=window.osto);b=Ge({Se:b,cg:d,Bc:e,Wj:window.onc,cs:f})}else b=!1}!b&&(b=c.Ac.match("/play[.]google[.]com/redeem?"))&&(b=c.Ac,"function"==typeof window.oit&&"function"==typeof window.onc?(window.onc(a),window.oit({id:"redemptionId",url:b,packageName:"com.android.vending"}),b=!0):b=!1);if(!b)a:{if(window.ona){b=c.Se;c=c.Ac;window.agss&&(b=window.agss(b));if(c.match(/^https?:\/\/itunes[.]apple[.]com/)){if(window.onc)window.onc(b),window.ona(c);else window.ona(b);b=!0;break a}c=b;if(c.match(/market[.]android[.]com|play[.]google[.]com/)&&c.match(/[\?&]sa=L/)&&!c.match(/googleadservices[.]com/)){if(d=window.location.host){b=1;e=d.split(":");for(d=[];0<b&&e.length;)d.push(e.shift()),b--;e.length&&d.push(e.join(":"));b=d[0];d=d[1];c=new _.N(c);ee(c,b);fe(c,d);c=c.toString()}c=Ae(c);b=new window.XMLHttpRequest;b.open("GET",c,!1);window.jstiming&&_.x(window.jstiming.report)?(d=new window.jstiming.Timer,b.send(),d.tick&&(d.tick("cr_csr"),window.jstiming.report(d))):b.send();b.responseText&&(b=b.responseText.match(/URL=\'([^\']*)\'/),1<b.length&&(c=b[1].replace(/&amp;/g,"&")));c=ze(c)}else c=null;if(c){window.ona(c);b=!0;break a}}b=!1}if(b)return!0;_.M.ona(a);return!0}return!1};_.Le=function(a){this.qa=a;this.gp=[];this.Ci=[];this.Pm={};this.da={};this.Jr=1;this.Ch="data-original-click-url";this.jo="data-landing-url";this.bd={};this.Tm=!1;this.Xi=[]};_.Le.prototype.Nh=_.l(52);var Me=function(a,b,c){var d=b=b.getAttribute(a.Ch);if(d)for(var e=0;e<a.gp.length;e++)d=Je(d,b,a.gp[e],c);return d},Ne=function(a,b,c,d){if(0!=a.Ci.length&&!_.rd(d)){var e=1==d.which&&!d.ctrlKey&&"_blank"!=b.target&&"_new"!=b.target;e&&_.qd(d);for(var f=[],h=0;h<a.Ci.length;h++){var k=a.Ci[h](c);if(k){var m=new td(function(a){_.jd(window,k,a)});f.push(m)}}c=Ad(f);f=new td(function(a){window.setTimeout(a,2E3)});e&&zd([c,f]).then((0,_.y)(_.Le.prototype.Lz,a,b,d))}};_.Le.prototype.Lz=function(a,b){this.Tm=!0;var c=!1;b.target&&(c=nd(b.target,"click",b.button,b.ctrlKey,b.shiftKey,b.metaKey));!a.href||c||Ke(b,a,{Se:a.href,Ac:vb(this.qa),cg:yb(this.qa),Bc:xb(this.qa)})||(_.M.top.location=a.href)};_.Le.prototype.iw=function(a,b,c,d){if(this.Tm)this.Tm=!1;else{d||(d=window.event);_.ma(this.da[c][b],function(a){a(d)});if(a.href){var e=Me(this,a,d.type);e&&(this.bd[b]?a.ping=e:a.href=e)}"click"==c&&Ne(this,a,b,d);Oe(this);"click"!=c||_.rd(d)||Ke(d,a,{Se:a.href,Ac:vb(this.qa),cg:yb(this.qa),Bc:xb(this.qa)})}};var Pe=function(a,b,c,d){a.da[d]||(a.da[d]={});a.da[d][c]||(a.da[d][c]={});_.F(b,d,(0,_.y)(a.iw,a,b,c,d))};_.g=_.Le.prototype;_.g.Fd=function(a,b){for(var c=0;c<a.length;c++){var d=a[c];d.href&&d.setAttribute(this.Ch,d.href);Pe(this,d,b,"mousedown");Pe(this,d,b,"click")}this.Pm[b]=!0};_.g.fi=_.l(54);_.g.Ug=_.l(56);_.g.Yh=_.l(58);_.g.Ph=_.l(60);_.g.queueOnObjectAfterClickModifiers=function(a,b,c,d){this.Xi.push({Ou:a,Wl:b,ew:c,lv:d})};var Oe=function(a){for(var b=0;b<a.Xi.length;b++){var c=a.Xi[b],d=c.Ou,e=c.Wl,f=c.ew;c.lv&&_.rd(f)||d.fireOnObject(e,f)}a.Xi=[]};var Qe,Re,Se;Qe="undefined"!=typeof window.DOMTokenList;Re=function(a,b){if(Qe){var c=a.classList;0==c.contains(b)&&c.toggle(b)}else if(c=a.className){for(var c=c.split(/\s+/),d=!1,e=0;e<c.length&&!d;++e)d=c[e]==b;d||(c.push(b),a.className=c.join(" "))}else a.className=b};Se=function(a,b){if(Qe){var c=a.classList;1==c.contains(b)&&c.toggle(b)}else if((c=a.className)&&!(0>c.indexOf(b))){for(var c=c.split(/\s+/),d=0;d<c.length;++d)c[d]==b&&c.splice(d--,1);a.className=c.join(" ")}};_.Ue=function(a,b,c){(c?Se:Re)(a,b)};_.O=function(a,b,c){this.aa=new _.tc;this.V=a;this.V[0]=[b];this.Ej=[];this.Sg=b.style.display;this.Qb=new _.Le(c);this.qa=c;if(b=window.document.getElementById("common_15click_anchor"))a[20]=[b],this.Fd(20)};_.g=_.O.prototype;_.g.navigationAdPieces=function(){return this.Ej};_.g.Qm=function(){return!0};_.g.hide=function(){for(var a=this.V[0],b=0;b<a.length;b++)a[b].style.display="none"};_.g.reset=function(){for(var a=this.V[0],b=0;b<a.length;b++)a[b].style.display=this.Sg};_.g.has=function(a){return(a=this.V[a])&&0<a.length};_.g.listen=function(a,b,c){var d=this.V[a];if(d){var e=this.Qb,f=Jd(b),h=("click"==b||"mousedown"==b)&&e.Pm[a],k=Kd(d,b,_.ia(c,a,this));e.da[f]||(e.da[f]={});e.da[f][a]||(e.da[f][a]={});var m=e.Jr;e.da[f][a][m]=k;e.Jr=m+1;if(!h)for(e=0;e<d.length;e++)_.F(d[e],f,k);c.rc||(c.rc={});c.rc[b]||(c.rc[b]={});c.rc[b][a]=m}};_.g.unlisten=function(a,b,c){var d;if(c.rc&&c.rc[b]&&c.rc[b][a]){var e=c.rc[b][a];delete c.rc[b][a];d=e}else d=-1;if(c=this.V[a]){var f=this.Qb,e=Jd(b);b=("click"==b||"mousedown"==b)&&f.Pm[a];if(f.da[e]&&f.da[e][a]){var h=f.da[e][a][d];delete f.da[e][a][d];a=h}else a=null;if(a&&!b)for(b=0;b<c.length;b++)_.vc(c[b],e,a)}};_.Ve=function(a,b,c,d,e,f){if(a=a.V[b])for(b=0;b<a.length;b++){var h="click",h=Jd(h);nd(a[b],h,c,d,e,f)}};_.O.prototype.registerClickUrlModifier=function(a){this.Qb.gp.push(a)};_.O.prototype.Nh=_.l(51);_.O.prototype.modifyCssClass=function(a,b,c){if(b&&(a=this.V[a]))for(var d=0;d<a.length;d++)_.Ue(a[d],b,c)};_.O.prototype.getComputedStyle=function(a){return(a=this.V[a])&&0<a.length?window.getComputedStyle(a[0]):null};var We=function(a,b){var c=a.V[b];if(!c||!c[0])return"rgb(255, 255, 255)";c=c[0].parentElement;if(!c)return"rgb(255, 255, 255)";for(var d=/rgba\([ \d]+,[ \d]+,[ \d]+,[ 0\.]+\)/;c;){var e=window.getComputedStyle(c).backgroundColor;if(e&&!d.exec(e)&&"transparent"!=e)return e;c=c.parentElement}return"rgb(255, 255, 255)"};_.g=_.O.prototype;_.g.getAttribute=function(a,b){var c=this.V[a];if(c&&b)for(var d=0;d<c.length;d++){var e=c[d].getAttribute(b);if(e)return e}return null};_.g.setAttribute=function(a,b,c){(a=this.V[a])&&0<a.length&&b&&a[0].setAttribute(b,c)};_.g.removeAttribute=function(a,b){var c=this.V[a];c&&0<c.length&&b&&c[0].removeAttribute(b)};_.g.getBoundingClientRect=function(a){return(a=this.V[a])?a[0].getBoundingClientRect():null};_.g.forEachAdPiece=function(a){var b=this.V;_.ma(He,function(c){b[c]&&0<b[c].length&&a(c)})};_.g.forEachNavigationAdPiece=function(a){for(var b=this.V,c=0;c<this.Ej.length;++c){var d=this.Ej[c];b[d]&&0<b[d].length&&a(d)}};_.g.Fd=function(a){this.V[a]&&this.Qm(a)&&(this.Ej.push(a),this.Qb.Fd(this.V[a],a))};_.g.fi=_.l(53);_.g.Ug=_.l(55);_.g.Yh=_.l(57);_.g.Ph=_.l(59);_.Xe=function(a,b){var c=a.V[b];if(!c)return!1;for(var d=0;d<c.length;d++)if(!c[d].href)return!1;return!0};_.g=_.O.prototype;_.g.getAdData=function(){return this.qa};_.g.creativeConversionUrl=function(){return this.qa.im()};_.g.adGroupCreativeId=function(){var a=this.qa.g[6];return null!=a?a:""};_.g.redirectUrl=function(){return this.qa.dj()};_.g.Ac=function(){return vb(this.qa)};_.g.getIndex=function(){return this.qa.getIndex()};_.g.getWidth=function(){return this.qa.getWidth()};_.g.getHeight=function(){return this.qa.getHeight()};_.g.listenOnObject=function(a,b){this.aa.subscribe(a,b)};_.g.unlistenOnObject=function(a,b){this.aa.unsubscribe(a,b)};_.g.fireOnObject=function(a,b){this.aa.zs(a,b)};_.g.queueOnObjectAfterClickModifiers=function(a,b,c){this.Qb.queueOnObjectAfterClickModifiers(this,a,b,c)};var Ye,Ze;Ye=function(a,b,c){this.Az=a;this.cw=b;this.zo=c;this.Bp=null;this.bw=this.zj;this.WA=!1};Ze=function(a,b,c){this.message=a;this.fileName=b||"";this.lineNumber=c||-1};_.af=function(a,b,c,d,e){var f;try{f=c()}catch(m){var h=a.zo;try{var k=$e(m),h=(e||a.bw).call(a,b,k,void 0,d)}catch(u){a.zj("pAR",u)}if(!h)throw m;}finally{}return f};_.ff=function(a,b,c,d){var e=_.ef;return function(){var f=arguments;return _.af(e,a,function(){return b.apply(c,f)},d)}};Ye.prototype.zj=function(a,b,c,d,e){var f={};f.context=a;b instanceof Ze||(b=$e(b));f.msg=b.message.substring(0,512);b.fileName&&(f.file=b.fileName);0<b.lineNumber&&(f.line=b.lineNumber.toString());a=_.p.document;f.url=a.URL.substring(0,512);f.ref=a.referrer.substring(0,512);if(this.Bp)try{this.Bp(f)}catch(h){}if(d)try{d(f)}catch(h){}kd(this.Az,e||this.cw,f,this.WA,c);return this.zo};var $e=function(a){var b=a.toString();a.name&&-1==b.indexOf(a.name)&&(b+=": "+a.name);a.message&&-1==b.indexOf(a.message)&&(b+=": "+a.message);if(a.stack){var c=a.stack,d=b;try{-1==c.indexOf(d)&&(c=d+"\n"+c);for(var e;c!=e;)e=c,c=c.replace(/((https?:\/..*\/)[^\/:]*:\d+(?:.|\n)*)\2/,"$1");b=c.replace(/\n */g,"\n")}catch(f){b=d}}return new Ze(b,a.fileName,a.lineNumber)};var gf,kf;gf=new function(){this.fv="http"+("http:"===_.M.location.protocol?"":"s")+"://pagead2.googlesyndication.com/pagead/gen_204?id=";this.Jv=.01;this.pA=Math.random()};_.ef=new Ye(gf,"jserror",!0);_.hf=_.ef.zj;_.jf=function(a,b,c){kd(gf,a,b,"jserror"!=a,c,void 0)};kf=function(a){_.ef.zj(a,Error("container is null"),void 0,void 0)};_.lf=function(){this.O=[];this.eg=[]};_.g=_.lf.prototype;_.g.ra=_.l(29);_.g.Z=function(){return this.eg.concat()};_.g.zb=function(){return this.O.concat()};_.g.Ua=function(a){return 0<=(0,_.Nb)(this.O,a)};_.g.clear=_.l(24);_.g.remove=function(a){a=(0,_.Nb)(this.O,a);return 0<=a?(this.O.splice(a,1),this.eg.splice(a,1),!0):!1};_.g.get=function(a,b){var c=(0,_.Nb)(this.O,a);return 0<=c?this.eg[c]:b};_.g.set=function(a,b){var c=(0,_.Nb)(this.O,a);0<=c?this.eg[c]=b:(this.O.push(a),this.eg.push(b))};_.P=function(a,b,c){this.aa=new _.tc;this.ua=a;this.Sg="none";this.ua&&(this.Sg=this.ua.style.display);this.fd=b;this.g=c;this.da={};this.An=[];this.hr=!1;this.pc=[]};_.g=_.P.prototype;_.g.forEachAd=function(a){(0,_.C)(this.fd,a)};_.g.kl=function(a){this.fd.push(a)};_.g.em=function(a){if(a=window.document.getElementById(a))this.ua=a,this.Sg=this.ua.style.display;if(0==this.fd.length)window.css=null;else{window.ImageExpandConstructor&&1==this.fd.length&&new window.ImageExpandConstructor(this,_.Va(this.g));window.IntentfulClickConstructor&&new window.IntentfulClickConstructor(this,ab(this.g).hm(),Hb(ab(this.g)),Ib(ab(this.g)),Jb(ab(this.g)));window.ona&&!_.Wa(this.g)&&(window.ona=null,window.osb=null);if(null!=window.ona&&null!=window.osb){if(pb(kb(this.g))){var b=Boolean(qb(kb(this.g))),c=Boolean(rb(kb(this.g)));window.ona=function(a){window.osb(a,{useFirstPackage:b,useRunningProcess:c})}}window.u2hgmob=Boolean(sb(kb(this.g)));window.asogmob=Boolean(ub(kb(this.g)))}for(a=0;a<this.An.length;++a)this.An[a]();this.hr=!0}};_.g.listenOnContainer=function(a,b){if(this.ua){var c=Kd([this.ua],a,_.ia(b,this));_.F(this.ua,Jd(a),c);this.da[a]||(this.da[a]=new _.lf);this.da[a].set(b,c)}else kf("hdrAsLoc")};_.g.unlistenOnContainer=function(a,b){if(this.ua){var c;this.da[a]&&this.da[a].Ua(b)?(c=this.da[a].get(b),this.da[a].remove(b)):c=null;c&&_.vc(this.ua,Jd(a),c)}else kf("hdrAsUoc")};_.g.listenOnObject=function(a,b){this.aa.subscribe(a,b)};_.g.unlistenOnObject=function(a,b){this.aa.unsubscribe(a,b)};_.g.fireOnObject=function(a,b){b.JC=this;this.aa.zs(a,b)};_.g.registerFinalizeCallback=function(a){this.hr?a():this.An.push(a)};_.g.registerWidget=function(a,b){_.Vb(this.pc,a)||(this.pc[b]=a,a.reset(this))};var mf=function(a){a.ua.style.display="none";for(var b=0;b<a.pc.length;b++)a.pc[b]&&a.pc[b].hide(a)};_.P.prototype.resetAll=function(){this.ua.style.display=this.Sg;for(var a=0;a<this.pc.length;a++)this.pc[a]&&this.pc[a].reset(this)};_.P.prototype.showOnly=function(a){var b=this;mf(this);nf(this,a,function(a){a.show(b)})};var nf=function(a,b,c){a.pc[b]&&c(a.pc[b])};_.P.prototype.isDirectContent=function(){var a=this.g.g[14];return null!=a?a:!1};_.P.prototype.fh=_.l(12);_.of=function(a,b){var c=[];try{if(a.ua.parentNode&&a.ua.parentNode.querySelectorAll)for(var d=a.ua.parentNode.querySelectorAll("*["+b+"]"),e=0;e<d.length;++e)c.push(d[e]);return c}catch(f){return c}};_.g=_.P.prototype;_.g.getEscapedQemQueryId=function(){return this.g.getEscapedQemQueryId()};_.g.getEscapedGwsQueryId=function(){return this.g.getEscapedGwsQueryId()};_.g.getWebProperty=function(){return this.g.getWebProperty()};_.g.getWidth=function(){return this.g.getWidth()};_.g.getHeight=function(){return this.g.getHeight()};_.g.hh=_.l(2);_.g.gh=_.l(4);_.g.kf=_.l(6);_.g.jf=_.l(8);_.g.hf=_.l(10);_.g.getSerializedAdSlotData=function(){return this.g.$()};_.g.getAdsLength=function(){return this.fd.length};_.g.getAd=function(a){return 0<=a&&a<this.fd.length&&this.fd[a].getIndex()==a?this.fd[a]:null};var qf;_.pf=function(a){a=String(a);if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/(?:"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)[\s\u2028\u2029]*(?=:|,|]|}|$)/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);};_.rf=function(a){return(new qf(void 0)).Vc(a)};qf=function(a){this.mk=a};qf.prototype.Vc=function(a){var b=[];sf(this,a,b);return b.join("")};var sf=function(a,b,c){if(null==b)c.push("null");else{if("object"==typeof b){if(_.ea(b)){var d=b;b=d.length;c.push("[");for(var e="",f=0;f<b;f++)c.push(e),e=d[f],sf(a,a.mk?a.mk.call(d,String(f),e):e,c),e=",";c.push("]");return}if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();else{c.push("{");f="";for(d in b)Object.prototype.hasOwnProperty.call(b,d)&&(e=b[d],"function"!=typeof e&&(c.push(f),tf(d,c),c.push(":"),sf(a,a.mk?a.mk.call(b,d,e):e,c),f=","));c.push("}");return}}switch(typeof b){case "string":tf(b,c);break;case "number":c.push((0,window.isFinite)(b)&&!(0,window.isNaN)(b)?String(b):"null");break;case "boolean":c.push(String(b));break;case "function":c.push("null");break;default:throw Error("Unknown type: "+typeof b);}}},uf={'"':'\\"',"\\":"\\\\","/":"\\/","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},vf=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g,tf=function(a,b){b.push('"',a.replace(vf,function(a){var b=uf[a];b||(b="\\u"+(a.charCodeAt(0)|65536).toString(16).substr(1),uf[a]=b);return b}),'"')};var wf=function(a,b){_.F(a,"message",function(a){try{var d=_.pf(a.data);d&&"auto-css"===d.googMsgType&&b(d,a)}catch(e){}})};var yf=function(a){var b;a:{var c=a.match(xf);if(c){b=Number(c[1]);var d=Number(c[2]),c=Number(c[3]);if(0<=b&&255>=b&&0<=d&&255>=d&&0<=c&&255>=c){b=[b,d,c];break a}}b=[]}if(!b.length)throw Error(a+" is not a valid RGB color");return b},zf=function(a){var b=a[0]/255,c=a[1]/255;a=a[2]/255;var d=Math.max(b,c,a),e=Math.min(b,c,a),f=0,h=0,k=.5*(d+e);d!=e&&(d==b?f=60*(c-a)/(d-e):d==c?f=60*(a-b)/(d-e)+120:d==a&&(f=60*(b-c)/(d-e)+240),h=0<k&&.5>=k?(d-e)/(2*k):(d-e)/(2-2*k));return[Math.round(f+360)%360,h,k]},xf=/^(?:rgb)?\((0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2}),\s?(0|[1-9]\d{0,2})\)$/i;var Af=function(a){this.Qg=a;this.ic=[]},Bf=function(a,b){try{var c=zf(yf(a)),d=zf(yf(b)),e,f;e=.5>=c[2]?c[1]*c[2]:c[1]*(1-c[2]);f=.5>=d[2]?d[1]*d[2]:d[1]*(1-d[2]);return.15<=(c[2]-d[2])*(c[2]-d[2])+e*e+f*f-2*e*f*Math.cos(2*(c[0]/360-d[0]/360)*Math.PI)}catch(h){return!1}},Cf=function(a,b){a||(a=0);b||(b=0);return $b(a,b)},Df=function(a,b){for(var c=0;c<a.ic.length;++c)if(Sb(a.Qg,function(a){return b[a]==this.ic[c].style[a]},a))return c;return-1},Ef=function(a,b,c){for(var d={},e=0;e<a.Qg.length;++e){var f=a.Qg[e];d[f]=b[f]}b={style:d,stats:c};d=Df(a,d);0<=d?-1==a.$p(b,a.ic[d])&&(a.ic[d].stats=c):a.ic.push(b)};Af.prototype.log=function(a){for(var b=0;b<this.ic.length&&10>b;++b)_.jf("auto_css",{style:_.rf(this.ic[b]),rank:b,qid:a},1)};Af.prototype.sort=function(){var a=(0,_.y)(this.$p,this);this.ic.sort(a||$b);for(var a=[],b=0;b<this.ic.length;++b){for(var c="",d=0;d<this.Qg.length;++d)var e=this.Qg[d],c=c+(e+": "+this.ic[b].style[e]+" !important; ");a.push(c)}return a};Af.prototype.$p=function(a,b){return this.compare(a.stats,b.stats)};Af.prototype.ck=function(a,b){Ef(this,a,b)};var Ff=function(){Af.call(this,"background-color color font-family font-size font-weight line-height letter-spacing".split(" "))};_.B(Ff,Af);Ff.prototype.ck=function(a,b,c){0!=b[1]&&Bf(a.color,c.bgcolor)&&Ef(this,a,b)};Ff.prototype.compare=function(a,b){return Cf(b[1],a[1])};var Gf=function(){Af.call(this,"background-color color font-family font-size font-weight letter-spacing line-height text-transform text-shadow".split(" "))};_.B(Gf,Af);Gf.prototype.ck=function(a,b,c){0!=b[1]&&Bf(a.color,c.bgcolor)&&Ef(this,a,b)};Gf.prototype.compare=function(a,b){var c=Cf(b[3],a[3]);return 0!=c?c:Cf(b[1],a[1])};var Hf=function(){Af.call(this,["background-color","color"])};_.B(Hf,Af);Hf.prototype.ck=function(a,b){var c;if(c=a["background-color"])c=a["background-color"],c=!("rgba(0, 0, 0, 0)"==c||"transparent"==c);c&&Ef(this,a,b)};Hf.prototype.compare=function(a,b){var c=Cf(b[9],a[9]);return 0!=c?c:Cf(b[1],a[1])};var Jf=function(a,b,c){_.O.call(this,a,b,c);for(a=0;a<If.length;a++)this.Fd(If[a])};_.B(Jf,_.O);var If=[1,2,3,4,8,6,9],Lf=function(a,b){var c=Kf,d={};if(!b)return null;d[0]=[b];for(var e in c){var f=He[e],h=d,k=_.Xc(window.document,null,c[e],b);h[f]=[];for(var m=0;m<k.length;m++)h[f].push(k[m])}return new Jf(d,b,a)};Jf.prototype.Qm=function(a){return _.Xe(this,a)||4==a};var Mf=function(a){var b=a.g[18];if(null!=b&&b)for(a=_.ka(a.g,19),b=0;b<a.length;b++)_.jd(_.M,a[b],void 0)};var Nf=function(a,b){var c=b.g[31];0==(null!=c?c:0)?(a.style.width=b.getWidth()+"px",a.style.height=b.getHeight()+"px"):(a.style.width="100%",a.style.height="100%");a.style.position="absolute";a.style.top="0";a.style.left="0";a.style.overflow="hidden"},Of=function(a){var b="";_.md(a,function(a,d){if(0===a||a)b+="&"+_.ba(d)+"="+_.ba(a)});return b},Pf="UNKNOWN",Qf="UNKNOWN",Rf=null,Sf=function(a,b){var c="//pagead2.googlesyndication.com"+("/pagead/gen_204?id=glaurung"+Of({gqid:Pf,qqid:Qf,com:a})+Of(b)),c=c.substring(0,2E3);_.jd(_.M,c,void 0)},Kf={mg:"ad-title",URL:"ad-url",kg:"ad-body",jg:"ad-button",FAVICON:"ad-favicon",lg:"ad-image",oi:"ad-price",ri:"ad-reviews",li:"ad-app-store-image",pi:"ad-promo-headline",fl:"ad-app-icon",ni:"ad-image-gallery",mi:"ad-background",hl:"ad-logo",dl:"ad-advertiser",gl:"ad-call-to-action",VIDEO:"ad-video"},Tf=function(a,b,c){var d=a.g;_.x(window.initSFVideoFlags)&&(window.initSFVideoFlags(d),a.registerFinalizeCallback(function(){_.x(window.AFMA_ReceiveMessage)&&window.AFMA_ReceiveMessage("onshow",{})}));var e=cb(d);e&&Kb(e)&&(Kf={mg:"title-link",URL:"url-link",kg:"body-link",jg:"button-link",FAVICON:"favicon-link",lg:"image-link",oi:"price",ri:"reviews",li:"app-store",pi:"promo-headline",fl:"app-icon",ni:"image-gallery",mi:"background",hl:"logo",dl:"advertiser",gl:"call-to-action",VIDEO:"video"});e=b.getElementById("adunit");b=b.getElementById("ads");if(!e||!b)return 1;Nf(e,d);try{c(b,a)}catch(h){return Xa(d)&&(Rf=h),2}for(c=0;c<_.la(d.g,0);c++){b=d.getAds(c);var e="taw"+b.getIndex(),f=window.document.getElementById(e);if(!f)return 3;f=Lf(b,f);if(!f)return 1;window.registerAd&&window.registerAd(f,e);wb(b)&&window.initAppPromo&&window.initAppPromo(f);Mf(b);a.kl(f)}return 0};var Uf=function(a,b,c){var d=[];d[0]=[c];d[15]=[b];(b=window.document.getElementById("button_15click_anchor"))&&d[15].push(b);(b=window.document.getElementById("abgc"))&&(d[27]=[b]);(b=window.document.getElementById("cbc"))&&(d[28]=[b]);_.O.call(this,d,c,a);this.Fd(15)};_.B(Uf,_.O);var Vf=function(a,b){var c={};c[0]=[b];_.O.call(this,c,b,a);this.Fd(0)};_.B(Vf,_.O);var Xf=function(a,b,c){_.O.call(this,a,b,c);for(a=0;a<Wf.length;a++)this.Fd(Wf[a])};_.B(Xf,_.O);var Wf=[1,2,4,5,7,8,3,9,6,14,15],Yf={mg:"headline",kg:"description",jg:"button",bu:"logo",lg:"product"};var $f=function(a,b,c){_.O.call(this,a,b,c);for(a=0;a<Zf.length;a++)this.Fd(Zf[a]);this.listen(4,"mouseover",(0,_.y)(this.modifyCssClass,this,0,"onhoverbg",!1));this.listen(4,"mouseout",(0,_.y)(this.modifyCssClass,this,0,"onhoverbg",!0))};_.B($f,_.O);var Zf=[1,2,4,5,7,8,3,9,6,14,15,34,26,24],ag={mg:"rhtitle",kg:"rhbody",URL:"rhurl",jg:"rhbutton",FAVICON:"rhfavicon",Wt:"rhaddress",lg:"rhimage",uu:"rhimagetemplate",ni:"rhimagegallery",Mu:"rhviewimagegallery",au:"rhcloseimagegalleryview",Ju:"rhtrydemobutton",$t:"rhclosetrydemoview",ku:"rhimage-container",tu:"rhexpand-button",ru:"rhimage-collapsed",mi:"rhbackground",cu:"rh-icore-empty",Hu:"rhsitelink",Du:"rhradlink",yu:"rh-multiframe",Zt:"rh-box-breadcrumbs",Xt:"rh-ms-mute-overlay",Bu:"rh-ms-mute-undo",ri:"rhstarratings",li:"rhstoreicon",pi:"rhpromotext",oi:"rhprice",Yt:"abgc",Au:"cbc",hu:"rhdemocountdowntimer",lu:"rhoverlap-imagegallery",mu:"rhoverlap-trydemo"},bg=function(a){var b={};b[0]=[a];for(var c in ag){var d=He[c],e=b,f=_.Xc(window.document,null,ag[c],a);e[d]=[];for(var h=0;h<f.length;h++)e[d].push(f[h])}return b};$f.prototype.Qm=function(a){return _.Xe(this,a)||4==a};var cg=function(a,b,c,d){$f.call(this,a,b,c);(!_.J||_.Lc("10"))&&window.getComputedStyle&&window.postMessage&&(this.Go=[],this.Ap={},this.tA={},this.Iv=this.FA=!1,this.A=d)};_.B(cg,$f);cg.prototype.Qs=function(){wf(window,(0,_.y)(this.gx,this));var a={};a.request=window.name;var b=window.top;a.googMsgType="auto-css";b.postMessage(_.rf(a),"*")};cg.prototype.gx=function(a){if(!this.FA||this.Iv)if(a=a.styles)for(var b=0;b<this.Go.length;++b){var c=this.Go[b];if(this.has(c)){var d=this.Ap[c],e={};e.bgcolor=We(this,c);c=e;for(e=0;e<a.length;++e){var f=a[e];d.ck(f.style,f.stats,c)}d.sort();d.log(this.A.getEscapedQemQueryId())}}};var dg=function(a,b,c,d){c&&(a.Go.push(b),a.Ap[b]=c,a.tA[b]=d)};_.P.prototype.forEachAd=_.P.prototype.forEachAd;_.P.prototype.addAd=_.P.prototype.kl;_.P.prototype.finalize=_.P.prototype.em;_.P.prototype.registerFinalizeCallback=_.P.prototype.registerFinalizeCallback;_.P.prototype.listenOnContainer=_.P.prototype.listenOnContainer;_.P.prototype.unlistenOnContainer=_.P.prototype.unlistenOnContainer;_.P.prototype.registerWidget=_.P.prototype.registerWidget;_.P.prototype.resetAll=_.P.prototype.resetAll;_.P.prototype.showOnly=_.P.prototype.showOnly;_.P.prototype.isDirectContent=_.P.prototype.isDirectContent;_.P.prototype.getEscapedQemQueryId=_.P.prototype.getEscapedQemQueryId;_.P.prototype.getEscapedGwsQueryId=_.P.prototype.getEscapedGwsQueryId;_.P.prototype.getWebProperty=_.P.prototype.getWebProperty;_.P.prototype.getAdsLength=_.P.prototype.getAdsLength;_.P.prototype.getAd=_.P.prototype.getAd;_.P.prototype.listenOnObject=_.P.prototype.listenOnObject;_.P.prototype.unlistenOnObject=_.P.prototype.unlistenOnObject;_.P.prototype.fireOnObject=_.P.prototype.fireOnObject;_.P.prototype.getSerializedAdSlotData=_.P.prototype.getSerializedAdSlotData;_.r("buildAdSlot",function(a){a=new _.P(null,[],new _.Ea(a));_.r("adSlot",a,void 0);return a},void 0);_.O.prototype.modifyCssClass=_.O.prototype.modifyCssClass;_.O.prototype.has=_.O.prototype.has;_.O.prototype.listen=_.O.prototype.listen;_.O.prototype.unlisten=_.O.prototype.unlisten;_.O.prototype.registerClickUrlModifier=_.O.prototype.registerClickUrlModifier;_.O.prototype.hide=_.O.prototype.hide;_.O.prototype.reset=_.O.prototype.reset;_.O.prototype.forEachAdPiece=_.O.prototype.forEachAdPiece;_.O.prototype.getAttribute=_.O.prototype.getAttribute;_.O.prototype.setAttribute=_.O.prototype.setAttribute;_.O.prototype.removeAttribute=_.O.prototype.removeAttribute;_.O.prototype.getBoundingClientRect=_.O.prototype.getBoundingClientRect;_.O.prototype.creativeConversionUrl=_.O.prototype.creativeConversionUrl;_.O.prototype.adGroupCreativeId=_.O.prototype.adGroupCreativeId;_.O.prototype.redirectUrl=_.O.prototype.redirectUrl;_.O.prototype.finalDestinationUrl=_.O.prototype.Ac;_.O.prototype.getIndex=_.O.prototype.getIndex;_.O.prototype.listenOnObject=_.O.prototype.listenOnObject;_.O.prototype.unlistenOnObject=_.O.prototype.unlistenOnObject;_.O.prototype.fireOnObject=_.O.prototype.fireOnObject;_.O.prototype.navigationAdPieces=_.O.prototype.navigationAdPieces;_.O.prototype.queueOnObjectAfterClickModifiers=_.O.prototype.queueOnObjectAfterClickModifiers;_.r("buildGlaurungAds",function(a,b,c){var d=(new Date).getTime(),e=1,f=!1;Rf=null;try{f=Xa(a.g),Pf=a.getEscapedGwsQueryId(),Qf=a.getEscapedQemQueryId(),e=Tf(a,b,c)}catch(h){f&&(Rf=h),e=1}a=(new Date).getTime();b={};b.r=e;b.d=a-d;Sf("bridge",b);return e},void 0);_.r("glaurungError",function(){return Rf},void 0);_.r("glaurungBridge.log",Sf,void 0);_.r("glaurungBridge.getGlaurungAdPieceClassNames",function(){return{TITLE:Kf.mg,URL:Kf.URL,BODY:Kf.kg,ACTION_BUTTON:Kf.jg,FAVICON:Kf.FAVICON,IMAGE_EXTENSION:Kf.lg,PRICE:Kf.oi,REVIEWS:Kf.ri,APP_STORE_IMAGE:Kf.li,PROMO_HEADLINE:Kf.pi,APP_ICON:Kf.fl,IMAGE_GALLERY:Kf.ni,BACKGROUND_ACTION_AREA:Kf.mi,LOGO:Kf.hl,ADVERTISER:Kf.dl,CALL_TO_ACTION:Kf.gl,VIDEO:Kf.VIDEO}},void 0);_.r("buildImageAd",function(a,b){if(0>b||b>=_.la(a.g.g,0))return null;var c=a.g.getAds(b),d=_.L.getElementById("google_image_div"),e=_.L.getElementById("aw0");return d&&e?new Uf(c,e,d):null},void 0);_.r("buildTemplateAd",function(a){var b;a=new _.Ja(a);var c={},d=window.document.getElementById("adContent");if(d){c[0]=[d];for(b in Yf){var e=He[b],f=c,h=_.Xc(window.document,null,Yf[b],d);f[e]=[];for(var k=0;k<h.length;k++)f[e].push(h[k])}b=new Xf(c,d,a)}else b=null;return b},void 0);_.r("buildRichmediaAd",function(a,b){if(0>b||b>=_.la(a.g.g,0))return null;var c=a.g.getAds(b),d=_.L.getElementById("google_richmedia_div");return d?new Vf(c,d):null},void 0);_.r("buildTextAd",function(a,b){var c=a.g;if(!(0>b||b>=_.la(c.g,0))){var d=null,d=eb(c).g[0];if(null!=d&&d){var e=a.g;if(0>b||b>=_.la(e.g,0))d=null;else{var d=a.g.getAds(b),f=window.document.getElementById("taw"+b);if(f)var h=bg(f),d=new cg(h,f,d,a);else d=null;d?(e=eb(e),f=e.g[2],dg(d,1,new Gf,null!=f?f:0),f=e.g[3],dg(d,2,new Ff,null!=f?f:0),f=e.g[4],dg(d,3,new Ff,null!=f?f:0),f=e.g[5],dg(d,4,new Hf,null!=f?f:0),f=e.g[6],e=d,f=null!=f?f:0,0<f?window.setTimeout((0,_.y)(e.Qs,e),f):e.Qs()):d=null}}else 0>b||b>=_.la(a.g.g,0)?d=null:(d=a.g.getAds(b),(e=window.document.getElementById("taw"+b))?(f=bg(e),d=new $f(f,e,d)):d=null);d&&(window.registerAd&&window.registerAd(d,"taw"+b),a.kl(d),c=c.getAds(b),e=c.g[11],null!=e&&e&&window.registerAdPing&&window.registerAdPing(d),null!=Cb(c).g[2]&&window.init_ctc&&(e=Cb(c),null!=e.g[1]?(f=e.g[1],window.init_ctc_gv(d,e.dj(),null!=f?f:"",Eb(e))):window.init_ctc(d,e.dj(),Eb(e))),wb(c)&&window.initAppPromo&&window.initAppPromo(d))}},void 0);_.r("buildAutoCssBodySorter",function(){return new Ff},void 0);_.r("buildAutoCssTitleSorter",function(){return new Gf},void 0);_.r("buildAutoCssButtonSorter",function(){return new Hf},void 0);if(_.L&&_.L.URL){var gd=_.L.URL,eg=!(gd&&0<hd().length);_.ef.zo=eg};_.fg=function(a){if(a.classList)return a.classList;a=a.className;return _.v(a)&&a.match(/\S+/g)||[]};_.gg=function(a,b){return a.classList?a.classList.contains(b):_.Vb(_.fg(a),b)};_.hg=function(a,b){a.classList?a.classList.add(b):_.gg(a,b)||(a.className+=0<a.className.length?" "+b:b)};_.ig=function(a){this.za=a};_.jg=/\s*;\s*/;_.g=_.ig.prototype;_.g.set=function(a,b,c,d,e,f){if(/[;=\s]/.test(a))throw Error('Invalid cookie name "'+a+'"');if(/[;\r\n]/.test(b))throw Error('Invalid cookie value "'+b+'"');_.q(c)||(c=-1);e=e?";domain="+e:"";d=d?";path="+d:"";f=f?";secure":"";c=0>c?"":0==c?";expires="+(new Date(1970,1,1)).toUTCString():";expires="+(new Date((0,_.A)()+1E3*c)).toUTCString();this.za.cookie=a+"="+b+e+d+c+f};_.g.get=function(a,b){for(var c=a+"=",d=(this.za.cookie||"").split(_.jg),e=0,f;f=d[e];e++){if(0==f.lastIndexOf(c,0))return f.substr(c.length);if(f==a)return""}return b};_.g.remove=function(a,b,c){var d=this.Ua(a);this.set(a,"",0,b,c);return d};_.g.zb=function(){return _.kg(this).keys};_.g.Z=function(){return _.kg(this).values};_.g.Cb=_.l(41);_.g.ra=_.l(28);_.g.Ua=function(a){return _.q(this.get(a))};_.g.clear=_.l(23);_.kg=function(a){a=(a.za.cookie||"").split(_.jg);for(var b=[],c=[],d,e,f=0;e=a[f];f++)d=e.indexOf("="),-1==d?(b.push(""),c.push(e)):(b.push(e.substring(0,d)),c.push(e.substring(d+1)));return{keys:b,values:c}};_.lg=new _.ig(window.document);_.lg.QB=3950;})(window.hydra=window.hydra||{});
c
home.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { SharedModule } from "@app/shared/shared.module"; import { NativeScriptCommonModule } from "nativescript-angular/common"; import { NativeScriptLocalizeModule } from "nativescript-localize/angular"; import { NativeScriptMaterialCardViewModule } from "nativescript-material-cardview/angular"; import { NativeScriptUIListViewModule } from "nativescript-ui-listview/angular"; import { HomeRoutingModule } from "./home-routing.module"; import { HomeComponent } from "./home.component"; @NgModule({ imports: [ NativeScriptLocalizeModule, NativeScriptUIListViewModule, NativeScriptCommonModule, NativeScriptMaterialCardViewModule, HomeRoutingModule,
HomeComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class HomeModule { }
SharedModule ], declarations: [
cloud_settings.py
# # module tank.core.cloud_settings # from enum import Enum import yaml import jsonschema from tank.core.exc import TankConfigError class CloudProvider(Enum): DIGITAL_OCEAN = 'digitalocean' GOOGLE_CLOUD_ENGINE = 'gce' def __repr__(self): return '<%s.%s>' % (self.__class__.__name__, self.name) def __str__(self): """ Serializes a member into string. """ return self.value @classmethod def from_string(cls, str_value): """ Deserializes a member from string. :param str_value: serialized form :return: enum member or None if not found """ for m in cls: if m.value == str_value: return m else: return None class CloudUserSettings:
""" Management and validation of cloud provider user-specific settings. """ def __init__(self, app_config): self.provider = CloudProvider.from_string(app_config.get('tank', 'provider')) if self.provider is None: raise TankConfigError('Cloud provider is not specified or not known') self.monitoring_vars = app_config.get_dict()['tank'].get('monitoring') try: jsonschema.validate(self.monitoring_vars, self.__class__._MONITORING_SCHEMA) except jsonschema.ValidationError as e: raise TankConfigError('Failed to validate admin_user/password monitoring settings', e) self.provider_vars = app_config.get_dict().get(self.provider.value) if self.provider_vars is None or not isinstance(self.provider_vars, dict): raise TankConfigError('Cloud provider is not configured') self.ansible_vars = self.provider_vars.pop('ansible', dict()) try: jsonschema.validate(self.provider_vars, self.__class__._SCHEMAS[self.provider]) except jsonschema.ValidationError as e: raise TankConfigError('Failed to validate config for cloud provider {}'.format(self.provider), e) assert 'pvt_key' in self.provider_vars, 'pvt_key is required for ansible' try: jsonschema.validate(self.ansible_vars, self.__class__._ANSIBLE_SCHEMA) except jsonschema.ValidationError as e: raise TankConfigError('Failed to validate ansible config for cloud provider {}'.format(self.provider), e) if 'private_interface' not in self.ansible_vars: self.ansible_vars['private_interface'] = { CloudProvider.DIGITAL_OCEAN: 'eth0', CloudProvider.GOOGLE_CLOUD_ENGINE: 'ens4', }[self.provider] _SCHEMAS = { CloudProvider.DIGITAL_OCEAN: yaml.safe_load(r''' type: object additionalProperties: False required: - token - pvt_key - ssh_fingerprint properties: token: type: string pvt_key: type: string ssh_fingerprint: type: string '''), CloudProvider.GOOGLE_CLOUD_ENGINE: yaml.safe_load(r''' type: object additionalProperties: False required: - pub_key - pvt_key - cred_path - project properties: pub_key: type: string pvt_key: type: string cred_path: type: string project: type: string '''), } _ANSIBLE_SCHEMA = yaml.safe_load(r''' type: object additionalProperties: False properties: private_interface: type: string ''') _MONITORING_SCHEMA = yaml.safe_load(r''' type: object additionalProperties: False required: - admin_user - admin_password properties: admin_user: type: string admin_password: type: string ''')
string.rs
use std::{fmt::{Debug}, ops::Add, fmt::Display}; use once_cell::sync::OnceCell; use smallvec::{SmallVec}; use unicode_segmentation::UnicodeSegmentation; use crate::{InternalString, RantList, RantValue, util, RantTuple}; type Graphemes = SmallVec<[(usize, usize); 1]>; /// Represents Rant's `string` type. #[derive(Debug, Default)] pub struct RantString { raw: InternalString, graphemes: OnceCell<Option<Graphemes>>, } impl RantString { /// Creates a new, empty string. #[inline] pub fn new() -> Self { Default::default() } #[inline] fn from_str(s: &str) -> Self { Self { raw: InternalString::from(s), .. Default::default() } } #[inline] fn from_char(c: char) -> Self { let mut s = InternalString::new(); s.push(c); Self { raw: s, .. Default::default() } } } impl RantString { #[inline] pub(crate) fn graphemes(&self) -> &Graphemes { self.graphemes.get_or_init(|| Some(UnicodeSegmentation::grapheme_indices(self.raw.as_str(), true) .map(|(i, slice)| (i, i + slice.len())) .collect::<Graphemes>()) ).as_ref().unwrap() } /// Creates a copy of the string with the graphemes in reverse order. #[inline] pub fn reversed(&self) -> Self { let mut buf = InternalString::new(); for i in (0..self.len()).rev() { if let Some(g) = self.grapheme_at(i) { buf.push_str(g.as_str()); } } Self { raw: buf, .. Default::default() } } /// Gets a reference to the string as a string slice. #[inline] pub fn as_str(&self) -> &str { self.raw.as_str() } /// Gets the grapheme string at the specified index. #[inline] pub fn grapheme_at(&self, index: usize) -> Option<RantString> { if index >= self.len() { return None } let (start, end) = self.graphemes()[index]; Some(RantString::from(&self.raw[start..end])) } /// Splits the string into individual graphemes and returns them as a Rant list. #[inline] pub fn to_rant_list(&self) -> RantList { let n = self.len(); let mut list = RantList::with_capacity(n); for i in 0..n { let c = self.grapheme_at(i).unwrap(); list.push(RantValue::String(c)); } list } /// Splits the string into individual graphemes and returns them as a Rant tuple. #[inline] pub fn to_rant_tuple(&self) -> RantTuple { let n = self.len(); let mut items = Vec::with_capacity(n); for i in 0..n { let c = self.grapheme_at(i).unwrap(); items.push(RantValue::String(c)); } RantTuple::from(items) } /// Gets the string at the specified slice. pub fn to_slice(&self, start: Option<usize>, end: Option<usize>) -> Option<RantString> { let graphemes = self.graphemes(); let len = graphemes.len(); // Bounds checks if let Some(start) = start { if start > len { return None } } if let Some(end) = end { if end > len { return None } } Some(match (start, end) { (None, None) => self.clone(), (None, Some(end)) => { let raw_end = if end < len { graphemes[end].0 } else { self.raw.len() }; Self::from(&self.raw[..raw_end]) }, (Some(start), None) => { let raw_start = graphemes[start].0; Self::from(&self.raw[raw_start..]) }, (Some(start), Some(end)) => { let (start, end) = util::minmax(start, end); if start == end { return Some(Self::default()) } let raw_start = graphemes[start].0; let raw_end = if end < len { graphemes[end].0 } else { self.raw.len() }; Self::from(&self.raw[raw_start..raw_end]) } }) } } impl Clone for RantString { #[inline] fn clone(&self) -> Self { Self { raw: self.raw.clone(), .. Default::default() } } } impl RantString { #[inline] pub fn len(&self) -> usize { self.graphemes().len() } #[inline] pub fn is_empty(&self) -> bool { self.graphemes().is_empty() } } impl From<InternalString> for RantString { fn from(s: InternalString) -> Self { Self::from_str(s.as_str()) } } impl From<&str> for RantString { fn from(s: &str) -> Self { Self::from_str(s) } } impl From<String> for RantString { fn from(s: String) -> Self { Self::from_str(&s) } } impl From<&String> for RantString { fn from(s: &String) -> Self { Self::from_str(s) } } impl From<char> for RantString { fn from(c: char) -> Self { Self::from_char(c) } }
fn add(self, rhs: Self) -> Self::Output { Self { raw: self.raw + rhs.raw, .. Default::default() } } } impl Display for RantString { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", &self.raw) } } impl PartialEq for RantString { fn eq(&self, other: &Self) -> bool { self.raw == other.raw } } impl PartialOrd for RantString { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { self.raw.partial_cmp(&other.raw) } }
impl Add for RantString { type Output = RantString;
tasklistmodel.go
// Package models defines the Models required in the project package models import ( "time" ) const ( layoutISO = "2006-01-02" ) //Task represents and defines a Task-List Item type Task struct { TimeCreatedModified int64 `json:"timeCreated" bson:"timeCreated"` TaskTitle string `json:"taskTitle" bson:"taskTitle"` DueDate int64 `json:"dueDate" bson:"dueDate"` TaskDone bool `json:"taskDone" bson:"taskDone"` } //ResultantTask represents and defines a Task-List Item to be sent type ResultantTask struct { TimeCreatedModified string `json:"timeCreated" bson:"timeCreated"` TaskTitle string `json:"taskTitle" bson:"taskTitle"` DueDate string `json:"dueDate" bson:"dueDate"` TaskDone bool `json:"taskDone" bson:"taskDone"` } //NewTask is responsible for creating a new instance of Task type func NewTask(taskTitle string, dueDate int64, taskDone bool) *Task { now := time.Now() unixTimestamp := now.Unix() t := Task{TimeCreatedModified: unixTimestamp, TaskTitle: taskTitle, DueDate: dueDate, TaskDone: taskDone}
func ConvertToResultantTask(t Task) ResultantTask { rt := ResultantTask{TimeCreatedModified: (time.Unix(t.TimeCreatedModified, 0).Format(layoutISO)), TaskTitle: t.TaskTitle, DueDate: (time.Unix(t.DueDate, 0).Format(layoutISO)), TaskDone: t.TaskDone} return rt }
return &t } //ConvertToResultantTask is responsible for converting system understandable JSON Task-list item into a more user friendly Task-list item JSON
rpc.py
# Copyright (c) 2012 OpenStack Foundation. # 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 itertools from oslo_log import log as logging import oslo_messaging from oslo_utils import timeutils from neutron.common import constants from neutron.common import rpc as n_rpc from neutron.common import topics from neutron.i18n import _LW LOG = logging.getLogger(__name__) def create_consumers(endpoints, prefix, topic_details, start_listening=True): """Create agent RPC consumers. :param endpoints: The list of endpoints to process the incoming messages. :param prefix: Common prefix for the plugin/agent message queues. :param topic_details: A list of topics. Each topic has a name, an operation, and an optional host param keying the subscription to topic.host for plugin calls. :param start_listening: if True, it starts the processing loop :returns: A common Connection. """ connection = n_rpc.create_connection(new=True) for details in topic_details: topic, operation, node_name = itertools.islice( itertools.chain(details, [None]), 3) topic_name = topics.get_topic_name(prefix, topic, operation) connection.create_consumer(topic_name, endpoints, fanout=True) if node_name: node_topic_name = '%s.%s' % (topic_name, node_name) connection.create_consumer(node_topic_name, endpoints, fanout=False) if start_listening: connection.consume_in_threads() return connection class PluginReportStateAPI(object): """RPC client used to report state back to plugin. This class implements the client side of an rpc interface. The server side can be found in neutron.db.agents_db.AgentExtRpcCallback. For more information on changing rpc interfaces, see doc/source/devref/rpc_api.rst. """ def __init__(self, topic): target = oslo_messaging.Target(topic=topic, version='1.0', namespace=constants.RPC_NAMESPACE_STATE) self.client = n_rpc.get_client(target) def report_state(self, context, agent_state, use_call=False): cctxt = self.client.prepare() kwargs = { 'agent_state': {'agent_state': agent_state}, 'time': timeutils.strtime(), } method = cctxt.call if use_call else cctxt.cast return method(context, 'report_state', **kwargs) class PluginApi(object):
'''Agent side of the rpc API. API version history: 1.0 - Initial version. 1.3 - get_device_details rpc signature upgrade to obtain 'host' and return value to include fixed_ips and device_owner for the device port 1.4 - tunnel_sync rpc signature upgrade to obtain 'host' ''' def __init__(self, topic): target = oslo_messaging.Target(topic=topic, version='1.0') self.client = n_rpc.get_client(target) def get_device_details(self, context, device, agent_id, host=None): cctxt = self.client.prepare() return cctxt.call(context, 'get_device_details', device=device, agent_id=agent_id, host=host) def get_devices_details_list(self, context, devices, agent_id, host=None): try: cctxt = self.client.prepare(version='1.3') res = cctxt.call(context, 'get_devices_details_list', devices=devices, agent_id=agent_id, host=host) except oslo_messaging.UnsupportedVersion: # If the server has not been upgraded yet, a DVR-enabled agent # may not work correctly, however it can function in 'degraded' # mode, in that DVR routers may not be in the system yet, and # it might be not necessary to retrieve info about the host. LOG.warn(_LW('DVR functionality requires a server upgrade.')) res = [ self.get_device_details(context, device, agent_id, host) for device in devices ] return res def update_device_down(self, context, device, agent_id, host=None): cctxt = self.client.prepare() return cctxt.call(context, 'update_device_down', device=device, agent_id=agent_id, host=host) def update_device_up(self, context, device, agent_id, host=None): cctxt = self.client.prepare() return cctxt.call(context, 'update_device_up', device=device, agent_id=agent_id, host=host) def tunnel_sync(self, context, tunnel_ip, tunnel_type=None, host=None): try: cctxt = self.client.prepare(version='1.4') res = cctxt.call(context, 'tunnel_sync', tunnel_ip=tunnel_ip, tunnel_type=tunnel_type, host=host) except oslo_messaging.UnsupportedVersion: LOG.warn(_LW('Tunnel synchronization requires a server upgrade.')) cctxt = self.client.prepare() res = cctxt.call(context, 'tunnel_sync', tunnel_ip=tunnel_ip, tunnel_type=tunnel_type) return res
types.ts
/* * Copyright 2021 ThoughtWorks, 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. */ import {Links} from "models/shared/links"; import {UserJSON} from "../users/users"; export interface ServerBackupJson { status: BackupStatus; message: string; time: Date; user: UserJSON; _links: any; progress_status?: BackupProgressStatus; } export enum BackupStatus { IN_PROGRESS, ERROR, COMPLETED, NOT_STARTED } export enum BackupProgressStatus { STARTING, CREATING_DIR, BACKUP_VERSION_FILE, BACKUP_CONFIG, BACKUP_WRAPPER_CONFIG, BACKUP_CONFIG_REPO,
BACKUP_DATABASE, POST_BACKUP_SCRIPT_START, POST_BACKUP_SCRIPT_COMPLETE } export class ServerBackup { readonly status: BackupStatus; readonly message: string; readonly time: Date; readonly username: string; readonly links: Links; readonly progressStatus?: BackupProgressStatus; constructor(status: BackupStatus, message: string, time: Date, username: string, links: Links, progressStatus?: BackupProgressStatus) { this.status = status; this.message = message; this.time = time; this.username = username; this.links = links; this.progressStatus = progressStatus; } static fromJSON(serverBackupJson: ServerBackupJson): ServerBackup { let progressStatus; if (serverBackupJson.progress_status) { progressStatus = BackupProgressStatus[serverBackupJson.progress_status]; } // @ts-ignore return new ServerBackup(BackupStatus[serverBackupJson.status], serverBackupJson.message, new Date(serverBackupJson.time), serverBackupJson.user.login_name, Links.fromJSON(serverBackupJson._links), progressStatus); } isInProgress(): boolean { return BackupStatus.IN_PROGRESS === this.status; } getStatus(): BackupStatus { return this.status; } getMessage(): string { return this.message; } isComplete(): boolean { return BackupStatus.COMPLETED === this.status; } }
chapter8p2.py
from manimlib.imports import * from old_projects.eola.chapter5 import get_det_text from old_projects.eola.chapter8 import * class OpeningQuote(Scene): def construct(self): words = TextMobject( "From [Grothendieck], I have also learned not", "to take glory in the ", "difficulty of a proof:", "difficulty means we have not understood.", "The idea is to be able to ", "paint a landscape", "in which the proof is obvious.", arg_separator = " " ) words.set_color_by_tex("difficulty of a proof:", RED) words.set_color_by_tex("paint a landscape", GREEN) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) author = TextMobject("-Pierre Deligne") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(4) self.play(Write(author, run_time = 3)) self.wait() class CrossProductSymbols(Scene): def construct(self): v_tex, w_tex, p_tex = get_vect_tex(*"vwp") equation = TexMobject( v_tex, "\\times", w_tex, "=", p_tex ) equation.set_color_by_tex(v_tex, V_COLOR) equation.set_color_by_tex(w_tex, W_COLOR) equation.set_color_by_tex(p_tex, P_COLOR) brace = Brace(equation[-1]) brace.stretch_to_fit_width(0.7) vector_text = brace.get_text("Vector") vector_text.set_color(RED) self.add(equation) self.play(*list(map(Write, [brace, vector_text]))) self.wait() class DeterminantTrickCopy(DeterminantTrick): pass class BruteForceVerification(Scene): def construct(self): v = Matrix(["v_1", "v_2", "v_3"]) w = Matrix(["w_1", "w_2", "w_3"]) v1, v2, v3 = v.get_entries() w1, w2, w3 = w.get_entries() v.set_color(V_COLOR) w.set_color(W_COLOR) def get_term(e1, e2, e3, e4): group = VGroup( e1.copy(), e2.copy(), TexMobject("-"), e3.copy(), e4.copy(), ) group.arrange() return group cross = Matrix(list(it.starmap(get_term, [ (v2, w3, v3, w2), (v3, w1, v1, w3), (v2, w3, v3, w2), ]))) cross_product = VGroup( v.copy(), TexMobject("\\times"), w.copy(), TexMobject("="), cross.copy() ) cross_product.arrange() cross_product.scale(0.75) formula_word = TextMobject("Numerical formula") computation_words = TextMobject(""" Facts you could (painfully) verify computationally """) computation_words.scale(0.75) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) computation_words.to_edge(UP, buff = MED_SMALL_BUFF/2) h_line.next_to(computation_words, DOWN) formula_word.next_to(h_line, UP, buff = MED_SMALL_BUFF) computation_words.shift(FRAME_X_RADIUS*RIGHT/2) formula_word.shift(FRAME_X_RADIUS*LEFT/2) cross_product.next_to(formula_word, DOWN, buff = LARGE_BUFF) self.add(formula_word, computation_words) self.play( ShowCreation(h_line), ShowCreation(v_line), Write(cross_product) ) v_tex, w_tex = get_vect_tex(*"vw") v_dot, w_dot = [ TexMobject( tex, "\\cdot", "(", v_tex, "\\times", w_tex, ")", "= 0" ) for tex in (v_tex, w_tex) ] theta_def = TexMobject( "\\theta", "= \\cos^{-1} \\big(", v_tex, "\\cdot", w_tex, "/", "(||", v_tex, "||", "\\cdot", "||", w_tex, "||)", "\\big)" ) length_check = TexMobject( "||", "(", v_tex, "\\times", w_tex, ")", "|| = ", "(||", v_tex, "||)", "(||", w_tex, "||)", "\\sin(", "\\theta", ")" ) last_point = h_line.get_center()+FRAME_X_RADIUS*RIGHT/2 max_width = FRAME_X_RADIUS-1 for mob in v_dot, w_dot, theta_def, length_check: mob.set_color_by_tex(v_tex, V_COLOR) mob.set_color_by_tex(w_tex, W_COLOR) mob.set_color_by_tex("\\theta", GREEN) mob.next_to(last_point, DOWN, buff = MED_SMALL_BUFF) if mob.get_width() > max_width: mob.set_width(max_width) last_point = mob self.play(FadeIn(mob)) self.wait() class ButWeCanDoBetter(TeacherStudentsScene): def construct(self): self.teacher_says("But we can do \\\\ better than that") self.change_student_modes(*["happy"]*3) self.random_blink(3) class Prerequisites(Scene): def construct(self): title = TextMobject("Prerequisites") title.to_edge(UP) title.set_color(YELLOW) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_width(FRAME_X_RADIUS - 1) left_rect, right_rect = [ rect.copy().shift(DOWN/2).to_edge(edge) for edge in (LEFT, RIGHT) ] chapter5 = TextMobject(""" \\centering Chapter 5 Determinants """) chapter7 = TextMobject(""" \\centering Chapter 7: Dot products and duality """) self.add(title) for chapter, rect in (chapter5, left_rect), (chapter7, right_rect): if chapter.get_width() > rect.get_width(): chapter.set_width(rect.get_width()) chapter.next_to(rect, UP) self.play( Write(chapter5), ShowCreation(left_rect) ) self.play( Write(chapter7), ShowCreation(right_rect) ) self.wait() class DualityReview(TeacherStudentsScene): def construct(self): words = TextMobject("Quick", "duality", "review") words[1].set_color_by_gradient(BLUE, YELLOW) self.teacher_says(words, target_mode = "surprised") self.change_student_modes("pondering") self.random_blink(2) class DotProductToTransformSymbol(Scene): CONFIG = { "vect_coords" : [2, 1] } def construct(self): v_mob = TexMobject(get_vect_tex("v")) v_mob.set_color(V_COLOR) matrix = Matrix([self.vect_coords]) vector = Matrix(self.vect_coords) matrix.set_column_colors(X_COLOR, Y_COLOR) vector.set_column_colors(YELLOW) _input = Matrix(["x", "y"]) _input.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR) left_input, right_input = [_input.copy() for x in range(2)] dot, equals = list(map(TexMobject, ["\\cdot", "="])) equation = VGroup( vector, dot, left_input, equals, matrix, right_input ) equation.arrange() left_brace = Brace(VGroup(vector, left_input)) right_brace = Brace(matrix, UP) left_words = left_brace.get_text("Dot product") right_words = right_brace.get_text("Transform") right_words.set_width(right_brace.get_width()) right_v_brace = Brace(right_input, UP) right_v_mob = v_mob.copy() right_v_brace.put_at_tip(right_v_mob) right_input.add(right_v_brace, right_v_mob) left_v_brace = Brace(left_input, UP) left_v_mob = v_mob.copy() left_v_brace.put_at_tip(left_v_mob) left_input.add(left_v_brace, left_v_mob) self.add(matrix, right_input) self.play( GrowFromCenter(right_brace), Write(right_words, run_time = 1) ) self.wait() self.play( Write(equals), Write(dot), Transform(matrix.copy(), vector), Transform(right_input.copy(), left_input) ) self.play( GrowFromCenter(left_brace), Write(left_words, run_time = 1) ) self.wait() class MathematicalWild(Scene): def construct(self): title = TextMobject("In the mathematical wild") title.to_edge(UP) self.add(title) randy = Randolph() randy.shift(DOWN) bubble = ThoughtBubble(width = 5, height = 4) bubble.write(""" \\centering Some linear transformation to the number line """) bubble.content.set_color(BLUE) bubble.content.shift(MED_SMALL_BUFF*UP/2) bubble.remove(*bubble[:-1]) bubble.add(bubble.content) bubble.next_to(randy.get_corner(UP+RIGHT), RIGHT) vector = Vector([1, 2]) vector.move_to(randy.get_corner(UP+LEFT), aligned_edge = DOWN+LEFT) dual_words = TextMobject("Dual vector") dual_words.set_color_by_gradient(BLUE, YELLOW) dual_words.next_to(vector, LEFT) self.add(randy) self.play(Blink(randy)) self.play(FadeIn(bubble)) self.play(randy.change_mode, "sassy") self.play(Blink(randy)) self.wait() self.play(randy.look, UP+LEFT) self.play( ShowCreation(vector), randy.change_mode, "raise_right_hand" ) self.wait() self.play(Write(dual_words)) self.play(Blink(randy)) self.wait() class ThreeStepPlan(Scene): def construct(self): title = TextMobject("The plan") title.set_color(YELLOW) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) v_tex, w_tex = get_vect_tex(*"vw") v_text, w_text, cross_text = [ "$%s$"%s for s in (v_tex, w_tex, v_tex + "\\times" + w_tex) ] steps = [ TextMobject( "1. Define a 3d-to-1d", "linear \\\\", "transformation", "in terms of", v_text, "and", w_text ), TextMobject( "2. Find its", "dual vector" ), TextMobject( "3. Show that this dual is", cross_text ) ] linear, transformation = steps[0][1:1+2] steps[0].set_color_by_tex(v_text, V_COLOR) steps[0].set_color_by_tex(w_text, W_COLOR) steps[1][1].set_color_by_gradient(BLUE, YELLOW) steps[2].set_color_by_tex(cross_text, P_COLOR) VGroup(*steps).arrange( DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ).next_to(h_line, DOWN, buff = MED_SMALL_BUFF) self.add(title) self.play(ShowCreation(h_line)) for step in steps: self.play(Write(step, run_time = 2)) self.wait() linear_transformation = TextMobject("Linear", "transformation") linear_transformation.next_to(h_line, DOWN, MED_SMALL_BUFF) det = self.get_det() rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(3.5) left_right_arrow = TexMobject("\\Leftrightarrow") left_right_arrow.shift(DOWN) det.next_to(left_right_arrow, LEFT) rect.next_to(left_right_arrow, RIGHT) steps[0].remove(linear, transformation) self.play( Transform( VGroup(linear, transformation), linear_transformation ), *list(map(FadeOut, steps)) ) self.wait() self.play(Write(left_right_arrow)) self.play(Write(det)) self.play(ShowCreation(rect)) self.wait(0) def get_det(self): matrix = Matrix(np.array([ ["\\hat{\\imath}", "\\hat{\\jmath}", "\\hat{k}"], ["v_%d"%d for d in range(1, 4)], ["w_%d"%d for d in range(1, 4)], ]).T) matrix.set_column_colors(X_COLOR, V_COLOR, W_COLOR) matrix.get_mob_matrix()[1, 0].set_color(Y_COLOR) matrix.get_mob_matrix()[2, 0].set_color(Z_COLOR) VGroup(*matrix.get_mob_matrix()[1, 1:]).shift(0.15*DOWN) VGroup(*matrix.get_mob_matrix()[2, 1:]).shift(0.35*DOWN) det_text = get_det_text(matrix) det_text.add(matrix) return det_text class DefineDualTransform(Scene): def construct(self): self.add_title() self.show_triple_cross_product() self.write_function() self.introduce_dual_vector() self.expand_dot_product() self.ask_question() def add_title(self): title = TextMobject("What a student might think") title.not_real = TextMobject("Not the real cross product") for mob in title, title.not_real: mob.set_width(FRAME_X_RADIUS - 1) mob.set_color(RED) mob.to_edge(UP) self.add(title) self.title = title def show_triple_cross_product(self): colors = [WHITE, ORANGE, W_COLOR] tex_mobs = list(map(TexMobject, get_vect_tex(*"uvw"))) u_tex, v_tex, w_tex = tex_mobs arrays = [ Matrix(["%s_%d"%(s, d) for d in range(1, 4)]) for s in "uvw" ] defs_equals = VGroup() definitions = VGroup() for array, tex_mob, color in zip(arrays, tex_mobs, colors): array.set_column_colors(color) tex_mob.set_color(color) equals = TexMobject("=") definition = VGroup(tex_mob, equals, array) definition.arrange(RIGHT) definitions.add(definition) defs_equals.add(equals) definitions.arrange(buff = MED_SMALL_BUFF) definitions.shift(2*DOWN) mobs_with_targets = list(it.chain( tex_mobs, *[a.get_entries() for a in arrays] )) for mob in mobs_with_targets: mob.target = mob.copy() matrix = Matrix(np.array([ [e.target for e in array.get_entries()] for array in arrays ]).T) det_text = get_det_text(matrix, background_rect = False) syms = times1, times2, equals = [ TexMobject(sym) for sym in ("\\times", "\\times", "=",) ] triple_cross = VGroup( u_tex.target, times1, v_tex.target, times2, w_tex.target, equals ) triple_cross.arrange() final_mobs = VGroup(triple_cross, VGroup(det_text, matrix)) final_mobs.arrange() final_mobs.next_to(self.title, DOWN, buff = MED_SMALL_BUFF) for mob in definitions, final_mobs: mob.set_width(FRAME_X_RADIUS - 1) for array in arrays: brackets = array.get_brackets() brackets.target = matrix.get_brackets() mobs_with_targets.append(brackets) for def_equals in defs_equals: def_equals.target = equals mobs_with_targets.append(def_equals) self.play(FadeIn( definitions, run_time = 2, lag_ratio = 0.5 )) self.wait(2) self.play(*[ Transform(mob.copy(), mob.target) for mob in tex_mobs ] + [ Write(times1), Write(times2), ]) triple_cross.add(*self.get_mobjects_from_last_animation()[:3]) self.play(*[ Transform(mob.copy(), mob.target) for mob in mobs_with_targets if mob not in tex_mobs ]) u_entries = self.get_mobjects_from_last_animation()[:3] v_entries = self.get_mobjects_from_last_animation()[3:6] w_entries = self.get_mobjects_from_last_animation()[6:9] self.play(Write(det_text)) self.wait(2) self.det_text = det_text self.definitions = definitions self.u_entries = u_entries self.v_entries = v_entries self.w_entries = w_entries self.matrix = matrix self.triple_cross = triple_cross self.v_tex, self.w_tex = v_tex, w_tex self.equals = equals def write_function(self): brace = Brace(self.det_text, DOWN) number_text = brace.get_text("Number") self.play(Transform(self.title, self.title.not_real)) self.wait() self.play(FadeOut(self.definitions)) self.play( GrowFromCenter(brace), Write(number_text) ) self.wait() x, y, z = variables = list(map(TexMobject, "xyz")) for var, entry in zip(variables, self.u_entries): var.scale(0.8) var.move_to(entry) entry.target = var brace.target = Brace(z) brace.target.stretch_to_fit_width(0.5) number_text.target = brace.target.get_text("Variable") v_brace = Brace(self.matrix.get_mob_matrix()[0, 1], UP) w_brace = Brace(self.matrix.get_mob_matrix()[0, 2], UP) for vect_brace, tex in (v_brace, self.v_tex), (w_brace, self.w_tex): vect_brace.stretch_to_fit_width(brace.target.get_width()) new_tex = tex.copy() vect_brace.put_at_tip(new_tex) vect_brace.tex = new_tex func_tex = TexMobject( "f\\left(%s\\right)"%matrix_to_tex_string(list("xyz")) ) func_tex.scale(0.7) func_input = Matrix(list("xyz")) func_input_template = VGroup(*func_tex[3:-2]) func_input.set_height(func_input_template.get_height()) func_input.next_to(VGroup(*func_tex[:3]), RIGHT) VGroup(*func_tex[-2:]).next_to(func_input, RIGHT) func_tex[0].scale_in_place(1.5) func_tex = VGroup( VGroup(*[func_tex[i] for i in (0, 1, 2, -2, -1)]), func_input ) func_tex.next_to(self.equals, LEFT) self.play( FadeOut(self.title), FadeOut(self.triple_cross), *[ Transform(mob, mob.target) for mob in [brace, number_text] ] ) self.play(*[ Transform(mob, mob.target) for mob in self.u_entries ]) self.play(*[ Write(VGroup(vect_brace, vect_brace.tex)) for vect_brace in (v_brace, w_brace) ]) self.wait() self.play(Write(func_tex)) self.wait() self.func_tex = func_tex self.variables_text = VGroup(brace, number_text) def introduce_dual_vector(self): everything = VGroup(*self.get_mobjects()) colors = [X_COLOR, Y_COLOR, Z_COLOR] q_marks = VGroup(*list(map(TextMobject, "???"))) q_marks.scale(2) q_marks.set_color_by_gradient(*colors) title = VGroup(TextMobject("This function is linear")) title.set_color(GREEN) title.to_edge(UP) matrix = Matrix([list(q_marks.copy())]) matrix.set_height(self.func_tex.get_height()/2) dual_vector = Matrix(list(q_marks)) dual_vector.set_height(self.func_tex.get_height()) dual_vector.get_brackets()[0].shift(0.2*LEFT) dual_vector.get_entries().shift(0.1*LEFT) dual_vector.scale(1.25) dual_dot = VGroup( dual_vector, TexMobject("\\cdot").next_to(dual_vector) ) matrix_words = TextMobject(""" $1 \\times 3$ matrix encoding the 3d-to-1d linear transformation """) self.play( Write(title, run_time = 2), everything.shift, DOWN ) self.remove(everything) self.add(*everything) self.wait() func, func_input = self.func_tex func_input.target = func_input.copy() func_input.target.scale(1.2) func_input.target.move_to(self.func_tex, aligned_edge = RIGHT) matrix.next_to(func_input.target, LEFT) dual_dot.next_to(func_input.target, LEFT) matrix_words.next_to(matrix, DOWN, buff = 1.5) matrix_words.shift_onto_screen() matrix_arrow = Arrow( matrix_words.get_top(), matrix.get_bottom(), color = WHITE ) self.play( Transform(func, matrix), MoveToTarget(func_input), FadeOut(self.variables_text), ) self.wait() self.play( Write(matrix_words), ShowCreation(matrix_arrow) ) self.wait(2) self.play(*list(map(FadeOut, [matrix_words, matrix_arrow]))) self.play( Transform(func, dual_vector), Write(dual_dot[1]) ) self.wait() p_coords = VGroup(*list(map(TexMobject, [ "p_%d"%d for d in range(1, 4) ]))) p_coords.set_color(RED) p_array = Matrix(list(p_coords)) p_array.set_height(dual_vector.get_height()) p_array.move_to(dual_vector, aligned_edge = RIGHT) p_brace = Brace(p_array, UP) p_tex = TexMobject(get_vect_tex("p")) p_tex.set_color(P_COLOR) p_brace.put_at_tip(p_tex) self.play( GrowFromCenter(p_brace), Write(p_tex) ) self.play(Transform( func, p_array, run_time = 2, lag_ratio = 0.5 )) self.remove(func) self.add(p_array) self.wait() self.play(FadeOut(title)) self.wait() self.p_array = p_array self.input_array = func_input def expand_dot_product(self): everything = VGroup(*self.get_mobjects()) self.play(everything.to_edge, UP) self.remove(everything) self.add(*everything) to_fade = VGroup() p_entries = self.p_array.get_entries() input_entries = self.input_array.get_entries() dot_components = VGroup() for p, x, i in zip(p_entries, input_entries, it.count()): if i == 2: x.sym = TexMobject("=") else: x.sym = TexMobject("+") p.sym = TexMobject("\\cdot") p.target = p.copy().scale(2) x.target = x.copy().scale(2) component = VGroup(p.target, p.sym, x.target, x.sym) component.arrange() dot_components.add(component) dot_components.arrange() dot_components.next_to(ORIGIN, LEFT) dot_components.shift(1.5*DOWN) dot_arrow = Arrow(self.p_array.get_corner(DOWN+RIGHT), dot_components) to_fade.add(dot_arrow) self.play(ShowCreation(dot_arrow)) new_ps = VGroup() for p, x in zip(p_entries, input_entries): self.play( MoveToTarget(p.copy()), MoveToTarget(x.copy()), Write(p.sym), Write(x.sym) ) mobs = self.get_mobjects_from_last_animation() new_ps.add(mobs[0]) to_fade.add(*mobs[1:]) self.wait() x, y, z = self.u_entries v1, v2, v3 = self.v_entries w1, w2, w3 = self.w_entries cross_components = VGroup() quints = [ (x, v2, w3, v3, w2), (y, v3, w1, v1, w3), (z, v1, w2, v2, w1), ] quints = [ [m.copy() for m in quint] for quint in quints ] for i, quint in enumerate(quints): sym_strings = ["(", "\\cdot", "-", "\\cdot", ")"] if i < 2: sym_strings[-1] += "+" syms = list(map(TexMobject, sym_strings)) for mob, sym in zip(quint, syms): mob.target = mob.copy() mob.target.scale(1.5) mob.sym = sym quint_targets = [mob.target for mob in quint] component = VGroup(*it.chain(*list(zip(quint_targets, syms)))) component.arrange() cross_components.add(component) to_fade.add(syms[0], syms[-1], quint[0]) cross_components.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) cross_components.next_to(dot_components, RIGHT) for quint in quints: self.play(*[ ApplyMethod(mob.set_color, YELLOW)
]) self.wait(0.5) self.play(*[ MoveToTarget(mob) for mob in quint ] + [ Write(mob.sym) for mob in quint ]) self.wait() self.play( ApplyFunction( lambda m : m.arrange( DOWN, buff = MED_SMALL_BUFF+SMALL_BUFF ).next_to(cross_components, LEFT), new_ps ), *list(map(FadeOut, to_fade)) ) self.play(*[ Write(TexMobject("=").next_to(p, buff = 2*SMALL_BUFF)) for p in new_ps ]) equals = self.get_mobjects_from_last_animation() self.wait(2) everything = everything.copy() self.play( FadeOut(VGroup(*self.get_mobjects())), Animation(everything) ) self.clear() self.add(everything) def ask_question(self): everything = VGroup(*self.get_mobjects()) p_tex = "$%s$"%get_vect_tex("p") question = TextMobject( "What vector", p_tex, "has \\\\ the property that" ) question.to_edge(UP) question.set_color(YELLOW) question.set_color_by_tex(p_tex, P_COLOR) everything.target = everything.copy() everything.target.next_to( question, DOWN, buff = MED_SMALL_BUFF ) self.play( MoveToTarget(everything), Write(question) ) self.wait() class WhyAreWeDoingThis(TeacherStudentsScene): def construct(self): self.student_says( "Um...why are \\\\ we doing this?", target_mode = "confused" ) self.random_blink() self.play(self.get_teacher().change_mode, "erm") self.change_student_modes("plain", "confused", "raise_left_hand") self.random_blink() self.change_student_modes("pondering", "confused", "raise_left_hand") self.random_blink(5) class ThreeDTripleCrossProduct(Scene): pass #Simple parallelepiped class ThreeDMovingVariableVector(Scene): pass #white u moves around class ThreeDMovingVariableVectorWithCrossShowing(Scene): pass #white u moves around, red p is present class NowForTheCoolPart(TeacherStudentsScene): def construct(self): self.teacher_says( "Now for the\\\\", "cool part" ) self.change_student_modes(*["happy"]*3) self.random_blink(2) self.teacher_says( "Let's answer the same question,\\\\", "but this time geometrically" ) self.change_student_modes(*["pondering"]*3) self.random_blink(2) class ThreeDDotProductProjection(Scene): pass # class DotProductWords(Scene): def construct(self): p_tex = "$%s$"%get_vect_tex("p") p_mob = TextMobject(p_tex) p_mob.scale(1.5) p_mob.set_color(P_COLOR) input_array = Matrix(list("xyz")) dot_product = VGroup(p_mob, Dot(radius = 0.07), input_array) dot_product.arrange(buff = MED_SMALL_BUFF/2) equals = TexMobject("=") dot_product.next_to(equals, LEFT) words = VGroup(*it.starmap(TextMobject, [ ("(Length of projection)",), ("(Length of ", p_tex, ")",) ])) times = TexMobject("\\times") words[1].set_color_by_tex(p_tex, P_COLOR) words[0].next_to(equals, RIGHT) words[1].next_to(words[0], DOWN, aligned_edge = LEFT) times.next_to(words[0], RIGHT) everyone = VGroup(dot_product, equals, times, words) everyone.center().set_width(FRAME_X_RADIUS - 1) self.add(dot_product) self.play(Write(equals)) self.play(Write(words[0])) self.wait() self.play( Write(times), Write(words[1]) ) self.wait() class ThreeDProjectToPerpendicular(Scene): pass # class GeometricVolumeWords(Scene): def construct(self): v_tex, w_tex = [ "$%s$"%s for s in get_vect_tex(*"vw") ] words = VGroup( TextMobject("(Area of", "parallelogram", ")$\\times$"), TextMobject( "(Component of $%s$"%matrix_to_tex_string(list("xyz")), "perpendicular to", v_tex, "and", w_tex, ")" ) ) words[0].set_color_by_tex("parallelogram", BLUE) words[1].set_color_by_tex(v_tex, ORANGE) words[1].set_color_by_tex(w_tex, W_COLOR) words.arrange(RIGHT) words.set_width(FRAME_WIDTH - 1) words.to_edge(DOWN, buff = SMALL_BUFF) for word in words: self.play(Write(word)) self.wait() class WriteXYZ(Scene): def construct(self): self.play(Write(Matrix(list("xyz")))) self.wait() class ThreeDDotProductWithCross(Scene): pass class CrossVectorEmphasisWords(Scene): def construct(self): v_tex, w_tex = ["$%s$"%s for s in get_vect_tex(*"vw")] words = [ TextMobject("Perpendicular to", v_tex, "and", w_tex), TextMobject("Length = (Area of ", "parallelogram", ")") ] for word in words: word.set_color_by_tex(v_tex, ORANGE) word.set_color_by_tex(w_tex, W_COLOR) word.set_color_by_tex("parallelogram", BLUE) self.play(Write(word)) self.wait() self.play(FadeOut(word)) class NextVideo(Scene): def construct(self): title = TextMobject(""" Next video: Change of basis """) title.to_edge(UP, buff = MED_SMALL_BUFF/2) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class ChangeOfBasisPreview(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 0 }, "t_matrix" : [[2, 1], [-1, 1]], "i_target_color" : YELLOW, "j_target_color" : MAROON_B, "sum_color" : PINK, "vector" : [-1, 2], } def construct(self): randy = Randolph() pinky = Mortimer(color = PINK) randy.to_corner(DOWN+LEFT) pinky.to_corner(DOWN+RIGHT) self.plane.fade() self.add_foreground_mobject(randy, pinky) coords = Matrix(self.vector) coords.add_to_back(BackgroundRectangle(coords)) self.add_foreground_mobject(coords) coords.move_to( randy.get_corner(UP+RIGHT), aligned_edge = DOWN+LEFT ) coords.target = coords.copy() coords.target.move_to( pinky.get_corner(UP+LEFT), aligned_edge = DOWN+RIGHT ) self.play( Write(coords), randy.change_mode, "speaking" ) self.scale_basis_vectors() self.apply_transposed_matrix( self.t_matrix, added_anims = [ MoveToTarget(coords), ApplyMethod(pinky.change_mode, "speaking"), ApplyMethod(randy.change_mode, "plain"), ] ) self.play( randy.change_mode, "erm", self.i_hat.set_color, self.i_target_color, self.j_hat.set_color, self.j_target_color, ) self.i_hat.color = self.i_target_color self.j_hat.color = self.j_target_color self.scale_basis_vectors() def scale_basis_vectors(self): for vect in self.i_hat, self.j_hat: vect.save_state() self.play(self.i_hat.scale, self.vector[0]) self.play(self.j_hat.scale, self.vector[1]) self.play(self.j_hat.shift, self.i_hat.get_end()) sum_vect = Vector(self.j_hat.get_end(), color = self.sum_color) self.play(ShowCreation(sum_vect)) self.wait(2) self.play( FadeOut(sum_vect), self.i_hat.restore, self.j_hat.restore, ) self.wait()
for mob in quint
datamodel_helpers.rs
use datamodel::{ dml::{ Datamodel, DefaultValue, Enum, Field, FieldArity, FieldType, IndexDefinition, Model, ScalarType, WithDatabaseName, }, RelationInfo, }; pub(crate) fn walk_models<'a>(datamodel: &'a Datamodel) -> impl Iterator<Item = ModelRef<'a>> + 'a { datamodel.models.iter().map(move |model| ModelRef { datamodel, model }) } /// Iterator to walk all the fields in the schema, associating them with their parent model. pub(super) fn walk_fields<'a>(datamodel: &'a Datamodel) -> impl Iterator<Item = FieldRef<'a>> + 'a { datamodel.models().flat_map(move |model| { model.fields().map(move |field| FieldRef { datamodel, model, field, }) }) } #[derive(Debug, Copy, Clone)] pub(crate) struct ModelRef<'a> { datamodel: &'a Datamodel, model: &'a Model, } impl<'a> ModelRef<'a> { pub(crate) fn new(model: &'a Model, datamodel: &'a Datamodel) -> Self { ModelRef { datamodel, model } } pub(super) fn database_name(&self) -> &'a str { self.model.database_name.as_ref().unwrap_or(&self.model.name) } pub(super) fn db_name(&self) -> &str { self.model.final_database_name() } pub(super) fn fields<'b>(&'b self) -> impl Iterator<Item = FieldRef<'a>> + 'b { self.model.fields().map(move |field| FieldRef { datamodel: self.datamodel, model: self.model, field, }) } pub(super) fn find_field(&self, name: &str) -> Option<FieldRef<'a>> { self.model .fields .iter() .find(|field| field.name == name) .map(|field| FieldRef { datamodel: self.datamodel, field, model: self.model, }) } pub(super) fn indexes<'b>(&'b self) -> impl Iterator<Item = &'a IndexDefinition> + 'b { self.model.indices.iter() } pub(super) fn name(&self) -> &'a str { &self.model.name } pub(super) fn id_fields<'b>(&'b self) -> impl Iterator<Item = FieldRef<'a>> + 'b { // Single-id models self.model .fields() .filter(|field| field.is_id) // Compound id models .chain( self.model .id_fields .iter() .filter_map(move |field_name| self.model.fields().find(|field| field.name.as_str() == field_name)), ) .map(move |field| FieldRef { datamodel: self.datamodel, model: self.model, field, }) } pub(super) fn unique_indexes<'b>(&'b self) -> impl Iterator<Item = IndexRef<'a>> + 'b { self.model .indices .iter() .filter(|index| index.is_unique()) .map(move |index| IndexRef { model: *self, index, datamodel: &self.datamodel, }) } } #[derive(Debug, Clone, Copy)] pub(super) struct FieldRef<'a> { datamodel: &'a Datamodel, model: &'a Model, field: &'a Field, } impl<'a> FieldRef<'a> { pub(super) fn arity(&self) -> FieldArity { self.field.arity } pub(super) fn db_name(&self) -> &'a str { self.field.final_database_name() } pub(super) fn default_value(&self) -> Option<&'a DefaultValue> { self.field.default_value.as_ref() } pub(super) fn field_type(&self) -> TypeRef<'a> { match &self.field.field_type { FieldType::Enum(name) => TypeRef::Enum(EnumRef { datamodel: self.datamodel, r#enum: self.datamodel.find_enum(name).unwrap(), }), FieldType::Base(scalar_type, _) => TypeRef::Base(*scalar_type), _ => TypeRef::Other, } } pub(super) fn as_relation_field(&self) -> Option<RelationFieldRef<'a>> { match &self.field.field_type { FieldType::Relation(relation_info) => Some(RelationFieldRef { field: *self, relation_info: relation_info, }), _ => None, } } pub(super) fn is_id(&self) -> bool { self.field.is_id } pub(super) fn is_required(&self) -> bool { match self.arity() { FieldArity::Required => true, _ => false, } } pub(super) fn is_unique(&self) -> bool { self.field.is_unique } pub(super) fn model(&self) -> ModelRef<'a> { ModelRef { model: self.model, datamodel: self.datamodel, } } pub(super) fn name(&self) -> &'a str { &self.field.name } } #[derive(Debug)] pub(super) enum TypeRef<'a> { Enum(EnumRef<'a>), Base(ScalarType), Other, } impl<'a> TypeRef<'a> { pub(super) fn as_enum(&self) -> Option<EnumRef<'a>> { match self { TypeRef::Enum(r) => Some(*r), _ => None, } } pub(super) fn is_json(&self) -> bool { matches!(self, TypeRef::Base(ScalarType::Json)) } } #[derive(Debug)] pub(super) struct RelationFieldRef<'a> { field: FieldRef<'a>, relation_info: &'a RelationInfo, } impl<'a> RelationFieldRef<'a> { pub(super) fn arity(&self) -> FieldArity { self.field.arity() } pub(crate) fn is_one_to_one(&self) -> bool { self.field.arity().is_singular() && self .opposite_side() .map(|rel| rel.field.arity().is_singular()) .unwrap_or(false) } pub(crate) fn is_virtual(&self) -> bool { self.relation_info.fields.is_empty() } pub(crate) fn opposite_side(&self) -> Option<RelationFieldRef<'a>>
pub(crate) fn referencing_columns<'b>(&'b self) -> impl Iterator<Item = &'a str> + 'b { self .relation_info .fields .iter() .map(move |field| { let model = self.field.model(); let field = model.find_field(field.as_str()) .expect(&format!("Unable to resolve field {} on {}, Expected relation `fields` to point to fields on the enclosing model.", field, model.name())); field.db_name() }) } pub(crate) fn referenced_columns<'b>(&'b self) -> impl Iterator<Item = &'a str> + 'b { self .relation_info .to_fields .iter() .map(move |field| { let model = self.referenced_model(); let field = model.find_field(field.as_str()) .expect(&format!("Unable to resolve field {} on {}, Expected relation `references` to point to fields on the related model.", field, model.name)); field.db_name() }) } pub(crate) fn relation_name(&self) -> &'a str { self.relation_info.name.as_ref() } pub(crate) fn referenced_table_name(&self) -> &'a str { self.referenced_model().final_database_name() } fn referenced_model(&self) -> &'a Model { self.field .datamodel .find_model(&self.relation_info.to) .ok_or_else(|| { anyhow::anyhow!( "Invariant violation: could not find model {} referenced in relation info.", self.relation_info.to ) }) .unwrap() } fn referenced_model_ref(&self) -> ModelRef<'a> { ModelRef { model: self.referenced_model(), datamodel: self.field.datamodel, } } } #[derive(Debug, Clone, Copy)] pub(super) struct EnumRef<'a> { pub(super) r#enum: &'a Enum, datamodel: &'a Datamodel, } impl<'a> EnumRef<'a> { pub(super) fn db_name(&self) -> &'a str { self.r#enum.final_database_name() } } #[derive(Debug)] pub(super) struct IndexRef<'a> { index: &'a IndexDefinition, model: ModelRef<'a>, datamodel: &'a Datamodel, } impl<'a> IndexRef<'a> { pub(super) fn fields<'b>(&'b self) -> impl Iterator<Item = FieldRef<'a>> + 'b { self.index.fields.iter().map(move |field_name| { self.model .fields() .find(|f| f.name() == field_name.as_str()) .expect("index on unknown model field") }) } }
{ self.referenced_model_ref() .fields() .filter_map(|f| f.as_relation_field()) .find(|relation_field| { relation_field.relation_name() == self.relation_name() && relation_field.referenced_model().name.as_str() == &self.field.model.name // This is to differentiate the opposite field from self in the self relation case. && relation_field.relation_info.to_fields != self.relation_info.to_fields && relation_field.relation_info.fields != self.relation_info.fields }) }
search-popover-notification.component.ts
import { animate, keyframes, style, transition, trigger } from '@angular/animations'; import { AfterViewInit, Component, Input, ViewChild, ViewEncapsulation } from '@angular/core'; import { PopoverDirective } from 'ngx-smart-popover'; import * as moment from 'moment'; import { setCookie, getCookie, hasCookie } from '../../cookies'; // TODO make sure this is actually the release date! const MONTH_AFTER_RELEASE = moment('2021-09-15', 'YYYY-MM-DD').add(1, 'months'); @Component({ selector: 'search-popover-notification', templateUrl: './search-popover-notification.component.html', styleUrls: ['./search-popover-notification.component.scss'], encapsulation: ViewEncapsulation.None, animations: [ trigger('mergeIconLeft', [ transition("unmerged => merged", [ animate("3s ease-out", keyframes([ style({ transform: "translate(0px, 0px)", offset: 0 }), style({ transform: "translate(0px, 0px)", offset: 0.3 }), style({ transform: "translate(14px, -7px)", offset: 0.7 }), style({ transform: "translate(14px, -10px)", offset: 1 }) ]))]) ]), trigger('mergeIconRight', [ transition("unmerged => merged", [ animate("3s ease-out", keyframes([ style({ transform: "translate(0px, 0px)", opacity: 1, offset: 0 }), style({ transform: "translate(0px, 0px)", opacity: 1, offset: 0.3 }), style({ transform: "translate(-14px, -7px)", opacity: 0.2, offset: 0.7 }), style({ transform: "translate(-14px, -7px)", opacity: 0.0, offset: 0.8 }), style({ transform: "translate(-14px, -10px)", opacity: 0, offset: 1 }) ]))]) ]) ] }) export class
implements AfterViewInit { @Input() upgradingLayer: boolean; @ViewChild("popoverTrigger") popoverTrigger: PopoverDirective; public animationState: string = "unmerged"; constructor() { } ngAfterViewInit(): void { let is_before_expiration = moment().isBefore(MONTH_AFTER_RELEASE) let has_seen_before = hasCookie("seenSearchUpdateNotification") && getCookie("seenSearchUpdateNotification") == "true"; // show only if we are within one month of release, we haven't dismissed the popup before, and we aren't upgrading a layer if (is_before_expiration && !has_seen_before && !this.upgradingLayer) { setTimeout(() => this.openPopover(), 2000); //show popover after two seconds to allow page to load } } private openPopover(): void { this.popoverTrigger.show(); // start the animation loop setTimeout(() => { this.animationState = "merged"; }, 0) } public closePopover(): void { this.popoverTrigger.hide(); // make sure the popover doesn't show on subsequent loads // save cookie for one month plus one day so that first-day users won't see it on the last day setCookie("seenSearchUpdateNotification", "true", 33); } onAnimationEnd(event) { //restart the animation this.animationState = 'unmerged'; if (event.toState === "unmerged") { setTimeout(() => { this.animationState = "merged"; }); } } }
SearchPopoverNotificationComponent
doc.go
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // Code generated by protoc-gen-go_gapic. DO NOT EDIT. // Package credentials is an auto-generated package for the // IAM Service Account Credentials API. // // Creates short-lived, limited-privilege credentials for IAM service // accounts. // // Use of Context // // The ctx passed to NewClient is used for authentication requests and // for creating the underlying connection, but is not used for subsequent calls. // Individual methods on the client use the ctx given to them. // // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more // please visit pkg.go.dev/cloud.google.com/go. package credentials // import "cloud.google.com/go/iam/credentials/apiv1" import ( "context" "os" "runtime" "strconv" "strings" "unicode" "google.golang.org/api/option" "google.golang.org/grpc/metadata" ) // For more information on implementing a client constructor hook, see // https://github.com/googleapis/google-cloud-go/wiki/Customizing-constructors. type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) const versionClient = "20210311" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) out = out.Copy() for _, md := range mds { for k, v := range md { out[k] = append(out[k], v...) } } return metadata.NewOutgoingContext(ctx, out) } func checkDisableDeadlines() (bool, error) { raw, ok := os.LookupEnv("GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE") if !ok { return false, nil } b, err := strconv.ParseBool(raw) return b, err } // DefaultAuthScopes reports the default set of authentication scopes to use with this package. func DefaultAuthScopes() []string { return []string{ "https://www.googleapis.com/auth/cloud-platform", } } // versionGo returns the Go runtime version. The returned string // has no whitespace, suitable for reporting in header. func versionGo() string { const develPrefix = "devel +" s := runtime.Version() if strings.HasPrefix(s, develPrefix) { s = s[len(develPrefix):] if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0
return s } notSemverRune := func(r rune) bool { return !strings.ContainsRune("0123456789.", r) } if strings.HasPrefix(s, "go1") { s = s[2:] var prerelease string if p := strings.IndexFunc(s, notSemverRune); p >= 0 { s, prerelease = s[:p], s[p:] } if strings.HasSuffix(s, ".") { s += "0" } else if strings.Count(s, ".") < 2 { s += ".0" } if prerelease != "" { s += "-" + prerelease } return s } return "UNKNOWN" }
{ s = s[:p] }
RegistrationForm.js
import React from 'react' import { Row, Col, Input, Button } from 'antd' import { PlusOutlined } from '@ant-design/icons'; import SubscriptionCard from './registration/SubscriptionCard'; import { SUBSCRIPTION_ERROR_OBJECT } from '../../../common/utils'; import SuccessfulRegistration from './registration/SuccessfulRegistration'; import FailedRegistration from './registration/FailedRegistration'; import Loader from '../common/Loader'; import ErrorMessage from '../common/ErrorMessage'; import { isSmallDevice } from '../../../common/utils' const isSmall = isSmallDevice(); const RegistrationForm = (props) => { const { onChangeSubscriptionField, onChangeRegistrationField, onAddSubscription, fetchDistricts, onRemoveSubscription, registerSubscription, registration, resetRegisterForm, } = props; const { subscriptions, phoneNumber, email, states, hasRegistered, regFailure, isLoading, errors, } = registration; return ( <div> <Row className={`${isSmall ? 'bring-to-front margin-one-half--top' : 'bring-to-front margin-large--top'}`}> <Row> <Col md={22} lg={18} sm={24} className='subheader-style margin---top margin-double--bottom'> <div style={{minWidth: isSmall ? '90vw' : '40vw'}}>Register </div></Col> </Row> <Row style={{display: 'contents'}}> <Col className={`background-grey border-round padding--sides padding--ends`} md={22} lg={18} sm={24} style={{width: '100%'}}> { isLoading ? <Loader /> : hasRegistered ? <SuccessfulRegistration resetRegisterForm={() => resetRegisterForm()} /> : regFailure ? <FailedRegistration resetRegisterForm={() => resetRegisterForm()} /> : <> <div className='para-style left margin--bottom'>Choose your preferences and get vaccine availability sent straight to your mailbox!</div> <div className='label'>Email:</div> <ErrorMessage message={errors.email} /> <Input autoComplete='off' name='email' block='true' value={email} onChange={(e) => onChangeRegistrationField({'email': e.target.value})} /> <div className='label'>Phone Number (optional):</div> <ErrorMessage message={errors.phoneNumber} /> <Input autoComplete='off' name='phone' block='true' value={phoneNumber} onChange={(e) => onChangeRegistrationField({'phoneNumber': e.target.value})}/> <div className='label'>Chosen Districts: </div> <ErrorMessage message={errors.chosenDistricts} /> { subscriptions.map((subscription, index) => { return ( <SubscriptionCard
fetchDistricts={(stateId) => fetchDistricts(stateId, index)} states={states} errors={errors.subscriptions[index] || SUBSCRIPTION_ERROR_OBJECT} /> ) }) } { subscriptions.length <= 5 ? <Button type="dashed" className='border-round' onClick={() => onAddSubscription()} block icon={<PlusOutlined />}> Add a district </Button> : null } <Button className='submit-button margin--top' onClick={() => registerSubscription()} block='true' > Subscribe to Notifications! </Button> </> } </Col> </Row> </Row> </div> ) } export default RegistrationForm
key={index} subscription={subscription} onChangeSubscriptionField={(changedField) => onChangeSubscriptionField(changedField, index)} onRemoveSubscription={() => onRemoveSubscription(index)}
blob.spec.js
'use strict' const test = require('japa') const AzureClient = require('../src/Drivers') const config = { driver: 'azure', container: 'adonis-driver-test', connection_string: 'UseDevelopmentStorage=true' } const containerString = `http://127.0.0.1:10000/devstoreaccount1/${config.container}` function bodyToString (response, length) { return new Promise((resolve, reject) => { response.readableStreamBody.on('readable', () => { const chunk = response.readableStreamBody.read(length) if (chunk) { resolve(chunk.toString()) } }) response.readableStreamBody.on('error', reject) }) } test.group('Blob storage testing', (group) => { group.before(async () => { const client = new AzureClient(config) if (!await client.existsContainer(config.container)) { await client.createContainer(config.container) } }) group.test('Create hello.txt file', async (assert) => { const client = new AzureClient(config) await client.put('hello.txt', Buffer.from('Hello world!')) assert.equal(await client.exists('hello.txt'), true) }) group.test('Create hello.txt file in folder', async (assert) => { const client = new AzureClient(config) const filePath = 'folder/hello.txt' await client.put(filePath, Buffer.from('Hello world!')) assert.equal(await client.exists(filePath), true) assert.equal(await client.getUrl(filePath), `${containerString}/${filePath}`) // Checking url is unescaped }) group.test('Create hello.txt file using Stream', async (assert) => { const client = new AzureClient(config) const { Readable } = require('stream') const buffer = Buffer.from('Hello world!') const readable = new Readable() readable._read = () => {} // _read is required but you can noop it readable.push(buffer) readable.push(null) await client.putStream('hello-stream.txt', readable) assert.equal(await client.exists('hello-stream.txt'), true) }) group.test('Check if file exists', async (assert) => { const client = new AzureClient(config) assert.equal(await client.exists('hello.txt'), true) }) group.test('Get hello.txt file', async (assert) => { const client = new AzureClient(config) assert.equal(await client.get('hello.txt'), 'Hello world!') }) group.test('Get hello.txt file as stream', async (assert) => { const client = new AzureClient(config) assert.equal(await bodyToString(await client.getStream('hello.txt')), 'Hello world!') }) // Disabled until next version of Azurite is released group.test('Move hello.txt file', async (assert) => { const client = new AzureClient(config) await client.move('hello.txt', 'hello-moved.txt') assert.equal(await client.exists('hello-moved.txt'), true) }) group.test('Copy hello.txt file', async (assert) => { const client = new AzureClient(config) await client.copy('hello-moved.txt', 'hello.txt') assert.equal(await client.exists('hello.txt'), true) })
group.test('Delete all created files (Clean up)', async (assert) => { const client = new AzureClient(config) await client.delete('hello.txt') await client.delete('hello-moved.txt') await client.delete('hello-stream.txt') await client.delete('folder/hello.txt') const doesExists = await client.exists('hello.txt') && await client.exists('hello-moved.txt') && await client.exists('hello-stream.txt') && await client.exists('folder/hello.txt') assert.equal(doesExists, false) }) group.after(async () => { const client = new AzureClient(config) await client.deleteContainer(config.container) }) })
glog_z_unit_chaining_test.go
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. package glog import ( "bytes" "fmt" "github.com/gogf/gf/os/gfile" "github.com/gogf/gf/os/gtime" "github.com/gogf/gf/test/gtest" "github.com/gogf/gf/text/gstr" "testing" "time" ) func Test_To(t *testing.T) { gtest.C(t, func(t *gtest.T) { w := bytes.NewBuffer(nil) To(w).Error(1, 2, 3)
t.Assert(gstr.Count(w.String(), defaultLevelPrefixes[LEVEL_ERRO]), 2) t.Assert(gstr.Count(w.String(), "1 2 3"), 2) }) } func Test_Path(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Stdout(false).Error(1, 2, 3) Path(path).File(file).Stdout(false).Errorf("%d %d %d", 1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 2) t.Assert(gstr.Count(content, "1 2 3"), 2) }) } func Test_Cat(t *testing.T) { gtest.C(t, func(t *gtest.T) { cat := "category" path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Cat(cat).Stdout(false).Error(1, 2, 3) Path(path).File(file).Cat(cat).Stdout(false).Errorf("%d %d %d", 1, 2, 3) content := gfile.GetContents(gfile.Join(path, cat, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 2) t.Assert(gstr.Count(content, "1 2 3"), 2) }) } func Test_Level(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Level(LEVEL_PROD).Stdout(false).Debug(1, 2, 3) Path(path).File(file).Level(LEVEL_PROD).Stdout(false).Debug("%d %d %d", 1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_DEBU]), 0) t.Assert(gstr.Count(content, "1 2 3"), 0) }) } func Test_Skip(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Skip(10).Stdout(false).Error(1, 2, 3) Path(path).File(file).Stdout(false).Errorf("%d %d %d", 1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 2) t.Assert(gstr.Count(content, "1 2 3"), 2) t.Assert(gstr.Count(content, "Stack"), 1) }) } func Test_Stack(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Stack(false).Stdout(false).Error(1, 2, 3) Path(path).File(file).Stdout(false).Errorf("%d %d %d", 1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 2) t.Assert(gstr.Count(content, "1 2 3"), 2) t.Assert(gstr.Count(content, "Stack"), 1) }) } func Test_StackWithFilter(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).StackWithFilter("none").Stdout(false).Error(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) t.Assert(gstr.Count(content, "Stack"), 1) fmt.Println("Content:") fmt.Println(content) }) gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).StackWithFilter("/gf/").Stdout(false).Error(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) t.Assert(gstr.Count(content, "Stack"), 0) fmt.Println("Content:") fmt.Println(content) }) } func Test_Header(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Header(true).Stdout(false).Error(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) }) gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Header(false).Stdout(false).Error(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_ERRO]), 0) t.Assert(gstr.Count(content, "1 2 3"), 1) }) } func Test_Line(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Line(true).Stdout(false).Debug(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_DEBU]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) t.Assert(gstr.Count(content, ".go"), 1) t.Assert(gstr.Contains(content, gfile.Separator), true) }) gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Line(false).Stdout(false).Debug(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_DEBU]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) t.Assert(gstr.Count(content, ".go"), 1) t.Assert(gstr.Contains(content, gfile.Separator), false) }) } func Test_Async(t *testing.T) { gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Async().Stdout(false).Debug(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(content, "") time.Sleep(200 * time.Millisecond) content = gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_DEBU]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) }) gtest.C(t, func(t *gtest.T) { path := gfile.TempDir(gtime.TimestampNanoStr()) file := fmt.Sprintf(`%d.log`, gtime.TimestampNano()) err := gfile.Mkdir(path) t.Assert(err, nil) defer gfile.Remove(path) Path(path).File(file).Async(false).Stdout(false).Debug(1, 2, 3) content := gfile.GetContents(gfile.Join(path, file)) t.Assert(gstr.Count(content, defaultLevelPrefixes[LEVEL_DEBU]), 1) t.Assert(gstr.Count(content, "1 2 3"), 1) }) }
To(w).Errorf("%d %d %d", 1, 2, 3)
follow_joint_trajectory_client.py
# Copyright 1996-2021 Cyberbotics Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generic client for the FollowJointTrajectory action used for multi-robot demonstration.""" from action_msgs.msg import GoalStatus from control_msgs.action import FollowJointTrajectory from control_msgs.msg import JointTrajectoryControllerState from trajectory_msgs.msg import JointTrajectoryPoint from builtin_interfaces.msg import Duration import rclpy from rclpy.action import ActionClient from rclpy.node import Node class FollowJointTrajectoryClient(Node): def __init__(self, name, prefix): super().__init__(name) self.__client = ActionClient(self, FollowJointTrajectory, prefix + '/follow_joint_trajectory') self.__state_subscriber = self.create_subscription( JointTrajectoryControllerState, prefix + '/state', self.__on_state_received, 1 ) self.__received_states_counter = 0 self.__remaining_iteration = 0 self.__current_trajectory = None self.__get_result_future = None self.__send_goal_future = None def __on_goal_response_callback(self, future): goal_handle = future.result() if not goal_handle.accepted: self.get_logger().info('Goal rejected by action server.') return self.get_logger().info('Goal accepted by action server.') self.__get_result_future = goal_handle.get_result_async() self.__get_result_future.add_done_callback(self.__on_get_result_callback) def __on_get_result_callback(self, future): status = future.result().status if status == GoalStatus.STATUS_SUCCEEDED: self.get_logger().info('Goal succeeded.') else: self.get_logger().info('Goal failed with status: {0}'.format(status)) if self.__remaining_iteration > 0: self.send_goal(self.__current_trajectory, self.__remaining_iteration - 1) else: rclpy.shutdown() def __on_state_received(self, _): self.__received_states_counter += 1 def send_goal(self, trajectory, iteration=1): self.get_logger().info('Waiting for action server to be ready...') self.__client.wait_for_server()
while self.__received_states_counter < 1: rclpy.spin_once(self) self.__current_trajectory = trajectory self.__remaining_iteration = iteration - 1 goal_message = FollowJointTrajectory.Goal() goal_message.trajectory.joint_names = trajectory['joint_names'] for point in trajectory['points']: trajectory_point = JointTrajectoryPoint( positions=point['positions'], time_from_start=Duration( sec=point['time_from_start']['sec'], nanosec=point['time_from_start']['nanosec'] ) ) goal_message.trajectory.points.append(trajectory_point) self.get_logger().info('Sending goal request...') self.__send_goal_future = self.__client.send_goal_async( goal_message ) self.__send_goal_future.add_done_callback(self.__on_goal_response_callback)
# WORKAROUND: The `wait_for_server()` method reports the `joint_trajectory_controller` node is ready even though it # needs a bit more time to get ready to receive commands.
providers.py
from typing import Any, Dict, Iterable, List, Optional, Union from resolvelib import AbstractProvider from resolvelib.resolvers import RequirementInformation from pdm.models.candidates import Candidate from pdm.models.repositories import BaseRepository from pdm.models.requirements import Requirement from pdm.models.specifiers import PySpecSet from pdm.utils import url_without_fragments class BaseProvider(AbstractProvider): def __init__( self, repository: BaseRepository, requires_python: PySpecSet, allow_prereleases: Optional[bool] = None, ) -> None: self.repository = repository self.requires_python = requires_python # Root python_requires value self.allow_prereleases = allow_prereleases # Root allow_prereleases value self.requires_python_collection: Dict[Optional[str], PySpecSet] = {} self.summary_collection: Dict[str, str] = {} self.fetched_dependencies: Dict[str, List[Requirement]] = {} def identify(self, req: Union[Requirement, Candidate]) -> Optional[str]: return req.identify() def get_preference( self, resolution: Candidate, candidates: List[Candidate], information: List[RequirementInformation], ) -> int: return len(candidates) def find_matches(self, requirements: List[Requirement]) -> Iterable[Candidate]: file_req = next((req for req in requirements if not req.is_named), None) if file_req: can = Candidate(file_req, self.repository.environment) can.get_metadata() candidates = [can] else: candidates = self.repository.find_candidates( requirements[0], self.requires_python, self.allow_prereleases ) return [ can for can in candidates if all(self.is_satisfied_by(r, can) for r in requirements) ] def is_satisfied_by(self, requirement: Requirement, candidate: Candidate) -> bool: if not requirement.is_named: return not candidate.req.is_named and url_without_fragments( candidate.req.url ) == url_without_fragments(requirement.url) if not candidate.version: candidate.get_metadata() if getattr(candidate, "_preferred", False) and not candidate._requires_python: candidate.requires_python = str( self.repository.get_dependencies(candidate)[1] ) allow_prereleases = requirement.allow_prereleases if allow_prereleases is None: allow_prereleases = self.allow_prereleases if allow_prereleases is None: # if not specified, should allow what `find_candidates()` returns allow_prereleases = True requires_python = self.requires_python & requirement.requires_python return requirement.specifier.contains( candidate.version, allow_prereleases ) and requires_python.is_subset(candidate.requires_python) def get_dependencies(self, candidate: Candidate) -> List[Requirement]: deps, requires_python, summary = self.repository.get_dependencies(candidate) # Filter out incompatible dependencies(e.g. functools32) early so that # we don't get errors when building wheels. valid_deps: List[Requirement] = [] for dep in deps: if ( dep.requires_python & requires_python & self.requires_python ).is_impossible: continue dep.requires_python &= candidate.req.requires_python valid_deps.append(dep) candidate_key = self.identify(candidate) self.fetched_dependencies[candidate_key] = valid_deps self.summary_collection[candidate.req.key] = summary self.requires_python_collection[candidate.req.key] = requires_python return valid_deps def get_hashes(self, candidate: Candidate) -> Optional[Dict[str, str]]: return self.repository.get_hashes(candidate) class ReusePinProvider(BaseProvider):
class EagerUpdateProvider(ReusePinProvider): """A specialized provider to handle an "eager" upgrade strategy. An eager upgrade tries to upgrade not only packages specified, but also their dependencies (recursively). This contrasts to the "only-if-needed" default, which only promises to upgrade the specified package, and prevents touching anything else if at all possible. The provider is implemented as to keep track of all dependencies of the specified packages to upgrade, and free their pins when it has a chance. """ def is_satisfied_by(self, requirement: Requirement, candidate: Candidate) -> bool: # If this is a tracking package, tell the resolver out of using the # preferred pin, and into a "normal" candidate selection process. if self.identify(requirement) in self.tracked_names and getattr( candidate, "_preferred", False ): return False return super().is_satisfied_by(requirement, candidate) def get_dependencies(self, candidate: Candidate) -> List[Requirement]: # If this package is being tracked for upgrade, remove pins of its # dependencies, and start tracking these new packages. dependencies = super().get_dependencies(candidate) if self.identify(candidate) in self.tracked_names: for dependency in dependencies: name = self.identify(dependency) self.tracked_names.add(name) return dependencies def get_preference( self, resolution: Candidate, candidates: List[Candidate], information: List[RequirementInformation], ) -> int: # Resolve tracking packages so we have a chance to unpin them first. name = self.identify(candidates[0]) if name in self.tracked_names: return -1 return len(candidates)
"""A provider that reuses preferred pins if possible. This is used to implement "add", "remove", and "reuse upgrade", where already-pinned candidates in lockfile should be preferred. """ def __init__( self, preferred_pins: Dict[str, Candidate], tracked_names: Iterable[str], *args: Any ) -> None: super().__init__(*args) self.preferred_pins = preferred_pins self.tracked_names = set(tracked_names) def find_matches(self, requirements: List[Requirement]) -> Iterable[Candidate]: ident = self.identify(requirements[0]) if ident not in self.tracked_names and ident in self.preferred_pins: pin = self.preferred_pins[ident] pin._preferred = True yield pin yield from super().find_matches(requirements)
uid.py
import os import threading from System.Core.Global import * from System.Core.Colors import * from System.Core.Modbus import * import ipcalc class Module: info = { 'Name': 'Brute Force UID', 'Author': ['@enddo'], 'Description': ("Brute Force UID"), } options = { 'RHOSTS' :['' ,True ,'The target address range or CIDR identifier'], 'RPORT' :[502 ,False ,'The port number for modbus protocol'], 'Function' :[1 ,False ,'Function code, Defualt:Read Coils.'], 'Threads' :[1 ,False ,'The number of concurrent threads'], 'Output' :[True ,False ,'The stdout save in output directory'] } output = '' def
(self): moduleName = self.info['Name'] print(bcolors.OKBLUE + '[+]' + bcolors.ENDC + ' Module ' + moduleName + ' Start') ips = list() for ip in ipcalc.Network(self.options['RHOSTS'][0]): ips.append(str(ip)) while ips: for i in range(int(self.options['Threads'][0])): if(len(ips) > 0): thread = threading.Thread(target=self.do,args=(ips.pop(0),)) thread.start() THREADS.append(thread) else: break for thread in THREADS: thread.join() if(self.options['Output'][0]): open(mainPath + '/Output/' + moduleName + '_' + self.options['RHOSTS'][0].replace('/','_') + '.txt','a').write('='*30 + '\n' + self.output + '\n\n') self.output = '' def printLine(self,str,color): self.output += str + '\n' if(str.find('[+]') != -1): print(str.replace('[+]', color + '[+]' + bcolors.ENDC)) elif(str.find('[-]') != -1): print(str.replace('[-]', color + '[+]' + bcolors.ENDC)) else: print(str) def do(self,ip): self.printLine('[+] Start Brute Force UID on : ' + ip,bcolors.OKGREEN) for i in range(10,11): # Total of 255 (legal) uid c = connectToTarget(ip,self.options['RPORT'][0]) if c is None: break try: c.sr1(ModbusADU(transId=getTransId(),unitId=i)/ModbusPDU_Read_Generic(funcCode=1),timeout=timeout, verbose=0) self.printLine('[+] UID on ' + ip + ' is : ' + str(i),bcolors.OKGREEN) closeConnectionToTarget(c) except Exception as e: print(e) closeConnectionToTarget(c)
exploit
client.go
/* Copyright 2017 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 github import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "strconv" "strings" "time" ) type Logger interface { Printf(s string, v ...interface{}) } type Client struct { // If Logger is non-nil, log all method calls with it. Logger Logger client *http.Client botName string token string base string dry bool fake bool } const ( githubBase = "https://api.github.com" maxRetries = 8 max404Retries = 2 maxSleepTime = 2 * time.Minute initialDelay = 2 * time.Second ) // NewClient creates a new fully operational GitHub client. func NewClient(botName, token string) *Client
// NewDryRunClient creates a new client that will not perform mutating actions // such as setting statuses or commenting, but it will still query GitHub and // use up API tokens. func NewDryRunClient(botName, token string) *Client { return &Client{ client: &http.Client{}, botName: botName, token: token, base: githubBase, dry: true, } } // NewFakeClient creates a new client that will not perform any actions at all. func NewFakeClient(botName string) *Client { return &Client{ botName: botName, fake: true, dry: true, } } func (c *Client) log(methodName string, args ...interface{}) { if c.Logger == nil { return } var as []string for _, arg := range args { as = append(as, fmt.Sprintf("%v", arg)) } c.Logger.Printf("%s(%s)", methodName, strings.Join(as, ", ")) } var timeSleep = time.Sleep type request struct { method string path string requestBody interface{} exitCodes []int } // Make a request with retries. If ret is not nil, unmarshal the response body // into it. Returns an error if the exit code is not one of the provided codes. func (c *Client) request(r *request, ret interface{}) (int, error) { if c.fake || (c.dry && r.method != http.MethodGet) { return r.exitCodes[0], nil } resp, err := c.requestRetry(r.method, r.path, r.requestBody) if err != nil { return 0, err } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { return 0, err } var okCode bool for _, code := range r.exitCodes { if code == resp.StatusCode { okCode = true break } } if !okCode { return resp.StatusCode, fmt.Errorf("status code %d not one of %v, body: %s", resp.StatusCode, r.exitCodes, string(b)) } if ret != nil { if err := json.Unmarshal(b, ret); err != nil { return 0, err } } return resp.StatusCode, nil } // Retry on transport failures. Retries on 500s, retries after sleep on // ratelimit exceeded, and retries 404s a couple times. func (c *Client) requestRetry(method, path string, body interface{}) (*http.Response, error) { var resp *http.Response var err error backoff := initialDelay for retries := 0; retries < maxRetries; retries++ { resp, err = c.doRequest(method, path, body) if err == nil { if resp.StatusCode == 404 && retries < max404Retries { // Retry 404s a couple times. Sometimes GitHub is inconsistent in // the sense that they send us an event such as "PR opened" but an // immediate request to GET the PR returns 404. We don't want to // retry more than a couple times in this case, because a 404 may // be caused by a bad API call and we'll just burn through API // tokens. resp.Body.Close() timeSleep(backoff) backoff *= 2 } else if resp.StatusCode == 403 && resp.Header.Get("X-RateLimit-Remaining") == "0" { // If we are out of API tokens, sleep first. The X-RateLimit-Reset // header tells us the time at which we can request again. var t int if t, err = strconv.Atoi(resp.Header.Get("X-RateLimit-Reset")); err == nil { // Sleep an extra second plus how long GitHub wants us to // sleep. If it's going to take too long, then break. sleepTime := time.Unix(int64(t), 0).Sub(time.Now()) + time.Second if sleepTime > 0 && sleepTime < maxSleepTime { timeSleep(sleepTime) } else { break } } resp.Body.Close() } else if resp.StatusCode < 500 { // Normal, happy case. break } else { // Retry 500 after a break. resp.Body.Close() timeSleep(backoff) backoff *= 2 } } else { timeSleep(backoff) backoff *= 2 } } return resp, err } func (c *Client) doRequest(method, path string, body interface{}) (*http.Response, error) { var buf io.Reader if body != nil { b, err := json.Marshal(body) if err != nil { return nil, err } buf = bytes.NewBuffer(b) } req, err := http.NewRequest(method, path, buf) if err != nil { return nil, err } req.Header.Set("Authorization", "Token "+c.token) if strings.HasSuffix(path, "reactions") { req.Header.Add("Accept", "application/vnd.github.squirrel-girl-preview") } else if strings.HasSuffix(path, "requested_reviewers") { req.Header.Add("Accept", "application/vnd.github.black-cat-preview+json") } else { req.Header.Add("Accept", "application/vnd.github.v3+json") } // Disable keep-alive so that we don't get flakes when GitHub closes the // connection prematurely. // https://go-review.googlesource.com/#/c/3210/ fixed it for GET, but not // for POST. req.Close = true return c.client.Do(req) } func (c *Client) BotName() string { return c.botName } // IsMember returns whether or not the user is a member of the org. func (c *Client) IsMember(org, user string) (bool, error) { c.log("IsMember", org, user) code, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("%s/orgs/%s/members/%s", c.base, org, user), exitCodes: []int{204, 404, 302}, }, nil) if err != nil { return false, err } if code == 204 { return true, nil } else if code == 404 { return false, nil } else if code == 302 { return false, fmt.Errorf("requester is not %s org member", org) } // Should be unreachable. return false, fmt.Errorf("unexpected status: %d", code) } // CreateComment creates a comment on the issue. func (c *Client) CreateComment(org, repo string, number int, comment string) error { c.log("CreateComment", org, repo, number, comment) ic := IssueComment{ Body: comment, } _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d/comments", c.base, org, repo, number), requestBody: &ic, exitCodes: []int{201}, }, nil) return err } // DeleteComment deletes the comment. func (c *Client) DeleteComment(org, repo string, ID int) error { c.log("DeleteComment", org, repo, ID) _, err := c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("%s/repos/%s/%s/issues/comments/%d", c.base, org, repo, ID), exitCodes: []int{204}, }, nil) return err } func (c *Client) EditComment(org, repo string, ID int, comment string) error { c.log("EditComment", org, repo, ID, comment) ic := IssueComment{ Body: comment, } _, err := c.request(&request{ method: http.MethodPatch, path: fmt.Sprintf("%s/repos/%s/%s/issues/comments/%d", c.base, org, repo, ID), requestBody: &ic, exitCodes: []int{200}, }, nil) return err } func (c *Client) CreateCommentReaction(org, repo string, ID int, reaction string) error { c.log("CreateCommentReaction", org, repo, ID, reaction) r := Reaction{Content: reaction} _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/issues/comments/%d/reactions", c.base, org, repo, ID), exitCodes: []int{201}, requestBody: &r, }, nil) return err } func (c *Client) CreateIssueReaction(org, repo string, ID int, reaction string) error { c.log("CreateIssueReaction", org, repo, ID, reaction) r := Reaction{Content: reaction} _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d/reactions", c.base, org, repo, ID), requestBody: &r, exitCodes: []int{200, 201}, }, nil) return err } // ListIssueComments returns all comments on an issue. This may use more than // one API token. func (c *Client) ListIssueComments(org, repo string, number int) ([]IssueComment, error) { c.log("ListIssueComments", org, repo, number) if c.fake { return nil, nil } nextURL := fmt.Sprintf("%s/repos/%s/%s/issues/%d/comments?per_page=100", c.base, org, repo, number) var comments []IssueComment for nextURL != "" { resp, err := c.requestRetry(http.MethodGet, nextURL, nil) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("return code not 2XX: %s", resp.Status) } b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var ics []IssueComment if err := json.Unmarshal(b, &ics); err != nil { return nil, err } comments = append(comments, ics...) nextURL = parseLinks(resp.Header.Get("Link"))["next"] } return comments, nil } // GetPullRequest gets a pull request. func (c *Client) GetPullRequest(org, repo string, number int) (*PullRequest, error) { c.log("GetPullRequest", org, repo, number) var pr PullRequest _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("%s/repos/%s/%s/pulls/%d", c.base, org, repo, number), exitCodes: []int{200}, }, &pr) return &pr, err } // GetPullRequestChanges gets a list of files modified in a pull request. func (c *Client) GetPullRequestChanges(pr PullRequest) ([]PullRequestChange, error) { c.log("GetPullRequestChanges", pr.Number) if c.fake { return []PullRequestChange{}, nil } nextURL := fmt.Sprintf("%s/repos/%s/pulls/%d/files", c.base, pr.Base.Repo.FullName, pr.Number) var changes []PullRequestChange for nextURL != "" { resp, err := c.requestRetry(http.MethodGet, nextURL, nil) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("return code not 2XX: %s", resp.Status) } b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var newChanges []PullRequestChange if err := json.Unmarshal(b, &newChanges); err != nil { return nil, err } changes = append(changes, newChanges...) nextURL = parseLinks(resp.Header.Get("Link"))["next"] } return changes, nil } // CreateStatus creates or updates the status of a commit. func (c *Client) CreateStatus(org, repo, ref string, s Status) error { c.log("CreateStatus", org, repo, ref, s) _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/statuses/%s", c.base, org, repo, ref), requestBody: &s, exitCodes: []int{201}, }, nil) return err } // GetCombinedStatus returns the latest statuses for a given ref. func (c *Client) GetCombinedStatus(org, repo, ref string) (*CombinedStatus, error) { c.log("GetCombinedStatus", org, repo, ref) var combinedStatus CombinedStatus _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("%s/repos/%s/%s/commits/%s/status", c.base, org, repo, ref), exitCodes: []int{200}, }, &combinedStatus) return &combinedStatus, err } func (c *Client) GetLabels(org, repo string) ([]Label, error) { c.log("GetLabel", org, repo) if c.fake { return nil, nil } nextURL := fmt.Sprintf("%s/repos/%s/%s/labels", c.base, org, repo) var labels []Label for nextURL != "" { resp, err := c.requestRetry(http.MethodGet, nextURL, nil) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("return code not 2XX: %s", resp.Status) } b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var labs []Label if err := json.Unmarshal(b, &labs); err != nil { return nil, err } labels = append(labels, labs...) nextURL = parseLinks(resp.Header.Get("Link"))["next"] } return labels, nil } func (c *Client) AddLabel(org, repo string, number int, label string) error { c.log("AddLabel", org, repo, number, label) _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d/labels", c.base, org, repo, number), requestBody: []string{label}, exitCodes: []int{200}, }, nil) return err } func (c *Client) RemoveLabel(org, repo string, number int, label string) error { c.log("RemoveLabel", org, repo, number, label) _, err := c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d/labels/%s", c.base, org, repo, number, label), // GitHub sometimes returns 200 for this call, which is a bug on their end. exitCodes: []int{200, 204}, }, nil) return err } type MissingUsers struct { Users []string action string } func (m MissingUsers) Error() string { return fmt.Sprintf("could not %s the following user(s): %s.", m.action, strings.Join(m.Users, ", ")) } func (c *Client) AssignIssue(org, repo string, number int, logins []string) error { c.log("AssignIssue", org, repo, number, logins) assigned := make(map[string]bool) var i Issue _, err := c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d/assignees", c.base, org, repo, number), requestBody: map[string][]string{"assignees": logins}, exitCodes: []int{201}, }, &i) if err != nil { return err } for _, assignee := range i.Assignees { assigned[assignee.Login] = true } missing := MissingUsers{action: "assign"} for _, login := range logins { if !assigned[login] { missing.Users = append(missing.Users, login) } } if len(missing.Users) > 0 { return missing } return nil } type ExtraUsers struct { Users []string action string } func (e ExtraUsers) Error() string { return fmt.Sprintf("could not %s the following user(s): %s.", e.action, strings.Join(e.Users, ", ")) } func (c *Client) UnassignIssue(org, repo string, number int, logins []string) error { c.log("UnassignIssue", org, repo, number, logins) assigned := make(map[string]bool) var i Issue _, err := c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d/assignees", c.base, org, repo, number), requestBody: map[string][]string{"assignees": logins}, exitCodes: []int{200}, }, &i) if err != nil { return err } for _, assignee := range i.Assignees { assigned[assignee.Login] = true } extra := ExtraUsers{action: "unassign"} for _, login := range logins { if assigned[login] { extra.Users = append(extra.Users, login) } } if len(extra.Users) > 0 { return extra } return nil } func (c *Client) tryRequestReview(org, repo string, number int, logins []string) (int, error) { c.log("RequestReview", org, repo, number, logins) var pr PullRequest return c.request(&request{ method: http.MethodPost, path: fmt.Sprintf("%s/repos/%s/%s/pulls/%d/requested_reviewers", c.base, org, repo, number), requestBody: map[string][]string{"reviewers": logins}, exitCodes: []int{http.StatusCreated /*201*/}, }, &pr) } // RequestReview tries to add the users listed in 'logins' as requested reviewers of the specified PR. // If any user in the 'logins' slice is not a contributor of the repo, the entire POST will fail // without adding any reviewers. The github API response does not specify which user(s) were invalid // so if we fail to request reviews from the members of 'logins' we try to request reviews from // each member individually. We try first with all users in 'logins' for efficiency in the common case. func (c *Client) RequestReview(org, repo string, number int, logins []string) error { statusCode, err := c.tryRequestReview(org, repo, number, logins) if err != nil && statusCode == http.StatusUnprocessableEntity /*422*/ { // Failed to set all members of 'logins' as reviewers, try individually. missing := MissingUsers{action: "request a PR review from"} for _, user := range logins { statusCode, err = c.tryRequestReview(org, repo, number, []string{user}) if err != nil && statusCode == http.StatusUnprocessableEntity /*422*/ { // User is not a contributor. missing.Users = append(missing.Users, user) } else if err != nil { return fmt.Errorf("failed to add reviewer to PR. Status code: %d, errmsg: %v", statusCode, err) } } if len(missing.Users) > 0 { return missing } return nil } return err } // UnrequestReview tries to remove the users listed in 'logins' from the requested reviewers of the // specified PR. The github API treats deletions of review requests differently than creations. Specifically, if // 'logins' contains a user that isn't a requested reviewer, other users that are valid are still removed. // Furthermore, the API response lists the set of requested reviewers after the deletion (unlike request creations), // so we can determine if each deletion was successful. // The API responds with http status code 200 no matter what the content of 'logins' is. func (c *Client) UnrequestReview(org, repo string, number int, logins []string) error { c.log("UnrequestReview", org, repo, number, logins) var pr PullRequest _, err := c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("%s/repos/%s/%s/pulls/%d/requested_reviewers", c.base, org, repo, number), requestBody: map[string][]string{"reviewers": logins}, exitCodes: []int{http.StatusOK /*200*/}, }, &pr) if err != nil { return err } extras := ExtraUsers{action: "remove the PR review request for"} for _, user := range pr.RequestedReviewers { found := false for _, toDelete := range logins { if user.Login == toDelete { found = true break } } if found { extras.Users = append(extras.Users, user.Login) } } if len(extras.Users) > 0 { return extras } return nil } func (c *Client) CloseIssue(org, repo string, number int) error { c.log("CloseIssue", org, repo, number) _, err := c.request(&request{ method: http.MethodPatch, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d", c.base, org, repo, number), requestBody: map[string]string{"state": "closed"}, exitCodes: []int{200}, }, nil) return err } // ReopenIssue re-opens the existing, closed issue provided func (c *Client) ReopenIssue(org, repo string, number int) error { c.log("ReopenIssue", org, repo, number) _, err := c.request(&request{ method: http.MethodPatch, path: fmt.Sprintf("%s/repos/%s/%s/issues/%d", c.base, org, repo, number), requestBody: map[string]string{"state": "open"}, exitCodes: []int{200}, }, nil) return err } // GetRef returns the SHA of the given ref, such as "heads/master". func (c *Client) GetRef(org, repo, ref string) (string, error) { c.log("GetRef", org, repo, ref) var res struct { Object map[string]string `json:"object"` } _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("%s/repos/%s/%s/git/refs/%s", c.base, org, repo, ref), exitCodes: []int{200}, }, &res) return res.Object["sha"], err } // FindIssues uses the github search API to find issues which match a particular query. // TODO(foxish): we should accept map[string][]string and use net/url properly. func (c *Client) FindIssues(query string) ([]Issue, error) { c.log("FindIssues", query) var issSearchResult IssuesSearchResult _, err := c.request(&request{ method: http.MethodGet, path: fmt.Sprintf("%s/search/issues?q=%s", c.base, query), exitCodes: []int{200}, }, &issSearchResult) return issSearchResult.Issues, err }
{ return &Client{ client: &http.Client{}, botName: botName, token: token, base: githubBase, dry: false, } }
ecdsakey.go
/* Copyright IBM Corp. 2016 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. */ package sw import ( "crypto/ecdsa" "crypto/x509" "fmt" "crypto/sha256" "errors" "github.com/hyperledger/fabric/core/crypto/bccsp" "github.com/hyperledger/fabric/core/crypto/primitives" ) type ecdsaPrivateKey struct {
// Bytes converts this key to its byte representation, // if this operation is allowed. func (k *ecdsaPrivateKey) Bytes() (raw []byte, err error) { return nil, errors.New("Not supported.") } // SKI returns the subject key identifier of this key. func (k *ecdsaPrivateKey) SKI() (ski []byte) { raw, _ := primitives.PrivateKeyToDER(k.privKey) // TODO: Error should not be thrown. Anyway, move the marshalling at initialization. hash := sha256.New() hash.Write(raw) return hash.Sum(nil) } // Symmetric returns true if this key is a symmetric key, // false if this key is asymmetric func (k *ecdsaPrivateKey) Symmetric() bool { return false } // Private returns true if this key is a private key, // false otherwise. func (k *ecdsaPrivateKey) Private() bool { return true } // PublicKey returns the corresponding public key part of an asymmetric public/private key pair. // This method returns an error in symmetric key schemes. func (k *ecdsaPrivateKey) PublicKey() (bccsp.Key, error) { return &ecdsaPublicKey{&k.privKey.PublicKey}, nil } type ecdsaPublicKey struct { pubKey *ecdsa.PublicKey } // Bytes converts this key to its byte representation, // if this operation is allowed. func (k *ecdsaPublicKey) Bytes() (raw []byte, err error) { raw, err = x509.MarshalPKIXPublicKey(k.pubKey) if err != nil { return nil, fmt.Errorf("Failed marshalling key [%s]", err) } return } // SKI returns the subject key identifier of this key. func (k *ecdsaPublicKey) SKI() (ski []byte) { raw, _ := primitives.PublicKeyToPEM(k.pubKey, nil) // TODO: Error should not be thrown. Anyway, move the marshalling at initialization. hash := sha256.New() hash.Write(raw) return hash.Sum(nil) } // Symmetric returns true if this key is a symmetric key, // false if this key is asymmetric func (k *ecdsaPublicKey) Symmetric() bool { return false } // Private returns true if this key is a private key, // false otherwise. func (k *ecdsaPublicKey) Private() bool { return false } // PublicKey returns the corresponding public key part of an asymmetric public/private key pair. // This method returns an error in symmetric key schemes. func (k *ecdsaPublicKey) PublicKey() (bccsp.Key, error) { return k, nil }
privKey *ecdsa.PrivateKey }
c_context_selector__toggle_PaddingLeft.d.ts
"var": "var(--pf-c-context-selector__toggle--PaddingLeft)" }; export default c_context_selector__toggle_PaddingLeft;
export const c_context_selector__toggle_PaddingLeft: { "name": "--pf-c-context-selector__toggle--PaddingLeft", "value": "0.5rem",
cognito_service.py
from uuid import UUID import dao.user_dao as dao from api import db from utils.common import PlutoException class InvalidUserException(PlutoException): pass def
(username: str, user_attributes): uuid = UUID(user_attributes.get('sub', None)) existing_user = dao.find_user(uuid) if existing_user is not None: return existing_user email = user_attributes.get('email', None) name = user_attributes.get('name', None) if username and email: user = dao.create_user(uuid, username, email, name) db.session.commit() return user raise InvalidUserException("Username or email not defined")
create_user
caffe.py
# -*- coding: utf-8 -*- from .__module__ import Module, dependency, source from .tools import Tools from .boost import Boost from .python import Python from .opencv import Opencv @dependency(Tools, Python, Boost, Opencv) @source('git') class Caffe(Module): def build(self): pyver = self.composer.ver(Python) cpu_only = self.composer.cuda_ver is None return (r''' $GIT_CLONE https://github.com/BVLC/caffe ~/caffe && \ cp ~/caffe/Makefile.config.example ~/caffe/Makefile.config && \ sed -i 's/# %s/%s/g' ~/caffe/Makefile.config && \ ''' % ( ('CPU_ONLY', 'CPU_ONLY') if cpu_only else \ ('USE_CUDNN', 'USE_CUDNN') \ )).rstrip() + ( '' if pyver == '2.7' else r''' sed -i 's/# PYTHON_LIBRARIES/PYTHON_LIBRARIES/g' ''' + r'''~/caffe/Makefile.config && \ '''.rstrip() ) + r''' sed -i 's/# WITH_PYTHON_LAYER/WITH_PYTHON_LAYER/g' ''' \ + r'''~/caffe/Makefile.config && \ sed -i 's/# OPENCV_VERSION/OPENCV_VERSION/g' ''' \ + r'''~/caffe/Makefile.config && \ '''.rstrip() + ( r'' if cpu_only else r''' sed -i 's/# USE_NCCL/USE_NCCL/g' ~/caffe/Makefile.config && \ sed -i 's/-gencode arch=compute_20,code=sm_20//g' ~/caffe/Makefile.config && \ sed -i 's/-gencode arch=compute_20,code=sm_21//g' ~/caffe/Makefile.config && \
'''.rstrip() ) + (r''' sed -i 's/2\.7/3\.5/g' ~/caffe/Makefile.config && \ ''' if pyver == '3.5' else ( r''' sed -i 's/2\.7/3\.6/g' ~/caffe/Makefile.config && \ sed -i 's/3\.5/3\.6/g' ~/caffe/Makefile.config && \ ''' if pyver == '3.6' else r''' ''' )).rstrip() + r''' sed -i 's/\/usr\/lib\/python/\/usr\/local\/lib\/python/g' ''' \ + r'''~/caffe/Makefile.config && \ sed -i 's/\/usr\/local\/include/\/usr\/local\/include ''' \ + r'''\/usr\/include\/hdf5\/serial/g' ~/caffe/Makefile.config && \ sed -i 's/hdf5/hdf5_serial/g' ~/caffe/Makefile && \ cd ~/caffe && \ make -j"$(nproc)" -Wno-deprecated-gpu-targets distribute && \ # fix ValueError caused by python-dateutil 1.x sed -i 's/,<2//g' ~/caffe/python/requirements.txt && \ $PIP_INSTALL \ -r ~/caffe/python/requirements.txt && \ cd ~/caffe/distribute/bin && \ for file in *.bin; do mv "$file" "${file%%%%.bin}"; done && \ cd ~/caffe/distribute && \ cp -r bin include lib proto /usr/local/ && \ cp -r python/caffe /usr/local/lib/python%s/dist-packages/ && \ ''' % pyver