code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author vignesh */ public class AutoCommandGroup extends CommandGroup { public AutoCommandGroup() { addParallel(new autoClawArmDownCommand()); addParallel(new CompressorCommand()); addSequential(new autoWinchCommand()); addSequential(new autoUnwinchCommand()); addSequential(new openLatchCommand()); addSequential(new AutoDriveCommand()); } }
viggy96/FRCteam3331_2014
src/edu/wpi/first/wpilibj/templates/commands/AutoCommandGroup.java
Java
bsd-3-clause
528
## # Contains all logic for gathering and displaying backtraces. class Backtrace include Enumerable attr_accessor :frames attr_accessor :top_context attr_accessor :first_color attr_accessor :kernel_color attr_accessor :eval_color def initialize @frames = [] @top_context = nil @first_color = "\033[0;31m" @kernel_color = "\033[0;34m" @eval_color = "\033[0;33m" end def [](index) @frames[index] end def show(sep="\n", colorize = true) first = true color_config = Rubinius::RUBY_CONFIG["rbx.colorize_backtraces"] if color_config == "no" or color_config == "NO" colorize = false color = "" clear = "" else clear = "\033[0m" end formatted = @frames.map do |ctx| recv = ctx.describe loc = ctx.location color = color_from_loc(loc, first) if colorize first = false # special handling for first line times = @max - recv.size times = 0 if times < 0 "#{color} #{' ' * times}#{recv} at #{loc}#{clear}" end return formatted.join(sep) end def join(sep) show end alias_method :to_s, :show def color_from_loc(loc, first) return @first_color if first if loc =~ /kernel/ @kernel_color elsif loc =~ /\(eval\)/ @eval_color else "" end end MAX_WIDTH = 40 def fill_backtrace @max = 0 @backtrace = [] # Skip the first frame if we are raising an exception from # an eval's BlockContext if @frames.at(0).from_eval? frames = @frames[1, @frames.length - 1] else frames = @frames end frames.each_with_index do |ctx, i| str = ctx.describe @max = str.size if str.size > @max @backtrace << [str, ctx.location] end @max = MAX_WIDTH if @max > MAX_WIDTH end def self.backtrace(ctx=nil) ctx ||= MethodContext.current.sender obj = new() obj.top_context = ctx obj.frames = ctx.context_stack # TODO - Consider not doing this step if we know we want MRI output obj.fill_backtrace return obj end def each @backtrace.each { |f| yield f.last } self end def to_mri return @top_context.stack_trace_starting_at(0) end end
chad/rubinius
kernel/delta/backtrace.rb
Ruby
bsd-3-clause
2,223
// Copyright (c) 2015 Mute Communications Ltd. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mixcrypt import ( "bytes" "crypto/rand" "crypto/sha256" "testing" "github.com/agl/ed25519" "github.com/mutecomm/mute/mix/mixaddr" "github.com/mutecomm/mute/mix/nymaddr" "github.com/mutecomm/mute/util/times" "golang.org/x/crypto/curve25519" ) var testMessage = []byte(` This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. This message needs to be 4096 byte long, no less, more is permissable. It's because the constants are that way. `) func TestClientMixHeader(t *testing.T) { testData := ClientMixHeader{ MessageType: MessageTypeRelay, SenderMinDelay: 10, SenderMaxDelay: 30, Token: []byte("Token"), Address: []byte("Address"), RevokeID: []byte("RevokeID"), } asn := testData.Marshal() testData2, lenB, err := new(ClientMixHeader).Unmarshal(asn) if err != nil { t.Fatalf("Unmarshal failed: %s", err) } if len(asn) != int(lenB) { t.Errorf("Bad length returned: %d != %d", len(asn), lenB) } if !bytes.Equal(testData.Token, testData2.Token) { t.Error("Decode: Token") } if !bytes.Equal(testData.Address, testData2.Address) { t.Error("Decode: Address") } if !bytes.Equal(testData.RevokeID, testData2.RevokeID) { t.Error("Decode: RevokeID") } if testData.MessageType != testData2.MessageType { t.Error("Decode: MessageType") } if testData.SenderMinDelay != testData2.SenderMinDelay { t.Error("Decode: SenderMinDelay") } if testData.SenderMaxDelay != testData2.SenderMaxDelay { t.Error("Decode: SenderMaxDelay") } } func TestSendReceiveForward(t *testing.T) { NextHop := "mix1@mute.berlin" NextHopPrivKey, _ := genNonce() NextHopPubKey := new([KeySize]byte) curve25519.ScalarBaseMult(NextHopPubKey, NextHopPrivKey) clientHeader := ClientMixHeader{ SenderMinDelay: 10, SenderMaxDelay: 30, Token: []byte("Example token"), } encMessage, nextaddress, err := clientHeader.NewForwardMessage(NextHop, NextHopPubKey, testMessage) if err != nil { t.Fatalf("NewForwardMessage: %s", err) } if nextaddress != NextHop { t.Error("Bad NextHop") } receiveData, err := ReceiveMessage(func(*[KeySize]byte) *[KeySize]byte { return NextHopPrivKey }, encMessage) if err != nil { t.Fatalf("ReceiveMessage: %s", err) } if !bytes.Equal(receiveData.Message, testMessage) { t.Error("Messages dont match") } if !bytes.Equal(receiveData.MixHeader.Token, clientHeader.Token) { t.Error("Tokens dont match") } if string(receiveData.MixHeader.Address) != NextHop { t.Error("Next hop doesnt match") } if receiveData.MixHeader.SenderMaxDelay != clientHeader.SenderMaxDelay { t.Error("Max delay does not match") } if receiveData.MixHeader.SenderMinDelay != clientHeader.SenderMinDelay { t.Error("Min delay does not match") } if len(receiveData.UniqueTest) != 1 { t.Error("Only one uniquetest should be done") } } func TestSendReceiveRelay(t *testing.T) { _, privkey, _ := ed25519.GenerateKey(rand.Reader) mixAddress := "mix01@mute.berlin" recAddress := "mailbox001@001." pseudonym := []byte("Pseudonym001") pseudoHash := sha256.Sum256(pseudonym) kl := mixaddr.New(privkey, mixAddress, 7200, 24*3600, "/tmp/mixkeydir") kl.AddKey() stmt := kl.GetStatement() // AddressTemplate contains parameters for address creation addressTemplate := nymaddr.AddressTemplate{ Secret: []byte("something super-secret"), MixCandidates: stmt.Addresses, Expire: times.Now() + 3600, SingleUse: true, MinDelay: 10, MaxDelay: 30, } NymAddress, err := addressTemplate.NewAddress([]byte(recAddress), pseudoHash[:]) if err != nil { t.Fatalf("NewAddress: %s", err) } clientHeader := ClientMixHeader{ SenderMinDelay: 10, SenderMaxDelay: 30, Token: []byte("Example token"), } encMessage, nextaddress, err := clientHeader.NewRelayMessage(NymAddress, testMessage) if err != nil { t.Fatalf("NewRelayMessage: %s", err) } if nextaddress != mixAddress { t.Error("Bad NextHop") } receiveData, err := ReceiveMessage(kl.GetPrivateKey, encMessage) if err != nil { t.Fatalf("ReceiveMessage: %s", err) } if len(receiveData.UniqueTest) != 2 { t.Error("SingleUse nymaddress, exactly two uniquetests necessary") } if !bytes.Equal(receiveData.Message, testMessage) { t.Error("Messages dont match") } if !bytes.Equal(receiveData.MixHeader.Token, clientHeader.Token) { t.Error("Tokens dont match") } if receiveData.MixHeader.SenderMaxDelay != clientHeader.SenderMaxDelay { t.Error("Max delay does not match") } if receiveData.MixHeader.SenderMinDelay != clientHeader.SenderMinDelay { t.Error("Min delay does not match") } newMessage, nextaddress, err := receiveData.Send() if err != nil { t.Fatalf("Send-Along: %s", err) } if nextaddress != "mailbox001@001.mute.one" { t.Error("Bad address expansion") } decMessage, nym, err := ReceiveFromMix(addressTemplate, []byte(recAddress), newMessage) if err != nil { t.Fatalf("ReceiveFromMix: %s", err) } if !bytes.Equal(nym, pseudoHash[:]) { t.Error("Nyms do not match") } if !bytes.Equal(decMessage, testMessage) { t.Error("Message decryption failed") } }
JonathanLogan/mute
mix/mixcrypt/clientmix_test.go
GO
bsd-3-clause
9,542
#mixin to automate testing of Rest services per controller test require 'libxml' require 'pp' module RestTestCases SCHEMA_FILE_PATH = File.join(Rails.root, 'public', '2010', 'xml', 'rest', 'schema-v1.xsd') def test_index_rest_api_xml #to make sure something in the database is created object=rest_api_test_object get :index, :format=>"xml" perform_api_checks end def test_get_rest_api_xml object=rest_api_test_object get :show,:id=>object, :format=>"xml" perform_api_checks end def perform_api_checks assert_response :success valid,message = check_xml assert valid,message validate_xml_against_schema(@response.body) end def check_xml assert_equal 'application/xml', @response.content_type xml=@response.body return false,"XML is nil" if xml.nil? return true,"" end def validate_xml_against_schema(xml,schema=SCHEMA_FILE_PATH) document = LibXML::XML::Document.string(xml) schema = LibXML::XML::Schema.new(schema) result = true begin document.validate_schema(schema) rescue LibXML::XML::Error => e result = false assert false,"Error validating against schema: #{e.message}" end return result end def display_xml xml x=1 xml.split("\n").each do |line| puts "#{x} #{line}" x=x+1 end end end
aina1205/virtualliverf1
test/rest_test_cases.rb
Ruby
bsd-3-clause
1,407
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/password_manager/password_store_mac.h" #include "chrome/browser/password_manager/password_store_mac_internal.h" #include "chrome/common/chrome_paths.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "content/public/test/test_browser_thread.h" #include "crypto/mock_apple_keychain.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using base::WideToUTF16; using content::BrowserThread; using crypto::MockAppleKeychain; using internal_keychain_helpers::FormsMatchForMerge; using internal_keychain_helpers::STRICT_FORM_MATCH; using testing::_; using testing::DoAll; using testing::Invoke; using testing::WithArg; namespace { class MockPasswordStoreConsumer : public PasswordStoreConsumer { public: MOCK_METHOD1(OnGetPasswordStoreResults, void(const std::vector<autofill::PasswordForm*>&)); void CopyElements(const std::vector<autofill::PasswordForm*>& forms) { last_result.clear(); for (size_t i = 0; i < forms.size(); ++i) { last_result.push_back(*forms[i]); } } std::vector<PasswordForm> last_result; }; ACTION(STLDeleteElements0) { STLDeleteContainerPointers(arg0.begin(), arg0.end()); } ACTION(QuitUIMessageLoop) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::MessageLoop::current()->Quit(); } class TestPasswordStoreMac : public PasswordStoreMac { public: TestPasswordStoreMac( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner, scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner, crypto::AppleKeychain* keychain, LoginDatabase* login_db) : PasswordStoreMac(main_thread_runner, db_thread_runner, keychain, login_db) { } using PasswordStoreMac::GetBackgroundTaskRunner; private: virtual ~TestPasswordStoreMac() {} DISALLOW_COPY_AND_ASSIGN(TestPasswordStoreMac); }; } // namespace #pragma mark - class PasswordStoreMacInternalsTest : public testing::Test { public: virtual void SetUp() { MockAppleKeychain::KeychainTestData test_data[] = { // Basic HTML form. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20020601171500Z", "joe_user", "sekrit", false }, // HTML form with path. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 0, NULL, "19991231235959Z", "joe_user", "sekrit", false }, // Secure HTML form with path. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTPS, "/secure.html", 0, NULL, "20100908070605Z", "secure_user", "password", false }, // True negative item. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20000101000000Z", "", "", true }, // De-facto negative item, type one. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20000101000000Z", "Password Not Stored", "", false }, // De-facto negative item, type two. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTPS, NULL, 0, NULL, "20000101000000Z", "Password Not Stored", " ", false }, // HTTP auth basic, with port and path. { kSecAuthenticationTypeHTTPBasic, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 4567, "low_security", "19980330100000Z", "basic_auth_user", "basic", false }, // HTTP auth digest, secure. { kSecAuthenticationTypeHTTPDigest, "some.domain.com", kSecProtocolTypeHTTPS, NULL, 0, "high_security", "19980330100000Z", "digest_auth_user", "digest", false }, // An FTP password with an invalid date, for edge-case testing. { kSecAuthenticationTypeDefault, "a.server.com", kSecProtocolTypeFTP, NULL, 0, NULL, "20010203040", "abc", "123", false }, }; keychain_ = new MockAppleKeychain(); for (unsigned int i = 0; i < arraysize(test_data); ++i) { keychain_->AddTestItem(test_data[i]); } } virtual void TearDown() { ExpectCreatesAndFreesBalanced(); ExpectCreatorCodesSet(); delete keychain_; } protected: // Causes a test failure unless everything returned from keychain_'s // ItemCopyAttributesAndData, SearchCreateFromAttributes, and SearchCopyNext // was correctly freed. void ExpectCreatesAndFreesBalanced() { EXPECT_EQ(0, keychain_->UnfreedSearchCount()); EXPECT_EQ(0, keychain_->UnfreedKeychainItemCount()); EXPECT_EQ(0, keychain_->UnfreedAttributeDataCount()); } // Causes a test failure unless any Keychain items added during the test have // their creator code set. void ExpectCreatorCodesSet() { EXPECT_TRUE(keychain_->CreatorCodesSetForAddedItems()); } MockAppleKeychain* keychain_; }; #pragma mark - // Struct used for creation of PasswordForms from static arrays of data. struct PasswordFormData { const PasswordForm::Scheme scheme; const char* signon_realm; const char* origin; const char* action; const wchar_t* submit_element; const wchar_t* username_element; const wchar_t* password_element; const wchar_t* username_value; // Set to NULL for a blacklist entry. const wchar_t* password_value; const bool preferred; const bool ssl_valid; const double creation_time; }; // Creates and returns a new PasswordForm built from form_data. Caller is // responsible for deleting the object when finished with it. static PasswordForm* CreatePasswordFormFromData( const PasswordFormData& form_data) { PasswordForm* form = new PasswordForm(); form->scheme = form_data.scheme; form->preferred = form_data.preferred; form->ssl_valid = form_data.ssl_valid; form->date_created = base::Time::FromDoubleT(form_data.creation_time); if (form_data.signon_realm) form->signon_realm = std::string(form_data.signon_realm); if (form_data.origin) form->origin = GURL(form_data.origin); if (form_data.action) form->action = GURL(form_data.action); if (form_data.submit_element) form->submit_element = WideToUTF16(form_data.submit_element); if (form_data.username_element) form->username_element = WideToUTF16(form_data.username_element); if (form_data.password_element) form->password_element = WideToUTF16(form_data.password_element); if (form_data.username_value) { form->username_value = WideToUTF16(form_data.username_value); if (form_data.password_value) form->password_value = WideToUTF16(form_data.password_value); } else { form->blacklisted_by_user = true; } return form; } // Macro to simplify calling CheckFormsAgainstExpectations with a useful label. #define CHECK_FORMS(forms, expectations, i) \ CheckFormsAgainstExpectations(forms, expectations, #forms, i) // Ensures that the data in |forms| match |expectations|, causing test failures // for any discrepencies. // TODO(stuartmorgan): This is current order-dependent; ideally it shouldn't // matter if |forms| and |expectations| are scrambled. static void CheckFormsAgainstExpectations( const std::vector<PasswordForm*>& forms, const std::vector<PasswordFormData*>& expectations, const char* forms_label, unsigned int test_number) { const unsigned int kBufferSize = 128; char test_label[kBufferSize]; snprintf(test_label, kBufferSize, "%s in test %u", forms_label, test_number); EXPECT_EQ(expectations.size(), forms.size()) << test_label; if (expectations.size() != forms.size()) return; for (unsigned int i = 0; i < expectations.size(); ++i) { snprintf(test_label, kBufferSize, "%s in test %u, item %u", forms_label, test_number, i); PasswordForm* form = forms[i]; PasswordFormData* expectation = expectations[i]; EXPECT_EQ(expectation->scheme, form->scheme) << test_label; EXPECT_EQ(std::string(expectation->signon_realm), form->signon_realm) << test_label; EXPECT_EQ(GURL(expectation->origin), form->origin) << test_label; EXPECT_EQ(GURL(expectation->action), form->action) << test_label; EXPECT_EQ(WideToUTF16(expectation->submit_element), form->submit_element) << test_label; EXPECT_EQ(WideToUTF16(expectation->username_element), form->username_element) << test_label; EXPECT_EQ(WideToUTF16(expectation->password_element), form->password_element) << test_label; if (expectation->username_value) { EXPECT_EQ(WideToUTF16(expectation->username_value), form->username_value) << test_label; EXPECT_EQ(WideToUTF16(expectation->password_value), form->password_value) << test_label; } else { EXPECT_TRUE(form->blacklisted_by_user) << test_label; } EXPECT_EQ(expectation->preferred, form->preferred) << test_label; EXPECT_EQ(expectation->ssl_valid, form->ssl_valid) << test_label; EXPECT_DOUBLE_EQ(expectation->creation_time, form->date_created.ToDoubleT()) << test_label; } } #pragma mark - TEST_F(PasswordStoreMacInternalsTest, TestKeychainToFormTranslation) { typedef struct { const PasswordForm::Scheme scheme; const char* signon_realm; const char* origin; const wchar_t* username; // Set to NULL to check for a blacklist entry. const wchar_t* password; const bool ssl_valid; const int creation_year; const int creation_month; const int creation_day; const int creation_hour; const int creation_minute; const int creation_second; } TestExpectations; TestExpectations expected[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", L"joe_user", L"sekrit", false, 2002, 6, 1, 17, 15, 0 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", L"joe_user", L"sekrit", false, 1999, 12, 31, 23, 59, 59 }, { PasswordForm::SCHEME_HTML, "https://some.domain.com/", "https://some.domain.com/secure.html", L"secure_user", L"password", true, 2010, 9, 8, 7, 6, 5 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", NULL, NULL, false, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", NULL, NULL, false, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_HTML, "https://dont.remember.com/", "https://dont.remember.com/", NULL, NULL, true, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", "http://some.domain.com:4567/insecure.html", L"basic_auth_user", L"basic", false, 1998, 03, 30, 10, 00, 00 }, { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", "https://some.domain.com/", L"digest_auth_user", L"digest", true, 1998, 3, 30, 10, 0, 0 }, // This one gives us an invalid date, which we will treat as a "NULL" date // which is 1601. { PasswordForm::SCHEME_OTHER, "http://a.server.com/", "http://a.server.com/", L"abc", L"123", false, 1601, 1, 1, 0, 0, 0 }, }; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(expected); ++i) { // Create our fake KeychainItemRef; see MockAppleKeychain docs. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(i + 1); PasswordForm form; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form, true); EXPECT_TRUE(parsed) << "In iteration " << i; EXPECT_EQ(expected[i].scheme, form.scheme) << "In iteration " << i; EXPECT_EQ(GURL(expected[i].origin), form.origin) << "In iteration " << i; EXPECT_EQ(expected[i].ssl_valid, form.ssl_valid) << "In iteration " << i; EXPECT_EQ(std::string(expected[i].signon_realm), form.signon_realm) << "In iteration " << i; if (expected[i].username) { EXPECT_EQ(WideToUTF16(expected[i].username), form.username_value) << "In iteration " << i; EXPECT_EQ(WideToUTF16(expected[i].password), form.password_value) << "In iteration " << i; EXPECT_FALSE(form.blacklisted_by_user) << "In iteration " << i; } else { EXPECT_TRUE(form.blacklisted_by_user) << "In iteration " << i; } base::Time::Exploded exploded_time; form.date_created.UTCExplode(&exploded_time); EXPECT_EQ(expected[i].creation_year, exploded_time.year) << "In iteration " << i; EXPECT_EQ(expected[i].creation_month, exploded_time.month) << "In iteration " << i; EXPECT_EQ(expected[i].creation_day, exploded_time.day_of_month) << "In iteration " << i; EXPECT_EQ(expected[i].creation_hour, exploded_time.hour) << "In iteration " << i; EXPECT_EQ(expected[i].creation_minute, exploded_time.minute) << "In iteration " << i; EXPECT_EQ(expected[i].creation_second, exploded_time.second) << "In iteration " << i; } { // Use an invalid ref, to make sure errors are reported. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(99); PasswordForm form; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form, true); EXPECT_FALSE(parsed); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainSearch) { struct TestDataAndExpectation { const PasswordFormData data; const size_t expected_fill_matches; const size_t expected_merge_matches; }; // Most fields are left blank because we don't care about them for searching. TestDataAndExpectation test_data[] = { // An HTML form we've seen. { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 }, 2, 2 }, { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, false, 0 }, 2, 0 }, // An HTML form we haven't seen { { PasswordForm::SCHEME_HTML, "http://www.unseendomain.com/", NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 }, 0, 0 }, // Basic auth that should match. { { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false, 0 }, 1, 1 }, // Basic auth with the wrong port. { { PasswordForm::SCHEME_BASIC, "http://some.domain.com:1111/low_security", NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false, 0 }, 0, 0 }, // Digest auth we've saved under https, visited with http. { { PasswordForm::SCHEME_DIGEST, "http://some.domain.com/high_security", NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, false, 0 }, 0, 0 }, // Digest auth that should match. { { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, true, 0 }, 1, 0 }, // Digest auth with the wrong domain. { { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/other_domain", NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, true, 0 }, 0, 0 }, // Garbage forms should have no matches. { { PasswordForm::SCHEME_HTML, "foo/bar/baz", NULL, NULL, NULL, NULL, NULL, NULL, NULL, false, false, 0 }, 0, 0 }, }; MacKeychainPasswordFormAdapter keychain_adapter(keychain_); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> query_form( CreatePasswordFormFromData(test_data[i].data)); // Check matches treating the form as a fill target. std::vector<PasswordForm*> matching_items = keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); EXPECT_EQ(test_data[i].expected_fill_matches, matching_items.size()); STLDeleteElements(&matching_items); // Check matches treating the form as a merging target. EXPECT_EQ(test_data[i].expected_merge_matches > 0, keychain_adapter.HasPasswordsMergeableWithForm(*query_form)); std::vector<SecKeychainItemRef> keychain_items; std::vector<internal_keychain_helpers::ItemFormPair> item_form_pairs = internal_keychain_helpers:: ExtractAllKeychainItemAttributesIntoPasswordForms(&keychain_items, *keychain_); matching_items = internal_keychain_helpers::ExtractPasswordsMergeableWithForm( *keychain_, item_form_pairs, *query_form); EXPECT_EQ(test_data[i].expected_merge_matches, matching_items.size()); STLDeleteContainerPairSecondPointers(item_form_pairs.begin(), item_form_pairs.end()); for (std::vector<SecKeychainItemRef>::iterator i = keychain_items.begin(); i != keychain_items.end(); ++i) { keychain_->Free(*i); } STLDeleteElements(&matching_items); // None of the pre-seeded items are owned by us, so none should match an // owned-passwords-only search. matching_items = owned_keychain_adapter.PasswordsFillingForm( query_form->signon_realm, query_form->scheme); EXPECT_EQ(0U, matching_items.size()); STLDeleteElements(&matching_items); } } // Changes just the origin path of |form|. static void SetPasswordFormPath(PasswordForm* form, const char* path) { GURL::Replacements replacement; std::string new_value(path); replacement.SetPathStr(new_value); form->origin = form->origin.ReplaceComponents(replacement); } // Changes just the signon_realm port of |form|. static void SetPasswordFormPort(PasswordForm* form, const char* port) { GURL::Replacements replacement; std::string new_value(port); replacement.SetPortStr(new_value); GURL signon_gurl = GURL(form->signon_realm); form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec(); } // Changes just the signon_ream auth realm of |form|. static void SetPasswordFormRealm(PasswordForm* form, const char* realm) { GURL::Replacements replacement; std::string new_value(realm); replacement.SetPathStr(new_value); GURL signon_gurl = GURL(form->signon_realm); form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec(); } TEST_F(PasswordStoreMacInternalsTest, TestKeychainExactSearch) { MacKeychainPasswordFormAdapter keychain_adapter(keychain_); PasswordFormData base_form_data[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 }, { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", "http://some.domain.com:4567/insecure.html", NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, true, false, 0 }, { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", "https://some.domain.com", NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, true, true, 0 }, }; for (unsigned int i = 0; i < arraysize(base_form_data); ++i) { // Create a base form and make sure we find a match. scoped_ptr<PasswordForm> base_form(CreatePasswordFormFromData( base_form_data[i])); EXPECT_TRUE(keychain_adapter.HasPasswordsMergeableWithForm(*base_form)); PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*base_form); EXPECT_TRUE(match != NULL); if (match) { EXPECT_EQ(base_form->scheme, match->scheme); EXPECT_EQ(base_form->origin, match->origin); EXPECT_EQ(base_form->username_value, match->username_value); delete match; } // Make sure that the matching isn't looser than it should be by checking // that slightly altered forms don't match. std::vector<PasswordForm*> modified_forms; modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->username_value = ASCIIToUTF16("wrong_user"); modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormPath(modified_forms.back(), "elsewhere.html"); modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->scheme = PasswordForm::SCHEME_OTHER; modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormPort(modified_forms.back(), "1234"); modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->blacklisted_by_user = true; if (base_form->scheme == PasswordForm::SCHEME_BASIC || base_form->scheme == PasswordForm::SCHEME_DIGEST) { modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormRealm(modified_forms.back(), "incorrect"); } for (unsigned int j = 0; j < modified_forms.size(); ++j) { PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*modified_forms[j]); EXPECT_EQ(NULL, match) << "In modified version " << j << " of base form " << i; } STLDeleteElements(&modified_forms); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainAdd) { struct TestDataAndExpectation { PasswordFormData data; bool should_succeed; }; TestDataAndExpectation test_data[] = { // Test a variety of scheme/port/protocol/path variations. { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, true }, { { PasswordForm::SCHEME_HTML, "https://web.site.com/", "https://web.site.com/", NULL, NULL, NULL, NULL, L"admin", L"p4ssw0rd", false, false, 0 }, true }, { { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm", "http://a.site.com:2222/", NULL, NULL, NULL, NULL, L"username", L"password", false, false, 0 }, true }, { { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm", "https://digest.site.com/secure.html", NULL, NULL, NULL, NULL, L"testname", L"testpass", false, false, 0 }, true }, // Make sure that garbage forms are rejected. { { PasswordForm::SCHEME_HTML, "gobbledygook", "gobbledygook", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, false }, // Test that failing to update a duplicate (forced using the magic failure // password; see MockAppleKeychain::ItemModifyAttributesAndData) is // reported. { { PasswordForm::SCHEME_HTML, "http://some.domain.com", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", L"fail_me", false, false, 0 }, false }, }; MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> in_form( CreatePasswordFormFromData(test_data[i].data)); bool add_succeeded = owned_keychain_adapter.AddPassword(*in_form); EXPECT_EQ(test_data[i].should_succeed, add_succeeded); if (add_succeeded) { EXPECT_TRUE(owned_keychain_adapter.HasPasswordsMergeableWithForm( *in_form)); scoped_ptr<PasswordForm> out_form( owned_keychain_adapter.PasswordExactlyMatchingForm(*in_form)); EXPECT_TRUE(out_form.get() != NULL); EXPECT_EQ(out_form->scheme, in_form->scheme); EXPECT_EQ(out_form->signon_realm, in_form->signon_realm); EXPECT_EQ(out_form->origin, in_form->origin); EXPECT_EQ(out_form->username_value, in_form->username_value); EXPECT_EQ(out_form->password_value, in_form->password_value); } } // Test that adding duplicate item updates the existing item. { PasswordFormData data = { PasswordForm::SCHEME_HTML, "http://some.domain.com", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", L"updated_password", false, false, 0 }; scoped_ptr<PasswordForm> update_form(CreatePasswordFormFromData(data)); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); EXPECT_TRUE(keychain_adapter.AddPassword(*update_form)); SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(2); PasswordForm stored_form; internal_keychain_helpers::FillPasswordFormFromKeychainItem(*keychain_, keychain_item, &stored_form, true); EXPECT_EQ(update_form->password_value, stored_form.password_value); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainRemove) { struct TestDataAndExpectation { PasswordFormData data; bool should_succeed; }; TestDataAndExpectation test_data[] = { // Test deletion of an item that we add. { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, true }, // Make sure we don't delete items we don't own. { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 }, false }, }; MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); // Add our test item so that we can delete it. PasswordForm* add_form = CreatePasswordFormFromData(test_data[0].data); EXPECT_TRUE(owned_keychain_adapter.AddPassword(*add_form)); delete add_form; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( test_data[i].data)); EXPECT_EQ(test_data[i].should_succeed, owned_keychain_adapter.RemovePassword(*form)); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*form); EXPECT_EQ(test_data[i].should_succeed, match == NULL); if (match) { delete match; } } } TEST_F(PasswordStoreMacInternalsTest, TestFormMatch) { PasswordForm base_form; base_form.signon_realm = std::string("http://some.domain.com/"); base_form.origin = GURL("http://some.domain.com/page.html"); base_form.username_value = ASCIIToUTF16("joe_user"); { // Check that everything unimportant can be changed. PasswordForm different_form(base_form); different_form.username_element = ASCIIToUTF16("username"); different_form.submit_element = ASCIIToUTF16("submit"); different_form.username_element = ASCIIToUTF16("password"); different_form.password_value = ASCIIToUTF16("sekrit"); different_form.action = GURL("http://some.domain.com/action.cgi"); different_form.ssl_valid = true; different_form.preferred = true; different_form.date_created = base::Time::Now(); EXPECT_TRUE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); // Check that path differences don't prevent a match. base_form.origin = GURL("http://some.domain.com/other_page.html"); EXPECT_TRUE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } // Check that any one primary key changing is enough to prevent matching. { PasswordForm different_form(base_form); different_form.scheme = PasswordForm::SCHEME_DIGEST; EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.signon_realm = std::string("http://some.domain.com:8080/"); EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.username_value = ASCIIToUTF16("john.doe"); EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.blacklisted_by_user = true; EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } // Blacklist forms should *never* match for merging, even when identical // (and certainly not when only one is a blacklist entry). { PasswordForm form_a(base_form); form_a.blacklisted_by_user = true; PasswordForm form_b(form_a); EXPECT_FALSE(FormsMatchForMerge(form_a, form_b, STRICT_FORM_MATCH)); } } TEST_F(PasswordStoreMacInternalsTest, TestFormMerge) { // Set up a bunch of test data to use in varying combinations. PasswordFormData keychain_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", L"joe_user", L"sekrit", false, false, 1010101010 }; PasswordFormData keychain_user_1_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "", L"", L"", L"", L"joe_user", L"otherpassword", false, false, 1010101010 }; PasswordFormData keychain_user_2 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", L"john.doe", L"sesame", false, false, 958739876 }; PasswordFormData keychain_blacklist = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", NULL, NULL, false, false, 1010101010 }; PasswordFormData db_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1212121212 }; PasswordFormData db_user_1_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1234567890 }; PasswordFormData db_user_3_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"second-account", L"", true, false, 1240000000 }; PasswordFormData database_blacklist_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/path.html", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", NULL, NULL, true, false, 1212121212 }; PasswordFormData merged_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"sekrit", true, false, 1212121212 }; PasswordFormData merged_user_1_with_db_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"sekrit", true, false, 1234567890 }; PasswordFormData merged_user_1_with_both_paths = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"otherpassword", true, false, 1234567890 }; // Build up the big multi-dimensional array of data sets that will actually // drive the test. Use vectors rather than arrays so that initialization is // simple. enum { KEYCHAIN_INPUT = 0, DATABASE_INPUT, MERGE_OUTPUT, KEYCHAIN_OUTPUT, DATABASE_OUTPUT, MERGE_IO_ARRAY_COUNT // termination marker }; const unsigned int kTestCount = 4; std::vector< std::vector< std::vector<PasswordFormData*> > > test_data( MERGE_IO_ARRAY_COUNT, std::vector< std::vector<PasswordFormData*> >( kTestCount, std::vector<PasswordFormData*>())); unsigned int current_test = 0; // Test a merge with a few accounts in both systems, with partial overlap. CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_2); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path); test_data[DATABASE_INPUT][current_test].push_back(&db_user_3_with_path); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1_with_db_path); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_2); test_data[DATABASE_OUTPUT][current_test].push_back(&db_user_3_with_path); // Test a merge where Chrome has a blacklist entry, and the keychain has // a stored account. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[DATABASE_INPUT][current_test].push_back( &database_blacklist_with_path); // We expect both to be present because a blacklist could be specific to a // subpath, and we want access to the password on other paths. test_data[MERGE_OUTPUT][current_test].push_back( &database_blacklist_with_path); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_1); // Test a merge where Chrome has an account, and Keychain has a blacklist // (from another browser) and the Chrome password data. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_blacklist); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_blacklist); // Test that matches are done using exact path when possible. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1_with_path); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[MERGE_OUTPUT][current_test].push_back( &merged_user_1_with_both_paths); for (unsigned int test_case = 0; test_case <= current_test; ++test_case) { std::vector<PasswordForm*> keychain_forms; for (std::vector<PasswordFormData*>::iterator i = test_data[KEYCHAIN_INPUT][test_case].begin(); i != test_data[KEYCHAIN_INPUT][test_case].end(); ++i) { keychain_forms.push_back(CreatePasswordFormFromData(*(*i))); } std::vector<PasswordForm*> database_forms; for (std::vector<PasswordFormData*>::iterator i = test_data[DATABASE_INPUT][test_case].begin(); i != test_data[DATABASE_INPUT][test_case].end(); ++i) { database_forms.push_back(CreatePasswordFormFromData(*(*i))); } std::vector<PasswordForm*> merged_forms; internal_keychain_helpers::MergePasswordForms(&keychain_forms, &database_forms, &merged_forms); CHECK_FORMS(keychain_forms, test_data[KEYCHAIN_OUTPUT][test_case], test_case); CHECK_FORMS(database_forms, test_data[DATABASE_OUTPUT][test_case], test_case); CHECK_FORMS(merged_forms, test_data[MERGE_OUTPUT][test_case], test_case); STLDeleteElements(&keychain_forms); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } } TEST_F(PasswordStoreMacInternalsTest, TestPasswordBulkLookup) { PasswordFormData db_data[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1212121212 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1234567890 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"second-account", L"", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", "http://dont.remember.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/path.html", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", NULL, NULL, true, false, 1212121212 }, }; std::vector<PasswordForm*> database_forms; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(db_data); ++i) { database_forms.push_back(CreatePasswordFormFromData(db_data[i])); } std::vector<PasswordForm*> merged_forms = internal_keychain_helpers::GetPasswordsForForms(*keychain_, &database_forms); EXPECT_EQ(2U, database_forms.size()); ASSERT_EQ(3U, merged_forms.size()); EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[0]->password_value); EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[1]->password_value); EXPECT_TRUE(merged_forms[2]->blacklisted_by_user); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } TEST_F(PasswordStoreMacInternalsTest, TestBlacklistedFiltering) { PasswordFormData db_data[] = { { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", "http://dont.remember.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"non_empty_password", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "https://dont.remember.com/", "https://dont.remember.com/", "https://dont.remember.com/handlepage_secure.cgi", L"submit", L"username", L"password", L"joe_user", L"non_empty_password", true, false, 1240000000 }, }; std::vector<PasswordForm*> database_forms; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(db_data); ++i) { database_forms.push_back(CreatePasswordFormFromData(db_data[i])); } std::vector<PasswordForm*> merged_forms = internal_keychain_helpers::GetPasswordsForForms(*keychain_, &database_forms); EXPECT_EQ(2U, database_forms.size()); ASSERT_EQ(0U, merged_forms.size()); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } TEST_F(PasswordStoreMacInternalsTest, TestFillPasswordFormFromKeychainItem) { // When |extract_password_data| is false, the password field must be empty, // and |blacklisted_by_user| must be false. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(1); PasswordForm form_without_extracted_password; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_without_extracted_password, false); // Do not extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(form_without_extracted_password.password_value.empty()); ASSERT_FALSE(form_without_extracted_password.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has a non-empty // password, the password field must be non-empty, and the value of // |blacklisted_by_user| must be false. keychain_item = reinterpret_cast<SecKeychainItemRef>(1); PasswordForm form_with_extracted_password; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_extracted_password, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_EQ(ASCIIToUTF16("sekrit"), form_with_extracted_password.password_value); ASSERT_FALSE(form_with_extracted_password.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has an empty // username and password (""), the password field must be empty, and the value // of |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(4); PasswordForm negative_form; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &negative_form, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(negative_form.username_value.empty()); ASSERT_TRUE(negative_form.password_value.empty()); ASSERT_TRUE(negative_form.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has an empty // password (""), the password field must be empty (""), and the value of // |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(5); PasswordForm form_with_empty_password_a; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_empty_password_a, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(form_with_empty_password_a.password_value.empty()); ASSERT_TRUE(form_with_empty_password_a.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has a single // space password (" "), the password field must be a single space (" "), and // the value of |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(6); PasswordForm form_with_empty_password_b; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_empty_password_b, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_EQ(ASCIIToUTF16(" "), form_with_empty_password_b.password_value); ASSERT_TRUE(form_with_empty_password_b.blacklisted_by_user); } TEST_F(PasswordStoreMacInternalsTest, TestPasswordGetAll) { MacKeychainPasswordFormAdapter keychain_adapter(keychain_); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); // Add a few passwords of various types so that we own some. PasswordFormData owned_password_data[] = { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm", "http://a.site.com:2222/", NULL, NULL, NULL, NULL, L"username", L"password", false, false, 0 }, { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm", "https://digest.site.com/secure.html", NULL, NULL, NULL, NULL, L"testname", L"testpass", false, false, 0 }, }; for (unsigned int i = 0; i < arraysize(owned_password_data); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( owned_password_data[i])); owned_keychain_adapter.AddPassword(*form); } std::vector<PasswordForm*> all_passwords = keychain_adapter.GetAllPasswordFormPasswords(); EXPECT_EQ(8 + arraysize(owned_password_data), all_passwords.size()); STLDeleteElements(&all_passwords); std::vector<PasswordForm*> owned_passwords = owned_keychain_adapter.GetAllPasswordFormPasswords(); EXPECT_EQ(arraysize(owned_password_data), owned_passwords.size()); STLDeleteElements(&owned_passwords); } #pragma mark - class PasswordStoreMacTest : public testing::Test { public: PasswordStoreMacTest() : ui_thread_(BrowserThread::UI, &message_loop_) {} virtual void SetUp() { login_db_ = new LoginDatabase(); ASSERT_TRUE(db_dir_.CreateUniqueTempDir()); base::FilePath db_file = db_dir_.path().AppendASCII("login.db"); ASSERT_TRUE(login_db_->Init(db_file)); keychain_ = new MockAppleKeychain(); store_ = new TestPasswordStoreMac( base::MessageLoopProxy::current(), base::MessageLoopProxy::current(), keychain_, login_db_); ASSERT_TRUE(store_->Init(syncer::SyncableService::StartSyncFlare())); } virtual void TearDown() { store_->Shutdown(); EXPECT_FALSE(store_->GetBackgroundTaskRunner()); } void WaitForStoreUpdate() { // Do a store-level query to wait for all the operations above to be done. MockPasswordStoreConsumer consumer; EXPECT_CALL(consumer, OnGetPasswordStoreResults(_)) .WillOnce(DoAll(WithArg<0>(STLDeleteElements0()), QuitUIMessageLoop())); store_->GetLogins(PasswordForm(), PasswordStore::ALLOW_PROMPT, &consumer); base::MessageLoop::current()->Run(); } protected: base::MessageLoopForUI message_loop_; content::TestBrowserThread ui_thread_; MockAppleKeychain* keychain_; // Owned by store_. LoginDatabase* login_db_; // Owned by store_. scoped_refptr<TestPasswordStoreMac> store_; base::ScopedTempDir db_dir_; }; TEST_F(PasswordStoreMacTest, TestStoreUpdate) { // Insert a password into both the database and the keychain. // This is done manually, rather than through store_->AddLogin, because the // Mock Keychain isn't smart enough to be able to support update generically, // so some.domain.com triggers special handling to test it that make inserting // fail. PasswordFormData joint_data = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", "login.cgi", L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1 }; scoped_ptr<PasswordForm> joint_form(CreatePasswordFormFromData(joint_data)); login_db_->AddLogin(*joint_form); MockAppleKeychain::KeychainTestData joint_keychain_data = { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 0, NULL, "20020601171500Z", "joe_user", "sekrit", false }; keychain_->AddTestItem(joint_keychain_data); // Insert a password into the keychain only. MockAppleKeychain::KeychainTestData keychain_only_data = { kSecAuthenticationTypeHTMLForm, "keychain.only.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20020601171500Z", "keychain", "only", false }; keychain_->AddTestItem(keychain_only_data); struct UpdateData { PasswordFormData form_data; const char* password; // NULL indicates no entry should be present. }; // Make a series of update calls. UpdateData updates[] = { // Update the keychain+db passwords (the normal password update case). { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", "login.cgi", L"username", L"password", L"submit", L"joe_user", L"53krit", true, false, 2 }, "53krit", }, // Update the keychain-only password; this simulates the initial use of a // password stored by another browsers. { { PasswordForm::SCHEME_HTML, "http://keychain.only.com/", "http://keychain.only.com/login.html", "login.cgi", L"username", L"password", L"submit", L"keychain", L"only", true, false, 2 }, "only", }, // Update a password that doesn't exist in either location. This tests the // case where a form is filled, then the stored login is removed, then the // form is submitted. { { PasswordForm::SCHEME_HTML, "http://different.com/", "http://different.com/index.html", "login.cgi", L"username", L"password", L"submit", L"abc", L"123", true, false, 2 }, NULL, }, }; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(updates); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( updates[i].form_data)); store_->UpdateLogin(*form); } WaitForStoreUpdate(); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(updates); ++i) { scoped_ptr<PasswordForm> query_form( CreatePasswordFormFromData(updates[i].form_data)); std::vector<PasswordForm*> matching_items = keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); if (updates[i].password) { EXPECT_GT(matching_items.size(), 0U) << "iteration " << i; if (matching_items.size() >= 1) EXPECT_EQ(ASCIIToUTF16(updates[i].password), matching_items[0]->password_value) << "iteration " << i; } else { EXPECT_EQ(0U, matching_items.size()) << "iteration " << i; } STLDeleteElements(&matching_items); login_db_->GetLogins(*query_form, &matching_items); EXPECT_EQ(updates[i].password ? 1U : 0U, matching_items.size()) << "iteration " << i; STLDeleteElements(&matching_items); } } TEST_F(PasswordStoreMacTest, TestDBKeychainAssociation) { // Tests that association between the keychain and login database parts of a // password added by fuzzy (PSL) matching works. // 1. Add a password for www.facebook.com // 2. Get a password for m.facebook.com. This fuzzy matches and returns the // www.facebook.com password. // 3. Add the returned password for m.facebook.com. // 4. Remove both passwords. // -> check: that both are gone from the login DB and the keychain // This test should in particular ensure that we don't keep passwords in the // keychain just before we think we still have other (fuzzy-)matching entries // for them in the login database. (For example, here if we deleted the // www.facebook.com password from the login database, we should not be blocked // from deleting it from the keystore just becaus the m.facebook.com password // fuzzy-matches the www.facebook.com one.) // 1. Add a password for www.facebook.com PasswordFormData www_form_data = { PasswordForm::SCHEME_HTML, "http://www.facebook.com/", "http://www.facebook.com/index.html", "login", L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1 }; scoped_ptr<PasswordForm> www_form(CreatePasswordFormFromData(www_form_data)); login_db_->AddLogin(*www_form); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); owned_keychain_adapter.AddPassword(*www_form); // 2. Get a password for m.facebook.com. PasswordForm m_form(*www_form); m_form.signon_realm = "http://m.facebook.com"; m_form.origin = GURL("http://m.facebook.com/index.html"); MockPasswordStoreConsumer consumer; EXPECT_CALL(consumer, OnGetPasswordStoreResults(_)).WillOnce(DoAll( WithArg<0>(Invoke(&consumer, &MockPasswordStoreConsumer::CopyElements)), WithArg<0>(STLDeleteElements0()), QuitUIMessageLoop())); store_->GetLogins(m_form, PasswordStore::ALLOW_PROMPT, &consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(1u, consumer.last_result.size()); // 3. Add the returned password for m.facebook.com. login_db_->AddLogin(consumer.last_result[0]); owned_keychain_adapter.AddPassword(m_form); // 4. Remove both passwords. store_->RemoveLogin(*www_form); store_->RemoveLogin(m_form); WaitForStoreUpdate(); std::vector<PasswordForm*> matching_items; // No trace of www.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( www_form->signon_realm, www_form->scheme); EXPECT_EQ(0u, matching_items.size()); login_db_->GetLogins(*www_form, &matching_items); EXPECT_EQ(0u, matching_items.size()); // No trace of m.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( m_form.signon_realm, m_form.scheme); EXPECT_EQ(0u, matching_items.size()); login_db_->GetLogins(m_form, &matching_items); EXPECT_EQ(0u, matching_items.size()); }
patrickm/chromium.src
chrome/browser/password_manager/password_store_mac_unittest.cc
C++
bsd-3-clause
53,108
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/message_loop.h" #include "base/run_loop.h" #include "base/time.h" #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "content/public/common/gpu_feature_type.h" #include "content/public/common/gpu_info.h" #include "googleurl/src/gurl.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "testing/gtest/include/gtest/gtest.h" #define LONG_STRING_CONST(...) #__VA_ARGS__ namespace content { namespace { class TestObserver : public GpuDataManagerObserver { public: TestObserver() : gpu_info_updated_(false), video_memory_usage_stats_updated_(false) { } virtual ~TestObserver() { } bool gpu_info_updated() const { return gpu_info_updated_; } bool video_memory_usage_stats_updated() const { return video_memory_usage_stats_updated_; } virtual void OnGpuInfoUpdate() OVERRIDE { gpu_info_updated_ = true; } virtual void OnVideoMemoryUsageStatsUpdate( const GPUVideoMemoryUsageStats& stats) OVERRIDE { video_memory_usage_stats_updated_ = true; } private: bool gpu_info_updated_; bool video_memory_usage_stats_updated_; }; static base::Time GetTimeForTesting() { return base::Time::FromDoubleT(1000); } static GURL GetDomain1ForTesting() { return GURL("http://foo.com/"); } static GURL GetDomain2ForTesting() { return GURL("http://bar.com/"); } } // namespace anonymous class GpuDataManagerImplTest : public testing::Test { public: GpuDataManagerImplTest() { } virtual ~GpuDataManagerImplTest() { } protected: // scoped_ptr doesn't work with GpuDataManagerImpl because its // destructor is private. GpuDataManagerImplTest is however a friend // so we can make a little helper class here. class ScopedGpuDataManagerImpl { public: ScopedGpuDataManagerImpl() : impl_(new GpuDataManagerImpl()) {} ~ScopedGpuDataManagerImpl() { delete impl_; } GpuDataManagerImpl* get() const { return impl_; } GpuDataManagerImpl* operator->() const { return impl_; } // Small violation of C++ style guide to avoid polluting several // tests with get() calls. operator GpuDataManagerImpl*() { return impl_; } private: GpuDataManagerImpl* impl_; DISALLOW_COPY_AND_ASSIGN(ScopedGpuDataManagerImpl); }; virtual void SetUp() { } virtual void TearDown() { } base::Time JustBeforeExpiration(GpuDataManagerImpl* manager); base::Time JustAfterExpiration(GpuDataManagerImpl* manager); void TestBlockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level); void TestUnblockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level); MessageLoop message_loop_; }; // We use new method instead of GetInstance() method because we want // each test to be independent of each other. TEST_F(GpuDataManagerImplTest, GpuSideBlacklisting) { // If a feature is allowed in preliminary step (browser side), but // disabled when GPU process launches and collects full GPU info, // it's too late to let renderer know, so we basically block all GPU // access, to be on the safe side. ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "features": [ "webgl" ] }, { "id": 2, "gl_renderer": { "op": "contains", "value": "GeForce" }, "features": [ "accelerated_2d_canvas" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x10de; gpu_info.gpu.device_id = 0x0640; manager->InitializeForTesting(blacklist_json, gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); gpu_info.gl_vendor = "NVIDIA"; gpu_info.gl_renderer = "NVIDIA GeForce GT 120"; manager->UpdateGpuInfo(gpu_info); EXPECT_FALSE(manager->GpuAccessAllowed()); EXPECT_EQ(2u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); EXPECT_TRUE(manager->IsFeatureBlacklisted( GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } TEST_F(GpuDataManagerImplTest, GpuSideExceptions) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "exceptions": [ { "gl_renderer": { "op": "contains", "value": "GeForce" } } ], "features": [ "webgl" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x10de; gpu_info.gpu.device_id = 0x0640; manager->InitializeForTesting(blacklist_json, gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); // Now assume gpu process launches and full GPU info is collected. gpu_info.gl_renderer = "NVIDIA GeForce GT 120"; manager->UpdateGpuInfo(gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); } TEST_F(GpuDataManagerImplTest, DisableHardwareAcceleration) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); manager->DisableHardwareAcceleration(); EXPECT_FALSE(manager->GpuAccessAllowed()); EXPECT_EQ(static_cast<size_t>(NUMBER_OF_GPU_FEATURE_TYPES), manager->GetBlacklistedFeatureCount()); } TEST_F(GpuDataManagerImplTest, SoftwareRendering) { // Blacklist, then register SwiftShader. ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); manager->DisableHardwareAcceleration(); EXPECT_FALSE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); // If software rendering is enabled, even if we blacklist GPU, // GPU process is still allowed. const base::FilePath test_path(FILE_PATH_LITERAL("AnyPath")); manager->RegisterSwiftShaderPath(test_path); EXPECT_TRUE(manager->ShouldUseSoftwareRendering()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE( manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } TEST_F(GpuDataManagerImplTest, SoftwareRendering2) { // Register SwiftShader, then blacklist. ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); const base::FilePath test_path(FILE_PATH_LITERAL("AnyPath")); manager->RegisterSwiftShaderPath(test_path); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_FALSE(manager->ShouldUseSoftwareRendering()); manager->DisableHardwareAcceleration(); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_TRUE(manager->ShouldUseSoftwareRendering()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE( manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)); } TEST_F(GpuDataManagerImplTest, GpuInfoUpdate) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); TestObserver observer; manager->AddObserver(&observer); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); GPUInfo gpu_info; manager->UpdateGpuInfo(gpu_info); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_TRUE(observer.gpu_info_updated()); } TEST_F(GpuDataManagerImplTest, NoGpuInfoUpdateWithSoftwareRendering) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->DisableHardwareAcceleration(); const base::FilePath test_path(FILE_PATH_LITERAL("AnyPath")); manager->RegisterSwiftShaderPath(test_path); EXPECT_TRUE(manager->ShouldUseSoftwareRendering()); EXPECT_TRUE(manager->GpuAccessAllowed()); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } TestObserver observer; manager->AddObserver(&observer); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); GPUInfo gpu_info; manager->UpdateGpuInfo(gpu_info); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); } TEST_F(GpuDataManagerImplTest, GPUVideoMemoryUsageStatsUpdate) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); TestObserver observer; manager->AddObserver(&observer); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.video_memory_usage_stats_updated()); GPUVideoMemoryUsageStats vram_stats; manager->UpdateVideoMemoryUsageStats(vram_stats); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_TRUE(observer.video_memory_usage_stats_updated()); } base::Time GpuDataManagerImplTest::JustBeforeExpiration( GpuDataManagerImpl* manager) { return GetTimeForTesting() + base::TimeDelta::FromMilliseconds( manager->GetBlockAllDomainsDurationInMs()) - base::TimeDelta::FromMilliseconds(3); } base::Time GpuDataManagerImplTest::JustAfterExpiration( GpuDataManagerImpl* manager) { return GetTimeForTesting() + base::TimeDelta::FromMilliseconds( manager->GetBlockAllDomainsDurationInMs()) + base::TimeDelta::FromMilliseconds(3); } void GpuDataManagerImplTest::TestBlockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), guilt_level, GetTimeForTesting()); // This domain should be blocked no matter what. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), GetTimeForTesting())); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustBeforeExpiration(manager))); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustAfterExpiration(manager))); } void GpuDataManagerImplTest::TestUnblockingDomainFrom3DAPIs( GpuDataManagerImpl::DomainGuilt guilt_level) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), guilt_level, GetTimeForTesting()); // Unblocking the domain should work. manager->UnblockDomainFrom3DAPIs(GetDomain1ForTesting()); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), GetTimeForTesting())); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustBeforeExpiration(manager))); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustAfterExpiration(manager))); } TEST_F(GpuDataManagerImplTest, BlockGuiltyDomainFrom3DAPIs) { TestBlockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_KNOWN); } TEST_F(GpuDataManagerImplTest, BlockDomainOfUnknownGuiltFrom3DAPIs) { TestBlockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN); } TEST_F(GpuDataManagerImplTest, BlockAllDomainsFrom3DAPIs) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN, GetTimeForTesting()); // Blocking of other domains should expire. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_ALL_DOMAINS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustBeforeExpiration(manager))); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustAfterExpiration(manager))); } TEST_F(GpuDataManagerImplTest, UnblockGuiltyDomainFrom3DAPIs) { TestUnblockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_KNOWN); } TEST_F(GpuDataManagerImplTest, UnblockDomainOfUnknownGuiltFrom3DAPIs) { TestUnblockingDomainFrom3DAPIs(GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN); } TEST_F(GpuDataManagerImplTest, UnblockOtherDomainFrom3DAPIs) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN, GetTimeForTesting()); manager->UnblockDomainFrom3DAPIs(GetDomain2ForTesting()); EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustBeforeExpiration(manager))); // The original domain should still be blocked. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain1ForTesting(), JustBeforeExpiration(manager))); } TEST_F(GpuDataManagerImplTest, UnblockThisDomainFrom3DAPIs) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->BlockDomainFrom3DAPIsAtTime(GetDomain1ForTesting(), GpuDataManagerImpl::DOMAIN_GUILT_UNKNOWN, GetTimeForTesting()); manager->UnblockDomainFrom3DAPIs(GetDomain1ForTesting()); // This behavior is debatable. Perhaps the GPU reset caused by // domain 1 should still cause other domains to be blocked. EXPECT_EQ(GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED, manager->Are3DAPIsBlockedAtTime(GetDomain2ForTesting(), JustBeforeExpiration(manager))); } #if defined(OS_LINUX) TEST_F(GpuDataManagerImplTest, SetGLStrings) { const char* kGLVendorMesa = "Tungsten Graphics, Inc"; const char* kGLRendererMesa = "Mesa DRI Intel(R) G41"; const char* kGLVersionMesa801 = "2.1 Mesa 8.0.1-DEVEL"; ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "vendor_id": "0x8086", "exceptions": [ { "device_id": ["0x0042"], "driver_version": { "op": ">=", "number": "8.0.2" } } ], "features": [ "webgl" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x8086; gpu_info.gpu.device_id = 0x0042; manager->InitializeForTesting(blacklist_json, gpu_info); // Not enough GPUInfo. EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); // Now assume browser gets GL strings from local state. // The entry applies, blacklist more features than from the preliminary step. // However, GPU process is not blocked because this is all browser side and // happens before renderer launching. manager->SetGLStrings(kGLVendorMesa, kGLRendererMesa, kGLVersionMesa801); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); } TEST_F(GpuDataManagerImplTest, SetGLStringsNoEffects) { const char* kGLVendorMesa = "Tungsten Graphics, Inc"; const char* kGLRendererMesa = "Mesa DRI Intel(R) G41"; const char* kGLVersionMesa801 = "2.1 Mesa 8.0.1-DEVEL"; const char* kGLVersionMesa802 = "2.1 Mesa 8.0.2-DEVEL"; ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->GpuAccessAllowed()); const std::string blacklist_json = LONG_STRING_CONST( { "name": "gpu blacklist", "version": "0.1", "entries": [ { "id": 1, "vendor_id": "0x8086", "exceptions": [ { "device_id": ["0x0042"], "driver_version": { "op": ">=", "number": "8.0.2" } } ], "features": [ "webgl" ] } ] } ); GPUInfo gpu_info; gpu_info.gpu.vendor_id = 0x8086; gpu_info.gpu.device_id = 0x0042; gpu_info.gl_vendor = kGLVendorMesa; gpu_info.gl_renderer = kGLRendererMesa; gpu_info.gl_version = kGLVersionMesa801; gpu_info.driver_vendor = "Mesa"; gpu_info.driver_version = "8.0.1"; manager->InitializeForTesting(blacklist_json, gpu_info); // Full GPUInfo, the entry applies. EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); // Now assume browser gets GL strings from local state. // SetGLStrings() has no effects because GPUInfo already got these strings. // (Otherwise the entry should not apply.) manager->SetGLStrings(kGLVendorMesa, kGLRendererMesa, kGLVersionMesa802); EXPECT_TRUE(manager->GpuAccessAllowed()); EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(GPU_FEATURE_TYPE_WEBGL)); } #endif // OS_LINUX TEST_F(GpuDataManagerImplTest, GpuDriverBugListSingle) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->gpu_driver_bugs_.insert(5); CommandLine command_line(0, NULL); manager->AppendGpuCommandLine(&command_line); EXPECT_TRUE(command_line.HasSwitch(switches::kGpuDriverBugWorkarounds)); std::string args = command_line.GetSwitchValueASCII( switches::kGpuDriverBugWorkarounds); EXPECT_STREQ("5", args.c_str()); } TEST_F(GpuDataManagerImplTest, GpuDriverBugListMultiple) { ScopedGpuDataManagerImpl manager; ASSERT_TRUE(manager.get()); manager->gpu_driver_bugs_.insert(5); manager->gpu_driver_bugs_.insert(7); CommandLine command_line(0, NULL); manager->AppendGpuCommandLine(&command_line); EXPECT_TRUE(command_line.HasSwitch(switches::kGpuDriverBugWorkarounds)); std::string args = command_line.GetSwitchValueASCII( switches::kGpuDriverBugWorkarounds); EXPECT_STREQ("5,7", args.c_str()); } } // namespace content
codenote/chromium-test
content/browser/gpu/gpu_data_manager_impl_unittest.cc
C++
bsd-3-clause
20,249
# Copyright (c) 2013,Vienna University of Technology, Department of Geodesy and Geoinformation # 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 the <organization> 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 <COPYRIGHT HOLDER> 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. ''' Created on Jul 31, 2013 @author: Christoph Paulik christoph.paulik@geo.tuwien.ac.at ''' import os import unittest from pytesmo.io.ismn import readers import pandas as pd from datetime import datetime import numpy as np class TestReaders(unittest.TestCase): def setUp(self): self.filename_format_header_values = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'format_header_values', 'SMOSMANIA', 'SMOSMANIA_SMOSMANIA_Narbonne_sm_0.050000_0.050000_ThetaProbe-ML2X_20070101_20070131.stm') self.filename_format_ceop_sep = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'format_ceop_sep', 'SMOSMANIA', 'SMOSMANIA_SMOSMANIA_Narbonne_sm_0.050000_0.050000_ThetaProbe-ML2X_20070101_20070131.stm') self.filename_format_ceop = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'format_ceop', 'SMOSMANIA', 'SMOSMANIA_SMOSMANIA_NBN_20100304_20130801.stm') self.filename_malformed = os.path.join(os.path.dirname(__file__), '..', 'test-data', 'ismn', 'malformed', 'mal_formed_file.txt') self.metadata_ref = {'network': 'SMOSMANIA', 'station': 'Narbonne', 'latitude': 43.15, 'longitude': 2.9567, 'elevation': 112.0, 'depth_from': [0.05], 'depth_to': [0.05], 'variable': ['soil moisture'], 'sensor': 'ThetaProbe-ML2X'} self.metadata_ref_ceop = dict(self.metadata_ref) self.metadata_ref_ceop['depth_from'] = ['multiple'] self.metadata_ref_ceop['depth_to'] = ['multiple'] self.metadata_ref_ceop['variable'] = ['ts', 'sm'] self.metadata_ref_ceop['sensor'] = 'n.s' def test_get_info_from_file(self): header_elements, filename_elements = readers.get_info_from_file( self.filename_format_ceop_sep) assert sorted(header_elements) == sorted(['2007/01/01', '01:00', '2007/01/01', '01:00', 'SMOSMANIA', 'SMOSMANIA', 'Narbonne', '43.15000', '2.95670', '112.00', '0.05', '0.05', '0.2140', 'U', 'M']) assert sorted(filename_elements) == sorted(['SMOSMANIA', 'SMOSMANIA', 'Narbonne', 'sm', '0.050000', '0.050000', 'ThetaProbe-ML2X', '20070101', '20070131.stm']) def test_get_metadata_header_values(self): metadata = readers.get_metadata_header_values( self.filename_format_header_values) for key in metadata: assert metadata[key] == self.metadata_ref[key] def test_reader_format_header_values(self): dataset = readers.read_format_header_values( self.filename_format_header_values) assert dataset.network == 'SMOSMANIA' assert dataset.station == 'Narbonne' assert dataset.latitude == 43.15 assert dataset.longitude == 2.9567 assert dataset.elevation == 112.0 assert dataset.variable == ['soil moisture'] assert dataset.depth_from == [0.05] assert dataset.depth_to == [0.05] assert dataset.sensor == 'ThetaProbe-ML2X' assert type(dataset.data) == pd.DataFrame assert dataset.data.index[7] == datetime(2007, 1, 1, 8, 0, 0) assert sorted(dataset.data.columns) == sorted( ['soil moisture', 'soil moisture_flag', 'soil moisture_orig_flag']) assert dataset.data['soil moisture'].values[8] == 0.2135 assert dataset.data['soil moisture_flag'].values[8] == 'U' assert dataset.data['soil moisture_orig_flag'].values[8] == 'M' def test_get_metadata_ceop_sep(self): metadata = readers.get_metadata_ceop_sep(self.filename_format_ceop_sep) for key in metadata: assert metadata[key] == self.metadata_ref[key] def test_reader_format_ceop_sep(self): dataset = readers.read_format_ceop_sep(self.filename_format_ceop_sep) assert dataset.network == 'SMOSMANIA' assert dataset.station == 'Narbonne' assert dataset.latitude == 43.15 assert dataset.longitude == 2.9567 assert dataset.elevation == 112.0 assert dataset.variable == ['soil moisture'] assert dataset.depth_from == [0.05] assert dataset.depth_to == [0.05] assert dataset.sensor == 'ThetaProbe-ML2X' assert type(dataset.data) == pd.DataFrame assert dataset.data.index[7] == datetime(2007, 1, 1, 8, 0, 0) assert sorted(dataset.data.columns) == sorted( ['soil moisture', 'soil moisture_flag', 'soil moisture_orig_flag']) assert dataset.data['soil moisture'].values[8] == 0.2135 assert dataset.data['soil moisture_flag'].values[8] == 'U' assert dataset.data['soil moisture_orig_flag'].values[347] == 'M' def test_get_metadata_ceop(self): metadata = readers.get_metadata_ceop(self.filename_format_ceop) assert metadata == self.metadata_ref_ceop def test_reader_format_ceop(self): dataset = readers.read_format_ceop(self.filename_format_ceop) assert dataset.network == 'SMOSMANIA' assert dataset.station == 'Narbonne' assert dataset.latitude == 43.15 assert dataset.longitude == 2.9567 assert dataset.elevation == 112.0 assert sorted(dataset.variable) == sorted(['sm', 'ts']) assert sorted(dataset.depth_from) == sorted([0.05, 0.1, 0.2, 0.3]) assert sorted(dataset.depth_to) == sorted([0.05, 0.1, 0.2, 0.3]) assert dataset.sensor == 'n.s' assert type(dataset.data) == pd.DataFrame assert dataset.data.index[7] == ( 0.05, 0.05, datetime(2010, 10, 21, 9, 0, 0)) assert sorted(dataset.data.columns) == sorted( ['sm', 'sm_flag', 'ts', 'ts_flag']) assert dataset.data['sm'].values[8] == 0.2227 assert dataset.data['sm_flag'].values[8] == 'U' assert np.isnan(dataset.data.ix[0.3, 0.3]['ts'].values[6]) assert dataset.data.ix[0.3, 0.3]['ts_flag'].values[6] == 'M' def test_reader_get_format(self): fileformat = readers.get_format(self.filename_format_header_values) assert fileformat == 'header_values' fileformat = readers.get_format(self.filename_format_ceop_sep) assert fileformat == 'ceop_sep' fileformat = readers.get_format(self.filename_format_ceop) assert fileformat == 'ceop' with self.assertRaises(readers.ReaderException): fileformat = readers.get_format(self.filename_malformed) if __name__ == '__main__': unittest.main()
christophreimer/pytesmo
tests/test_ismn/test_readers.py
Python
bsd-3-clause
8,660
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/ppapi_command_buffer_proxy.h" #include "base/numerics/safe_conversions.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/api_id.h" #include "ppapi/shared_impl/host_resource.h" #include "ppapi/shared_impl/proxy_lock.h" namespace ppapi { namespace proxy { PpapiCommandBufferProxy::PpapiCommandBufferProxy( const ppapi::HostResource& resource, PluginDispatcher* dispatcher, const gpu::Capabilities& capabilities, const SerializedHandle& shared_state, uint64_t command_buffer_id) : command_buffer_id_(command_buffer_id), capabilities_(capabilities), resource_(resource), dispatcher_(dispatcher), next_fence_sync_release_(1), pending_fence_sync_release_(0), flushed_fence_sync_release_(0) { shared_state_shm_.reset( new base::SharedMemory(shared_state.shmem(), false)); shared_state_shm_->Map(shared_state.size()); InstanceData* data = dispatcher->GetInstanceData(resource.instance()); flush_info_ = &data->flush_info_; } PpapiCommandBufferProxy::~PpapiCommandBufferProxy() { // gpu::Buffers are no longer referenced, allowing shared memory objects to be // deleted, closing the handle in this process. } bool PpapiCommandBufferProxy::Initialize() { return true; } gpu::CommandBuffer::State PpapiCommandBufferProxy::GetLastState() { ppapi::ProxyLock::AssertAcquiredDebugOnly(); return last_state_; } int32 PpapiCommandBufferProxy::GetLastToken() { ppapi::ProxyLock::AssertAcquiredDebugOnly(); TryUpdateState(); return last_state_.token; } void PpapiCommandBufferProxy::Flush(int32 put_offset) { if (last_state_.error != gpu::error::kNoError) return; OrderingBarrier(put_offset); FlushInternal(); } void PpapiCommandBufferProxy::OrderingBarrier(int32 put_offset) { if (last_state_.error != gpu::error::kNoError) return; if (flush_info_->flush_pending && flush_info_->resource != resource_) { FlushInternal(); } flush_info_->flush_pending = true; flush_info_->resource = resource_; flush_info_->put_offset = put_offset; pending_fence_sync_release_ = next_fence_sync_release_ - 1; } void PpapiCommandBufferProxy::WaitForTokenInRange(int32 start, int32 end) { TryUpdateState(); if (!InRange(start, end, last_state_.token) && last_state_.error == gpu::error::kNoError) { bool success = false; gpu::CommandBuffer::State state; if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForTokenInRange( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, start, end, &state, &success))) UpdateState(state, success); } DCHECK(InRange(start, end, last_state_.token) || last_state_.error != gpu::error::kNoError); } void PpapiCommandBufferProxy::WaitForGetOffsetInRange(int32 start, int32 end) { TryUpdateState(); if (!InRange(start, end, last_state_.get_offset) && last_state_.error == gpu::error::kNoError) { bool success = false; gpu::CommandBuffer::State state; if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForGetOffsetInRange( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, start, end, &state, &success))) UpdateState(state, success); } DCHECK(InRange(start, end, last_state_.get_offset) || last_state_.error != gpu::error::kNoError); } void PpapiCommandBufferProxy::SetGetBuffer(int32 transfer_buffer_id) { if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_SetGetBuffer( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, transfer_buffer_id)); } } scoped_refptr<gpu::Buffer> PpapiCommandBufferProxy::CreateTransferBuffer( size_t size, int32* id) { *id = -1; if (last_state_.error != gpu::error::kNoError) return NULL; // Assuming we are in the renderer process, the service is responsible for // duplicating the handle. This might not be true for NaCl. ppapi::proxy::SerializedHandle handle( ppapi::proxy::SerializedHandle::SHARED_MEMORY); if (!Send(new PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, base::checked_cast<uint32_t>(size), id, &handle))) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kLostContext; return NULL; } if (*id <= 0 || !handle.is_shmem()) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kOutOfBounds; return NULL; } scoped_ptr<base::SharedMemory> shared_memory( new base::SharedMemory(handle.shmem(), false)); // Map the shared memory on demand. if (!shared_memory->memory()) { if (!shared_memory->Map(handle.size())) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kOutOfBounds; *id = -1; return NULL; } } return gpu::MakeBufferFromSharedMemory(shared_memory.Pass(), handle.size()); } void PpapiCommandBufferProxy::DestroyTransferBuffer(int32 id) { if (last_state_.error != gpu::error::kNoError) return; Send(new PpapiHostMsg_PPBGraphics3D_DestroyTransferBuffer( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id)); } void PpapiCommandBufferProxy::SetLock(base::Lock*) { NOTIMPLEMENTED(); } bool PpapiCommandBufferProxy::IsGpuChannelLost() { NOTIMPLEMENTED(); return false; } gpu::CommandBufferNamespace PpapiCommandBufferProxy::GetNamespaceID() const { return gpu::CommandBufferNamespace::GPU_IO; } uint64_t PpapiCommandBufferProxy::GetCommandBufferID() const { return command_buffer_id_; } uint64_t PpapiCommandBufferProxy::GenerateFenceSyncRelease() { return next_fence_sync_release_++; } bool PpapiCommandBufferProxy::IsFenceSyncRelease(uint64_t release) { return release != 0 && release < next_fence_sync_release_; } bool PpapiCommandBufferProxy::IsFenceSyncFlushed(uint64_t release) { return release <= flushed_fence_sync_release_; } bool PpapiCommandBufferProxy::IsFenceSyncFlushReceived(uint64_t release) { return IsFenceSyncFlushed(release); } void PpapiCommandBufferProxy::SignalSyncToken(const gpu::SyncToken& sync_token, const base::Closure& callback) { NOTIMPLEMENTED(); } bool PpapiCommandBufferProxy::CanWaitUnverifiedSyncToken( const gpu::SyncToken* sync_token) { return false; } uint32 PpapiCommandBufferProxy::InsertSyncPoint() { uint32 sync_point = 0; if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_InsertSyncPoint( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point)); } return sync_point; } uint32 PpapiCommandBufferProxy::InsertFutureSyncPoint() { uint32 sync_point = 0; if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_InsertFutureSyncPoint( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point)); } return sync_point; } void PpapiCommandBufferProxy::RetireSyncPoint(uint32 sync_point) { if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_RetireSyncPoint( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, sync_point)); } } void PpapiCommandBufferProxy::SignalSyncPoint(uint32 sync_point, const base::Closure& callback) { NOTREACHED(); } void PpapiCommandBufferProxy::SignalQuery(uint32 query, const base::Closure& callback) { NOTREACHED(); } gpu::Capabilities PpapiCommandBufferProxy::GetCapabilities() { return capabilities_; } int32 PpapiCommandBufferProxy::CreateImage(ClientBuffer buffer, size_t width, size_t height, unsigned internalformat) { NOTREACHED(); return -1; } void PpapiCommandBufferProxy::DestroyImage(int32 id) { NOTREACHED(); } int32 PpapiCommandBufferProxy::CreateGpuMemoryBufferImage( size_t width, size_t height, unsigned internalformat, unsigned usage) { NOTREACHED(); return -1; } bool PpapiCommandBufferProxy::Send(IPC::Message* msg) { DCHECK(last_state_.error == gpu::error::kNoError); // We need to hold the Pepper proxy lock for sync IPC, because the GPU command // buffer may use a sync IPC with another lock held which could lead to lock // and deadlock if we dropped the proxy lock here. // http://crbug.com/418651 if (dispatcher_->SendAndStayLocked(msg)) return true; last_state_.error = gpu::error::kLostContext; return false; } void PpapiCommandBufferProxy::UpdateState( const gpu::CommandBuffer::State& state, bool success) { // Handle wraparound. It works as long as we don't have more than 2B state // updates in flight across which reordering occurs. if (success) { if (state.generation - last_state_.generation < 0x80000000U) { last_state_ = state; } } else { last_state_.error = gpu::error::kLostContext; ++last_state_.generation; } } void PpapiCommandBufferProxy::TryUpdateState() { if (last_state_.error == gpu::error::kNoError) shared_state()->Read(&last_state_); } gpu::CommandBufferSharedState* PpapiCommandBufferProxy::shared_state() const { return reinterpret_cast<gpu::CommandBufferSharedState*>( shared_state_shm_->memory()); } void PpapiCommandBufferProxy::FlushInternal() { DCHECK(last_state_.error == gpu::error::kNoError); DCHECK(flush_info_->flush_pending); DCHECK_GE(pending_fence_sync_release_, flushed_fence_sync_release_); IPC::Message* message = new PpapiHostMsg_PPBGraphics3D_AsyncFlush( ppapi::API_ID_PPB_GRAPHICS_3D, flush_info_->resource, flush_info_->put_offset); // Do not let a synchronous flush hold up this message. If this handler is // deferred until after the synchronous flush completes, it will overwrite the // cached last_state_ with out-of-date data. message->set_unblock(true); Send(message); flush_info_->flush_pending = false; flush_info_->resource.SetHostResource(0, 0); flushed_fence_sync_release_ = pending_fence_sync_release_; } } // namespace proxy } // namespace ppapi
Workday/OpenFrame
ppapi/proxy/ppapi_command_buffer_proxy.cc
C++
bsd-3-clause
10,421
var cdb = require('cartodb.js'); var $ = require('jquery'); var DatasetItem = require('./dataset_item_view'); var Utils = require('cdb.Utils'); var UploadConfig = require('../../../../background_importer/upload_config'); var pluralizeString = require('../../../../view_helpers/pluralize_string'); /** * Remote dataset item view * */ module.exports = DatasetItem.extend({ tagName: 'li', className: 'DatasetsList-item', events: { 'click .js-tag-link': '_onTagClick', 'click': '_toggleSelected' }, initialize: function() { this.elder('initialize'); this.template = cdb.templates.getTemplate('common/views/create/listing/remote_dataset_item'); this.table = new cdb.admin.CartoDBTableMetadata(this.model.get('external_source')); }, render: function() { var vis = this.model; var table = this.table; var tags = vis.get('tags') || []; var description = vis.get('description') && Utils.stripHTML(markdown.toHTML(vis.get('description'))) || ''; var source = vis.get('source') && markdown.toHTML(vis.get('source')) || ''; var d = { isRaster: vis.get('kind') === 'raster', geometryType: table.geomColumnTypes().length > 0 ? table.geomColumnTypes()[0] : '', title: vis.get('name'), source: source, description: description, timeDiff: moment(vis.get('updated_at')).fromNow(), tags: tags, tagsCount: tags.length, routerModel: this.routerModel, maxTagsToShow: 3, canImportDataset: this._canImportDataset(), rowCount: undefined, datasetSize: undefined }; var rowCount = table.get('row_count'); if (rowCount >= 0) { d.rowCount = ( rowCount < 10000 ? Utils.formatNumber(rowCount) : Utils.readizableNumber(rowCount) ); d.pluralizedRows = pluralizeString('Row', rowCount); } var datasetSize = table.get('size'); if (datasetSize >= 0) { d.datasetSize = Utils.readablizeBytes(datasetSize, true); } this.$el.html(this.template(d)); this._setItemClasses(); this._renderTooltips(); return this; }, _setItemClasses: function() { // Item selected? this.$el[ this.model.get('selected') ? 'addClass' : 'removeClass' ]('is--selected'); // Check if it is selectable this.$el[ this._canImportDataset() ? 'addClass' : 'removeClass' ]('DatasetsList-item--selectable'); // Check if it is importable this.$el[ this._canImportDataset() ? 'removeClass' : 'addClass' ]('DatasetsList-item--banned'); }, _renderTooltips: function() { this.addView( new cdb.common.TipsyTooltip({ el: this.$('.DatasetsList-itemStatus'), title: function(e) { return $(this).attr('data-title') } }) ) }, _onTagClick: function(ev) { if (ev) { this.killEvent(ev); } var tag = $(ev.target).val(); if (tag) { this.routerModel.set({ tag: tag, library: true }); } }, _canImportDataset: function() { return ( this.user.get('remaining_byte_quota') * UploadConfig.fileTimesBigger ) >= ( this.table.get('size') || 0 ) }, _toggleSelected: function(ev) { // Let links use default behaviour if (ev.target.tagName !== 'A') { this.killEvent(ev); if (this._canImportDataset() && this.options.createModel.canSelect(this.model)) { this.model.set('selected', !this.model.get('selected')); } } } });
raquel-ucl/cartodb
lib/assets/javascripts/cartodb/common/dialogs/create/listing/datasets/remote_dataset_item_view.js
JavaScript
bsd-3-clause
3,614
<?php namespace SanAuth\Model; use Zend\Authentication\Storage; class MyAuthStorage extends Storage\Session { public function setRememberMe($rememberMe = 0, $time = 1209600) { if ($rememberMe == 1) { $this->session->getManager()->rememberMe($time); } } public function forgetMe() { $this->session->getManager()->forgetMe(); } /*Set tableGateway as save handler muscreate a table session CREATE TABLE IF NOT EXISTS `session` ( `id` char(32) NOT NULL DEFAULT '', `name` char(32) NOT NULL DEFAULT '', `modified` int(11) DEFAULT NULL, `lifetime` int(11) DEFAULT NULL, `data` text, PRIMARY KEY (`id`,`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; */ public function setDbHandler() { $tableGateway = new TableGateway('session', $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')); $saveHandler = new DbTableGateway($tableGateway, new DbTableGatewayOptions()); //open session $sessionConfig = new SessionConfig(); $saveHandler->open($sessionConfig->getOption('save_path'), $this->namespace); $this->session->getManager()->setSaveHandler($saveHandler); } }
manguiatmarvin/osms
module/SanAuth/src/SanAuth/Model/MyAuthStorage.php
PHP
bsd-3-clause
1,233
<?php namespace bug_010498195; class True { }
manuelpichler/staticReflection
src/test/resources/files/regression/010498195/True.php
PHP
bsd-3-clause
50
package workflow import ( "github.com/go-gorp/gorp" "github.com/ovh/cds/sdk" ) // InsertAudit insert a workflow audit func InsertAudit(db gorp.SqlExecutor, a *sdk.AuditWorkflow) error { audit := auditWorkflow(*a) if err := db.Insert(&audit); err != nil { return sdk.WrapError(err, "Unable to insert audit") } a.ID = audit.ID return nil } // LoadAudits Load audits for the given workflow func LoadAudits(db gorp.SqlExecutor, workflowID int64) ([]sdk.AuditWorkflow, error) { query := ` SELECT * FROM workflow_audit WHERE workflow_id = $1 ORDER BY created DESC ` var audits []auditWorkflow if _, err := db.Select(&audits, query, workflowID); err != nil { return nil, sdk.WrapError(err, "Unable to load audits") } workflowAudits := make([]sdk.AuditWorkflow, len(audits)) for i := range audits { workflowAudits[i] = sdk.AuditWorkflow(audits[i]) } return workflowAudits, nil } // LoadAudit Load audit for the given workflow func LoadAudit(db gorp.SqlExecutor, auditID int64, workflowID int64) (sdk.AuditWorkflow, error) { var audit auditWorkflow if err := db.SelectOne(&audit, "SELECT * FROM workflow_audit WHERE id = $1 AND workflow_id = $2", auditID, workflowID); err != nil { return sdk.AuditWorkflow{}, sdk.WrapError(err, "Unable to load audit") } return sdk.AuditWorkflow(audit), nil }
ovh/cds
engine/api/workflow/dao_audit.go
GO
bsd-3-clause
1,322
require 'test_helper' require 'v_object/i_tip/broker_tester' module Tilia module VObject class BrokerProcessReplyTest < ITip::BrokerTester def test_reply_no_original itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS old = nil expected = nil process(itip, old, expected) end def test_reply_accept itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.0:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_request_status itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT UID:foobar REQUEST-STATUS:2.3;foo-bar! ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foobar SEQUENCE:2 ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foobar SEQUENCE:2 ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.3:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_party_crasher itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:crasher@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org ATTENDEE;PARTSTAT=ACCEPTED:mailto:crasher@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_new_exception # This is a reply to 1 instance of a recurring event. This should # automatically create an exception. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID:20140725T000000Z UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT BEGIN:VEVENT SEQUENCE:2 UID:foobar DTSTART:20140725T000000Z DTEND:20140725T010000Z ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org RECURRENCE-ID:20140725T000000Z END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_new_exception_tz # This is a reply to 1 instance of a recurring event. This should # automatically create an exception. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID;TZID=America/Toronto:20140725T000000 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART;TZID=America/Toronto:20140724T000000 DTEND;TZID=America/Toronto:20140724T010000 ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART;TZID=America/Toronto:20140724T000000 DTEND;TZID=America/Toronto:20140724T010000 ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT BEGIN:VEVENT SEQUENCE:2 UID:foobar DTSTART;TZID=America/Toronto:20140725T000000 DTEND;TZID=America/Toronto:20140725T010000 ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org RECURRENCE-ID;TZID=America/Toronto:20140725T000000 END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_party_crash_create_excepton # IN this test there's a recurring event that has an exception. The # exception is missing the attendee. # # The attendee party crashes the instance, so it should show up in the # resulting object. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:crasher@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID:20140725T000000Z UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ORGANIZER:mailto:bar@example.org END:VEVENT BEGIN:VEVENT SEQUENCE:2 UID:foobar DTSTART:20140725T000000Z DTEND:20140725T010000Z ORGANIZER:mailto:bar@example.org RECURRENCE-ID:20140725T000000Z ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:crasher@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_new_exception_no_master_event # This iTip message would normally create a new exception, but the # server is not able to create this new instance, because there's no # master event to clone from. # # This test checks if the message is ignored. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:crasher@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID:20140725T000000Z UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z RECURRENCE-ID:20140724T000000Z ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = nil process(itip, old, expected) end def test_reply_accept_update_rsvp itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;RSVP=TRUE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.0:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end end end end
tilia/tilia-vobject
test/v_object/i_tip/broker_process_reply_test.rb
Ruby
bsd-3-clause
7,897
from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.db import transaction from django.forms.models import inlineformset_factory, modelform_factory from django.forms.widgets import HiddenInput from django.shortcuts import get_object_or_404 from vanilla import FormView from django.utils.translation import ugettext_lazy as _ from declry.forms import BootstrapModelForm from django import http from django.utils.decorators import classonlymethod from django.template import (RequestContext, loader, TemplateDoesNotExist) import autocomplete_light from django.views.decorators.csrf import requires_csrf_token import logging import smtplib from email.mime.text import MIMEText __author__ = 'jorgeramos' class ModelFormView(FormView): model = None related_model = None success_url_path = '{}_{}_view' success_url_args = '' template_name = "edit.html" title = _('Edit') form = BootstrapModelForm fields = None hidden_fields = [] exclude = [] formfield_callback = None instance = None @classonlymethod def as_view(cls, **initkwargs): view = super(ModelFormView, cls).as_view(**initkwargs) if hasattr(cls, 'title'): view.label = cls.title return view def get_form_class(self): """ Returns the form class to use in this view. """ if self.form_class: return self.form_class elif self.related_model: widgets = autocomplete_light.get_widgets_dict(self.related_model) return modelform_factory(self.related_model, widgets = widgets, form = self.form, fields=self.fields, exclude =self.exclude, formfield_callback=self.get_formfield_callback()) elif self.model: widgets = autocomplete_light.get_widgets_dict(self.model) return modelform_factory(self.model, widgets = widgets, form = self.form, fields=self.fields, exclude =self.exclude, formfield_callback=self.get_formfield_callback()) msg = "'%s' must either define 'form_class' or define 'model' or override 'get_form_class()'" raise ImproperlyConfigured(msg % self.__class__.__name__) def get_form(self, data=None, files=None, **kwargs): """ Given `data` and `files` QueryDicts, and optionally other named arguments, and returns a form. """ cls = self.get_form_class() return cls(instance = self.get_modelform_instance(), data=data, files=files, **kwargs) def get(self, request, object_id=None, *args, **kwargs): self.request = request self.object_id = object_id form = self.get_form() context = self.get_context_data(form=form) return self.render_to_response(context) def post(self, request, object_id=None): self.request = request self.object_id = object_id if 'go_back' in request.POST: return self.form_valid(None) form = self.get_form(data=request.POST, files=request.FILES) if form.is_valid(): inst= form.save() if not self.object_id: self.object_id = inst.pk self.success_url = self.get_success_url() return self.form_valid(form) return self.form_invalid(form) def get_success_url(self): return reverse(self.success_url_path.format(self.model._meta.app_label, self.model._meta.module_name), args=(self.object_id,)) + self.success_url_args def form_invalid(self, form, **kwargs): context = self.get_context_data(form=form, **kwargs) return self.render_to_response(context) def get_context_data(self, **kwargs): kwargs['title'] = self.title kwargs['instance'] = self.get_instance() kwargs['view'] = self return kwargs def get_formfield_callback(self): def formfield_callback(f, **kwargs): field = f.formfield(**kwargs) if f.name in self.hidden_fields: field.widget = HiddenInput() return field return formfield_callback def get_instance(self): if self.instance: return self.instance if self.request and self.object_id: return get_object_or_404(self.model, pk=self.object_id) def get_modelform_instance(self): return self.get_instance() class InlineFormView(FormView): model = None related_model = None form = BootstrapModelForm prefix = "inlineform" template_name = "inline_edit.html" title = None instance = None success_path = '{}_{}_view' success_path_args = '' fields = None extra = 1 exclude = [] formfield_callback = None @classonlymethod def as_view(cls, **initkwargs): view = super(InlineFormView,cls).as_view(**initkwargs) if hasattr(cls, 'title'): view.label = cls.title return view def get_form_class(self): """ Returns the form class to use in this view. """ if self.form_class: return self.form_class if self.model and self.related_model: return inlineformset_factory(self.model, self.related_model, form=self.form, extra=self.extra, exclude = self.exclude, fields = self.fields, formfield_callback= self.get_formfield_callback()) msg = "'%s' must either define 'form_class' or define 'model' and 'related_model' or override 'get_form_class()'" raise ImproperlyConfigured(msg % self.__class__.__name__) def get_form(self, data=None, files=None, **kwargs): """ Given `data` and `files` QueryDicts, and optionally other named arguments, and returns a form. """ cls = self.get_form_class() return cls(prefix = self.prefix, instance=self.get_instance(), data=data, files=files, **kwargs) def get_context_data(self, **kwargs): """ Takes a set of keyword arguments to use as the base context, and returns a context dictionary to use for the view, additionally adding in 'view'. """ kwargs.update({ 'prefix' : self.prefix, 'title': self.title, 'instance' : self.get_instance() }) kwargs['view'] = self return kwargs def get(self, request, object_id, *args, **kwargs): self.request = request self.object_id = object_id form = self.get_form() context = self.get_context_data(form=form) return self.render_to_response(context) def post(self, request, object_id): self.request = request self.object_id = object_id if 'add_{}'.format(self.prefix) in request.POST: return self.process_add_element() elif 'go_back' in request.POST: return self.form_valid(None) else: form = self.get_form(data = request.POST, files= request.FILES) if form.is_valid(): with transaction.commit_on_success(): #try: form.save() #except: # transaction.rollback() return self.form_valid(form) return self.form_invalid(form) def process_add_element(self): post_copy = self.request.POST.copy() post_copy['{}-TOTAL_FORMS'.format(self.prefix)] = int(post_copy['{}-TOTAL_FORMS'.format(self.prefix)]) + 1 form = self.get_form(data=post_copy, files=self.request.FILES) context = self.get_context_data(form=form) return self.render_to_response(context) def get_success_url(self): if self.success_path is None: msg = "'%s' must define 'success_url' or override 'form_valid()'" raise ImproperlyConfigured(msg % self.__class__.__name__) else: return reverse(self.success_path.format(self.model._meta.app_label, self.model._meta.module_name), args=(self.object_id,)) + self.success_path_args def get_instance(self): if self.instance: return self.instance if self.request and self.object_id: return get_object_or_404(self.model, pk=self.object_id) def get_formfield_callback(self): return self.formfield_callback # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. session_logger = logging.getLogger('session') @requires_csrf_token def permission_denied(request, template_name='403.html'): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 2616) will be returned. """ print "YAAAA" email_txt=""" Erro 403 Path: {} Cookies: {} User: {} Roles: {} Bom trabalho A Equipa do Scholr """ user = request.user if hasattr(request, 'user') else '?' roles = request.user.roles if hasattr(request, 'user') and hasattr(request.user,'roles') else '---' session_logger.error(u'{} with cookies {}, user: {}, roles: {}'.format(request.path, request.COOKIES, user, roles)) try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseForbidden('<h1>403 TESTE</h1>') return http.HttpResponseForbidden(template.render(RequestContext(request)))
jAlpedrinha/DeclRY
declry/views.py
Python
bsd-3-clause
9,652
package de.plushnikov.intellij.plugin.processor.handler.singular; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiSubstitutor; import com.intellij.psi.PsiType; import com.intellij.psi.PsiVariable; import de.plushnikov.intellij.plugin.processor.field.AccessorsInfo; import org.jetbrains.annotations.NotNull; import java.util.List; class EmptyBuilderElementHandler implements BuilderElementHandler { @Override public void addBuilderField(@NotNull List<PsiField> fields, @NotNull PsiVariable psiVariable, @NotNull PsiClass innerClass, @NotNull AccessorsInfo accessorsInfo, @NotNull PsiSubstitutor substitutor) { } @Override public void addBuilderMethod(@NotNull List<PsiMethod> methods, @NotNull PsiVariable psiVariable, @NotNull String fieldName, @NotNull PsiClass innerClass, boolean fluentBuilder, PsiType returnType, String singularName, PsiSubstitutor builderSubstitutor) { } @Override public String createSingularName(PsiAnnotation singularAnnotation, String psiFieldName) { return psiFieldName; } @Override public void appendBuildPrepare(@NotNull StringBuilder buildMethodParameters, @NotNull PsiVariable psiVariable, @NotNull String fieldName) { } @Override public void appendBuildCall(@NotNull StringBuilder buildMethodParameters, @NotNull String fieldName) { buildMethodParameters.append(fieldName); } }
AlexejK/lombok-intellij-plugin
src/main/java/de/plushnikov/intellij/plugin/processor/handler/singular/EmptyBuilderElementHandler.java
Java
bsd-3-clause
1,477
using System; using RedGate.Shared.SQL; using RedGate.SQLCompare.Engine; namespace SyncDBNantTasks { public abstract class SyncDatabaseParmsBase { private DBConnectionInformation connection; public Database RegisteredDatabase { get; protected set; } public DBConnectionInformation Connection { get { if (connection == null) { throw new NotImplementedException("Connection not supported"); } else { return connection; } } set { connection = value; } } } }
tcabanski/SouthSideDevToys
SyncDBNantTasks/SyncDatabaseParmsBase.cs
C#
bsd-3-clause
637
using System.Data; using Orchard.ContentManagement.MetaData; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.SEO.Services; namespace Orchard.SEO { public class Migrations : DataMigrationImpl { public int Create() { SchemaBuilder.CreateTable("MetaRecord", table => table .ContentPartRecord() .Column<string>("Keywords") .Column<string>("Title") .Column<string>("Description") .Column<string>("Robots") ); ContentDefinitionManager.AlterPartDefinition( "MetaPart", cfg => cfg .WithDescription("Provides meta tags: title, description, keywords, robots") .Attachable()); SchemaBuilder.CreateTable("RobotsFileRecord", table => table .Column<int>("Id", col => col.PrimaryKey().Identity()) .Column<string>("FileContent", col => col.Unlimited() .WithDefault(@"User-agent: * Allow: /")) ); SchemaBuilder.CreateTable("SitemapFileRecord", table => table .Column<int>("Id", col => col.PrimaryKey().Identity()) .Column<string>("FileContent", col => col.Unlimited().WithDefault(SitemapService.DefaultFileText)) ); return 1; } } }
dmitry-urenev/extended-orchard-cms-v10.1
src/Orchard.Web/Modules/Orchard.SEO/Migrations.cs
C#
bsd-3-clause
1,459
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='FanUser', fields=[ ('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ('slug', models.SlugField(unique=True)), ('is_contributor', models.BooleanField(default=False)), ('desc', models.TextField(blank=True)), ], options={ 'abstract': False, 'verbose_name': 'user', 'verbose_name_plural': 'users', }, bases=('users.user',), ), ]
vivyly/fancastic_17
fancastic_17/fan/migrations/0001_initial.py
Python
bsd-3-clause
909
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ return array( 'service_manager' => array( 'invokables' => array( 'Blog\Service\PostServiceInterface' => 'Blog\Service\PostService' ) ), 'view_manager' => array( 'template_path_stack' => array( __DIR__ . '/../view', ), ), 'controllers' => array( 'factories' => array( 'Blog\Controller\List' => 'Blog\Factory\ListControllerFactory' ) ), // This lines opens the configuration for the RouteManager 'router' => array( // Open configuration for all possible routes 'routes' => array( // Define a new route called "post" 'post' => array( // Define the routes type to be "Zend\Mvc\Router\Http\Literal", which is basically just a string 'type' => 'literal', // Configure the route itself 'options' => array( // Listen to "/blog" as uri 'route' => '/blog', // Define default controller and action to be called when this route is matched 'defaults' => array( 'controller' => 'Blog\Controller\List', 'action' => 'index', ) ) ) ) ) );
acericonia/zf2-blog
module/Blog/config/module.config.php
PHP
bsd-3-clause
1,534
/* * Copyright (c) 2015, Institute of Computer Engineering, University of Lübeck * 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 the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.uni_luebeck.iti.smachapp.app; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.HashMap; import de.uni_luebeck.iti.smachapp.model.BeepColorSensor; import de.uni_luebeck.iti.smachapp.model.BeepIRSensor; import de.uni_luebeck.iti.smachapp.model.BeepRobot; import de.uni_luebeck.iti.smachapp.model.StateMachine; import de.uni_luebeck.iti.smachapp.model.Transition; import de.uni_luebeck.iti.smachapp.view.ColorSelector; import de.uni_luebeck.iti.smachapp.view.IntSlider; import de.uni_luebeck.iti.smachapp.view.SensorUI; public class TransitionProperty extends Activity implements TextWatcher { private Transition transition; private StateMachine machine; private int priority; private int maxPriority; private HashMap<String, SensorUI> uis = new HashMap<String, SensorUI>(); private TextView priorityField; private static Transition setupTransition; private static BeepRobot setupRobot; private static StateMachine setupMachine; private static int setupPriority; private static int setupMaxPriority; public static int getPriority() { return setupPriority; } public static void setupTransition(Transition t, BeepRobot r, StateMachine m, int pri, int maxPri) { setupTransition = t; setupRobot = r; setupMachine = m; setupPriority = pri; setupMaxPriority = maxPri; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_transition_property); transition = setupTransition; machine = setupMachine; BeepRobot robot = setupRobot; priority = setupPriority; maxPriority = setupMaxPriority; priorityField = (TextView) findViewById(R.id.priority); priorityField.setText(String.valueOf(priority)); LinearLayout container = (LinearLayout) findViewById(R.id.sensorContainer); for (BeepIRSensor sen : robot.getIntSensors()) { IntSlider slider = new IntSlider(this, sen); container.addView(slider); uis.put(sen.getName(), slider); slider.setToGuard(transition.getSmachableGuard(), true); slider.setToGuard(transition.getDisabledGuard(), false); } for (BeepColorSensor sen : robot.getColorSensors()) { ColorSelector sel = new ColorSelector(this, sen); container.addView(sel); uis.put(sen.getName(), sel); sel.setToGuard(transition.getSmachableGuard(), true); sel.setToGuard(transition.getDisabledGuard(), false); } EditText text = (EditText) findViewById(R.id.transitionName); text.setText(transition.getLabel()); text.addTextChangedListener(this); } @Override public void onBackPressed() { String newName = ((EditText) findViewById(R.id.transitionName)).getText().toString().trim(); if (!newName.equals(transition.getLabel()) && !newName.isEmpty()) { if (machine.getTransition(newName) == null) { transition.setLabel(newName); } else { Toast toast = Toast.makeText(this, R.string.nameAlreadyExists, Toast.LENGTH_LONG); toast.show(); return; } } transition.getSmachableGuard().clear(); transition.getDisabledGuard().clear(); for (SensorUI ui : uis.values()) { if (ui.isChecked()) { ui.fillGuard(transition.getSmachableGuard()); } else { ui.fillGuard(transition.getDisabledGuard()); } } setupPriority = priority; finish(); } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { String name = editable.toString().trim(); if (!name.equals(transition.getLabel()) && machine.getTransition(name) != null) { Toast toast = Toast.makeText(this, R.string.nameAlreadyExists, Toast.LENGTH_LONG); toast.show(); } if (name.isEmpty()) { Toast toast = Toast.makeText(this, R.string.empty_name_in_property, Toast.LENGTH_LONG); toast.show(); } } public void increasePriority(View view) { priority = priority + 1; if(priority>maxPriority){ priority=maxPriority; Toast.makeText(this,R.string.max_priority_reached,Toast.LENGTH_SHORT).show(); } priorityField.setText(String.valueOf(priority)); } public void decreasePriority(View view) { priority = priority - 1; if(priority<0){ priority=0; Toast.makeText(this,R.string.min_priority_reached,Toast.LENGTH_SHORT).show(); } priorityField.setText(String.valueOf(priority)); } }
iti-luebeck/SmachApp
app/src/main/java/de/uni_luebeck/iti/smachapp/app/TransitionProperty.java
Java
bsd-3-clause
6,939
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit29a195fdeafbaf46892c28c394475c18::getLoader();
sagargopale/zend-api-dev
vendor/autoload.php
PHP
bsd-3-clause
183
<?php namespace Database\Entity; use Doctrine\ORM\Mapping as ORM; /** * Purchases * * @ORM\Table(name="Purchases", indexes={@ORM\Index(name="fk_Purchases_Suppliers1_idx", columns={"supplier_id"})}) * @ORM\Entity */ class Purchases { /** * @var integer * * @ORM\Column(name="purchase_id", type="integer", precision=0, scale=0, nullable=false, unique=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $purchaseId; /** * @var string * * @ORM\Column(name="reference_no", type="string", length=45, precision=0, scale=0, nullable=true, unique=false) */ private $referenceNo; /** * @var \DateTime * * @ORM\Column(name="purchase_date", type="date", precision=0, scale=0, nullable=true, unique=false) */ private $purchaseDate; /** * @var \DateTime * * @ORM\Column(name="expected_arrival_date", type="date", precision=0, scale=0, nullable=true, unique=false) */ private $expectedArrivalDate; /** * @var string * * @ORM\Column(name="purchase_status", type="string", length=45, precision=0, scale=0, nullable=true, unique=false) */ private $purchaseStatus; /** * @var string * * @ORM\Column(name="purchase_notes", type="text", precision=0, scale=0, nullable=true, unique=false) */ private $purchaseNotes; /** * @var \Database\Entity\Suppliers * * @ORM\ManyToOne(targetEntity="Database\Entity\Suppliers") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="supplier_id", referencedColumnName="supplier_id", nullable=true) * }) */ private $supplier; /** * Get purchaseId * * @return integer */ public function getPurchaseId() { return $this->purchaseId; } /** * Set referenceNo * * @param string $referenceNo * @return Purchases */ public function setReferenceNo($referenceNo) { $this->referenceNo = $referenceNo; return $this; } /** * Get referenceNo * * @return string */ public function getReferenceNo() { return $this->referenceNo; } /** * Set purchaseDate * * @param \DateTime $purchaseDate * @return Purchases */ public function setPurchaseDate($purchaseDate) { $this->purchaseDate = $purchaseDate; return $this; } /** * Get purchaseDate * * @return \DateTime */ public function getPurchaseDate() { return $this->purchaseDate; } /** * Set expectedArrivalDate * * @param \DateTime $expectedArrivalDate * @return Purchases */ public function setExpectedArrivalDate($expectedArrivalDate) { $this->expectedArrivalDate = $expectedArrivalDate; return $this; } /** * Get expectedArrivalDate * * @return \DateTime */ public function getExpectedArrivalDate() { return $this->expectedArrivalDate; } /** * Set purchaseStatus * * @param string $purchaseStatus * @return Purchases */ public function setPurchaseStatus($purchaseStatus) { $this->purchaseStatus = $purchaseStatus; return $this; } /** * Get purchaseStatus * * @return string */ public function getPurchaseStatus() { return $this->purchaseStatus; } /** * Set purchaseNotes * * @param string $purchaseNotes * @return Purchases */ public function setPurchaseNotes($purchaseNotes) { $this->purchaseNotes = $purchaseNotes; return $this; } /** * Get purchaseNotes * * @return string */ public function getPurchaseNotes() { return $this->purchaseNotes; } /** * Set supplier * * @param \Database\Entity\Suppliers $supplier * @return Purchases */ public function setSupplier(\Database\Entity\Suppliers $supplier = null) { $this->supplier = $supplier; return $this; } /** * Get supplier * * @return \Database\Entity\Suppliers */ public function getSupplier() { return $this->supplier; } }
devhood/erp-blpi
module/Database/src/Entity/Purchases.php
PHP
bsd-3-clause
4,349
""" ===================================================== Analysis for project 29 ===================================================== :Author: Nick Ilott :Release: $Id$ :Date: |today| :Tags: Python """ # load modules from ruffus import * import CGAT.Experiment as E import logging as L import CGAT.Database as Database import CGAT.CSV as CSV import sys import os import re import shutil import itertools import math import glob import time import gzip import collections import random import numpy import sqlite3 import CGAT.GTF as GTF import CGAT.IOTools as IOTools import CGAT.IndexedFasta as IndexedFasta from rpy2.robjects import r as R import rpy2.robjects as ro import rpy2.robjects.vectors as rovectors from rpy2.rinterface import RRuntimeError #from pandas import * import PipelineProj029 ################################################### ################################################### ################################################### # Pipeline configuration ################################################### # load options from the config file import CGATPipelines.Pipeline as P P.getParameters( ["pipeline.ini"]) PARAMS = P.PARAMS ################################################################### # connecting to database ################################################################### def connect(): '''connect to database. This method also attaches to helper databases. ''' dbh = sqlite3.connect(PARAMS["database"]) return dbh ################################################################### ################################################################### ################################################################### # This first section deals with collating the information from # pipeline_metagenomeassembly.py. We produce plots of relative # abundance correllations etc between different samples ################################################################### ################################################################### ################################################################### @follows(mkdir("metaphlan.dir")) @split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")), "metaphlan.dir/relab.*.matrix") def buildRelativeAbundanceMatricesMetaphlan(infile, outfiles): ''' build a matrix combining the relative abundance estimations for all samples ''' # filenames to derive tablenames dirname = PARAMS.get("communities_dir") exp = "metaphlan.dir/*.relab" files = glob.glob(os.path.join(dirname, exp)) tablenames = [ os.path.basename(x).replace(".", "_").replace("-", "_") \ for x in files] tablenames.sort() for level in ["phylum", "class", "order", "family", "genus", "species"]: outfile = os.path.join("communities.dir", "relab." + level + ".matrix") PipelineProj029.buildRelativeAbundanceMatrix(infile, tablenames, outfile, level = level) ################################################################### ################################################################### ################################################################### @follows(mkdir("kraken.dir")) @split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")), "kraken.dir/*norm*.matrix") def buildAbundanceMatricesKraken(infile, outfiles): ''' build a matrix combining the rpm estimations for all samples ''' # filenames to derive tablenames dirname = PARAMS.get("communities_dir") exp = "kraken.dir/*.counts.norm.tsv.gz" files = glob.glob(os.path.join(dirname, exp)) tablenames = [ "kraken_" + os.path.basename(P.snip(x, ".tsv.gz")).replace(".", "_").replace("-", "_") \ for x in files] tablenames.sort() for level in ["phylum", "class", "order", "family", "genus", "species"]: outfile = os.path.join("kraken.dir", "counts.norm." + level + ".matrix") PipelineProj029.buildRelativeAbundanceMatrix(infile, tablenames, outfile, level = level) ################################################################### ################################################################### ################################################################### @follows(mkdir("diamond.dir")) @split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")), "diamond.dir/*norm*.matrix") def buildAbundanceMatricesDiamond(infile, outfiles): ''' build a matrix combining the rpm estimations for all samples ''' # filenames to derive tablenames dirname = PARAMS.get("communities_dir") exp = "diamond.dir/*.taxa.count" files = glob.glob(os.path.join(dirname, exp)) tablenames = [ os.path.basename(x).replace(".", "_").replace("-", "_") \ for x in files] tablenames.sort() for level in ["phylum", "class", "order", "family", "genus", "species"]: outfile = os.path.join("diamond.dir", "counts.norm." + level + ".matrix") PipelineProj029.buildRelativeAbundanceMatrix(infile, tablenames, outfile, level = level) ################################################################### ################################################################### ################################################################### COMMUNITIES_TARGETS = [] communities_targets = {"kraken": buildAbundanceMatricesKraken, "metaphlan": buildRelativeAbundanceMatricesMetaphlan, "diamond": buildAbundanceMatricesDiamond} for x in P.asList(PARAMS.get("classifiers")): COMMUNITIES_TARGETS.append(communities_targets[x]) @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".barplot.pdf") def barplotAbundances(infile, outfile): ''' barplot the species relative abundances ''' threshold = PARAMS.get("communities_threshold") PipelineProj029.barplotAbundances(infile, outfile, threshold) ################################################################### ################################################################### ################################################################### @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".ratio.tsv") def calculateFirmicutesBacteroidetesRatio(infile, outfile): ''' barplot the species relative abundances ''' threshold = PARAMS.get("communities_threshold") PipelineProj029.calculateFirmicutesBacteroidetesRatio(infile, outfile, threshold) ################################################################### ################################################################### ################################################################### @transform(calculateFirmicutesBacteroidetesRatio, suffix(".tsv"), ".pdf") def plotFirmicutesBacteroidetesRatio(infile, outfile): ''' produce boxplot of firmicutes/bacteroidetes ratio ''' PipelineProj029.plotFirmicutesBacteroidetesRatio(infile, outfile) ################################################################### ################################################################### ################################################################### @transform(calculateFirmicutesBacteroidetesRatio, suffix(".tsv"), ".signif") def calculateSignificanceOfFirmicutesBacteroidetesRatio(infile, outfile): ''' use tuleyHSD to calculate significance between groups with multiple testing correction ''' PipelineProj029.calculateSignificanceOfFirmicutesBacteroidetesRatio(infile, outfile) ################################################################### ################################################################### ################################################################### @jobs_limit(1, "R") @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".barplot.numbers.pdf") def plotHowManySpecies(infile, outfile): ''' how many samples have how many species? ''' PipelineProj029.plotHowManySpecies(infile, outfile) ################################################################### ################################################################### ################################################################### @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".heatmap.pdf") def heatmapAbundances(infile, outfile): ''' heatmap the species relative abundances ''' threshold = PARAMS.get("communities_threshold") PipelineProj029.heatmapAbundances(infile, outfile, threshold, "covariates.tsv") ################################################################### ################################################################### ################################################################### @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".signif") def testSignificanceOfAbundances(infile, outfile): ''' use an anova to test significance. This is not ideal but serves as a quick look ''' PipelineProj029.anovaTest(infile, "covariates.tsv", outfile, threshold = PARAMS.get("communities_threshold"), over = PARAMS.get("communities_over")) ################################################################### ################################################################### ################################################################### @transform(testSignificanceOfAbundances, suffix(".signif"), add_inputs(COMMUNITIES_TARGETS), ".signif.pdf") def plotSignificantResults(infiles, outfile): ''' barplot those taxa that are different across groups ''' inf = infiles[0] track = P.snip(inf, ".signif") abundance_file = [m for m in infiles[1] if m.find(track) != -1][0] threshold = PARAMS.get("communities_threshold") PipelineProj029.plotSignificantResults(inf, abundance_file, outfile, threshold) ################################################################### ################################################################### ################################################################### # KEGG analysis ################################################################### ################################################################### ################################################################### @follows(mkdir("kegg.dir")) @merge(glob.glob(os.path.join(PARAMS.get("communities_dir"), "kegg.dir/*.kegg.counts")), "kegg.dir/kegg.pathways.matrix") def combineKeggTables(infiles, outfile): ''' merge counts for kegg pathways ''' headers = ",".join( [re.match(".*.dir/(.*).kegg.counts", x).groups()[0] for x in infiles]) directory = os.path.dirname(infiles[0]) statement = '''python %(scriptsdir)s/combine_tables.py --glob=%(directory)s/*.kegg.counts --headers=%(headers)s --columns=1 --log=%(outfile)s.log > %(outfile)s''' P.run() ######################################### ######################################### ######################################### @follows(barplotAbundances, plotFirmicutesBacteroidetesRatio, calculateSignificanceOfFirmicutesBacteroidetesRatio, plotHowManySpecies, heatmapAbundances, plotSignificantResults) def full(): pass ######################################### ######################################### ######################################### if __name__ == "__main__": sys.exit(P.main(sys.argv))
CGATOxford/proj029
Proj029Pipelines/pipeline_proj029.py
Python
bsd-3-clause
12,528
import os from time import sleep from cement.utils.test import TestApp from cement.utils.misc import init_defaults if 'REDIS_HOST' in os.environ.keys(): redis_host = os.environ['REDIS_HOST'] else: redis_host = 'localhost' defaults = init_defaults('cache.redis') defaults['cache.redis']['host'] = redis_host defaults['cache.redis']['port'] = 6379 defaults['cache.redis']['db'] = 0 class RedisApp(TestApp): class Meta: extensions = ['redis'] cache_handler = 'redis' config_defaults = defaults def test_redis_set(key): with RedisApp() as app: app.cache.set(key, 1001) assert int(app.cache.get(key)) == 1001 def test_redis_get(key): with RedisApp() as app: # get empty value app.cache.delete(key) assert app.cache.get(key) is None # get empty value with fallback assert app.cache.get(key, 1234) == 1234 def test_redis_delete(key): with RedisApp() as app: app.cache.set(key, 1001) assert int(app.cache.get(key)) == 1001 app.cache.delete(key) assert app.cache.get(key) is None def test_redis_purge(key): with RedisApp() as app: app.cache.set(key, 1002) app.cache.purge() assert app.cache.get(key) is None def test_redis_expire(key): with RedisApp() as app: app.cache.set(key, 1003, time=2) sleep(3) assert app.cache.get(key) is None
datafolklabs/cement
tests/ext/test_ext_redis.py
Python
bsd-3-clause
1,437
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * 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 the United States Government 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 UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.notify.adapter.proxy; import gov.hhs.fha.nhinc.adapternotificationconsumersecured.AdapterNotificationConsumerPortSecureType; import gov.hhs.fha.nhinc.common.nhinccommon.AcknowledgementType; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType; import gov.hhs.fha.nhinc.hiem.consumerreference.ReferenceParametersHelper; import gov.hhs.fha.nhinc.hiem.consumerreference.SoapMessageElements; import gov.hhs.fha.nhinc.hiem.dte.marshallers.NhincCommonAcknowledgementMarshaller; import gov.hhs.fha.nhinc.hiem.dte.marshallers.WsntSubscribeMarshaller; import gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import gov.hhs.fha.nhinc.notify.adapter.proxy.service.HiemNotifyAdapterSecuredServicePortDescriptor; import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis_open.docs.wsn.b_2.Notify; import org.w3c.dom.Element; /** * * @author Jon Hoppesch */ public class HiemNotifyAdapterWebServiceProxySecured implements HiemNotifyAdapterProxy { private static Log log = LogFactory.getLog(HiemNotifyAdapterWebServiceProxySecured.class); private static WebServiceProxyHelper oProxyHelper = null; public Element notify(Element notifyElement, SoapMessageElements referenceParametersElements, AssertionType assertion, NhinTargetSystemType target) throws Exception { Element responseElement = null; String url = getWebServiceProxyHelper().getAdapterEndPointFromConnectionManager( NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME); if (NullChecker.isNotNullish(url)) { WsntSubscribeMarshaller subscribeMarshaller = new WsntSubscribeMarshaller(); Notify notify = subscribeMarshaller.unmarshalNotifyRequest(notifyElement); String wsAddressingTo = ReferenceParametersHelper.getWsAddressingTo(referenceParametersElements); if (wsAddressingTo == null) { wsAddressingTo = url; } HiemNotifyAdapterSecuredServicePortDescriptor portDescriptor = new HiemNotifyAdapterSecuredServicePortDescriptor(); CONNECTClient<AdapterNotificationConsumerPortSecureType> client = getCONNECTClientSecured(portDescriptor, url, assertion, wsAddressingTo); AcknowledgementType response = (AcknowledgementType) client.invokePort( AdapterNotificationConsumerPortSecureType.class, "notify", notify); NhincCommonAcknowledgementMarshaller acknowledgementMarshaller = new NhincCommonAcknowledgementMarshaller(); responseElement = acknowledgementMarshaller.marshal(response); } else { log.error("Failed to call the web service (" + NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME + "). The URL is null."); } return responseElement; } public Element notifySubscribersOfDocument(Element docNotify, AssertionType assertion, NhinTargetSystemType target) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public Element notifySubscribersOfCdcBioPackage(Element cdcNotify, AssertionType assertion, NhinTargetSystemType target) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } protected CONNECTClient<AdapterNotificationConsumerPortSecureType> getCONNECTClientSecured( ServicePortDescriptor<AdapterNotificationConsumerPortSecureType> portDescriptor, String url, AssertionType assertion, String wsAddressingTo) { return CONNECTCXFClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, url, assertion, wsAddressingTo); } protected WebServiceProxyHelper getWebServiceProxyHelper() { if (oProxyHelper == null) { oProxyHelper = new WebServiceProxyHelper(); } return oProxyHelper; } }
alameluchidambaram/CONNECT
Product/Production/Services/HIEMCore/src/main/java/gov/hhs/fha/nhinc/notify/adapter/proxy/HiemNotifyAdapterWebServiceProxySecured.java
Java
bsd-3-clause
6,017
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Tests for WebSocketBasicStream. Note that we do not attempt to verify that // frame parsing itself functions correctly, as that is covered by the // WebSocketFrameParser tests. #include "net/websockets/websocket_basic_stream.h" #include <stddef.h> #include <stdint.h> #include <string.h> // for memcpy() and memset(). #include <utility> #include "base/big_endian.h" #include "base/containers/span.h" #include "base/optional.h" #include "base/stl_util.h" #include "net/base/io_buffer.h" #include "net/base/privacy_mode.h" #include "net/base/test_completion_callback.h" #include "net/log/test_net_log.h" #include "net/socket/connect_job.h" #include "net/socket/socket_tag.h" #include "net/socket/socket_test_util.h" #include "net/socket/ssl_client_socket.h" #include "net/test/gtest_util.h" #include "net/test/test_with_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using net::test::IsError; using net::test::IsOk; namespace net { namespace { #define WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(name, value) \ const char k##name[] = value; \ const size_t k##name##Size = base::size(k##name) - 1 WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(SampleFrame, "\x81\x06Sample"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT( PartialLargeFrame, "\x81\x7F\x00\x00\x00\x00\x7F\xFF\xFF\xFF" "chromiunum ad pasco per loca insanis pullum manducat frumenti"); const size_t kLargeFrameHeaderSize = 10; WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(MultipleFrames, "\x81\x01X\x81\x01Y\x81\x01Z"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyFirstFrame, "\x01\x00"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyMiddleFrame, "\x00\x00"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyFinalTextFrame, "\x81\x00"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(EmptyFinalContinuationFrame, "\x80\x00"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(ValidPong, "\x8A\x00"); // This frame encodes a payload length of 7 in two bytes, which is always // invalid. WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(InvalidFrame, "\x81\x7E\x00\x07Invalid"); // Control frames must have the FIN bit set. This one does not. WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(PingFrameWithoutFin, "\x09\x00"); // Control frames must have a payload of 125 bytes or less. This one has // a payload of 126 bytes. WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT( 126BytePong, "\x8a\x7e\x00\x7eZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ" "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(CloseFrame, "\x88\x09\x03\xe8occludo"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(WriteFrame, "\x81\x85\x00\x00\x00\x00Write"); WEBSOCKET_BASIC_STREAM_TEST_DEFINE_CONSTANT(MaskedEmptyPong, "\x8A\x80\x00\x00\x00\x00"); const WebSocketMaskingKey kNulMaskingKey = {{'\0', '\0', '\0', '\0'}}; const WebSocketMaskingKey kNonNulMaskingKey = { {'\x0d', '\x1b', '\x06', '\x17'}}; // A masking key generator function which generates the identity mask, // ie. "\0\0\0\0". WebSocketMaskingKey GenerateNulMaskingKey() { return kNulMaskingKey; } // A masking key generation function which generates a fixed masking key with no // nul characters. WebSocketMaskingKey GenerateNonNulMaskingKey() { return kNonNulMaskingKey; } // A subclass of StaticSocketDataProvider modified to require that all data // expected to be read or written actually is. class StrictStaticSocketDataProvider : public StaticSocketDataProvider { public: StrictStaticSocketDataProvider(base::span<const MockRead> reads, base::span<const MockWrite> writes, bool strict_mode) : StaticSocketDataProvider(reads, writes), strict_mode_(strict_mode) {} ~StrictStaticSocketDataProvider() override { if (strict_mode_) { EXPECT_EQ(read_count(), read_index()); EXPECT_EQ(write_count(), write_index()); } } private: const bool strict_mode_; }; // A fixture for tests which only perform normal socket operations. class WebSocketBasicStreamSocketTest : public TestWithTaskEnvironment { protected: WebSocketBasicStreamSocketTest() : common_connect_job_params_( &factory_, nullptr /* host_resolver */, nullptr /* http_auth_cache */, nullptr /* http_auth_handler_factory */, nullptr /* spdy_session_pool */, nullptr /* quic_supported_versions */, nullptr /* quic_stream_factory */, nullptr /* proxy_delegate */, nullptr /* http_user_agent_settings */, nullptr /* ssl_client_context */, nullptr /* socket_performance_watcher_factory */, nullptr /* network_quality_estimator */, nullptr /* net_log */, nullptr /* websocket_endpoint_lock_manager */), pool_(1, 1, &common_connect_job_params_), generator_(&GenerateNulMaskingKey), expect_all_io_to_complete_(true) {} ~WebSocketBasicStreamSocketTest() override { // stream_ has a reference to socket_data_ (via MockTCPClientSocket) and so // should be destroyed first. stream_.reset(); } std::unique_ptr<ClientSocketHandle> MakeTransportSocket( base::span<const MockRead> reads, base::span<const MockWrite> writes) { socket_data_ = std::make_unique<StrictStaticSocketDataProvider>( reads, writes, expect_all_io_to_complete_); socket_data_->set_connect_data(MockConnect(SYNCHRONOUS, OK)); factory_.AddSocketDataProvider(socket_data_.get()); auto transport_socket = std::make_unique<ClientSocketHandle>(); scoped_refptr<ClientSocketPool::SocketParams> null_params; ClientSocketPool::GroupId group_id( HostPortPair("a", 80), ClientSocketPool::SocketType::kHttp, PrivacyMode::PRIVACY_MODE_DISABLED, NetworkIsolationKey(), false /* disable_secure_dns */); transport_socket->Init( group_id, null_params, base::nullopt /* proxy_annotation_tag */, MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); return transport_socket; } void SetHttpReadBuffer(const char* data, size_t size) { http_read_buffer_ = base::MakeRefCounted<GrowableIOBuffer>(); http_read_buffer_->SetCapacity(size); memcpy(http_read_buffer_->data(), data, size); http_read_buffer_->set_offset(size); } void CreateStream(base::span<const MockRead> reads, base::span<const MockWrite> writes) { stream_ = WebSocketBasicStream::CreateWebSocketBasicStreamForTesting( MakeTransportSocket(reads, writes), http_read_buffer_, sub_protocol_, extensions_, generator_); } std::unique_ptr<SocketDataProvider> socket_data_; MockClientSocketFactory factory_; const CommonConnectJobParams common_connect_job_params_; MockTransportClientSocketPool pool_; std::vector<std::unique_ptr<WebSocketFrame>> frames_; TestCompletionCallback cb_; scoped_refptr<GrowableIOBuffer> http_read_buffer_; std::string sub_protocol_; std::string extensions_; WebSocketBasicStream::WebSocketMaskingKeyGeneratorFunction generator_; bool expect_all_io_to_complete_; std::unique_ptr<WebSocketBasicStream> stream_; }; // A test fixture for the common case of tests that only perform a single read. class WebSocketBasicStreamSocketSingleReadTest : public WebSocketBasicStreamSocketTest { protected: void CreateRead(const MockRead& read) { reads_[0] = read; CreateStream(reads_, base::span<MockWrite>()); } MockRead reads_[1]; }; // A test fixture for tests that perform chunked reads. class WebSocketBasicStreamSocketChunkedReadTest : public WebSocketBasicStreamSocketTest { protected: // Specify the behaviour if there aren't enough chunks to use all the data. If // LAST_FRAME_BIG is specified, then the rest of the data will be // put in the last chunk. If LAST_FRAME_NOT_BIG is specified, then the last // frame will be no bigger than the rest of the frames (but it can be smaller, // if not enough data remains). enum LastFrameBehaviour { LAST_FRAME_BIG, LAST_FRAME_NOT_BIG }; // Prepares a read from |data| of |data_size|, split into |number_of_chunks|, // each of |chunk_size| (except that the last chunk may be larger or // smaller). All reads must be either SYNCHRONOUS or ASYNC (not a mixture), // and errors cannot be simulated. Once data is exhausted, further reads will // return 0 (ie. connection closed). void CreateChunkedRead(IoMode mode, const char data[], size_t data_size, int chunk_size, size_t number_of_chunks, LastFrameBehaviour last_frame_behaviour) { reads_.clear(); const char* start = data; for (size_t i = 0; i < number_of_chunks; ++i) { int len = chunk_size; const bool is_last_chunk = (i == number_of_chunks - 1); if ((last_frame_behaviour == LAST_FRAME_BIG && is_last_chunk) || static_cast<int>(data + data_size - start) < len) { len = static_cast<int>(data + data_size - start); } reads_.push_back(MockRead(mode, start, len)); start += len; } CreateStream(reads_, base::span<MockWrite>()); } std::vector<MockRead> reads_; }; // Test fixture for write tests. class WebSocketBasicStreamSocketWriteTest : public WebSocketBasicStreamSocketTest { protected: // All write tests use the same frame, so it is easiest to create it during // test creation. void SetUp() override { PrepareWriteFrame(); } // Creates a WebSocketFrame with a wire format matching kWriteFrame and adds // it to |frames_|. void PrepareWriteFrame() { auto frame = std::make_unique<WebSocketFrame>(WebSocketFrameHeader::kOpCodeText); const size_t payload_size = kWriteFrameSize - (WebSocketFrameHeader::kBaseHeaderSize + WebSocketFrameHeader::kMaskingKeyLength); auto buffer = base::MakeRefCounted<IOBuffer>(payload_size); frame_buffers_.push_back(buffer); memcpy(buffer->data(), kWriteFrame + kWriteFrameSize - payload_size, payload_size); frame->payload = buffer->data(); WebSocketFrameHeader& header = frame->header; header.final = true; header.masked = true; header.payload_length = payload_size; frames_.push_back(std::move(frame)); } // TODO(yoichio): Make this type std::vector<std::string>. std::vector<scoped_refptr<IOBuffer>> frame_buffers_; }; TEST_F(WebSocketBasicStreamSocketTest, ConstructionWorks) { CreateStream(base::span<MockRead>(), base::span<MockWrite>()); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncReadWorks) { CreateRead(MockRead(SYNCHRONOUS, kSampleFrame, kSampleFrameSize)); int result = stream_->ReadFrames(&frames_, cb_.callback()); EXPECT_THAT(result, IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); EXPECT_TRUE(frames_[0]->header.final); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncReadWorks) { CreateRead(MockRead(ASYNC, kSampleFrame, kSampleFrameSize)); int result = stream_->ReadFrames(&frames_, cb_.callback()); ASSERT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); // Don't repeat all the tests from SyncReadWorks; just enough to be sure the // frame was really read. } // ReadFrames will not return a frame whose header has not been wholly received. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, HeaderFragmentedSync) { CreateChunkedRead( SYNCHRONOUS, kSampleFrame, kSampleFrameSize, 1, 2, LAST_FRAME_BIG); int result = stream_->ReadFrames(&frames_, cb_.callback()); EXPECT_THAT(result, IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); } // The same behaviour applies to asynchronous reads. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, HeaderFragmentedAsync) { CreateChunkedRead( ASYNC, kSampleFrame, kSampleFrameSize, 1, 2, LAST_FRAME_BIG); int result = stream_->ReadFrames(&frames_, cb_.callback()); ASSERT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); } // If it receives an incomplete header in a synchronous call, then has to wait // for the rest of the frame, ReadFrames will return ERR_IO_PENDING. TEST_F(WebSocketBasicStreamSocketTest, HeaderFragmentedSyncAsync) { MockRead reads[] = {MockRead(SYNCHRONOUS, kSampleFrame, 1), MockRead(ASYNC, kSampleFrame + 1, kSampleFrameSize - 1)}; CreateStream(reads, base::span<MockWrite>()); int result = stream_->ReadFrames(&frames_, cb_.callback()); ASSERT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); } // An extended header should also return ERR_IO_PENDING if it is not completely // received. TEST_F(WebSocketBasicStreamSocketTest, FragmentedLargeHeader) { MockRead reads[] = { MockRead(SYNCHRONOUS, kPartialLargeFrame, kLargeFrameHeaderSize - 1), MockRead(SYNCHRONOUS, ERR_IO_PENDING)}; CreateStream(reads, base::span<MockWrite>()); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); } // A frame that does not arrive in a single read should be broken into separate // frames. TEST_F(WebSocketBasicStreamSocketSingleReadTest, LargeFrameFirstChunk) { CreateRead(MockRead(SYNCHRONOUS, kPartialLargeFrame, kPartialLargeFrameSize)); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_FALSE(frames_[0]->header.final); EXPECT_EQ(kPartialLargeFrameSize - kLargeFrameHeaderSize, static_cast<size_t>(frames_[0]->header.payload_length)); } // If only the header of a data frame arrives, we should receive a frame with a // zero-size payload. TEST_F(WebSocketBasicStreamSocketSingleReadTest, HeaderOnlyChunk) { CreateRead(MockRead(SYNCHRONOUS, kPartialLargeFrame, kLargeFrameHeaderSize)); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(nullptr, frames_[0]->payload); EXPECT_EQ(0U, frames_[0]->header.payload_length); EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode); } // If the header and the body of a data frame arrive seperately, we should see // them as separate frames. TEST_F(WebSocketBasicStreamSocketTest, HeaderBodySeparated) { MockRead reads[] = { MockRead(SYNCHRONOUS, kPartialLargeFrame, kLargeFrameHeaderSize), MockRead(ASYNC, kPartialLargeFrame + kLargeFrameHeaderSize, kPartialLargeFrameSize - kLargeFrameHeaderSize)}; CreateStream(reads, base::span<MockWrite>()); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(nullptr, frames_[0]->payload); EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode); frames_.clear(); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(kPartialLargeFrameSize - kLargeFrameHeaderSize, frames_[0]->header.payload_length); EXPECT_EQ(WebSocketFrameHeader::kOpCodeContinuation, frames_[0]->header.opcode); } // Every frame has a header with a correct payload_length field. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, LargeFrameTwoChunks) { const size_t kChunkSize = 16; CreateChunkedRead(ASYNC, kPartialLargeFrame, kPartialLargeFrameSize, kChunkSize, 2, LAST_FRAME_NOT_BIG); TestCompletionCallback cb[2]; ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[0].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(kChunkSize - kLargeFrameHeaderSize, frames_[0]->header.payload_length); frames_.clear(); ASSERT_THAT(stream_->ReadFrames(&frames_, cb[1].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[1].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(kChunkSize, frames_[0]->header.payload_length); } // Only the final frame of a fragmented message has |final| bit set. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, OnlyFinalChunkIsFinal) { static const size_t kFirstChunkSize = 4; CreateChunkedRead(ASYNC, kSampleFrame, kSampleFrameSize, kFirstChunkSize, 2, LAST_FRAME_BIG); TestCompletionCallback cb[2]; ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[0].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); ASSERT_FALSE(frames_[0]->header.final); frames_.clear(); ASSERT_THAT(stream_->ReadFrames(&frames_, cb[1].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[1].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); ASSERT_TRUE(frames_[0]->header.final); } // All frames after the first have their opcode changed to Continuation. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, ContinuationOpCodeUsed) { const size_t kFirstChunkSize = 3; const int kChunkCount = 3; // The input data is one frame with opcode Text, which arrives in three // separate chunks. CreateChunkedRead(ASYNC, kSampleFrame, kSampleFrameSize, kFirstChunkSize, kChunkCount, LAST_FRAME_BIG); TestCompletionCallback cb[kChunkCount]; ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[0].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode); // This test uses a loop to verify that the opcode for every frames generated // after the first is converted to Continuation. for (int i = 1; i < kChunkCount; ++i) { frames_.clear(); ASSERT_THAT(stream_->ReadFrames(&frames_, cb[i].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[i].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeContinuation, frames_[0]->header.opcode); } } // Multiple frames that arrive together should be parsed correctly. TEST_F(WebSocketBasicStreamSocketSingleReadTest, ThreeFramesTogether) { CreateRead(MockRead(SYNCHRONOUS, kMultipleFrames, kMultipleFramesSize)); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(3U, frames_.size()); EXPECT_TRUE(frames_[0]->header.final); EXPECT_TRUE(frames_[1]->header.final); EXPECT_TRUE(frames_[2]->header.final); } // ERR_CONNECTION_CLOSED must be returned on close. TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncClose) { CreateRead(MockRead(SYNCHRONOUS, "", 0)); EXPECT_EQ(ERR_CONNECTION_CLOSED, stream_->ReadFrames(&frames_, cb_.callback())); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncClose) { CreateRead(MockRead(ASYNC, "", 0)); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED)); } // The result should be the same if the socket returns // ERR_CONNECTION_CLOSED. This is not expected to happen on an established // connection; a Read of size 0 is the expected behaviour. The key point of this // test is to confirm that ReadFrames() behaviour is identical in both cases. TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncCloseWithErr) { CreateRead(MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED)); EXPECT_EQ(ERR_CONNECTION_CLOSED, stream_->ReadFrames(&frames_, cb_.callback())); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncCloseWithErr) { CreateRead(MockRead(ASYNC, ERR_CONNECTION_CLOSED)); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED)); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncErrorsPassedThrough) { // ERR_INSUFFICIENT_RESOURCES here represents an arbitrary error that // WebSocketBasicStream gives no special handling to. CreateRead(MockRead(SYNCHRONOUS, ERR_INSUFFICIENT_RESOURCES)); EXPECT_EQ(ERR_INSUFFICIENT_RESOURCES, stream_->ReadFrames(&frames_, cb_.callback())); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncErrorsPassedThrough) { CreateRead(MockRead(ASYNC, ERR_INSUFFICIENT_RESOURCES)); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_INSUFFICIENT_RESOURCES)); } // If we get a frame followed by a close, we should receive them separately. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, CloseAfterFrame) { // The chunk size equals the data size, so the second chunk is 0 size, closing // the connection. CreateChunkedRead(SYNCHRONOUS, kSampleFrame, kSampleFrameSize, kSampleFrameSize, 2, LAST_FRAME_NOT_BIG); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); EXPECT_EQ(1U, frames_.size()); frames_.clear(); EXPECT_EQ(ERR_CONNECTION_CLOSED, stream_->ReadFrames(&frames_, cb_.callback())); } // Synchronous close after an async frame header is handled by a different code // path. TEST_F(WebSocketBasicStreamSocketTest, AsyncCloseAfterIncompleteHeader) { MockRead reads[] = {MockRead(ASYNC, kSampleFrame, 1U), MockRead(SYNCHRONOUS, "", 0)}; CreateStream(reads, base::span<MockWrite>()); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED)); } // When Stream::Read returns ERR_CONNECTION_CLOSED we get the same result via a // slightly different code path. TEST_F(WebSocketBasicStreamSocketTest, AsyncErrCloseAfterIncompleteHeader) { MockRead reads[] = {MockRead(ASYNC, kSampleFrame, 1U), MockRead(SYNCHRONOUS, ERR_CONNECTION_CLOSED)}; CreateStream(reads, base::span<MockWrite>()); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_CONNECTION_CLOSED)); } // An empty first frame is not ignored. TEST_F(WebSocketBasicStreamSocketSingleReadTest, EmptyFirstFrame) { CreateRead(MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize)); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(nullptr, frames_[0]->payload); EXPECT_EQ(0U, frames_[0]->header.payload_length); } // An empty frame in the middle of a message is ignored. TEST_F(WebSocketBasicStreamSocketTest, EmptyMiddleFrame) { MockRead reads[] = { MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize), MockRead(SYNCHRONOUS, kEmptyMiddleFrame, kEmptyMiddleFrameSize), MockRead(SYNCHRONOUS, ERR_IO_PENDING)}; CreateStream(reads, base::span<MockWrite>()); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); EXPECT_EQ(1U, frames_.size()); frames_.clear(); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); } // An empty frame in the middle of a message that arrives separately is still // ignored. TEST_F(WebSocketBasicStreamSocketTest, EmptyMiddleFrameAsync) { MockRead reads[] = { MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize), MockRead(ASYNC, kEmptyMiddleFrame, kEmptyMiddleFrameSize), // We include a pong message to verify the middle frame was actually // processed. MockRead(ASYNC, kValidPong, kValidPongSize)}; CreateStream(reads, base::span<MockWrite>()); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); EXPECT_EQ(1U, frames_.size()); frames_.clear(); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodePong, frames_[0]->header.opcode); } // An empty final frame is not ignored. TEST_F(WebSocketBasicStreamSocketSingleReadTest, EmptyFinalFrame) { CreateRead( MockRead(SYNCHRONOUS, kEmptyFinalTextFrame, kEmptyFinalTextFrameSize)); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(nullptr, frames_[0]->payload); EXPECT_EQ(0U, frames_[0]->header.payload_length); } // An empty middle frame is ignored with a final frame present. TEST_F(WebSocketBasicStreamSocketTest, ThreeFrameEmptyMessage) { MockRead reads[] = { MockRead(SYNCHRONOUS, kEmptyFirstFrame, kEmptyFirstFrameSize), MockRead(SYNCHRONOUS, kEmptyMiddleFrame, kEmptyMiddleFrameSize), MockRead(SYNCHRONOUS, kEmptyFinalContinuationFrame, kEmptyFinalContinuationFrameSize)}; CreateStream(reads, base::span<MockWrite>()); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode); frames_.clear(); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_TRUE(frames_[0]->header.final); } // If there was a frame read at the same time as the response headers (and the // handshake succeeded), then we should parse it. TEST_F(WebSocketBasicStreamSocketTest, HttpReadBufferIsUsed) { SetHttpReadBuffer(kSampleFrame, kSampleFrameSize); CreateStream(base::span<MockRead>(), base::span<MockWrite>()); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); ASSERT_TRUE(frames_[0]->payload); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); } // Check that a frame whose header partially arrived at the end of the response // headers works correctly. TEST_F(WebSocketBasicStreamSocketSingleReadTest, PartialFrameHeaderInHttpResponse) { SetHttpReadBuffer(kSampleFrame, 1); CreateRead(MockRead(ASYNC, kSampleFrame + 1, kSampleFrameSize - 1)); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); ASSERT_TRUE(frames_[0]->payload); EXPECT_EQ(UINT64_C(6), frames_[0]->header.payload_length); EXPECT_EQ(WebSocketFrameHeader::kOpCodeText, frames_[0]->header.opcode); } // Check that a control frame which partially arrives at the end of the response // headers works correctly. TEST_F(WebSocketBasicStreamSocketSingleReadTest, PartialControlFrameInHttpResponse) { const size_t kPartialFrameBytes = 3; SetHttpReadBuffer(kCloseFrame, kPartialFrameBytes); CreateRead(MockRead(ASYNC, kCloseFrame + kPartialFrameBytes, kCloseFrameSize - kPartialFrameBytes)); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode); EXPECT_EQ(kCloseFrameSize - 2, frames_[0]->header.payload_length); EXPECT_EQ(std::string(frames_[0]->payload, kCloseFrameSize - 2), std::string(kCloseFrame + 2, kCloseFrameSize - 2)); } // Check that a control frame which partially arrives at the end of the response // headers works correctly. Synchronous version (unlikely in practice). TEST_F(WebSocketBasicStreamSocketSingleReadTest, PartialControlFrameInHttpResponseSync) { const size_t kPartialFrameBytes = 3; SetHttpReadBuffer(kCloseFrame, kPartialFrameBytes); CreateRead(MockRead(SYNCHRONOUS, kCloseFrame + kPartialFrameBytes, kCloseFrameSize - kPartialFrameBytes)); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode); } // Check that an invalid frame results in an error. TEST_F(WebSocketBasicStreamSocketSingleReadTest, SyncInvalidFrame) { CreateRead(MockRead(SYNCHRONOUS, kInvalidFrame, kInvalidFrameSize)); EXPECT_EQ(ERR_WS_PROTOCOL_ERROR, stream_->ReadFrames(&frames_, cb_.callback())); } TEST_F(WebSocketBasicStreamSocketSingleReadTest, AsyncInvalidFrame) { CreateRead(MockRead(ASYNC, kInvalidFrame, kInvalidFrameSize)); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_WS_PROTOCOL_ERROR)); } // A control frame without a FIN flag is invalid and should not be passed // through to higher layers. RFC6455 5.5 "All control frames ... MUST NOT be // fragmented." TEST_F(WebSocketBasicStreamSocketSingleReadTest, ControlFrameWithoutFin) { CreateRead( MockRead(SYNCHRONOUS, kPingFrameWithoutFin, kPingFrameWithoutFinSize)); EXPECT_EQ(ERR_WS_PROTOCOL_ERROR, stream_->ReadFrames(&frames_, cb_.callback())); EXPECT_TRUE(frames_.empty()); } // A control frame over 125 characters is invalid. RFC6455 5.5 "All control // frames MUST have a payload length of 125 bytes or less". Since we use a // 125-byte buffer to assemble fragmented control frames, we need to detect this // error before attempting to assemble the fragments. TEST_F(WebSocketBasicStreamSocketSingleReadTest, OverlongControlFrame) { CreateRead(MockRead(SYNCHRONOUS, k126BytePong, k126BytePongSize)); EXPECT_EQ(ERR_WS_PROTOCOL_ERROR, stream_->ReadFrames(&frames_, cb_.callback())); EXPECT_TRUE(frames_.empty()); } // A control frame over 125 characters should still be rejected if it is split // into multiple chunks. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, SplitOverlongControlFrame) { const size_t kFirstChunkSize = 16; expect_all_io_to_complete_ = false; CreateChunkedRead(SYNCHRONOUS, k126BytePong, k126BytePongSize, kFirstChunkSize, 2, LAST_FRAME_BIG); EXPECT_EQ(ERR_WS_PROTOCOL_ERROR, stream_->ReadFrames(&frames_, cb_.callback())); EXPECT_TRUE(frames_.empty()); } TEST_F(WebSocketBasicStreamSocketChunkedReadTest, AsyncSplitOverlongControlFrame) { const size_t kFirstChunkSize = 16; expect_all_io_to_complete_ = false; CreateChunkedRead(ASYNC, k126BytePong, k126BytePongSize, kFirstChunkSize, 2, LAST_FRAME_BIG); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsError(ERR_WS_PROTOCOL_ERROR)); // The caller should not call ReadFrames() again after receiving an error // other than ERR_IO_PENDING. EXPECT_TRUE(frames_.empty()); } // In the synchronous case, ReadFrames assembles the whole control frame before // returning. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, SyncControlFrameAssembly) { const size_t kChunkSize = 3; CreateChunkedRead( SYNCHRONOUS, kCloseFrame, kCloseFrameSize, kChunkSize, 3, LAST_FRAME_BIG); EXPECT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode); } // In the asynchronous case, the callback is not called until the control frame // has been completely assembled. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, AsyncControlFrameAssembly) { const size_t kChunkSize = 3; CreateChunkedRead( ASYNC, kCloseFrame, kCloseFrameSize, kChunkSize, 3, LAST_FRAME_BIG); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_EQ(WebSocketFrameHeader::kOpCodeClose, frames_[0]->header.opcode); } // A frame with a 1MB payload that has to be read in chunks. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, OneMegFrame) { // This should be equal to the definition of kReadBufferSize in // websocket_basic_stream.cc. const int kReadBufferSize = 32 * 1024; const uint64_t kPayloadSize = 1 << 20; const size_t kWireSize = kPayloadSize + kLargeFrameHeaderSize; const size_t kExpectedFrameCount = (kWireSize + kReadBufferSize - 1) / kReadBufferSize; std::unique_ptr<char[]> big_frame(new char[kWireSize]); memcpy(big_frame.get(), "\x81\x7F", 2); base::WriteBigEndian(big_frame.get() + 2, kPayloadSize); memset(big_frame.get() + kLargeFrameHeaderSize, 'A', kPayloadSize); CreateChunkedRead(ASYNC, big_frame.get(), kWireSize, kReadBufferSize, kExpectedFrameCount, LAST_FRAME_BIG); for (size_t frame = 0; frame < kExpectedFrameCount; ++frame) { frames_.clear(); ASSERT_THAT(stream_->ReadFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); size_t expected_payload_size = kReadBufferSize; if (frame == 0) { expected_payload_size = kReadBufferSize - kLargeFrameHeaderSize; } else if (frame == kExpectedFrameCount - 1) { expected_payload_size = kLargeFrameHeaderSize; } EXPECT_EQ(expected_payload_size, frames_[0]->header.payload_length); } } // A frame with reserved flag(s) set that arrives in chunks should only have the // reserved flag(s) set on the first chunk when split. TEST_F(WebSocketBasicStreamSocketChunkedReadTest, ReservedFlagCleared) { static const char kReservedFlagFrame[] = "\x41\x05Hello"; const size_t kReservedFlagFrameSize = base::size(kReservedFlagFrame) - 1; const size_t kChunkSize = 5; CreateChunkedRead(ASYNC, kReservedFlagFrame, kReservedFlagFrameSize, kChunkSize, 2, LAST_FRAME_BIG); TestCompletionCallback cb[2]; ASSERT_THAT(stream_->ReadFrames(&frames_, cb[0].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[0].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_TRUE(frames_[0]->header.reserved1); frames_.clear(); ASSERT_THAT(stream_->ReadFrames(&frames_, cb[1].callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb[1].WaitForResult(), IsOk()); ASSERT_EQ(1U, frames_.size()); EXPECT_FALSE(frames_[0]->header.reserved1); } // Check that writing a frame all at once works. TEST_F(WebSocketBasicStreamSocketWriteTest, WriteAtOnce) { MockWrite writes[] = {MockWrite(SYNCHRONOUS, kWriteFrame, kWriteFrameSize)}; CreateStream(base::span<MockRead>(), writes); EXPECT_THAT(stream_->WriteFrames(&frames_, cb_.callback()), IsOk()); } // Check that completely async writing works. TEST_F(WebSocketBasicStreamSocketWriteTest, AsyncWriteAtOnce) { MockWrite writes[] = {MockWrite(ASYNC, kWriteFrame, kWriteFrameSize)}; CreateStream(base::span<MockRead>(), writes); ASSERT_THAT(stream_->WriteFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); } // Check that writing a frame to an extremely full kernel buffer (so that it // ends up being sent in bits) works. The WriteFrames() callback should not be // called until all parts have been written. TEST_F(WebSocketBasicStreamSocketWriteTest, WriteInBits) { MockWrite writes[] = {MockWrite(SYNCHRONOUS, kWriteFrame, 4), MockWrite(ASYNC, kWriteFrame + 4, 4), MockWrite(ASYNC, kWriteFrame + 8, kWriteFrameSize - 8)}; CreateStream(base::span<MockRead>(), writes); ASSERT_THAT(stream_->WriteFrames(&frames_, cb_.callback()), IsError(ERR_IO_PENDING)); EXPECT_THAT(cb_.WaitForResult(), IsOk()); } // Check that writing a Pong frame with a nullptr body works. TEST_F(WebSocketBasicStreamSocketWriteTest, WriteNullptrPong) { MockWrite writes[] = { MockWrite(SYNCHRONOUS, kMaskedEmptyPong, kMaskedEmptyPongSize)}; CreateStream(base::span<MockRead>(), writes); auto frame = std::make_unique<WebSocketFrame>(WebSocketFrameHeader::kOpCodePong); WebSocketFrameHeader& header = frame->header; header.final = true; header.masked = true; header.payload_length = 0; std::vector<std::unique_ptr<WebSocketFrame>> frames; frames.push_back(std::move(frame)); EXPECT_THAT(stream_->WriteFrames(&frames, cb_.callback()), IsOk()); } // Check that writing with a non-nullptr mask works correctly. TEST_F(WebSocketBasicStreamSocketTest, WriteNonNulMask) { std::string masked_frame = std::string("\x81\x88"); masked_frame += std::string(kNonNulMaskingKey.key, 4); masked_frame += "jiggered"; MockWrite writes[] = { MockWrite(SYNCHRONOUS, masked_frame.data(), masked_frame.size())}; generator_ = &GenerateNonNulMaskingKey; CreateStream(base::span<MockRead>(), writes); auto frame = std::make_unique<WebSocketFrame>(WebSocketFrameHeader::kOpCodeText); const std::string unmasked_payload = "graphics"; const size_t payload_size = unmasked_payload.size(); auto buffer = base::MakeRefCounted<IOBuffer>(payload_size); memcpy(buffer->data(), unmasked_payload.data(), payload_size); frame->payload = buffer->data(); WebSocketFrameHeader& header = frame->header; header.final = true; header.masked = true; header.payload_length = payload_size; frames_.push_back(std::move(frame)); EXPECT_THAT(stream_->WriteFrames(&frames_, cb_.callback()), IsOk()); } TEST_F(WebSocketBasicStreamSocketTest, GetExtensionsWorks) { extensions_ = "inflate-uuencode"; CreateStream(base::span<MockRead>(), base::span<MockWrite>()); EXPECT_EQ("inflate-uuencode", stream_->GetExtensions()); } TEST_F(WebSocketBasicStreamSocketTest, GetSubProtocolWorks) { sub_protocol_ = "cyberchat"; CreateStream(base::span<MockRead>(), base::span<MockWrite>()); EXPECT_EQ("cyberchat", stream_->GetSubProtocol()); } } // namespace } // namespace net
endlessm/chromium-browser
net/websockets/websocket_basic_stream_test.cc
C++
bsd-3-clause
39,587
#include <stdio.h> #include <iostream> #include <math.h> using namespace std; #define eps 1e-6 struct TPoint { double x, y; }; struct TLine { TPoint p1, p2; }; double max(double x, double y) { //±È½ÏÁ½¸öÊýµÄ´óС£¬·µ»Ø´óµÄÊý if(x > y) return x; else return y; } double min(double x, double y) { //±È½ÏÁ½¸öÊýµÄ´óС£¬·µ»ØÐ¡µÄÊý if(x < y) return x; else return y; } double multi(TPoint p1, TPoint p2, TPoint p0) { //ÇóʸÁ¿[p0, p1], [p0, p2]µÄ²æ»ý //p0ÊǶ¥µã return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y); //Èô½á¹ûµÈÓÚ0£¬ÔòÕâÈýµã¹²Ïß //Èô½á¹û´óÓÚ0£¬Ôòp0p2ÔÚp0p1µÄÄæÊ±Õë·½Ïò //Èô½á¹ûСÓÚ0£¬Ôòp0p2ÔÚp0p1µÄ˳ʱÕë·½Ïò } bool isIntersected(TPoint s1, TPoint e1, TPoint s2, TPoint e2) { //ÅжÏÏß¶ÎÊÇ·ñÏཻ //1.¿ìËÙÅųâÊÔÑéÅжÏÒÔÁ½ÌõÏß¶ÎΪ¶Ô½ÇÏßµÄÁ½¸ö¾ØÐÎÊÇ·ñÏཻ //2.¿çÁ¢ÊÔÑé if( (max(s1.x, e1.x) >= min(s2.x, e2.x)) && (max(s2.x, e2.x) >= min(s1.x, e1.x)) && (max(s1.y, e1.y) >= min(s2.y, e2.y)) && (max(s2.y, e2.y) >= min(s1.y, e1.y)) && (multi(s2, e1, s1) * multi(e1, e2, s1) >= 0) && (multi(s1, e2, s2) * multi(e2, e1, s2) >= 0) ) return true; return false; } int main() { //freopen("in.in", "r", stdin); //freopen("out.out", "w", stdout); int ca, n, i, j, t, ltmp, qn; double tmp[100]; TPoint p0, point[80]; TPoint Q[300]; TLine line[40]; while(scanf("%d", &n) != EOF){ t = 0; for(i = 0;i < n;i++ ){ scanf("%lf%lf%lf%lf", &line[i].p1.x, &line[i].p1.y, &line[i].p2.x, &line[i].p2.y); point[t++] = line[i].p1; point[t++] = line[i].p2; } scanf("%lf%lf", &p0.x, &p0.y); //x = 0ÕâÌõÏßÉ쵀 ltmp = 1; tmp[0] = 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].x) < eps) tmp[ltmp++] = point[i].y; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); qn = 0; for(i = 1;i < ltmp;i++){ Q[qn].x = 0.0; Q[qn++].y = (tmp[i - 1] + tmp[i]) / 2; } //y = 0ÕâÌõÏßÉÏ ltmp = 1; tmp[0]= 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].y) < eps) tmp[ltmp++] = point[i].x; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); for(i = 1;i < ltmp;i++){ Q[qn].x = (tmp[i - 1] + tmp[i]) / 2; Q[qn++].y = 0.0; } //x = 100 ÕâÌõÏßÉÏ ltmp = 1; tmp[0] = 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].x - 100) < eps) tmp[ltmp++] = point[i].y; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); for(i = 1;i < ltmp;i++){ Q[qn].x = 100.0; Q[qn++].y = (tmp[i - 1] + tmp[i]) / 2; } //y = 100ÕâÌõÏß ltmp = 1; tmp[0] = 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].y - 100.0) < eps) tmp[ltmp++] = point[i].x; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); for(i = 1;i < ltmp;i++){ Q[qn].x = (tmp[i - 1] + tmp[i]) / 2; Q[qn++].y = 100.0; } int ans = 9999999, ans1; for(i = 0;i < qn;i++){ ans1 = 0; for(j = 0;j < n;j++){ if(isIntersected(line[j].p1, line[j].p2, Q[i], p0)) ans1++; } if(ans1 < ans) ans = ans1; } printf("Number of doors = %d\n", ans + 1); } return 0; }
yubo/program
ds/计算几何模板/pku_1066_Treasure Hunt.cpp
C++
bsd-3-clause
3,649
<?php /* * recurrent homeworks * */ include "utils.php"; session_start(); //si no hay sesion iniciada if(!isset($_SESSION["usrUserName"]) ) { //retornar al index (login) header("location: ../../index.php"); exit(); } //verificar que viene el campo activity del form if(isset($_POST["cmb_activity"] )) { $task = mysql_real_escape_string($_POST['recTaskName']); $remind_by = mysql_real_escape_string($_POST['dayWeekMonth']); //obtener el dato dependiendo si sera por semana o por mes if($remind_by == 'weekly') { //dia en que se asignara $remind_day = mysql_real_escape_string($_POST['week_day']); } else { //dia en que se asignara la tarea $remind_day = mysql_real_escape_string($_POST['monthDay']); } //dia que se debera realizar dicha actividad if($remind_by == 'weekly') { //dia en que se realizara $due_day = mysql_real_escape_string($_POST['due_weekday']); } else { //dia en que se asignara $due_day = mysql_real_escape_string($_POST['monthly_day']); } $points = mysql_real_escape_string($_POST["hw_points"]); $actID = mysql_real_escape_string($_POST["cmb_activity"]); $type_hw = mysql_real_escape_string($_POST["type_hw"]); $asignatorID = $_SESSION['usrID']; $profileID = $_SESSION['profileID']; $notify = isset($_POST["notify"]); $result = mysql_query("INSERT into recurringTasks (task, remind_by, remind_day, due_day, notify_email, actID, asignatorID, state, points, type) values ('$task','$remind_by', '$remind_day', '$due_day', '$notify', '$actID', '$asignatorID', 'assigned', '$points', '$type_hw')"); //ATENCION: AQUI IRA LA CONSULTA DE INSERCION DE EVENTO EN MYSQL if(isset($_POST["notify"])) { $email = get_value('usrTable', 'usrEmail', 'usrID', $profileID); $body = " <html> <head> <title> OrgBoat Recurrent Task </title> <style> p {font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace; color:#4F4F4F;} h3 { font-size: 16px; line-height: 1.5em; color: #2D465F; font-family: Courier New; font-style: normal; font-weight: bold; } h5 { color:#000000; } h6 { color:#000000; } </style> </head> <body> <h3>OrgBoat</h3> <p>You have been assigned a new task:</p></br> <p> - $task.</p></br> <h5>Visit:http://www.orgboat.com to see it.</br> Do Not Reply to this e-mail address.</h5> </body> </html>"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n". 'From: OrgBoat@non-reply.com' . "\r\n" . 'Reply-To: orgboat@non-reply.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($email, "New Task", $body , $headers); } //if this homework is public if($type_hw == 'Public') { if($assignator == -1) { $assignatorName = "Admin"; } else { $assignatorName = get_value('usrTable', 'usrUserName', 'usrID', $assignator); } /* //agregar esta accion a newsTable $creatorID = $_SESSION["usrID"]; $divID = get_value('usrTable', 'divID', 'usrID', $usrID); $usrUserName = get_value('usrTable', 'usrUserName', 'usrID', $usrID); mysql_query("insert into newsTable(title, description, newdate, divID, creatorID) values('Added homework', 'The homework $hmwrk was added to the user $usrUserName', NOW(), '$divID', '$creatorID') "); */ } if($result) header("location: ../../web/admin.php?msg=Recurring task added !&tabpage=1"); else header("location: ../../web/admin.php?error=Sorry something went wrong!&tabpage=1"); } else { header("location: ../../web/admin.php?error=No POST data on add_rescttsk.php&tabpage=1"); } ?> </body> </html>
suiGn/orgboat
cod/php/add_rectsk.php
PHP
bsd-3-clause
4,190
// sagebot.hpp - SageBot class definition // sage - A TeamPlanets bot written for MachineZone job application // // Copyright (c) 2015 Vadim Litvinov <vadim_litvinov@fastmail.com> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the author 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 AUTHOR 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 AUTHOR 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. #ifndef _TEAMPLANETS_SAGE_SAGE_HPP_ #define _TEAMPLANETS_SAGE_SAGE_HPP_ #include <vector> #include "bot.hpp" #include "utils.hpp" namespace sage { class SageBot: public Bot { private: typedef std::vector<team_planets::planet_id> neighbors_list; typedef std::vector<neighbors_list> neighborhoods_list; public: DISABLE_COPY(SageBot) SageBot(): num_ships_per_reinforcement_(10), planets_mean_distance_(0), neighborhood_radius_multiplier_(1), neighborhood_radius_(0) {} virtual ~SageBot() {} protected: virtual void init_(); virtual void perform_turn_(); neighbors_list& neighbors_(team_planets::planet_id planet) { return neighborhoods_[planet - 1]; } const neighbors_list& neighbors_(team_planets::planet_id planet) const { return neighborhoods_[planet - 1]; } bool is_frontline_(team_planets::planet_id id) const; unsigned int num_ships_to_take_a_planet_(team_planets::planet_id src, team_planets::planet_id dst) const; void take_attack_decisions_(); void process_backline_planet_(team_planets::planet_id id); private: unsigned int compute_planets_mean_distance_() const; void compute_planets_neighborhoods_(); // User defined bot parameters const unsigned int num_ships_per_reinforcement_; // Precomputed map parameters unsigned int planets_mean_distance_; unsigned int neighborhood_radius_multiplier_; unsigned int neighborhood_radius_; // Precomputed planets neighborhoods neighborhoods_list neighborhoods_; // Per turn data structures std::vector<team_planets::planet_id> frontline_planets_; std::vector<team_planets::planet_id> backline_planets_; }; } #endif
merlin86/TeamPlanets
bots/sage0/sagebot.hpp
C++
bsd-3-clause
3,431
using System; using System.Configuration; using System.Diagnostics; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using org.ncore.Ioc; namespace _unittests.org.ncore.Ioc { /// <summary> /// Summary description for NewTests /// </summary> [TestClass] public class NewTests { public NewTests() { // // TODO: Add constructor logic here // } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion [TestMethod] public void Instance_dynamic_works_creates_new() { // ARRANGE Locator.Registry.Clear(); Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } ); // ACT dynamic myClass = New.Instance( "MyClass" ); string greeting = myClass.Greet( "Uni" ); // ASSERT Assert.AreEqual( "Hello Uni from MyClassA", greeting ); Assert.IsNull( Locator.Registry[ "MyClass" ].Instance ); } [TestMethod] public void Instance_dynamic_works_creates_new_with_anonymous_injector_registry() { // ARRANGE Locator.Registry.Clear(); Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } ); // ACT dynamic myClass = New.Instance( "MyClass", new { FieldA = "Inject this value", ParamB = "Inject this too" } ); string greeting = myClass.Greet( "Uni" ); // ASSERT Assert.AreEqual( "Hello Uni from MyClassA", greeting ); Assert.IsNull( Locator.Registry[ "MyClass" ].Instance ); } [TestMethod] public void Instance_dynamic_works_creates_new_with_typed_injector_registry() { // ARRANGE Locator.Registry.Clear(); Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } ); // ACT dynamic myClass = New.Instance( "MyClass", new InjectorRegistry{ { "FieldA", "Inject this value" }, { "PropertyB", "Inject this too" } } ); string greeting = myClass.Greet( "Uni" ); // ASSERT Assert.AreEqual( "Hello Uni from MyClassA", greeting ); Assert.IsNull( Locator.Registry[ "MyClass" ].Instance ); } [TestMethod] public void Instance_dynamic_works_creates_new_with_constructor_params() { // ARRANGE Locator.Registry.Clear(); Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } ); // ACT dynamic myClass = New.Instance( "MyClass", constructorParams: new object[] { "My ParamA value", "My ParamB value" } ); string greeting = myClass.Greet( "Uni" ); // ASSERT Assert.AreEqual( "Hello Uni from MyClassA", greeting ); Assert.IsNull( Locator.Registry[ "MyClass" ].Instance ); } [TestMethod] public void Instance_typed_from_type_works_creates_new() { // ARRANGE Locator.Registry.Clear(); Locator.Add( new LocatorType( typeof( IMyClass ), typeof( MyClassA ) ) { AllowSave = false } ); // ACT IMyClass myClass = New.Instance<IMyClass>(); string greeting = myClass.Greet( "Uni" ); // ASSERT Assert.AreEqual( "Hello Uni from MyClassA", greeting ); Assert.IsNull( Locator.Registry[ typeof( IMyClass ).FullName ].Instance ); } [TestMethod] public void Instance_typed_from_string_works_creates_new() { // ARRANGE Locator.Registry.Clear(); Locator.Add( new LocatorType( "MyClass", typeof( MyClassA ) ) { AllowSave = false } ); // ACT IMyClass myClass = New.Instance<IMyClass>("MyClass"); string greeting = myClass.Greet( "Uni" ); // ASSERT Assert.AreEqual( "Hello Uni from MyClassA", greeting ); Assert.IsNull( Locator.Registry[ "MyClass" ].Instance ); } public interface IMyClass { string Greet( string name ); } public class MyClassA : IMyClass { public string Greeter = "MyClassA"; public string FieldA; public string PropertyB {get;set;} public string Greet( string name ) { return "Hello " + name + " from " + Greeter; } public MyClassA() { } public MyClassA( string paramA, string paramB ) { FieldA = paramA; PropertyB = paramB; } } } }
jakefoster/ncore-ioc
src/_unittests.org.ncore.Ioc/NewTests.cs
C#
bsd-3-clause
6,200
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stack> #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/pickle.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_error_job.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/appcache/appcache_response.h" #include "webkit/appcache/appcache_url_request_job.h" #include "webkit/appcache/mock_appcache_service.h" using net::IOBuffer; using net::WrappedIOBuffer; namespace appcache { static const char kHttpBasicHeaders[] = "HTTP/1.0 200 OK\0Content-Length: 5\0\0"; static const char kHttpBasicBody[] = "Hello"; static const int kNumBlocks = 4; static const int kBlockSize = 1024; class AppCacheURLRequestJobTest : public testing::Test { public: // Test Harness ------------------------------------------------------------- // TODO(michaeln): share this test harness with AppCacheResponseTest class MockStorageDelegate : public AppCacheStorage::Delegate { public: explicit MockStorageDelegate(AppCacheURLRequestJobTest* test) : loaded_info_id_(0), test_(test) { } virtual void OnResponseInfoLoaded(AppCacheResponseInfo* info, int64 response_id) OVERRIDE { loaded_info_ = info; loaded_info_id_ = response_id; test_->ScheduleNextTask(); } scoped_refptr<AppCacheResponseInfo> loaded_info_; int64 loaded_info_id_; AppCacheURLRequestJobTest* test_; }; class MockURLRequestDelegate : public net::URLRequest::Delegate { public: explicit MockURLRequestDelegate(AppCacheURLRequestJobTest* test) : test_(test), received_data_(new net::IOBuffer(kNumBlocks * kBlockSize)), did_receive_headers_(false), amount_received_(0), kill_after_amount_received_(0), kill_with_io_pending_(false) { } virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE { amount_received_ = 0; did_receive_headers_ = false; if (request->status().is_success()) { EXPECT_TRUE(request->response_headers()); did_receive_headers_ = true; received_info_ = request->response_info(); ReadSome(request); } else { RequestComplete(); } } virtual void OnReadCompleted(net::URLRequest* request, int bytes_read) OVERRIDE { if (bytes_read > 0) { amount_received_ += bytes_read; if (kill_after_amount_received_ && !kill_with_io_pending_) { if (amount_received_ >= kill_after_amount_received_) { request->Cancel(); return; } } ReadSome(request); if (kill_after_amount_received_ && kill_with_io_pending_) { if (amount_received_ >= kill_after_amount_received_) { request->Cancel(); return; } } } else { RequestComplete(); } } void ReadSome(net::URLRequest* request) { DCHECK(amount_received_ + kBlockSize <= kNumBlocks * kBlockSize); scoped_refptr<IOBuffer> wrapped_buffer( new net::WrappedIOBuffer(received_data_->data() + amount_received_)); int bytes_read = 0; EXPECT_FALSE(request->Read(wrapped_buffer, kBlockSize, &bytes_read)); EXPECT_EQ(0, bytes_read); } void RequestComplete() { test_->ScheduleNextTask(); } AppCacheURLRequestJobTest* test_; net::HttpResponseInfo received_info_; scoped_refptr<net::IOBuffer> received_data_; bool did_receive_headers_; int amount_received_; int kill_after_amount_received_; bool kill_with_io_pending_; }; static net::URLRequestJob* MockHttpJobFactory( net::URLRequest* request, net::NetworkDelegate* network_delegate, const std::string& scheme) { if (mock_factory_job_) { net::URLRequestJob* temp = mock_factory_job_; mock_factory_job_ = NULL; return temp; } else { return new net::URLRequestErrorJob(request, network_delegate, net::ERR_INTERNET_DISCONNECTED); } } // Helper callback to run a test on our io_thread. The io_thread is spun up // once and reused for all tests. template <class Method> void MethodWrapper(Method method) { SetUpTest(); (this->*method)(); } static void SetUpTestCase() { io_thread_.reset(new base::Thread("AppCacheURLRequestJobTest Thread")); base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); io_thread_->StartWithOptions(options); } static void TearDownTestCase() { io_thread_.reset(NULL); } AppCacheURLRequestJobTest() {} template <class Method> void RunTestOnIOThread(Method method) { test_finished_event_ .reset(new base::WaitableEvent(false, false)); io_thread_->message_loop()->PostTask( FROM_HERE, base::Bind(&AppCacheURLRequestJobTest::MethodWrapper<Method>, base::Unretained(this), method)); test_finished_event_->Wait(); } void SetUpTest() { DCHECK(base::MessageLoop::current() == io_thread_->message_loop()); DCHECK(task_stack_.empty()); orig_http_factory_ = net::URLRequest::Deprecated::RegisterProtocolFactory( "http", MockHttpJobFactory); url_request_delegate_.reset(new MockURLRequestDelegate(this)); storage_delegate_.reset(new MockStorageDelegate(this)); service_.reset(new MockAppCacheService()); expected_read_result_ = 0; expected_write_result_ = 0; written_response_id_ = 0; reader_deletion_count_down_ = 0; writer_deletion_count_down_ = 0; } void TearDownTest() { DCHECK(base::MessageLoop::current() == io_thread_->message_loop()); net::URLRequest::Deprecated::RegisterProtocolFactory("http", orig_http_factory_); orig_http_factory_ = NULL; request_.reset(); url_request_delegate_.reset(); DCHECK(!mock_factory_job_); while (!task_stack_.empty()) task_stack_.pop(); reader_.reset(); read_buffer_ = NULL; read_info_buffer_ = NULL; writer_.reset(); write_buffer_ = NULL; write_info_buffer_ = NULL; storage_delegate_.reset(); service_.reset(); } void TestFinished() { // We unwind the stack prior to finishing up to let stack // based objects get deleted. DCHECK(base::MessageLoop::current() == io_thread_->message_loop()); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&AppCacheURLRequestJobTest::TestFinishedUnwound, base::Unretained(this))); } void TestFinishedUnwound() { TearDownTest(); test_finished_event_->Signal(); } void PushNextTask(const base::Closure& task) { task_stack_.push(std::pair<base::Closure, bool>(task, false)); } void PushNextTaskAsImmediate(const base::Closure& task) { task_stack_.push(std::pair<base::Closure, bool>(task, true)); } void ScheduleNextTask() { DCHECK(base::MessageLoop::current() == io_thread_->message_loop()); if (task_stack_.empty()) { TestFinished(); return; } base::Closure task =task_stack_.top().first; bool immediate = task_stack_.top().second; task_stack_.pop(); if (immediate) task.Run(); else base::MessageLoop::current()->PostTask(FROM_HERE, task); } // Wrappers to call AppCacheResponseReader/Writer Read and Write methods void WriteBasicResponse() { scoped_refptr<IOBuffer> body(new WrappedIOBuffer(kHttpBasicBody)); std::string raw_headers(kHttpBasicHeaders, arraysize(kHttpBasicHeaders)); WriteResponse(MakeHttpResponseInfo(raw_headers), body, strlen(kHttpBasicBody)); } void WriteResponse(net::HttpResponseInfo* head, IOBuffer* body, int body_len) { DCHECK(body); scoped_refptr<IOBuffer> body_ref(body); PushNextTask(base::Bind(&AppCacheURLRequestJobTest::WriteResponseBody, base::Unretained(this), body_ref, body_len)); WriteResponseHead(head); } void WriteResponseHead(net::HttpResponseInfo* head) { EXPECT_FALSE(writer_->IsWritePending()); expected_write_result_ = GetHttpResponseInfoSize(head); write_info_buffer_ = new HttpResponseInfoIOBuffer(head); writer_->WriteInfo( write_info_buffer_, base::Bind(&AppCacheURLRequestJobTest::OnWriteInfoComplete, base::Unretained(this))); } void WriteResponseBody(scoped_refptr<IOBuffer> io_buffer, int buf_len) { EXPECT_FALSE(writer_->IsWritePending()); write_buffer_ = io_buffer; expected_write_result_ = buf_len; writer_->WriteData( write_buffer_, buf_len, base::Bind(&AppCacheURLRequestJobTest::OnWriteComplete, base::Unretained(this))); } void ReadResponseBody(scoped_refptr<IOBuffer> io_buffer, int buf_len) { EXPECT_FALSE(reader_->IsReadPending()); read_buffer_ = io_buffer; expected_read_result_ = buf_len; reader_->ReadData( read_buffer_, buf_len, base::Bind(&AppCacheURLRequestJobTest::OnReadComplete, base::Unretained(this))); } // AppCacheResponseReader / Writer completion callbacks void OnWriteInfoComplete(int result) { EXPECT_FALSE(writer_->IsWritePending()); EXPECT_EQ(expected_write_result_, result); ScheduleNextTask(); } void OnWriteComplete(int result) { EXPECT_FALSE(writer_->IsWritePending()); EXPECT_EQ(expected_write_result_, result); ScheduleNextTask(); } void OnReadInfoComplete(int result) { EXPECT_FALSE(reader_->IsReadPending()); EXPECT_EQ(expected_read_result_, result); ScheduleNextTask(); } void OnReadComplete(int result) { EXPECT_FALSE(reader_->IsReadPending()); EXPECT_EQ(expected_read_result_, result); ScheduleNextTask(); } // Helpers to work with HttpResponseInfo objects net::HttpResponseInfo* MakeHttpResponseInfo(const std::string& raw_headers) { net::HttpResponseInfo* info = new net::HttpResponseInfo; info->request_time = base::Time::Now(); info->response_time = base::Time::Now(); info->was_cached = false; info->headers = new net::HttpResponseHeaders(raw_headers); return info; } int GetHttpResponseInfoSize(const net::HttpResponseInfo* info) { Pickle pickle; return PickleHttpResonseInfo(&pickle, info); } bool CompareHttpResponseInfos(const net::HttpResponseInfo* info1, const net::HttpResponseInfo* info2) { Pickle pickle1; Pickle pickle2; PickleHttpResonseInfo(&pickle1, info1); PickleHttpResonseInfo(&pickle2, info2); return (pickle1.size() == pickle2.size()) && (0 == memcmp(pickle1.data(), pickle2.data(), pickle1.size())); } int PickleHttpResonseInfo(Pickle* pickle, const net::HttpResponseInfo* info) { const bool kSkipTransientHeaders = true; const bool kTruncated = false; info->Persist(pickle, kSkipTransientHeaders, kTruncated); return pickle->size(); } // Helpers to fill and verify blocks of memory with a value void FillData(char value, char* data, int data_len) { memset(data, value, data_len); } bool CheckData(char value, const char* data, int data_len) { for (int i = 0; i < data_len; ++i, ++data) { if (*data != value) return false; } return true; } // Individual Tests --------------------------------------------------------- // Some of the individual tests involve multiple async steps. Each test // is delineated with a section header. // Basic ------------------------------------------------------------------- void Basic() { AppCacheStorage* storage = service_->storage(); net::URLRequest request(GURL("http://blah/"), NULL, &empty_context_); scoped_refptr<AppCacheURLRequestJob> job; // Create an instance and see that it looks as expected. job = new AppCacheURLRequestJob( &request, NULL, storage); EXPECT_TRUE(job->is_waiting()); EXPECT_FALSE(job->is_delivering_appcache_response()); EXPECT_FALSE(job->is_delivering_network_response()); EXPECT_FALSE(job->is_delivering_error_response()); EXPECT_FALSE(job->has_been_started()); EXPECT_FALSE(job->has_been_killed()); EXPECT_EQ(GURL(), job->manifest_url()); EXPECT_EQ(kNoCacheId, job->cache_id()); EXPECT_FALSE(job->entry().has_response_id()); TestFinished(); } // DeliveryOrders ----------------------------------------------------- void DeliveryOrders() { AppCacheStorage* storage = service_->storage(); net::URLRequest request(GURL("http://blah/"), NULL, &empty_context_); scoped_refptr<AppCacheURLRequestJob> job; // Create an instance, give it a delivery order and see that // it looks as expected. job = new AppCacheURLRequestJob(&request, NULL, storage); job->DeliverErrorResponse(); EXPECT_TRUE(job->is_delivering_error_response()); EXPECT_FALSE(job->has_been_started()); job = new AppCacheURLRequestJob(&request, NULL, storage); job->DeliverNetworkResponse(); EXPECT_TRUE(job->is_delivering_network_response()); EXPECT_FALSE(job->has_been_started()); job = new AppCacheURLRequestJob(&request, NULL, storage); const GURL kManifestUrl("http://blah/"); const int64 kCacheId(1); const int64 kGroupId(1); const AppCacheEntry kEntry(AppCacheEntry::EXPLICIT, 1); job->DeliverAppCachedResponse(kManifestUrl, kCacheId, kGroupId, kEntry, false); EXPECT_FALSE(job->is_waiting()); EXPECT_TRUE(job->is_delivering_appcache_response()); EXPECT_FALSE(job->has_been_started()); EXPECT_EQ(kManifestUrl, job->manifest_url()); EXPECT_EQ(kCacheId, job->cache_id()); EXPECT_EQ(kGroupId, job->group_id()); EXPECT_EQ(kEntry.types(), job->entry().types()); EXPECT_EQ(kEntry.response_id(), job->entry().response_id()); TestFinished(); } // DeliverNetworkResponse -------------------------------------------------- void DeliverNetworkResponse() { // This test has async steps. PushNextTask( base::Bind(&AppCacheURLRequestJobTest::VerifyDeliverNetworkResponse, base::Unretained(this))); AppCacheStorage* storage = service_->storage(); request_.reset(empty_context_.CreateRequest( GURL("http://blah/"), url_request_delegate_.get())); // Setup to create an AppCacheURLRequestJob with orders to deliver // a network response. mock_factory_job_ = new AppCacheURLRequestJob( request_.get(), NULL, storage); mock_factory_job_->DeliverNetworkResponse(); EXPECT_TRUE(mock_factory_job_->is_delivering_network_response()); EXPECT_FALSE(mock_factory_job_->has_been_started()); // Start the request. request_->Start(); // The job should have been picked up. EXPECT_FALSE(mock_factory_job_); // Completion is async. } void VerifyDeliverNetworkResponse() { EXPECT_EQ(request_->status().error(), net::ERR_INTERNET_DISCONNECTED); TestFinished(); } // DeliverErrorResponse -------------------------------------------------- void DeliverErrorResponse() { // This test has async steps. PushNextTask( base::Bind(&AppCacheURLRequestJobTest::VerifyDeliverErrorResponse, base::Unretained(this))); AppCacheStorage* storage = service_->storage(); request_.reset(empty_context_.CreateRequest(GURL( "http://blah/"), url_request_delegate_.get())); // Setup to create an AppCacheURLRequestJob with orders to deliver // a network response. mock_factory_job_ = new AppCacheURLRequestJob( request_.get(), NULL, storage); mock_factory_job_->DeliverErrorResponse(); EXPECT_TRUE(mock_factory_job_->is_delivering_error_response()); EXPECT_FALSE(mock_factory_job_->has_been_started()); // Start the request. request_->Start(); // The job should have been picked up. EXPECT_FALSE(mock_factory_job_); // Completion is async. } void VerifyDeliverErrorResponse() { EXPECT_EQ(request_->status().error(), net::ERR_FAILED); TestFinished(); } // DeliverSmallAppCachedResponse -------------------------------------- // "Small" being small enough to read completely in a single // request->Read call. void DeliverSmallAppCachedResponse() { // This test has several async steps. // 1. Write a small response to response storage. // 2. Use net::URLRequest to retrieve it. // 3. Verify we received what we expected to receive. PushNextTask(base::Bind( &AppCacheURLRequestJobTest::VerifyDeliverSmallAppCachedResponse, base::Unretained(this))); PushNextTask( base::Bind(&AppCacheURLRequestJobTest::RequestAppCachedResource, base::Unretained(this), false)); writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0)); written_response_id_ = writer_->response_id(); WriteBasicResponse(); // Continues async } void RequestAppCachedResource(bool start_after_delivery_orders) { AppCacheStorage* storage = service_->storage(); request_.reset(empty_context_.CreateRequest( GURL("http://blah/"), url_request_delegate_.get())); // Setup to create an AppCacheURLRequestJob with orders to deliver // a network response. scoped_refptr<AppCacheURLRequestJob> job(new AppCacheURLRequestJob( request_.get(), NULL, storage)); if (start_after_delivery_orders) { job->DeliverAppCachedResponse( GURL(), 0, 111, AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_), false); EXPECT_TRUE(job->is_delivering_appcache_response()); } // Start the request. EXPECT_FALSE(job->has_been_started()); mock_factory_job_ = job; request_->Start(); EXPECT_FALSE(mock_factory_job_); EXPECT_TRUE(job->has_been_started()); if (!start_after_delivery_orders) { job->DeliverAppCachedResponse( GURL(), 0, 111, AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_), false); EXPECT_TRUE(job->is_delivering_appcache_response()); } // Completion is async. } void VerifyDeliverSmallAppCachedResponse() { EXPECT_TRUE(request_->status().is_success()); EXPECT_TRUE(CompareHttpResponseInfos( write_info_buffer_->http_info.get(), &url_request_delegate_->received_info_)); EXPECT_EQ(5, url_request_delegate_->amount_received_); EXPECT_EQ(0, memcmp(kHttpBasicBody, url_request_delegate_->received_data_->data(), strlen(kHttpBasicBody))); TestFinished(); } // DeliverLargeAppCachedResponse -------------------------------------- // "Large" enough to require multiple calls to request->Read to complete. void DeliverLargeAppCachedResponse() { // This test has several async steps. // 1. Write a large response to response storage. // 2. Use net::URLRequest to retrieve it. // 3. Verify we received what we expected to receive. PushNextTask(base::Bind( &AppCacheURLRequestJobTest::VerifyDeliverLargeAppCachedResponse, base::Unretained(this))); PushNextTask(base::Bind( &AppCacheURLRequestJobTest::RequestAppCachedResource, base::Unretained(this), true)); writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0)); written_response_id_ = writer_->response_id(); WriteLargeResponse(); // Continues async } void WriteLargeResponse() { // 3, 1k blocks static const char kHttpHeaders[] = "HTTP/1.0 200 OK\0Content-Length: 3072\0\0"; scoped_refptr<IOBuffer> body(new IOBuffer(kBlockSize * 3)); char* p = body->data(); for (int i = 0; i < 3; ++i, p += kBlockSize) FillData(i + 1, p, kBlockSize); std::string raw_headers(kHttpHeaders, arraysize(kHttpHeaders)); WriteResponse(MakeHttpResponseInfo(raw_headers), body, kBlockSize * 3); } void VerifyDeliverLargeAppCachedResponse() { EXPECT_TRUE(request_->status().is_success()); EXPECT_TRUE(CompareHttpResponseInfos( write_info_buffer_->http_info.get(), &url_request_delegate_->received_info_)); EXPECT_EQ(3072, url_request_delegate_->amount_received_); char* p = url_request_delegate_->received_data_->data(); for (int i = 0; i < 3; ++i, p += kBlockSize) EXPECT_TRUE(CheckData(i + 1, p, kBlockSize)); TestFinished(); } // DeliverPartialResponse -------------------------------------- void DeliverPartialResponse() { // This test has several async steps. // 1. Write a small response to response storage. // 2. Use net::URLRequest to retrieve it a subset using a range request // 3. Verify we received what we expected to receive. PushNextTask(base::Bind( &AppCacheURLRequestJobTest::VerifyDeliverPartialResponse, base::Unretained(this))); PushNextTask(base::Bind( &AppCacheURLRequestJobTest::MakeRangeRequest, base::Unretained(this))); writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0)); written_response_id_ = writer_->response_id(); WriteBasicResponse(); // Continues async } void MakeRangeRequest() { AppCacheStorage* storage = service_->storage(); request_.reset(empty_context_.CreateRequest( GURL("http://blah/"), url_request_delegate_.get())); // Request a range, the 3 middle chars out of 'Hello' net::HttpRequestHeaders extra_headers; extra_headers.SetHeader("Range", "bytes= 1-3"); request_->SetExtraRequestHeaders(extra_headers); // Create job with orders to deliver an appcached entry. scoped_refptr<AppCacheURLRequestJob> job(new AppCacheURLRequestJob( request_.get(), NULL, storage)); job->DeliverAppCachedResponse( GURL(), 0, 111, AppCacheEntry(AppCacheEntry::EXPLICIT, written_response_id_), false); EXPECT_TRUE(job->is_delivering_appcache_response()); // Start the request. EXPECT_FALSE(job->has_been_started()); mock_factory_job_ = job; request_->Start(); EXPECT_FALSE(mock_factory_job_); EXPECT_TRUE(job->has_been_started()); // Completion is async. } void VerifyDeliverPartialResponse() { EXPECT_TRUE(request_->status().is_success()); EXPECT_EQ(3, url_request_delegate_->amount_received_); EXPECT_EQ(0, memcmp(kHttpBasicBody + 1, url_request_delegate_->received_data_->data(), 3)); net::HttpResponseHeaders* headers = url_request_delegate_->received_info_.headers.get(); EXPECT_EQ(206, headers->response_code()); EXPECT_EQ(3, headers->GetContentLength()); int64 range_start, range_end, object_size; EXPECT_TRUE( headers->GetContentRange(&range_start, &range_end, &object_size)); EXPECT_EQ(1, range_start); EXPECT_EQ(3, range_end); EXPECT_EQ(5, object_size); TestFinished(); } // CancelRequest -------------------------------------- void CancelRequest() { // This test has several async steps. // 1. Write a large response to response storage. // 2. Use net::URLRequest to retrieve it. // 3. Cancel the request after data starts coming in. PushNextTask(base::Bind( &AppCacheURLRequestJobTest::VerifyCancel, base::Unretained(this))); PushNextTask(base::Bind( &AppCacheURLRequestJobTest::RequestAppCachedResource, base::Unretained(this), true)); writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0)); written_response_id_ = writer_->response_id(); WriteLargeResponse(); url_request_delegate_->kill_after_amount_received_ = kBlockSize; url_request_delegate_->kill_with_io_pending_ = false; // Continues async } void VerifyCancel() { EXPECT_EQ(net::URLRequestStatus::CANCELED, request_->status().status()); TestFinished(); } // CancelRequestWithIOPending -------------------------------------- void CancelRequestWithIOPending() { // This test has several async steps. // 1. Write a large response to response storage. // 2. Use net::URLRequest to retrieve it. // 3. Cancel the request after data starts coming in. PushNextTask(base::Bind( &AppCacheURLRequestJobTest::VerifyCancel, base::Unretained(this))); PushNextTask(base::Bind( &AppCacheURLRequestJobTest::RequestAppCachedResource, base::Unretained(this), true)); writer_.reset(service_->storage()->CreateResponseWriter(GURL(), 0)); written_response_id_ = writer_->response_id(); WriteLargeResponse(); url_request_delegate_->kill_after_amount_received_ = kBlockSize; url_request_delegate_->kill_with_io_pending_ = true; // Continues async } // Data members -------------------------------------------------------- scoped_ptr<base::WaitableEvent> test_finished_event_; scoped_ptr<MockStorageDelegate> storage_delegate_; scoped_ptr<MockAppCacheService> service_; std::stack<std::pair<base::Closure, bool> > task_stack_; scoped_ptr<AppCacheResponseReader> reader_; scoped_refptr<HttpResponseInfoIOBuffer> read_info_buffer_; scoped_refptr<IOBuffer> read_buffer_; int expected_read_result_; int reader_deletion_count_down_; int64 written_response_id_; scoped_ptr<AppCacheResponseWriter> writer_; scoped_refptr<HttpResponseInfoIOBuffer> write_info_buffer_; scoped_refptr<IOBuffer> write_buffer_; int expected_write_result_; int writer_deletion_count_down_; net::URLRequest::ProtocolFactory* orig_http_factory_; net::URLRequestContext empty_context_; scoped_ptr<net::URLRequest> request_; scoped_ptr<MockURLRequestDelegate> url_request_delegate_; static scoped_ptr<base::Thread> io_thread_; static AppCacheURLRequestJob* mock_factory_job_; }; // static scoped_ptr<base::Thread> AppCacheURLRequestJobTest::io_thread_; AppCacheURLRequestJob* AppCacheURLRequestJobTest::mock_factory_job_ = NULL; TEST_F(AppCacheURLRequestJobTest, Basic) { RunTestOnIOThread(&AppCacheURLRequestJobTest::Basic); } TEST_F(AppCacheURLRequestJobTest, DeliveryOrders) { RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliveryOrders); } TEST_F(AppCacheURLRequestJobTest, DeliverNetworkResponse) { RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverNetworkResponse); } TEST_F(AppCacheURLRequestJobTest, DeliverErrorResponse) { RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverErrorResponse); } TEST_F(AppCacheURLRequestJobTest, DeliverSmallAppCachedResponse) { RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverSmallAppCachedResponse); } TEST_F(AppCacheURLRequestJobTest, DeliverLargeAppCachedResponse) { RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverLargeAppCachedResponse); } TEST_F(AppCacheURLRequestJobTest, DeliverPartialResponse) { RunTestOnIOThread(&AppCacheURLRequestJobTest::DeliverPartialResponse); } TEST_F(AppCacheURLRequestJobTest, CancelRequest) { RunTestOnIOThread(&AppCacheURLRequestJobTest::CancelRequest); } TEST_F(AppCacheURLRequestJobTest, CancelRequestWithIOPending) { RunTestOnIOThread(&AppCacheURLRequestJobTest::CancelRequestWithIOPending); } } // namespace appcache
loopCM/chromium
webkit/appcache/appcache_url_request_job_unittest.cc
C++
bsd-3-clause
27,756
var a00494 = [ [ "calculate_nnz", "a00494.html#aca63ccfbd14352eade58fd2a2ec6b5e4", null ], [ "nnz_internal", "a00494.html#a710993cf2d56652448517817943ad10f", null ], [ "optimizeWildfire", "a00494.html#adc947c65dcf861c33a24399614c0791a", null ], [ "optimizeWildfire", "a00494.html#a33509e7a55b46fe677e682d01f8fbd87", null ], [ "optimizeWildfireNode", "a00494.html#aadd9b9f920ceaa21f31cb0695fc3c12d", null ], [ "optimizeWildfireNonRecursive", "a00494.html#ad11ffb44abea89e42c6de7a9f2f97221", null ] ];
devbharat/gtsam
doc/html/a00494.js
JavaScript
bsd-3-clause
523
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.image.BinaryImage; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.CriteriaCollection; import edu.wpi.first.wpilibj.image.NIVision.MeasurementType; import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; /** * * @author Rajath, Michael */ public class ImageProcessing { ParticleAnalysisReport particles[] = null; CriteriaCollection criteriaCollection = new CriteriaCollection(); ParticleAnalysisReport bottomTarget, topTarget, middleTargetLeft, middleTargetRight; Messager msg = new Messager(); static final double FOV = 34.42900061182182;//camera field of view in degrees static final double camResWidth = 640; static final double camResHeight = 480; static final double targetHeight = 18.125; static final double cameraTilt = 13.4; static final double cameraHeight = 61; static final double maxDisparity = .5; static final double lambda = camResHeight / FOV; static final double topTargetHeight = 109;//inches to middle static final double middleTargetHeight = 72;//inches to middle static final double bottomTargetHeight = 39;//inches to middle static final double T_topTargetHeight = 118;//inches to top of tape static final double T_middleTargetHeight = 81;//inches to top of tape static final double T_bottomTargetHeight = 48;//inches to top of tape static final double B_topTargetHeight = 100;//inches to bottom of tape static final double B_middleTargetHeight = 63;//inches to bottom of tape static final double B_bottomTargetHeight = 30;//inches to bottom of tape public ImageProcessing() { criteriaCollection.addCriteria( MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, 30, 400, false); criteriaCollection.addCriteria( MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, 40, 400, false); } public static double getHorizontalAngle(ParticleAnalysisReport particle) { double p = (camResWidth / 2) - particle.center_mass_x; double angle = p / lambda; return angle; } public static ParticleAnalysisReport getTopMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport greatest = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_y > greatest.center_mass_y) { greatest = particle; } } return greatest; } public static ParticleAnalysisReport getBottomMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport lowest = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_y < lowest.center_mass_y) { lowest = particle; } } return lowest; } public static ParticleAnalysisReport getRightMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport rightistTarget = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_x > rightistTarget.center_mass_x) { rightistTarget = particle; } } return rightistTarget; } public static ParticleAnalysisReport getLeftMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport leftistTarget = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_x < leftistTarget.center_mass_x) { leftistTarget = particle; } } return leftistTarget; } /** * Fills the array (particles) with all found particle analysis reports * * @param camera the camera to get the particle analysis report from * @throws Exception */ public void getTheParticles(AxisCamera camera) throws Exception { int erosionCount = 2; // true means use connectivity 8, false means connectivity 4 boolean useConnectivity8 = false; ColorImage colorImage; BinaryImage binaryImage; BinaryImage cleanImage; BinaryImage convexHullImage; BinaryImage filteredImage; colorImage = camera.getImage(); //seperate the light and dark image binaryImage = colorImage.thresholdRGB(0, 42, 71, 255, 0, 255); cleanImage = binaryImage.removeSmallObjects( useConnectivity8, erosionCount); //fill the rectangles that were created convexHullImage = cleanImage.convexHull(useConnectivity8); filteredImage = convexHullImage.particleFilter(criteriaCollection); particles = filteredImage.getOrderedParticleAnalysisReports(); colorImage.free(); binaryImage.free(); cleanImage.free(); convexHullImage.free(); filteredImage.free(); } public double getCameraTilt() { double level = particles[0].center_mass_y - particles[0].boundingRectHeight / 2; level *= FOV; level /= camResHeight; return level - FOV / 2; } /** * Get the horizontal distance to the target * * @param part the particle analysis report to get the report from * @param height the height of the target to get the report from * @return distance to target, in inches */ public double getDistance(ParticleAnalysisReport part, double height) { double ph = part.boundingRectHeight; double delta = height - cameraHeight; double R = targetHeight / MathX.tan(ph / lambda); double D = 0; for (int i = 0; i < 4; i++) { double theta = MathX.asin(delta / R); double new_ph = ph / MathX.cos(theta); R = targetHeight / MathX.tan(new_ph / lambda); D = MathX.sqrt(R * R - delta * delta); } return D; } private double max(double d1, double d2) { if (d1 > d2) { return d1; } return d2; } private double min(double d1, double d2) { if (d1 < d2) { return d1; } return d2; } public double isTopTarget(ParticleAnalysisReport part) { double D1 = getDistance(part, T_topTargetHeight); double D2 = getDistance(part, B_topTargetHeight); double disparity = max(D1, D2) - min(D1, D2); System.out.println("Top1:" + D1); System.out.println("Top2:" + D2); System.out.println("----------------------"); /* * if (disparity < maxDisparity) { return true; } else { return false; } * */ return disparity; } public double isBottomTarget(ParticleAnalysisReport part) { double D1 = getDistance(part, T_bottomTargetHeight); double D2 = getDistance(part, B_bottomTargetHeight); double disparity = max(D1, D2) - min(D1, D2); System.out.println("Bottom1:" + D1); System.out.println("Bottom2:" + D2); System.out.println("----------------------"); /* * * if (disparity < maxDisparity) { return true; } else { return false; } * */ return disparity; } public boolean isMiddleTarget(ParticleAnalysisReport part) { double D1 = getDistance(part, T_middleTargetHeight); double D2 = getDistance(part, B_middleTargetHeight); double disparity = max(D1, D2) / min(D1, D2); if (disparity < maxDisparity) { return true; } else { return false; } } }
erhs-53-hackers/Robo2012
src/edu/wpi/first/wpilibj/templates/ImageProcessing.java
Java
bsd-3-clause
7,992
<?php /** * Service repository class file * * @package ShnfuCarver * @subpackage Kernel\Service * @copyright 2012 Shnfu * @author Zhao Xianghu <xianghuzhao@gmail.com> * @license http://carver.shnfu.com/license.txt New BSD License */ namespace ShnfuCarver\Kernel\Service; /** * Service repository class * * @package ShnfuCarver * @subpackage Kernel\Service * @copyright 2012 Shnfu * @author Zhao Xianghu <xianghuzhao@gmail.com> * @license http://carver.shnfu.com/license.txt New BSD License */ class ServiceRepository { /** * Service repository * * @var array */ protected $_repository = array(); /** * Register a service * * @param \ShnfuCarver\Kernel\Service\Service $service * @return \ShnfuCarver\Kernel\Service\Service */ public function register($service) { if (!$service instanceof ServiceInterface) { throw new \InvalidArgumentException('Not an instance of ServiceInterface!'); } $name = $service->getName(); if (!$this->exist($name)) { $this->_repository[$name] = $service; } return $this->get($name); } /** * Check whether a service exists * * @param string $name * @return bool */ public function exist($name) { return isset($this->_repository[$name]); } /** * Get a service * * @param string $name * @return object */ public function get($name) { if (!isset($this->_repository[$name])) { throw new \InvalidArgumentException("The service $name does not exist!"); } return $this->_repository[$name]->get(); } } ?>
shnfu/shnfucarver
library/ShnfuCarver/Kernel/Service/ServiceRepository.php
PHP
bsd-3-clause
1,772
// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> 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. // // ***************************************************************************** #include <mapviz_plugins/laserscan_plugin.h> // C++ standard libraries #include <cmath> #include <cstdio> #include <algorithm> #include <vector> // Boost libraries #include <boost/algorithm/string.hpp> // QT libraries #include <QColorDialog> #include <QDialog> #include <QGLWidget> // OpenGL #include <GL/glew.h> // QT Autogenerated #include "ui_topic_select.h" // ROS libraries #include <ros/master.h> #include <swri_transform_util/transform.h> #include <swri_yaml_util/yaml_util.h> #include <mapviz/select_topic_dialog.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_DECLARE_CLASS( mapviz_plugins, laserscan, mapviz_plugins::LaserScanPlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { LaserScanPlugin::LaserScanPlugin() : config_widget_(new QWidget()), topic_(""), alpha_(1.0), min_value_(0.0), max_value_(100.0), point_size_(3) { ui_.setupUi(config_widget_); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); // Initialize color selector colors ui_.min_color->setColor(Qt::white); ui_.max_color->setColor(Qt::black); // Set color transformer choices ui_.color_transformer->addItem(QString("Flat Color"), QVariant(0)); ui_.color_transformer->addItem(QString("Intensity"), QVariant(1)); ui_.color_transformer->addItem(QString("Range"), QVariant(2)); ui_.color_transformer->addItem(QString("X Axis"), QVariant(3)); ui_.color_transformer->addItem(QString("Y Axis"), QVariant(4)); ui_.color_transformer->addItem(QString("Z Axis"), QVariant(5)); QObject::connect(ui_.selecttopic, SIGNAL(clicked()), this, SLOT(SelectTopic())); QObject::connect(ui_.topic, SIGNAL(editingFinished()), this, SLOT(TopicEdited())); QObject::connect(ui_.alpha, SIGNAL(editingFinished()), this, SLOT(AlphaEdited())); QObject::connect(ui_.color_transformer, SIGNAL(currentIndexChanged(int)), this, SLOT(ColorTransformerChanged(int))); QObject::connect(ui_.max_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(UpdateColors())); QObject::connect(ui_.min_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(UpdateColors())); QObject::connect(ui_.minValue, SIGNAL(valueChanged(double)), this, SLOT(MinValueChanged(double))); QObject::connect(ui_.maxValue, SIGNAL(valueChanged(double)), this, SLOT(MaxValueChanged(double))); QObject::connect(ui_.bufferSize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int))); QObject::connect(ui_.pointSize, SIGNAL(valueChanged(int)), this, SLOT(PointSizeChanged(int))); QObject::connect(ui_.use_rainbow, SIGNAL(stateChanged(int)), this, SLOT(UseRainbowChanged(int))); QObject::connect(ui_.max_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(DrawIcon())); QObject::connect(ui_.min_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(DrawIcon())); PrintInfo("Constructed LaserScanPlugin"); } LaserScanPlugin::~LaserScanPlugin() { } void LaserScanPlugin::DrawIcon() { if (icon_) { QPixmap icon(16, 16); icon.fill(Qt::transparent); QPainter painter(&icon); painter.setRenderHint(QPainter::Antialiasing, true); QPen pen; pen.setWidth(4); pen.setCapStyle(Qt::RoundCap); pen.setColor(ui_.min_color->color()); painter.setPen(pen); painter.drawPoint(2, 13); pen.setColor(ui_.min_color->color()); painter.setPen(pen); painter.drawPoint(4, 6); pen.setColor(ui_.max_color->color()); painter.setPen(pen); painter.drawPoint(12, 9); pen.setColor(ui_.max_color->color()); painter.setPen(pen); painter.drawPoint(13, 2); icon_->SetPixmap(icon); } } QColor LaserScanPlugin::CalculateColor(const StampedPoint& point, bool has_intensity) { double val; unsigned int color_transformer = ui_.color_transformer->currentIndex(); if (color_transformer == COLOR_RANGE) { val = point.range; } else if (color_transformer == COLOR_INTENSITY && has_intensity) { val = point.intensity; } else if (color_transformer == COLOR_X) { val = point.point.x(); } else if (color_transformer == COLOR_Y) { val = point.point.y(); } else if (color_transformer == COLOR_Z) { val = point.transformed_point.z(); } else // No intensity or (color_transformer == COLOR_FLAT) { return ui_.min_color->color(); } if (max_value_ > min_value_) val = (val - min_value_) / (max_value_ - min_value_); val = std::max(0.0, std::min(val, 1.0)); if (ui_.use_rainbow->isChecked()) { // Hue Interpolation int hue = val * 255; return QColor::fromHsl(hue, 255, 127, 255); } else { const QColor min_color = ui_.min_color->color(); const QColor max_color = ui_.max_color->color(); // RGB Interpolation int red, green, blue; red = val * max_color.red() + ((1.0 - val) * min_color.red()); green = val * max_color.green() + ((1.0 - val) * min_color.green()); blue = val * max_color.blue() + ((1.0 - val) * min_color.blue()); return QColor(red, green, blue, 255); } } void LaserScanPlugin::UpdateColors() { std::deque<Scan>::iterator scan_it = scans_.begin(); for (; scan_it != scans_.end(); ++scan_it) { std::vector<StampedPoint>::iterator point_it = scan_it->points.begin(); for (; point_it != scan_it->points.end(); point_it++) { point_it->color = CalculateColor(*point_it, scan_it->has_intensity); } } } void LaserScanPlugin::SelectTopic() { ros::master::TopicInfo topic = mapviz::SelectTopicDialog::selectTopic( "sensor_msgs/LaserScan"); if (!topic.name.empty()) { ui_.topic->setText(QString::fromStdString(topic.name)); TopicEdited(); } } void LaserScanPlugin::TopicEdited() { std::string topic = ui_.topic->text().trimmed().toStdString(); if (topic != topic_) { initialized_ = false; scans_.clear(); has_message_ = false; PrintWarning("No messages received."); laserscan_sub_.shutdown(); topic_ = topic; if (!topic.empty()) { laserscan_sub_ = node_.subscribe(topic_, 100, &LaserScanPlugin::laserScanCallback, this); ROS_INFO("Subscribing to %s", topic_.c_str()); } } } void LaserScanPlugin::MinValueChanged(double value) { min_value_ = value; UpdateColors(); } void LaserScanPlugin::MaxValueChanged(double value) { max_value_ = value; UpdateColors(); } void LaserScanPlugin::BufferSizeChanged(int value) { buffer_size_ = value; if (buffer_size_ > 0) { while (scans_.size() > buffer_size_) { scans_.pop_front(); } } } void LaserScanPlugin::PointSizeChanged(int value) { point_size_ = value; } void LaserScanPlugin::laserScanCallback(const sensor_msgs::LaserScanConstPtr& msg) { if (!has_message_) { initialized_ = true; has_message_ = true; } // Note that unlike some plugins, this one does not store nor rely on the // source_frame_ member variable. This one can potentially store many // messages with different source frames, so we need to store and transform // them individually. Scan scan; scan.stamp = msg->header.stamp; scan.color = QColor::fromRgbF(1.0f, 0.0f, 0.0f, 1.0f); scan.source_frame_ = msg->header.frame_id; scan.transformed = true; scan.has_intensity = !msg->intensities.empty(); scan.points.clear(); swri_transform_util::Transform transform; if (!GetTransform(scan.source_frame_, msg->header.stamp, transform)) { scan.transformed = false; PrintError("No transform between " + source_frame_ + " and " + target_frame_); } double angle, x, y; for (size_t i = 0; i < msg->ranges.size(); i++) { // Discard the point if it's out of range if (msg->ranges[i] > msg->range_max || msg->ranges[i] < msg->range_min) { continue; } StampedPoint point; angle = msg->angle_min + msg->angle_increment * i; x = cos(angle) * msg->ranges[i]; y = sin(angle) * msg->ranges[i]; point.point = tf::Point(x, y, 0.0f); point.range = msg->ranges[i]; if (i < msg->intensities.size()) point.intensity = msg->intensities[i]; if (scan.transformed) { point.transformed_point = transform * point.point; } point.color = CalculateColor(point, scan.has_intensity); scan.points.push_back(point); } scans_.push_back(scan); // If there are more items in the scan buffer than buffer_size_, remove them if (buffer_size_ > 0) { while (scans_.size() > buffer_size_) { scans_.pop_front(); } } } void LaserScanPlugin::PrintError(const std::string& message) { if (message == ui_.status->text().toStdString()) return; ROS_ERROR("Error: %s", message.c_str()); QPalette p(ui_.status->palette()); p.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p); ui_.status->setText(message.c_str()); } void LaserScanPlugin::PrintInfo(const std::string& message) { if (message == ui_.status->text().toStdString()) return; ROS_INFO("%s", message.c_str()); QPalette p(ui_.status->palette()); p.setColor(QPalette::Text, Qt::green); ui_.status->setPalette(p); ui_.status->setText(message.c_str()); } void LaserScanPlugin::PrintWarning(const std::string& message) { if (message == ui_.status->text().toStdString()) return; ROS_WARN("%s", message.c_str()); QPalette p(ui_.status->palette()); p.setColor(QPalette::Text, Qt::darkYellow); ui_.status->setPalette(p); ui_.status->setText(message.c_str()); } QWidget* LaserScanPlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool LaserScanPlugin::Initialize(QGLWidget* canvas) { canvas_ = canvas; DrawIcon(); return true; } void LaserScanPlugin::Draw(double x, double y, double scale) { ros::Time now = ros::Time::now(); glPointSize(point_size_); glBegin(GL_POINTS); std::deque<Scan>::const_iterator scan_it = scans_.begin(); while (scan_it != scans_.end()) { if (scan_it->transformed) { std::vector<StampedPoint>::const_iterator point_it = scan_it->points.begin(); for (; point_it != scan_it->points.end(); ++point_it) { glColor4f( point_it->color.redF(), point_it->color.greenF(), point_it->color.blueF(), alpha_); glVertex2f( point_it->transformed_point.getX(), point_it->transformed_point.getY()); } } ++scan_it; } glEnd(); PrintInfo("OK"); } void LaserScanPlugin::UseRainbowChanged(int check_state) { if (check_state == Qt::Checked) { ui_.max_color->setVisible(false); ui_.min_color->setVisible(false); ui_.maxColorLabel->setVisible(false); ui_.minColorLabel->setVisible(false); } else { ui_.max_color->setVisible(true); ui_.min_color->setVisible(true); ui_.maxColorLabel->setVisible(true); ui_.minColorLabel->setVisible(true); } UpdateColors(); } void LaserScanPlugin::Transform() { std::deque<Scan>::iterator scan_it = scans_.begin(); for (; scan_it != scans_.end(); ++scan_it) { Scan& scan = *scan_it; swri_transform_util::Transform transform; bool was_using_latest_transforms = this->use_latest_transforms_; this->use_latest_transforms_ = false; if (GetTransform(scan.source_frame_, scan.stamp, transform)) { scan.transformed = true; std::vector<StampedPoint>::iterator point_it = scan.points.begin(); for (; point_it != scan.points.end(); ++point_it) { point_it->transformed_point = transform * point_it->point; } } else { scan.transformed = false; } this->use_latest_transforms_ = was_using_latest_transforms; } // Z color is based on transformed color, so it is dependent on the // transform if (ui_.color_transformer->currentIndex() == COLOR_Z) { UpdateColors(); } } void LaserScanPlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["topic"]) { std::string topic; node["topic"] >> topic; ui_.topic->setText(boost::trim_copy(topic).c_str()); TopicEdited(); } if (node["size"]) { node["size"] >> point_size_; ui_.pointSize->setValue(point_size_); } if (node["buffer_size"]) { node["buffer_size"] >> buffer_size_; ui_.bufferSize->setValue(buffer_size_); } if (node["color_transformer"]) { std::string color_transformer; node["color_transformer"] >> color_transformer; if (color_transformer == "Intensity") ui_.color_transformer->setCurrentIndex(COLOR_INTENSITY); else if (color_transformer == "Range") ui_.color_transformer->setCurrentIndex(COLOR_RANGE); else if (color_transformer == "X Axis") ui_.color_transformer->setCurrentIndex(COLOR_X); else if (color_transformer == "Y Axis") ui_.color_transformer->setCurrentIndex(COLOR_Y); else if (color_transformer == "Z Axis") ui_.color_transformer->setCurrentIndex(COLOR_Z); else ui_.color_transformer->setCurrentIndex(COLOR_FLAT); } if (node["min_color"]) { std::string min_color_str; node["min_color"] >> min_color_str; ui_.min_color->setColor(QColor(min_color_str.c_str())); } if (node["max_color"]) { std::string max_color_str; node["max_color"] >> max_color_str; ui_.max_color->setColor(QColor(max_color_str.c_str())); } if (node["value_min"]) { node["value_min"] >> min_value_; ui_.minValue->setValue(min_value_); } if (node["max_value"]) { node["value_max"] >> max_value_; ui_.maxValue->setValue(max_value_); } if (node["alpha"]) { node["alpha"] >> alpha_; ui_.alpha->setValue(alpha_); AlphaEdited(); } if (node["use_rainbow"]) { bool use_rainbow; node["use_rainbow"] >> use_rainbow; ui_.use_rainbow->setChecked(use_rainbow); } // UseRainbowChanged must be called *before* ColorTransformerChanged UseRainbowChanged(ui_.use_rainbow->checkState()); // ColorTransformerChanged will also update colors of all points ColorTransformerChanged(ui_.color_transformer->currentIndex()); } void LaserScanPlugin::ColorTransformerChanged(int index) { ROS_DEBUG("Color transformer changed to %d", index); switch (index) { case COLOR_FLAT: ui_.min_color->setVisible(true); ui_.max_color->setVisible(false); ui_.maxColorLabel->setVisible(false); ui_.minColorLabel->setVisible(false); ui_.minValueLabel->setVisible(false); ui_.maxValueLabel->setVisible(false); ui_.minValue->setVisible(false); ui_.maxValue->setVisible(false); ui_.use_rainbow->setVisible(false); break; case COLOR_INTENSITY: // Intensity case COLOR_RANGE: // Range case COLOR_X: // X Axis case COLOR_Y: // Y Axis case COLOR_Z: // Z axis default: ui_.min_color->setVisible(!ui_.use_rainbow->isChecked()); ui_.max_color->setVisible(!ui_.use_rainbow->isChecked()); ui_.maxColorLabel->setVisible(!ui_.use_rainbow->isChecked()); ui_.minColorLabel->setVisible(!ui_.use_rainbow->isChecked()); ui_.minValueLabel->setVisible(true); ui_.maxValueLabel->setVisible(true); ui_.minValue->setVisible(true); ui_.maxValue->setVisible(true); ui_.use_rainbow->setVisible(true); break; } UpdateColors(); } /** * Coerces alpha to [0.0, 1.0] and stores it in alpha_ */ void LaserScanPlugin::AlphaEdited() { alpha_ = std::max(0.0f, std::min(ui_.alpha->text().toFloat(), 1.0f)); ui_.alpha->setValue(alpha_); } void LaserScanPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { emitter << YAML::Key << "topic" << YAML::Value << boost::trim_copy(ui_.topic->text().toStdString()); emitter << YAML::Key << "size" << YAML::Value << ui_.pointSize->value(); emitter << YAML::Key << "buffer_size" << YAML::Value << ui_.bufferSize->value(); emitter << YAML::Key << "alpha" << YAML::Value << alpha_; emitter << YAML::Key << "color_transformer" << YAML::Value << ui_.color_transformer->currentText().toStdString(); emitter << YAML::Key << "min_color" << YAML::Value << ui_.min_color->color().name().toStdString(); emitter << YAML::Key << "max_color" << YAML::Value << ui_.max_color->color().name().toStdString(); emitter << YAML::Key << "value_min" << YAML::Value << ui_.minValue->text().toDouble(); emitter << YAML::Key << "value_max" << YAML::Value << ui_.maxValue->text().toDouble(); emitter << YAML::Key << "use_rainbow" << YAML::Value << ui_.use_rainbow->isChecked(); } }
evenator/mapviz
mapviz_plugins/src/laserscan_plugin.cpp
C++
bsd-3-clause
20,064
#!/usr/bin/env python import sys from hiclib import mapping, fragmentHiC from mirnylib import h5dict, genome import h5py basedir = sys.argv[1] genome_db = genome.Genome('%s/Data/Genome/mm9_fasta' % basedir, readChrms=['1'], chrmFileTemplate="%s.fa") temp = h5py.File('%s/Data/Timing/hiclib_data_norm.hdf5' % basedir, 'r') weights = temp['weights'][...] temp.close() fragments = fragmentHiC.HiCdataset( filename='temp', genome=genome_db, maximumMoleculeLength=500, mode='a', enzymeName="NcoI", inMemory=True) fragments.load('%s/Data/Timing/hiclib_data_norm.hdf5' % basedir) fragments.weights = weights fragments.fragmentWeights = weights fragments.vectors['weights'] = 'float32' fragments.saveHeatmap('%s/Data/Timing/hiclib_heatmap.hdf5' % basedir, resolution=10000, useWeights=True)
bxlab/HiFive_Paper
Scripts/Timing/hiclib_heatmap.py
Python
bsd-3-clause
813
<div class="member_section"> <div class="login_home"> <a href="<?php echo Yii::app()->getHomeUrl(true); ?>"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/login_home_img.png" alt="" /></a> </div> <div class="login_arrow"> <a href="javascript:history.back()"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/login_representation_img.png" alt="" /></a> </div> <div class="clear"></div> <div class="mid_blocks" id="mid_blocks"> <?php if(!empty($models)){ foreach($models as $model){ $time1 = date("Y-m-d H:i:s"); $time2 = $model->LastLoginDate; $timeDiff = Profile::model()->getDateTimeDiff($time1,$time2); if($timeDiff < 1){ ?> <div class="view"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/img1.png" alt=""> <div class="mask"> <div class="test_section"><span><?php echo CHtml::link($model->UserName,array('profile/'.$model->UserId)); ?></span></div> <div class="age_section"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/inner_man.png" alt="" /> <span><?php echo ($model->Gender) ? "Female" : "Male"; ?>, <?php if($model->DateOfBirth != '0000-00-00') echo Profile::model()->getAge(($model->DateOfBirth)); ?></span> </div> <div class="age_section"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/map_icon.png" alt="" /> <span><?php echo $model->CityOrPostal; ?></span> </div> <div class="hover_navigation"> <ul> <li><a href="#">Mail </a></li> <li><a href="#">Chat </a></li> <li><a href="#">Wink</a></li> </ul> </div> </div> </div> <?php } } }else{ echo '<div class="notFound">Not Found!</div>'; } ?> <div class="clear"></div> </div> </div>
brahmajiayatas/getweiss
protected/views/profile/online.php
PHP
bsd-3-clause
1,760
<?php /** * Webino (http://webino.sk/) * * @link https://github.com/webino/WebinoDev/ for the canonical source repository * @copyright Copyright (c) 2014-2017 Webino, s. r. o. (http://webino.sk/) * @license BSD-3-Clause */ namespace WebinoDev; /** * WebinDev module tests */ class ModuleTest extends \PHPUnit_Framework_TestCase { /** * @var Module */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new Module; } /** * Module initialization */ public function testInit() { $this->assertTrue(function_exists('d')); $this->assertTrue(function_exists('dd')); $this->assertTrue(function_exists('p')); $this->assertTrue(function_exists('pd')); $this->assertTrue(function_exists('pr')); $this->assertTrue(function_exists('e')); } /** * Module getConfig() * * @covers WebinoDev\Module::getConfig */ public function testGetConfig() { $this->assertTrue(is_array($this->object->getConfig())); } }
webino/WebinoDev
tests/WebinoDev/ModuleTest.php
PHP
bsd-3-clause
1,226
'use strict'; angular.module('app.controllers', []) .controller('HomeController', ['$scope','CountryFactory', function($scope, CountryFactory){ $scope.paisSeleccionado = []; CountryFactory.getAllCountries(); $scope.mostrarPaises = function(){ CountryFactory.getAllCountries(); var countries = CountryFactory.getCountries(); $scope.paisSeleccionado = countries[0]; } $scope.crearPais = function(){ CountryFactory.crearPais(); } }])
UsuarioCristian/basic2015
api/assets/js/controllers/controllers.js
JavaScript
bsd-3-clause
450
/* * Copyright (C) 2013 Google Inc. 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 Google Inc. 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. */ #include "config.h" #include "public/web/WebRuntimeFeatures.h" #include "platform/RuntimeEnabledFeatures.h" #include "web/WebMediaPlayerClientImpl.h" namespace blink { void WebRuntimeFeatures::enableExperimentalFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalFeaturesEnabled(enable); } void WebRuntimeFeatures::enableBleedingEdgeFastPaths(bool enable) { ASSERT(enable); RuntimeEnabledFeatures::setBleedingEdgeFastPathsEnabled(enable); RuntimeEnabledFeatures::setWebAnimationsAPIEnabled(enable); } void WebRuntimeFeatures::enableBlinkScheduler(bool enable) { RuntimeEnabledFeatures::setBlinkSchedulerEnabled(enable); } void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable) { RuntimeEnabledFeatures::setTestFeaturesEnabled(enable); } void WebRuntimeFeatures::enableApplicationCache(bool enable) { RuntimeEnabledFeatures::setApplicationCacheEnabled(enable); } void WebRuntimeFeatures::enableCompositedSelectionUpdate(bool enable) { RuntimeEnabledFeatures::setCompositedSelectionUpdateEnabled(enable); } bool WebRuntimeFeatures::isCompositedSelectionUpdateEnabled() { return RuntimeEnabledFeatures::compositedSelectionUpdateEnabled(); } void WebRuntimeFeatures::enableDatabase(bool enable) { RuntimeEnabledFeatures::setDatabaseEnabled(enable); } void WebRuntimeFeatures::enableDecodeToYUV(bool enable) { RuntimeEnabledFeatures::setDecodeToYUVEnabled(enable); } void WebRuntimeFeatures::forceDisplayList2dCanvas(bool enable) { RuntimeEnabledFeatures::setForceDisplayList2dCanvasEnabled(enable); } void WebRuntimeFeatures::enableDisplayList2dCanvas(bool enable) { RuntimeEnabledFeatures::setDisplayList2dCanvasEnabled(enable); } void WebRuntimeFeatures::enableEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable); } bool WebRuntimeFeatures::isEncryptedMediaEnabled() { return RuntimeEnabledFeatures::encryptedMediaEnabled(); } void WebRuntimeFeatures::enablePrefixedEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setPrefixedEncryptedMediaEnabled(enable); } bool WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() { return RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled(); } void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable); } void WebRuntimeFeatures::enableFastMobileScrolling(bool enable) { RuntimeEnabledFeatures::setFastMobileScrollingEnabled(enable); } void WebRuntimeFeatures::enableFileSystem(bool enable) { RuntimeEnabledFeatures::setFileSystemEnabled(enable); } void WebRuntimeFeatures::enableImageColorProfiles(bool enable) { RuntimeEnabledFeatures::setImageColorProfilesEnabled(enable); } void WebRuntimeFeatures::enableLocalStorage(bool enable) { RuntimeEnabledFeatures::setLocalStorageEnabled(enable); } void WebRuntimeFeatures::enableMediaPlayer(bool enable) { RuntimeEnabledFeatures::setMediaEnabled(enable); } void WebRuntimeFeatures::enableMediaCapture(bool enable) { RuntimeEnabledFeatures::setMediaCaptureEnabled(enable); } void WebRuntimeFeatures::enableMediaSource(bool enable) { RuntimeEnabledFeatures::setMediaSourceEnabled(enable); } void WebRuntimeFeatures::enableNotifications(bool enable) { RuntimeEnabledFeatures::setNotificationsEnabled(enable); } void WebRuntimeFeatures::enableNavigatorContentUtils(bool enable) { RuntimeEnabledFeatures::setNavigatorContentUtilsEnabled(enable); } void WebRuntimeFeatures::enableNavigationTransitions(bool enable) { RuntimeEnabledFeatures::setNavigationTransitionsEnabled(enable); } void WebRuntimeFeatures::enableNetworkInformation(bool enable) { RuntimeEnabledFeatures::setNetworkInformationEnabled(enable); } void WebRuntimeFeatures::enableOrientationEvent(bool enable) { RuntimeEnabledFeatures::setOrientationEventEnabled(enable); } void WebRuntimeFeatures::enablePagePopup(bool enable) { RuntimeEnabledFeatures::setPagePopupEnabled(enable); } void WebRuntimeFeatures::enablePeerConnection(bool enable) { RuntimeEnabledFeatures::setPeerConnectionEnabled(enable); } void WebRuntimeFeatures::enableRequestAutocomplete(bool enable) { RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable); } void WebRuntimeFeatures::enableScreenOrientation(bool enable) { RuntimeEnabledFeatures::setScreenOrientationEnabled(enable); } void WebRuntimeFeatures::enableScriptedSpeech(bool enable) { RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable); } void WebRuntimeFeatures::enableServiceWorker(bool enable) { RuntimeEnabledFeatures::setServiceWorkerEnabled(enable); } void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } void WebRuntimeFeatures::enableSlimmingPaint(bool enable) { RuntimeEnabledFeatures::setSlimmingPaintEnabled(enable); } void WebRuntimeFeatures::enableTouch(bool enable) { RuntimeEnabledFeatures::setTouchEnabled(enable); } void WebRuntimeFeatures::enableTouchIconLoading(bool enable) { RuntimeEnabledFeatures::setTouchIconLoadingEnabled(enable); } void WebRuntimeFeatures::enableWebAudio(bool enable) { RuntimeEnabledFeatures::setWebAudioEnabled(enable); } void WebRuntimeFeatures::enableWebGLDraftExtensions(bool enable) { RuntimeEnabledFeatures::setWebGLDraftExtensionsEnabled(enable); } void WebRuntimeFeatures::enableWebGLImageChromium(bool enable) { RuntimeEnabledFeatures::setWebGLImageChromiumEnabled(enable); } void WebRuntimeFeatures::enableWebMIDI(bool enable) { return RuntimeEnabledFeatures::setWebMIDIEnabled(enable); } void WebRuntimeFeatures::enableXSLT(bool enable) { RuntimeEnabledFeatures::setXSLTEnabled(enable); } void WebRuntimeFeatures::enableOverlayScrollbars(bool enable) { RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enable); } void WebRuntimeFeatures::enableOverlayFullscreenVideo(bool enable) { RuntimeEnabledFeatures::setOverlayFullscreenVideoEnabled(enable); } void WebRuntimeFeatures::enableSharedWorker(bool enable) { RuntimeEnabledFeatures::setSharedWorkerEnabled(enable); } void WebRuntimeFeatures::enablePreciseMemoryInfo(bool enable) { RuntimeEnabledFeatures::setPreciseMemoryInfoEnabled(enable); } void WebRuntimeFeatures::enableShowModalDialog(bool enable) { RuntimeEnabledFeatures::setShowModalDialogEnabled(enable); } void WebRuntimeFeatures::enableLaxMixedContentChecking(bool enable) { RuntimeEnabledFeatures::setLaxMixedContentCheckingEnabled(enable); } void WebRuntimeFeatures::enableCredentialManagerAPI(bool enable) { RuntimeEnabledFeatures::setCredentialManagerEnabled(enable); } void WebRuntimeFeatures::enableTextBlobs(bool enable) { RuntimeEnabledFeatures::setTextBlobEnabled(enable); } void WebRuntimeFeatures::enableCSSViewport(bool enable) { RuntimeEnabledFeatures::setCSSViewportEnabled(enable); } void WebRuntimeFeatures::enableV8IdleTasks(bool enable) { RuntimeEnabledFeatures::setV8IdleTasksEnabled(enable); } void WebRuntimeFeatures::enableSVG1DOM(bool enable) { RuntimeEnabledFeatures::setSVG1DOMEnabled(enable); } void WebRuntimeFeatures::enableReducedReferrerGranularity(bool enable) { RuntimeEnabledFeatures::setReducedReferrerGranularityEnabled(enable); } } // namespace blink
primiano/blink-gitcs
Source/web/WebRuntimeFeatures.cpp
C++
bsd-3-clause
8,907
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/test/ash_test_base.h" #include "ash/test/shell_test_api.h" #include "ash/test/test_activation_delegate.h" #include "ash/wm/window_util.h" #include "ui/aura/client/activation_client.h" #include "ui/aura/client/activation_delegate.h" #include "ui/aura/client/cursor_client_observer.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/env.h" #include "ui/aura/root_window.h" #include "ui/aura/test/aura_test_base.h" #include "ui/aura/test/event_generator.h" #include "ui/aura/test/test_event_handler.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/test/test_windows.h" #include "ui/base/cursor/cursor.h" #include "ui/base/hit_test.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/gfx/screen.h" #include "ui/views/corewm/compound_event_filter.h" #include "ui/views/corewm/corewm_switches.h" #include "ui/views/corewm/input_method_event_filter.h" namespace { class TestingCursorClientObserver : public aura::client::CursorClientObserver { public: TestingCursorClientObserver() : cursor_visibility_(false), did_visibility_change_(false) {} void reset() { cursor_visibility_ = did_visibility_change_ = false; } bool is_cursor_visible() const { return cursor_visibility_; } bool did_visibility_change() const { return did_visibility_change_; } // Overridden from aura::client::CursorClientObserver: virtual void OnCursorVisibilityChanged(bool is_visible) OVERRIDE { cursor_visibility_ = is_visible; did_visibility_change_ = true; } private: bool cursor_visibility_; bool did_visibility_change_; DISALLOW_COPY_AND_ASSIGN(TestingCursorClientObserver); }; base::TimeDelta getTime() { return ui::EventTimeForNow(); } // A slightly changed TestEventHandler which can be configured to return a // specified value for key/mouse event handling. class CustomEventHandler : public aura::test::TestEventHandler { public: CustomEventHandler() : key_result_(ui::ER_UNHANDLED), mouse_result_(ui::ER_UNHANDLED) { } virtual ~CustomEventHandler() {} void set_key_event_handling_result(ui::EventResult result) { key_result_ = result; } void set_mouse_event_handling_result(ui::EventResult result) { mouse_result_ = result; } // Overridden from ui::EventHandler: virtual void OnKeyEvent(ui::KeyEvent* event) OVERRIDE { aura::test::TestEventHandler::OnKeyEvent(event); if (key_result_ & ui::ER_HANDLED) event->SetHandled(); if (key_result_ & ui::ER_CONSUMED) event->StopPropagation(); } virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { aura::test::TestEventHandler::OnMouseEvent(event); if (mouse_result_ & ui::ER_HANDLED) event->SetHandled(); if (mouse_result_ & ui::ER_CONSUMED) event->StopPropagation(); } private: ui::EventResult key_result_; ui::EventResult mouse_result_; DISALLOW_COPY_AND_ASSIGN(CustomEventHandler); }; } // namespace namespace ash { typedef test::AshTestBase WindowManagerTest; class NonFocusableDelegate : public aura::test::TestWindowDelegate { public: NonFocusableDelegate() {} private: virtual bool CanFocus() OVERRIDE { return false; } DISALLOW_COPY_AND_ASSIGN(NonFocusableDelegate); }; class HitTestWindowDelegate : public aura::test::TestWindowDelegate { public: HitTestWindowDelegate() : hittest_code_(HTNOWHERE) { } virtual ~HitTestWindowDelegate() {} void set_hittest_code(int hittest_code) { hittest_code_ = hittest_code; } private: // Overridden from TestWindowDelegate: virtual int GetNonClientComponent(const gfx::Point& point) const OVERRIDE { return hittest_code_; } int hittest_code_; DISALLOW_COPY_AND_ASSIGN(HitTestWindowDelegate); }; TEST_F(WindowManagerTest, Focus) { // The IME event filter interferes with the basic key event propagation we // attempt to do here, so we remove it. test::ShellTestApi shell_test(Shell::GetInstance()); Shell::GetInstance()->RemovePreTargetHandler( shell_test.input_method_event_filter()); aura::Window* root_window = Shell::GetPrimaryRootWindow(); root_window->SetBounds(gfx::Rect(0, 0, 510, 510)); // Supplied ids are negative so as not to collide with shell ids. // TODO(beng): maybe introduce a MAKE_SHELL_ID() macro that generates a safe // id beyond shell id max? scoped_ptr<aura::Window> w1(CreateTestWindowInShell( SK_ColorWHITE, -1, gfx::Rect(10, 10, 500, 500))); scoped_ptr<aura::Window> w11(aura::test::CreateTestWindow( SK_ColorGREEN, -11, gfx::Rect(5, 5, 100, 100), w1.get())); scoped_ptr<aura::Window> w111(aura::test::CreateTestWindow( SK_ColorCYAN, -111, gfx::Rect(5, 5, 75, 75), w11.get())); scoped_ptr<aura::Window> w1111(aura::test::CreateTestWindow( SK_ColorRED, -1111, gfx::Rect(5, 5, 50, 50), w111.get())); scoped_ptr<aura::Window> w12(aura::test::CreateTestWindow( SK_ColorMAGENTA, -12, gfx::Rect(10, 420, 25, 25), w1.get())); aura::test::ColorTestWindowDelegate* w121delegate = new aura::test::ColorTestWindowDelegate(SK_ColorYELLOW); scoped_ptr<aura::Window> w121(aura::test::CreateTestWindowWithDelegate( w121delegate, -121, gfx::Rect(5, 5, 5, 5), w12.get())); aura::test::ColorTestWindowDelegate* w122delegate = new aura::test::ColorTestWindowDelegate(SK_ColorRED); scoped_ptr<aura::Window> w122(aura::test::CreateTestWindowWithDelegate( w122delegate, -122, gfx::Rect(10, 5, 5, 5), w12.get())); aura::test::ColorTestWindowDelegate* w123delegate = new aura::test::ColorTestWindowDelegate(SK_ColorRED); scoped_ptr<aura::Window> w123(aura::test::CreateTestWindowWithDelegate( w123delegate, -123, gfx::Rect(15, 5, 5, 5), w12.get())); scoped_ptr<aura::Window> w13(aura::test::CreateTestWindow( SK_ColorGRAY, -13, gfx::Rect(5, 470, 50, 50), w1.get())); // Click on a sub-window (w121) to focus it. aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), w121.get()); generator.ClickLeftButton(); aura::client::FocusClient* focus_client = aura::client::GetFocusClient(w121.get()); EXPECT_EQ(w121.get(), focus_client->GetFocusedWindow()); aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher(); // The key press should be sent to the focused sub-window. ui::KeyEvent keyev(ui::ET_KEY_PRESSED, ui::VKEY_E, 0, false); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&keyev); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::VKEY_E, w121delegate->last_key_code()); // Touch on a sub-window (w122) to focus it. gfx::Point click_point = w122->bounds().CenterPoint(); aura::Window::ConvertPointToTarget(w122->parent(), root_window, &click_point); ui::TouchEvent touchev(ui::ET_TOUCH_PRESSED, click_point, 0, getTime()); details = dispatcher->OnEventFromSource(&touchev); ASSERT_FALSE(details.dispatcher_destroyed); focus_client = aura::client::GetFocusClient(w122.get()); EXPECT_EQ(w122.get(), focus_client->GetFocusedWindow()); // The key press should be sent to the focused sub-window. details = dispatcher->OnEventFromSource(&keyev); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::VKEY_E, w122delegate->last_key_code()); // Hiding the focused window will set the focus to its parent if // it's focusable. w122->Hide(); EXPECT_EQ(aura::client::GetFocusClient(w12.get()), aura::client::GetFocusClient(w122.get())); EXPECT_EQ(w12.get(), aura::client::GetFocusClient(w12.get())->GetFocusedWindow()); // Sets the focus back to w122. w122->Show(); w122->Focus(); EXPECT_EQ(w122.get(), aura::client::GetFocusClient(w12.get())->GetFocusedWindow()); // Removing the focused window from parent should set the focus to // its parent if it's focusable. w12->RemoveChild(w122.get()); EXPECT_EQ(NULL, aura::client::GetFocusClient(w122.get())); EXPECT_EQ(w12.get(), aura::client::GetFocusClient(w12.get())->GetFocusedWindow()); // Set the focus to w123, but make the w1 not activatable. test::TestActivationDelegate activation_delegate(false); w123->Focus(); EXPECT_EQ(w123.get(), aura::client::GetFocusClient(w12.get())->GetFocusedWindow()); aura::client::SetActivationDelegate(w1.get(), &activation_delegate); // Hiding the focused window will set the focus to NULL because // parent window is not focusable. w123->Hide(); EXPECT_EQ(aura::client::GetFocusClient(w12.get()), aura::client::GetFocusClient(w123.get())); EXPECT_EQ(NULL, aura::client::GetFocusClient(w12.get())->GetFocusedWindow()); details = dispatcher->OnEventFromSource(&keyev); EXPECT_FALSE(keyev.handled() || details.dispatcher_destroyed); // Set the focus back to w123 aura::client::SetActivationDelegate(w1.get(), NULL); w123->Show(); w123->Focus(); EXPECT_EQ(w123.get(), aura::client::GetFocusClient(w12.get())->GetFocusedWindow()); aura::client::SetActivationDelegate(w1.get(), &activation_delegate); // Removing the focused window will set the focus to NULL because // parent window is not focusable. w12->RemoveChild(w123.get()); EXPECT_EQ(NULL, aura::client::GetFocusClient(w123.get())); details = dispatcher->OnEventFromSource(&keyev); EXPECT_FALSE(keyev.handled() || details.dispatcher_destroyed); } // Various assertion testing for activating windows. TEST_F(WindowManagerTest, ActivateOnMouse) { aura::Window* root_window = Shell::GetPrimaryRootWindow(); test::TestActivationDelegate d1; aura::test::TestWindowDelegate wd; scoped_ptr<aura::Window> w1(CreateTestWindowInShellWithDelegate( &wd, -1, gfx::Rect(10, 10, 50, 50))); d1.SetWindow(w1.get()); test::TestActivationDelegate d2; scoped_ptr<aura::Window> w2(CreateTestWindowInShellWithDelegate( &wd, -2, gfx::Rect(70, 70, 50, 50))); d2.SetWindow(w2.get()); aura::client::FocusClient* focus_client = aura::client::GetFocusClient(w1.get()); d1.Clear(); d2.Clear(); // Activate window1. wm::ActivateWindow(w1.get()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(1, d1.activated_count()); EXPECT_EQ(0, d1.lost_active_count()); d1.Clear(); { // Click on window2. aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), w2.get()); generator.ClickLeftButton(); // Window2 should have become active. EXPECT_TRUE(wm::IsActiveWindow(w2.get())); EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(0, d1.activated_count()); EXPECT_EQ(1, d1.lost_active_count()); EXPECT_EQ(1, d2.activated_count()); EXPECT_EQ(0, d2.lost_active_count()); d1.Clear(); d2.Clear(); } { // Click back on window1, but set it up so w1 doesn't activate on click. aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), w1.get()); d1.set_activate(false); generator.ClickLeftButton(); // Window2 should still be active and focused. EXPECT_TRUE(wm::IsActiveWindow(w2.get())); EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(0, d1.activated_count()); EXPECT_EQ(0, d1.lost_active_count()); EXPECT_EQ(0, d2.activated_count()); EXPECT_EQ(0, d2.lost_active_count()); d1.Clear(); d2.Clear(); } // Destroy window2, this should make window1 active. d1.set_activate(true); w2.reset(); EXPECT_EQ(0, d2.activated_count()); EXPECT_EQ(1, d2.lost_active_count()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(1, d1.activated_count()); EXPECT_EQ(0, d1.lost_active_count()); // Clicking an active window with a child shouldn't steal the // focus from the child. { scoped_ptr<aura::Window> w11(CreateTestWindowWithDelegate( &wd, -11, gfx::Rect(10, 10, 10, 10), w1.get())); aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), w11.get()); // First set the focus to the child |w11|. generator.ClickLeftButton(); EXPECT_EQ(w11.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(w1.get(), wm::GetActiveWindow()); // Then click the parent active window. The focus shouldn't move. gfx::Point left_top = w1->bounds().origin(); aura::Window::ConvertPointToTarget(w1->parent(), root_window, &left_top); left_top.Offset(1, 1); generator.MoveMouseTo(left_top); generator.ClickLeftButton(); EXPECT_EQ(w11.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(w1.get(), wm::GetActiveWindow()); } // Clicking on a non-focusable window inside a background window should still // give focus to the background window. { NonFocusableDelegate nfd; scoped_ptr<aura::Window> w11(CreateTestWindowWithDelegate( &nfd, -1, gfx::Rect(10, 10, 10, 10), w1.get())); // Move focus to |w2| first. scoped_ptr<aura::Window> w2(CreateTestWindowInShellWithDelegate( &wd, -1, gfx::Rect(70, 70, 50, 50))); aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow(), w2.get()); generator.ClickLeftButton(); EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow()); EXPECT_FALSE(w11->CanFocus()); // Click on |w11|. This should focus w1. generator.MoveMouseToCenterOf(w11.get()); generator.ClickLeftButton(); EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow()); } } TEST_F(WindowManagerTest, PanelActivation) { aura::test::TestWindowDelegate wd; scoped_ptr<aura::Window> w1(CreateTestWindowInShellWithDelegate( &wd, -1, gfx::Rect(10, 10, 50, 50))); aura::test::TestWindowDelegate pd; scoped_ptr<aura::Window> p1(CreateTestWindowInShellWithDelegateAndType( &pd, ui::wm::WINDOW_TYPE_PANEL, -1, gfx::Rect(10, 10, 50, 50))); aura::client::FocusClient* focus_client = aura::client::GetFocusClient(w1.get()); // Activate w1. wm::ActivateWindow(w1.get()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); // Activate p1. wm::ActivateWindow(p1.get()); EXPECT_TRUE(wm::IsActiveWindow(p1.get())); EXPECT_EQ(p1.get(), focus_client->GetFocusedWindow()); // Activate w1. wm::ActivateWindow(w1.get()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow()); // Clicking on a non-activatable window should not change the active window. { NonFocusableDelegate nfd; scoped_ptr<aura::Window> w3(CreateTestWindowInShellWithDelegate( &nfd, -1, gfx::Rect(70, 70, 50, 50))); aura::test::EventGenerator generator3(Shell::GetPrimaryRootWindow(), w3.get()); wm::ActivateWindow(p1.get()); EXPECT_TRUE(wm::IsActiveWindow(p1.get())); generator3.ClickLeftButton(); EXPECT_TRUE(wm::IsActiveWindow(p1.get())); } } // Essentially the same as ActivateOnMouse, but for touch events. TEST_F(WindowManagerTest, ActivateOnTouch) { aura::Window* root_window = Shell::GetPrimaryRootWindow(); test::TestActivationDelegate d1; aura::test::TestWindowDelegate wd; scoped_ptr<aura::Window> w1(CreateTestWindowInShellWithDelegate( &wd, -1, gfx::Rect(10, 10, 50, 50))); d1.SetWindow(w1.get()); test::TestActivationDelegate d2; scoped_ptr<aura::Window> w2(CreateTestWindowInShellWithDelegate( &wd, -2, gfx::Rect(70, 70, 50, 50))); d2.SetWindow(w2.get()); aura::client::FocusClient* focus_client = aura::client::GetFocusClient(w1.get()); d1.Clear(); d2.Clear(); // Activate window1. wm::ActivateWindow(w1.get()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(1, d1.activated_count()); EXPECT_EQ(0, d1.lost_active_count()); d1.Clear(); // Touch window2. gfx::Point press_point = w2->bounds().CenterPoint(); aura::Window::ConvertPointToTarget(w2->parent(), root_window, &press_point); ui::TouchEvent touchev1(ui::ET_TOUCH_PRESSED, press_point, 0, getTime()); aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher(); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&touchev1); ASSERT_FALSE(details.dispatcher_destroyed); // Window2 should have become active. EXPECT_TRUE(wm::IsActiveWindow(w2.get())); EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(0, d1.activated_count()); EXPECT_EQ(1, d1.lost_active_count()); EXPECT_EQ(1, d2.activated_count()); EXPECT_EQ(0, d2.lost_active_count()); d1.Clear(); d2.Clear(); // Touch window1, but set it up so w1 doesn't activate on touch. press_point = w1->bounds().CenterPoint(); aura::Window::ConvertPointToTarget(w1->parent(), root_window, &press_point); d1.set_activate(false); ui::TouchEvent touchev2(ui::ET_TOUCH_PRESSED, press_point, 1, getTime()); details = dispatcher->OnEventFromSource(&touchev2); ASSERT_FALSE(details.dispatcher_destroyed); // Window2 should still be active and focused. EXPECT_TRUE(wm::IsActiveWindow(w2.get())); EXPECT_EQ(w2.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(0, d1.activated_count()); EXPECT_EQ(0, d1.lost_active_count()); EXPECT_EQ(0, d2.activated_count()); EXPECT_EQ(0, d2.lost_active_count()); d1.Clear(); d2.Clear(); // Destroy window2, this should make window1 active. d1.set_activate(true); w2.reset(); EXPECT_EQ(0, d2.activated_count()); EXPECT_EQ(1, d2.lost_active_count()); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), focus_client->GetFocusedWindow()); EXPECT_EQ(1, d1.activated_count()); EXPECT_EQ(0, d1.lost_active_count()); } TEST_F(WindowManagerTest, MouseEventCursors) { aura::Window* root_window = Shell::GetPrimaryRootWindow(); // Create a window. const int kWindowLeft = 123; const int kWindowTop = 45; HitTestWindowDelegate window_delegate; scoped_ptr<aura::Window> window(CreateTestWindowInShellWithDelegate( &window_delegate, -1, gfx::Rect(kWindowLeft, kWindowTop, 640, 480))); // Create two mouse movement events we can switch between. gfx::Point point1(kWindowLeft, kWindowTop); aura::Window::ConvertPointToTarget(window->parent(), root_window, &point1); gfx::Point point2(kWindowLeft + 1, kWindowTop + 1); aura::Window::ConvertPointToTarget(window->parent(), root_window, &point2); aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher(); // Cursor starts as a pointer (set during Shell::Init()). EXPECT_EQ(ui::kCursorPointer, dispatcher->host()->last_cursor().native_type()); { // Resize edges and corners show proper cursors. window_delegate.set_hittest_code(HTBOTTOM); ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorSouthResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTBOTTOMLEFT); ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorSouthWestResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTBOTTOMRIGHT); ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorSouthEastResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTLEFT); ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorWestResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTRIGHT); ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorEastResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTTOP); ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorNorthResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTTOPLEFT); ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorNorthWestResize, dispatcher->host()->last_cursor().native_type()); } { window_delegate.set_hittest_code(HTTOPRIGHT); ui::MouseEvent move2(ui::ET_MOUSE_MOVED, point2, point2, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move2); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorNorthEastResize, dispatcher->host()->last_cursor().native_type()); } { // Client area uses null cursor. window_delegate.set_hittest_code(HTCLIENT); ui::MouseEvent move1(ui::ET_MOUSE_MOVED, point1, point1, 0, 0); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move1); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(ui::kCursorNull, dispatcher->host()->last_cursor().native_type()); } } #if defined(OS_WIN) #define MAYBE_TransformActivate DISABLED_TransformActivate #else #define MAYBE_TransformActivate TransformActivate #endif TEST_F(WindowManagerTest, MAYBE_TransformActivate) { aura::Window* root_window = Shell::GetPrimaryRootWindow(); gfx::Size size = root_window->bounds().size(); EXPECT_EQ(gfx::Rect(size).ToString(), Shell::GetScreen()->GetDisplayNearestPoint( gfx::Point()).bounds().ToString()); // Rotate it clock-wise 90 degrees. gfx::Transform transform; transform.Translate(size.width(), 0); transform.Rotate(90.0f); root_window->GetDispatcher()->host()->SetTransform(transform); test::TestActivationDelegate d1; aura::test::TestWindowDelegate wd; scoped_ptr<aura::Window> w1( CreateTestWindowInShellWithDelegate(&wd, 1, gfx::Rect(0, 15, 50, 50))); d1.SetWindow(w1.get()); w1->Show(); gfx::Point miss_point(5, 5); transform.TransformPoint(&miss_point); ui::MouseEvent mouseev1(ui::ET_MOUSE_PRESSED, miss_point, miss_point, ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher(); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&mouseev1); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(NULL, aura::client::GetFocusClient(w1.get())->GetFocusedWindow()); ui::MouseEvent mouseup(ui::ET_MOUSE_RELEASED, miss_point, miss_point, ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); details = dispatcher->OnEventFromSource(&mouseup); ASSERT_FALSE(details.dispatcher_destroyed); gfx::Point hit_point(5, 15); transform.TransformPoint(&hit_point); ui::MouseEvent mouseev2(ui::ET_MOUSE_PRESSED, hit_point, hit_point, ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); details = dispatcher->OnEventFromSource(&mouseev2); ASSERT_FALSE(details.dispatcher_destroyed); EXPECT_TRUE(wm::IsActiveWindow(w1.get())); EXPECT_EQ(w1.get(), aura::client::GetFocusClient(w1.get())->GetFocusedWindow()); } TEST_F(WindowManagerTest, AdditionalFilters) { // The IME event filter interferes with the basic key event propagation we // attempt to do here, so we remove it. test::ShellTestApi shell_test(Shell::GetInstance()); Shell::GetInstance()->RemovePreTargetHandler( shell_test.input_method_event_filter()); aura::Window* root_window = Shell::GetPrimaryRootWindow(); // Creates a window and make it active scoped_ptr<aura::Window> w1(CreateTestWindowInShell( SK_ColorWHITE, -1, gfx::Rect(0, 0, 100, 100))); wm::ActivateWindow(w1.get()); // Creates two addition filters scoped_ptr<CustomEventHandler> f1(new CustomEventHandler); scoped_ptr<CustomEventHandler> f2(new CustomEventHandler); // Adds them to root window event filter. views::corewm::CompoundEventFilter* env_filter = Shell::GetInstance()->env_filter(); env_filter->AddHandler(f1.get()); env_filter->AddHandler(f2.get()); // Dispatches mouse and keyboard events. ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, 0, false); aura::WindowEventDispatcher* dispatcher = root_window->GetDispatcher(); ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&key_event); ASSERT_FALSE(details.dispatcher_destroyed); ui::MouseEvent mouse_pressed( ui::ET_MOUSE_PRESSED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); details = dispatcher->OnEventFromSource(&mouse_pressed); ASSERT_FALSE(details.dispatcher_destroyed); // Both filters should get the events. EXPECT_EQ(1, f1->num_key_events()); EXPECT_EQ(1, f1->num_mouse_events()); EXPECT_EQ(1, f2->num_key_events()); EXPECT_EQ(1, f2->num_mouse_events()); f1->Reset(); f2->Reset(); // Makes f1 consume events. f1->set_key_event_handling_result(ui::ER_CONSUMED); f1->set_mouse_event_handling_result(ui::ER_CONSUMED); // Dispatches events. details = dispatcher->OnEventFromSource(&key_event); ASSERT_FALSE(details.dispatcher_destroyed); ui::MouseEvent mouse_released( ui::ET_MOUSE_RELEASED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); details = dispatcher->OnEventFromSource(&mouse_released); ASSERT_FALSE(details.dispatcher_destroyed); // f1 should still get the events but f2 no longer gets them. EXPECT_EQ(1, f1->num_key_events()); EXPECT_EQ(1, f1->num_mouse_events()); EXPECT_EQ(0, f2->num_key_events()); EXPECT_EQ(0, f2->num_mouse_events()); f1->Reset(); f2->Reset(); // Remove f1 from additonal filters list. env_filter->RemoveHandler(f1.get()); // Dispatches events. details = dispatcher->OnEventFromSource(&key_event); ASSERT_FALSE(details.dispatcher_destroyed); details = dispatcher->OnEventFromSource(&mouse_pressed); ASSERT_FALSE(details.dispatcher_destroyed); // f1 should get no events since it's out and f2 should get them. EXPECT_EQ(0, f1->num_key_events()); EXPECT_EQ(0, f1->num_mouse_events()); EXPECT_EQ(1, f2->num_key_events()); EXPECT_EQ(1, f2->num_mouse_events()); env_filter->RemoveHandler(f2.get()); } #if defined(OS_CHROMEOS) // Touch visually hides the cursor on ChromeOS and Windows, but we only update // our internal tracking of the cursor state on ChromeOS (crbug.com/333952). TEST_F(WindowManagerTest, UpdateCursorVisibility) { aura::test::EventGenerator& generator = GetEventGenerator(); views::corewm::CursorManager* cursor_manager = ash::Shell::GetInstance()->cursor_manager(); generator.MoveMouseTo(gfx::Point(0, 0)); EXPECT_TRUE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); generator.PressTouch(); EXPECT_FALSE(cursor_manager->IsCursorVisible()); EXPECT_FALSE(cursor_manager->IsMouseEventsEnabled()); generator.MoveMouseTo(gfx::Point(0, 0)); EXPECT_TRUE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); generator.ReleaseTouch(); EXPECT_TRUE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); } // ChromeOS is the only platform for which the cursor is hidden on keypress // (crbug.com/304296). TEST_F(WindowManagerTest, UpdateCursorVisibilityOnKeyEvent) { aura::test::EventGenerator& generator = GetEventGenerator(); views::corewm::CursorManager* cursor_manager = ash::Shell::GetInstance()->cursor_manager(); // Pressing a key hides the cursor but does not disable mouse events. generator.PressKey(ui::VKEY_A, ui::EF_NONE); EXPECT_FALSE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); // Moving mouse shows the cursor. generator.MoveMouseTo(gfx::Point(0, 0)); EXPECT_TRUE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); // Releasing a key also hides the cursor but does not disable mouse events. generator.ReleaseKey(ui::VKEY_A, ui::EF_NONE); EXPECT_FALSE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); // Moving mouse shows the cursor again. generator.MoveMouseTo(gfx::Point(0, 0)); EXPECT_TRUE(cursor_manager->IsCursorVisible()); EXPECT_TRUE(cursor_manager->IsMouseEventsEnabled()); } TEST_F(WindowManagerTest, TestCursorClientObserver) { aura::test::EventGenerator& generator = GetEventGenerator(); views::corewm::CursorManager* cursor_manager = ash::Shell::GetInstance()->cursor_manager(); scoped_ptr<aura::Window> w1(CreateTestWindowInShell( SK_ColorWHITE, -1, gfx::Rect(0, 0, 100, 100))); wm::ActivateWindow(w1.get()); // Add two observers. Both should have OnCursorVisibilityChanged() // invoked when an event changes the visibility of the cursor. TestingCursorClientObserver observer_a; TestingCursorClientObserver observer_b; cursor_manager->AddObserver(&observer_a); cursor_manager->AddObserver(&observer_b); // Initial state before any events have been sent. observer_a.reset(); observer_b.reset(); EXPECT_FALSE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_b.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); EXPECT_FALSE(observer_b.is_cursor_visible()); // Keypress should hide the cursor. generator.PressKey(ui::VKEY_A, ui::EF_NONE); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_TRUE(observer_b.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); EXPECT_FALSE(observer_b.is_cursor_visible()); // Mouse move should show the cursor. observer_a.reset(); observer_b.reset(); generator.MoveMouseTo(50, 50); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_TRUE(observer_b.did_visibility_change()); EXPECT_TRUE(observer_a.is_cursor_visible()); EXPECT_TRUE(observer_b.is_cursor_visible()); // Remove observer_b. Its OnCursorVisibilityChanged() should // not be invoked past this point. cursor_manager->RemoveObserver(&observer_b); // Gesture tap should hide the cursor. observer_a.reset(); observer_b.reset(); generator.GestureTapAt(gfx::Point(25, 25)); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_b.did_visibility_change()); EXPECT_FALSE(observer_a.is_cursor_visible()); // Mouse move should show the cursor. observer_a.reset(); observer_b.reset(); generator.MoveMouseTo(50, 50); EXPECT_TRUE(observer_a.did_visibility_change()); EXPECT_FALSE(observer_b.did_visibility_change()); EXPECT_TRUE(observer_a.is_cursor_visible()); } #endif // defined(OS_CHROMEOS) } // namespace ash
ChromiumWebApps/chromium
ash/wm/window_manager_unittest.cc
C++
bsd-3-clause
31,970
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\issue */ $this->title = 'Update Issue: ' . ' ' . $model->id; $this->params['breadcrumbs'][] = ['label' => 'Issues', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="issue-update"> <h1 style='margin-top:0px; padding-top:15px'>Update Issue</h1> <hr> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
fahmihdyt/propensi
views/Issue/update.php
PHP
bsd-3-clause
550
<?php use app\core\helpers\Url; \app\assets\BootBoxAsset::register($this); ?> <style type="text/css"> #option-box { font-size:12px;} #option-box table tr{ margin-bottom:1em; border-bottom:1px dotted #e1e1e1; } #option-box table td { vertical-align:middle; padding:2px 0px 3px 3px; } #option-box table td span { background-color:#ccd8ed; border-radius:3px; padding:2px 5px; color:#666;} #option-box table td div { width:100px; float:left; line-height:30px; } </style> <div class="row"> <div class="col-xs-3"> <img class="img-circle" width="64" src="<?=$tomb->getThumb('200x100', '/static/images/default.png')?>"> </div> <div class="col-xs-9"> 墓位号:<code><?=$tomb->tomb_no?></code> 价格:<code>¥<?=$tomb->price?></code> 穴数:<code><?=$tomb->hole?></code> </div> <div id="option-box" class="col-xs-12"> <hr /> <table> <?php foreach($options as $key=>$opt):?> <tr> <td width="80px;" valign="top" style="padding-top:4px;"> <?php switch ($key) { case 'common': echo '<span class="option-title">普通操作</span>'; break; case 'operate': echo '<span class="option-title">业务操作</span>'; break; case 'other': echo '<span class="option-title">其他操作</span>'; break; case 'tombwithdraw': echo '<span class="option-title">退墓操作</span>'; break; case 'careful': echo '<span class="option-title">改墓操作</span>'; break; // ..... 其他的 } ?> </td> <td> <?php foreach($opt as $item): ?> <div> <a class="<?php echo $item[2];?>" href="<?php echo $item[1];?>" target="_blank"><?php echo $item[0];?></a> </div> <?php endforeach;?> </td> </tr> <?php endforeach;?> </table> </div> </div> <div id='ylw-tpl' style="display:none;"> <div id="recommand-form" class="recommand-box"> <form action="" method="post"> <textarea placeholder="操作理由" rows="5" class="form-control" name="recommand_intro"></textarea> </div> <div id="retain-form" class="retain-box"> <form action="" method="post"> <textarea placeholder="操作理由" rows="5" class="form-control" name="retain_intro"></textarea> </form> </div> </div> <script type="text/javascript" charset="utf-8"> $(function(){ // 操作项 - 墓位预订------------------------------------------------- $('body').on('click', 'a.tomb-preorder', function(e){ e.preventDefault(); var url = $(this).attr('href'); $.get(url, function(xhr){ if (xhr.status) { window.location = "<?php echo Url::toRoute(['/grave/admin/process/index', 'step'=>1, 'tomb_id'=>$tomb->id]) ?>" } else { //alert(xhr.info); } }, 'json'); return false; }); // 操作项 - 取消预订------------------------------------------------- $('body').on('click', 'a.tomb-unpreorder', function(e){ e.preventDefault(); var url = $(this).attr('href'); $.get(url, function(json){ if (json.status == 0) { bootbox.dialog({ title: "错误信息", message: json.info }) } else { window.location.reload(); } }, 'json'); }); // 保留墓位操作 $('body').on('click', 'a.tomb-retain', function(e){ e.preventDefault(); var $this = $(this); var url = $(this).attr('href'); var retainForm = $('#ylw-tpl').find('#retain-form') .clone().removeAttr('id'); retainForm.find('textarea').attr('rel','retain-box'); retainArt = bootbox.dialog({ title: "保留该墓位", message: retainForm.html(), buttons: { "success" : { "label" : "<i class='icon-ok'></i> 保留", "className" : "btn-sm btn-success", "callback": function() { var content = $('textarea[rel=retain-box]').val(); var datas = { 'retain_intro' : content, 'sale_status' : -1 }; $.get(url, datas, function(rs){ if (rs.status) { $this.text(''); bootbox.dialog({ title: "保留墓位成功", message: '<p style="font-size:1.5em" class="alert alert-success"><i class="icon-comment-alt"></i> 保留墓位成功</p>', buttons: { "success" : { "label" : "<i class='icon-ok'></i> 结束", "className" : "btn-sm btn-success", "callback": function() {location.reload()} }, } }) } },'json'); } }, "button" : { "label" : "返回", "className" : "btn-sm", "callback": function() { } } } }) }); // 保留墓位操作 $('body').on('click', 'a.tomb-retain-del', function(e){ e.preventDefault(); var $this = $(this); var url = $(this).attr('href'); var retainForm = $('#ylw-tpl').find('#retain-form') .clone().removeAttr('id') retainForm.find('textarea').attr('rel','retain-box'); retainArt = bootbox.dialog({ title: "取消保留", message: retainForm.html(), buttons: { "success" : { "label" : "<i class='icon-ok'></i> 取消保留", "className" : "btn-sm btn-success", "callback": function() { var content = $('textarea[rel=retain-box]').val(); var datas = { 'retain_intro' : content, 'sale_status' : 1 }; $.get(url, datas, function(rs){ if (rs.status) { $this.text(''); bootbox.dialog({ title: "取消保留墓位成功", message: '<p style="font-size:1.5em" class="alert alert-success"><i class="icon-comment-alt"></i> 取消保留成功</p>', buttons: { "success" : { "label" : "<i class='icon-ok'></i> 结束", "className" : "btn-sm btn-success", "callback": function() {location.reload()} }, } }) } },'json'); } }, "button" : { "label" : "返回", "className" : "btn-sm", "callback": function() { } } } }) }); // 推荐墓位操作 $('body').on('click', 'a.tomb-recommand', function(e){ e.preventDefault(); var $this = $(this); var url = $(this).attr('href'); var recommandForm = $('#ylw-tpl').find('#recommand-form') .clone().removeAttr('id') recommandForm.find('textarea').attr('rel','recommand-box'); recommandArt = bootbox.dialog({ title: "推荐该墓位", message: recommandForm.html(), buttons: { "success" : { "label" : "<i class='icon-ok'></i> 推荐", "className" : "btn-sm btn-success", "callback": function() { var content = $('textarea[rel=recommand-box]').val(); var datas = { 'recommand_intro' : content }; $.post(url, datas, function(rs){ if (rs.info == 'ok') { $this.attr('href', rs.data.url); $this.attr('class', 'tomb-unrecommand'); $this.text('取消推荐'); } },'json'); } }, "button" : { "label" : "返回", "className" : "btn-sm", "callback": function() { } } } }) }); // 取消推荐 $('body').on('click', 'a.tomb-unrecommand', function(e){ e.preventDefault(); var $this = $(this); var url = $this.attr('href'); $.get(url, function(rs) { if (rs.info == 'ok') { $this.attr('class', 'tomb-recommand'); $this.attr('href', rs.data.url); $this.text('推荐该墓位'); } },'json'); }); }); </script>
cboy868/lion
modules/grave/views/admin/tomb/option.php
PHP
bsd-3-clause
10,602
/* * ----------------------------------------------------------------- * Programmer(s): Slaven Peles, Cody J. Balos @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2021, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- */ #ifndef _NVECTOR_HIP_KERNELS_HIP_HPP_ #define _NVECTOR_HIP_KERNELS_HIP_HPP_ #include <limits> #include <hip/hip_runtime.h> #include "sundials_hip_kernels.hip.hpp" using namespace sundials::hip; namespace sundials { namespace nvector_hip { /* ----------------------------------------------------------------- * The namespace for HIP kernels * * Reduction HIP kernels in nvector are based in part on "reduction" * example in NVIDIA Corporation CUDA Samples, and parallel reduction * examples in textbook by J. Cheng at al. "CUDA C Programming". * ----------------------------------------------------------------- */ /* * Sets all elements of the vector X to constant value a. * */ template <typename T, typename I> __global__ void setConstKernel(T a, T *X, I n) { GRID_STRIDE_XLOOP(I, i, n) { X[i] = a; } } /* * Computes linear sum (combination) of two vectors. * */ template <typename T, typename I> __global__ void linearSumKernel(T a, const T *X, T b, const T *Y, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = a*X[i] + b*Y[i]; } } /* * Elementwise product of two vectors. * */ template <typename T, typename I> __global__ void prodKernel(const T *X, const T *Y, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = X[i]*Y[i]; } } /* * Elementwise division of two vectors. * */ template <typename T, typename I> __global__ void divKernel(const T *X, const T *Y, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = X[i]/Y[i]; } } /* * Scale vector with scalar value 'a'. * */ template <typename T, typename I> __global__ void scaleKernel(T a, const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = a*X[i]; } } /* * Stores absolute values of vector X elements into vector Z. * */ template <typename T, typename I> __global__ void absKernel(const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = abs(X[i]); } } /* * Elementwise inversion. * */ template <typename T, typename I> __global__ void invKernel(const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = 1.0/(X[i]); } } /* * Add constant 'c' to each vector element. * */ template <typename T, typename I> __global__ void addConstKernel(T a, const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = a + X[i]; } } /* * Compare absolute values of vector 'X' with constant 'c'. * */ template <typename T, typename I> __global__ void compareKernel(T c, const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = (abs(X[i]) >= c) ? 1.0 : 0.0; } } /* * Dot product of two vectors. * */ template <typename T, typename I> __global__ void dotProdKernel(const T *x, const T *y, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { sum += x[i] * y[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Finds max norm the vector. * */ template <typename T, typename I> __global__ void maxNormKernel(const T *x, T *out, I n) { T maximum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { maximum = max(abs(x[i]), maximum); } maximum = blockReduce<T, RMAX>(maximum, 0.0); // Maximum of reduction result for each block if (threadIdx.x == 0) AtomicMax(out, maximum); } /* * Weighted L2 norm squared. * */ template <typename T, typename I> __global__ void wL2NormSquareKernel(const T *x, const T *w, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { sum += x[i] * w[i] * x[i] * w[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Weighted L2 norm squared with mask. Vector id specifies the mask. * */ template <typename T, typename I> __global__ void wL2NormSquareMaskKernel(const T *x, const T *w, const T *id, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { if(id[i] > 0.0) sum += x[i] * w[i] * x[i] * w[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Finds min value in the vector. * */ template <typename T, typename I> __global__ void findMinKernel(T MAX_VAL, const T *x, T *out, I n) { T minimum = MAX_VAL; GRID_STRIDE_XLOOP(I, i, n) { minimum = min(x[i], minimum); } minimum = blockReduce<T, RMIN>(minimum, MAX_VAL); // minimum of reduction result for each block if (threadIdx.x == 0) AtomicMin(out, minimum); } /* * Computes L1 norm of vector * */ template <typename T, typename I> __global__ void L1NormKernel(const T *x, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { sum += abs(x[i]); } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Vector inverse z[i] = 1/x[i] with check for zeros. Reduction is performed * to flag the result if any x[i] = 0. * */ template <typename T, typename I> __global__ void invTestKernel(const T *x, T *z, T *out, I n) { T flag = 0.0; GRID_STRIDE_XLOOP(I, i, n) { if (x[i] == static_cast<T>(0.0)) flag += 1.0; else z[i] = 1.0/x[i]; } flag = blockReduce<T, RSUM>(flag, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, flag); } /* * Checks if inequality constraints are satisfied. Constraint check * results are stored in vector 'm'. A sum reduction over all elements * of 'm' is performed to find if any of the constraints is violated. * If all constraints are satisfied sum == 0. * */ template <typename T, typename I> __global__ void constrMaskKernel(const T *c, const T *x, T *m, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { // test = true if constraints violated bool test = (std::abs(c[i]) > 1.5 && c[i]*x[i] <= 0.0) || (std::abs(c[i]) > 0.5 && c[i]*x[i] < 0.0); m[i] = test ? 1.0 : 0.0; sum = m[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Finds minimum component-wise quotient. * */ template <typename T, typename I> __global__ void minQuotientKernel(const T MAX_VAL, const T *num, const T *den, T *min_quotient, I n) { T minimum = MAX_VAL; T quotient = 0.0; GRID_STRIDE_XLOOP(I, i, n) { quotient = (den[i] == static_cast<T>(0.0)) ? MAX_VAL : num[i]/den[i]; minimum = min(quotient, minimum); } minimum = blockReduce<T, RMIN>(minimum, MAX_VAL); // minimum of reduction result for each block if (threadIdx.x == 0) AtomicMin(min_quotient, minimum); } } // namespace nvector_hip } // namespace sundials #endif // _NVECTOR_HIP_KERNELS_HIP_HPP_
stan-dev/math
lib/sundials_6.0.0/src/nvector/hip/VectorKernels.hip.hpp
C++
bsd-3-clause
7,402
/* * DisplayObject by Grant Skinner. Dec 5, 2010 * Visit http://easeljs.com/ for documentation, updates and examples. * * * Copyright (c) 2010 Grant Skinner * * 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. */ /** * The Easel Javascript library provides a retained graphics mode for canvas * including a full, hierarchical display list, a core interaction model, and * helper classes to make working with Canvas much easier. * @module EaselJS **/ (function(window) { /** * DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as * Sprite, Bitmap, and Shape. DisplayObject is the base class for all display classes in the CanvasDisplay library. * It defines the core properties and methods that are shared between all display objects. * @class DisplayObject * @constructor **/ DisplayObject = function() { this.initialize(); } var p = DisplayObject.prototype; /** * Suppresses errors generated when using features like hitTest, onPress/onClick, and getObjectsUnderPoint with cross * domain content * @property suppressCrossDomainErrors * @static * @type Boolean * @default false **/ DisplayObject.suppressCrossDomainErrors = false; /** * @property _hitTestCanvas * @type HTMLCanvasElement * @static * @protected **/ DisplayObject._hitTestCanvas = document.createElement("canvas"); DisplayObject._hitTestCanvas.width = DisplayObject._hitTestCanvas.height = 1; /** * @property _hitTestContext * @type CanvasRenderingContext2D * @static * @protected **/ DisplayObject._hitTestContext = DisplayObject._hitTestCanvas.getContext("2d"); /** * @property _workingMatrix * @type Matrix2D * @static * @protected **/ DisplayObject._workingMatrix = new Matrix2D(); /** * The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque. * @property alpha * @type Number * @default 1 **/ p.alpha = 1; /** * If a cache is active, this returns the canvas that holds the cached version of this display object. See cache() * for more information. READ-ONLY. * @property cacheCanvas * @type HTMLCanvasElement * @default null **/ p.cacheCanvas = null; /** * Unique ID for this display object. Makes display objects easier for some uses. * @property id * @type Number * @default -1 **/ p.id = -1; /** * Indicates whether to include this object when running Stage.getObjectsUnderPoint(). Setting this to true for * Sprites will cause the Sprite to be returned (not its children) regardless of whether it's mouseChildren property * is true. * @property mouseEnabled * @type Boolean * @default true **/ p.mouseEnabled = true; /** * An optional name for this display object. Included in toString(). Useful for debugging. * @property name * @type String * @default null **/ p.name = null; /** * A reference to the Sprite or Stage object that contains this display object, or null if it has not been added to * one. READ-ONLY. * @property parent * @final * @type DisplayObject * @default null **/ p.parent = null; /** * The x offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around * it's center, you would set regX and regY to 50. * @property regX * @type Number * @default 0 **/ p.regX = 0; /** * The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around * it's center, you would set regX and regY to 50. * @property regY * @type Number * @default 0 **/ p.regY = 0; /** * The rotation in degrees for this display object. * @property rotation * @type Number * @default 0 **/ p.rotation = 0; /** * The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display * object to twice it's nominal width. * @property scaleX * @type Number * @default 1 **/ p.scaleX = 1; /** * The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display * object to half it's nominal height. * @property scaleY * @type Number * @default 1 **/ p.scaleY = 1; /** * The factor to skew this display object horizontally. * @property skewX * @type Number * @default 0 **/ p.skewX = 0; /** * The factor to skew this display object vertically. * @property skewY * @type Number * @default 0 **/ p.skewY = 0; /** * A shadow object that defines the shadow to render on this display object. Set to null to remove a shadow. If * null, this property is inherited from the parent container. * @property shadow * @type Shadow * @default null **/ p.shadow = null; /** * Indicates whether this display object should be rendered to the canvas and included when running * Stage.getObjectsUnderPoint(). * @property visible * @type Boolean * @default true **/ p.visible = true; /** * The x (horizontal) position of the display object, relative to its parent. * @property x * @type Number * @default 0 **/ p.x = 0; /** The y (vertical) position of the display object, relative to its parent. * @property y * @type Number * @default 0 **/ p.y = 0; /** * The composite operation indicates how the pixels of this display object will be composited with the elements * behind it. If null, this property is inherited from the parent container. For more information, read the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing"> * whatwg spec on compositing</a>. * @property compositeOperation * @type String * @default null **/ p.compositeOperation = null; /** * Indicates whether the display object should have it's x & y position rounded prior to drawing it to stage. * This only applies if the enclosing stage has snapPixelsEnabled set to true, and the display object's composite * transform does not include any scaling, rotation, or skewing. The snapToPixel property is true by default for * Bitmap and BitmapSequence instances, and false for all other display objects. * @property snapToPixel * @type Boolean * @default false **/ p.snapToPixel = false; /** * The onPress callback is called when the user presses down on their mouse over this display object. The handler * is passed a single param containing the corresponding MouseEvent instance. You can subscribe to the onMouseMove * and onMouseUp callbacks of the event object to receive these events until the user releases the mouse button. * If an onPress handler is set on a container, it will receive the event if any of its children are clicked. * @event onPress * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onPress = null; /** * The onClick callback is called when the user presses down on and then releases the mouse button over this * display object. The handler is passed a single param containing the corresponding MouseEvent instance. If an * onClick handler is set on a container, it will receive the event if any of its children are clicked. * @event onClick * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onClick = null; /** * The onMouseOver callback is called when the user rolls over the display object. You must enable this event using * stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance. * @event onMouseOver * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onMouseOver = null; /** * The onMouseOut callback is called when the user rolls off of the display object. You must enable this event using * stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance. * @event onMouseOut * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onMouseOut = null; // private properties: /** * @property _cacheOffsetX * @protected * @type Number * @default 0 **/ p._cacheOffsetX = 0; /** * @property _cacheOffsetY * @protected * @type Number * @default 0 **/ p._cacheOffsetY = 0; /** * @property _cacheDraw * @protected * @type Boolean * @default false **/ p._cacheDraw = false; /** * @property _activeContext * @protected * @type CanvasRenderingContext2D * @default null **/ p._activeContext = null; /** * @property _restoreContext * @protected * @type Boolean * @default false **/ p._restoreContext = false; /** * @property _revertShadow * @protected * @type Boolean * @default false **/ p._revertShadow = false; /** * @property _revertX * @protected * @type Number * @default 0 **/ p._revertX = 0; /** * @property _revertY * @protected * @type Number * @default 0 **/ p._revertY = 0; /** * @property _revertAlpha * @protected * @type Number * @default 1 **/ p._revertAlpha = 1; // constructor: // separated so it can be easily addressed in subclasses: /** * Initialization method. * @method initialize * @protected */ p.initialize = function() { this.id = UID.get(); this.children = []; } // public methods: /** * Returns true or false indicating whether the display object would be visible if drawn to a canvas. * This does not account for whether it would be visible within the boundaries of the stage. * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method isVisible * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas **/ p.isVisible = function() { return this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0; } /** * Draws the display object into the specified context ignoring it's visible, alpha, shadow, and transform. * Returns true if the draw was handled (useful for overriding functionality). * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method draw * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back * into itself). **/ p.draw = function(ctx, ignoreCache) { if (ignoreCache || !this.cacheCanvas) { return false; } ctx.translate(this._cacheOffsetX, this._cacheOffsetY); ctx.drawImage(this.cacheCanvas, 0, 0); ctx.translate(-this._cacheOffsetX, -this._cacheOffsetY); return true; } /** * Draws the display object into a new canvas, which is then used for subsequent draws. For complex content * that does not change frequently (ex. a Sprite with many children that do not move, or a complex vector Shape), * this can provide for much faster rendering because the content does not need to be re-rendered each tick. The * cached display object can be moved, rotated, faded, etc freely, however if it's content changes, you must manually * update the cache by calling updateCache() or cache() again. You must specify the cache area via the x, y, w, * and h parameters. This defines the rectangle that will be rendered and cached using this display object's * coordinates. For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25, you could call * myShape.cache(-25, -25, 50, 50) to cache the full shape. * @method cache * @param {Number} x The x coordinate origin for the cache region. * @param {Number} y The y coordinate origin for the cache region. * @param {Number} width The width of the cache region. * @param {Number} height The height of the cache region. **/ p.cache = function(x, y, width, height) { // draw to canvas. var ctx; if (this.cacheCanvas == null) { this.cacheCanvas = document.createElement("canvas"); } ctx = this.cacheCanvas.getContext("2d"); this.cacheCanvas.width = width; this.cacheCanvas.height = height; ctx.setTransform(1, 0, 0, 1, -x, -y); ctx.clearRect(0, 0, width+1, height+1); // because some browsers don't correctly clear if the width/height //remain the same. this.draw(ctx, true); this._cacheOffsetX = x; this._cacheOffsetY = y; } /** * Redraws the display object to its cache. Calling updateCache without an active cache will throw an error. * If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object * will be drawn over the existing cache using the specified compositeOperation. * @method updateCache * @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it. * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing"> * whatwg spec on compositing</a>. **/ p.updateCache = function(compositeOperation) { if (this.cacheCanvas == null) { throw "cache() must be called before updateCache()"; } var ctx = this.cacheCanvas.getContext("2d"); ctx.setTransform(1, 0, 0, 1, -this._cacheOffsetX, -this._cacheOffsetY); if (!compositeOperation) { ctx.clearRect(0, 0, this.cacheCanvas.width+1, this.cacheCanvas.height+1); } else { ctx.globalCompositeOperation = compositeOperation; } this.draw(ctx, true); if (compositeOperation) { ctx.globalCompositeOperation = "source-over"; } } /** * Clears the current cache. See cache() for more information. * @method uncache **/ p.uncache = function() { this.cacheCanvas = null; this.cacheOffsetX = this.cacheOffsetY = 0; } /** * Returns the stage that this display object will be rendered on, or null if it has not been added to one. * @method getStage * @return {Stage} The Stage instance that the display object is a descendent of. null if the DisplayObject has not * been added to a Stage. **/ p.getStage = function() { var o = this; while (o.parent) { o = o.parent; } if (o instanceof Stage) { return o; } return null; } /** * Transforms the specified x and y position from the coordinate space of the display object * to the global (stage) coordinate space. For example, this could be used to position an HTML label * over a specific point on a nested display object. Returns a Point instance with x and y properties * correlating to the transformed coordinates on the stage. * @method localToGlobal * @param {Number} x The x position in the source display object to transform. * @param {Number} y The y position in the source display object to transform. * @return {Point} A Point instance with x and y properties correlating to the transformed coordinates * on the stage. **/ p.localToGlobal = function(x, y) { var mtx = this.getConcatenatedMatrix(); if (mtx == null) { return null; } mtx.append(1, 0, 0, 1, x, y); return new Point(mtx.tx, mtx.ty); } /** * Transforms the specified x and y position from the global (stage) coordinate space to the * coordinate space of the display object. For example, this could be used to determine * the current mouse position within the display object. Returns a Point instance with x and y properties * correlating to the transformed position in the display object's coordinate space. * @method globalToLocal * @param {Number} x The x position on the stage to transform. * @param {Number} y The y position on the stage to transform. * @return {Point} A Point instance with x and y properties correlating to the transformed position in the * display object's coordinate space. **/ p.globalToLocal = function(x, y) { var mtx = this.getConcatenatedMatrix(); if (mtx == null) { return null; } mtx.invert(); mtx.append(1, 0, 0, 1, x, y); return new Point(mtx.tx, mtx.ty); } /** * Transforms the specified x and y position from the coordinate space of this display object to the * coordinate space of the target display object. Returns a Point instance with x and y properties * correlating to the transformed position in the target's coordinate space. Effectively the same as calling * var pt = this.localToGlobal(x, y); pt = target.globalToLocal(pt.x, pt.y); * @method localToLocal * @param {Number} x The x position in the source display object to transform. * @param {Number} y The y position on the stage to transform. * @param {DisplayObject} target The target display object to which the coordinates will be transformed. * @return {Point} Returns a Point instance with x and y properties correlating to the transformed position * in the target's coordinate space. **/ p.localToLocal = function(x, y, target) { var pt = this.localToGlobal(x, y); return target.globalToLocal(pt.x, pt.y); } /** * Generates a concatenated Matrix2D object representing the combined transform of * the display object and all of its parent Containers up to the highest level ancestor * (usually the stage). This can be used to transform positions between coordinate spaces, * such as with localToGlobal and globalToLocal. * @method getConcatenatedMatrix * @param {Matrix2D} mtx Optional. A Matrix2D object to populate with the calculated values. If null, a new * Matrix object is returned. * @return {Matrix2D} a concatenated Matrix2D object representing the combined transform of * the display object and all of its parent Containers up to the highest level ancestor (usually the stage). **/ p.getConcatenatedMatrix = function(mtx) { if (mtx) { mtx.identity(); } else { mtx = new Matrix2D(); } var target = this; while (target != null) { mtx.prependTransform(target.x, target.y, target.scaleX, target.scaleY, target.rotation, target.skewX, target.skewY, target.regX, target.regY); mtx.prependProperties(target.alpha, target.shadow, target.compositeOperation); target = target.parent; } return mtx; } /** * Tests whether the display object intersects the specified local point (ie. draws a pixel with alpha > 0 at * the specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all * transform properties including regX/Y. * @method hitTest * @param {Number} x The x position to check in the display object's local coordinates. * @param {Number} y The y position to check in the display object's local coordinates. * @return {Boolean} A Boolean indicting whether a visible portion of the DisplayObject intersect the specified * local Point. */ p.hitTest = function(x, y) { var ctx = DisplayObject._hitTestContext; var canvas = DisplayObject._hitTestCanvas; ctx.setTransform(1, 0, 0, 1, -x, -y); this.draw(ctx); var hit = this._testHit(ctx); canvas.width = 0; canvas.width = 1; return hit; } /** * Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are * reverted to their defaults (for example .parent). * @method clone @return {DisplayObject} A clone of the current DisplayObject instance. **/ p.clone = function() { var o = new DisplayObject(); this.cloneProps(o); return o; } /** * Returns a string representation of this object. * @method toString * @return {String} a string representation of the instance. **/ p.toString = function() { return "[DisplayObject (name="+ this.name +")]"; } // private methods: // separated so it can be used more easily in subclasses: /** * @method cloneProps * @protected * @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject * instance copied into. **/ p.cloneProps = function(o) { o.alpha = this.alpha; o.name = this.name; o.regX = this.regX; o.regY = this.regY; o.rotation = this.rotation; o.scaleX = this.scaleX; o.scaleY = this.scaleY; o.shadow = this.shadow; o.skewX = this.skewX; o.skewY = this.skewY; o.visible = this.visible; o.x = this.x; o.y = this.y; o.mouseEnabled = this.mouseEnabled; o.compositeOperation = this.compositeOperation; } /** * @method applyShadow * @protected * @param {CanvasRenderingContext2D} ctx * @param {Shadow} shadow **/ p.applyShadow = function(ctx, shadow) { shadow = shadow || Shadow.identity; ctx.shadowColor = shadow.color; ctx.shadowOffsetX = shadow.offsetX; ctx.shadowOffsetY = shadow.offsetY; ctx.shadowBlur = shadow.blur; } /** * @method _testHit * @protected * @param {CanvasRenderingContext2D} ctx * @return {Boolean} **/ p._testHit = function(ctx) { try { var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1; } catch (e) { if (!DisplayObject.suppressCrossDomainErrors) { throw "An error has occured. This is most likely due to security restrictions on reading canvas pixel " + "data with local or cross-domain images."; } } return hit; } window.DisplayObject = DisplayObject; }(window));
PaulWoow/HTML5JUEGOGRAFICACION
Mini Valle PaJou/libs/easeljs/display/DisplayObject.js
JavaScript
bsd-3-clause
21,794
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.ndexbio.cxio.core.interfaces; import java.io.InputStream; import org.ndexbio.model.cx.NiceCXNetwork; import org.ndexbio.model.exceptions.NdexException; /** * Implementing interfaces support generating {@link org.ndexbio.model.cx.NiceCXNetwork} * objects from an {@link java.io.InputStream} * @author churas */ public interface INiceCXNetworkReader { /** * Reads {@code in} and generates {@link org.ndexbio.model.cx.NiceCXNetwork} * object * @param in {@link java.io.InputStream} to extract the {@link org.ndexbio.model.cx.NiceCXNetwork} from * @return {@link org.ndexbio.model.cx.NiceCXNetwork} object representing data from {@code in} * @throws NdexException If there was a problem parsing the input. */ public NiceCXNetwork readNiceCXNetwork(final InputStream in) throws NdexException; }
ndexbio/ndex-object-model
src/main/java/org/ndexbio/cxio/core/interfaces/INiceCXNetworkReader.java
Java
bsd-3-clause
1,040
<?php use yii\helpers\Html; use yii\helpers\ArrayHelper; $this->title = Yii::t('app', 'Create Role'); $this->params['breadcrumbs'][] = ['label'=>Yii::t('app', 'Admin'), 'url'=>['index']]; $this->params['breadcrumbs'][] = ['label'=>Yii::t('app', 'Roles'), 'url'=>['roles/index']]; $this->params['breadcrumbs'][] = $this->title; ?> <?= Html::beginForm('', 'POST') ?> <div class="form-group"> <?= Html::label(Yii::t('app', 'Role Name'), null, ['class'=>'control-label']) ?> <?= Html::input('text', 'role[name]', null, ['class'=>'form-control']) ?> </div> <div class="form-group"> <?= Html::label(Yii::t('app', 'Role Description'), null, ['class'=>'control-label']) ?> <?= Html::input('text', 'role[description]', null, ['class'=>'form-control']) ?> </div> <div class="form-group"> <?= Html::submitButton(Yii::t('app', 'Create'), ['class'=>'btn btn-success']) ?> </div> <?= Html::endForm() ?>
magdielikari/HidroLab-Manager
backend/modules/admin/views/roles/create.php
PHP
bsd-3-clause
901
package transmission // Copyright 2015, JuanDeFu.ca. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. import ( "encoding/json" "fmt" "log" "strings" ) /* Method name torrent-add */ /* Either "filename" OR "metainfo" MUST be included. */ /* Response arguments: On success, a "torrent-added" object contains id, name, and hashString. On failure due to a duplicate torrent existing, a "torrent-duplicate" object in the same form. */ type Add_Argument struct { Cookies string `json:"cookies,omitempty"` DownloadDir string `json:"download-dir,omitempty"` Filename string `json:"filename,omitempty"` MetaInfo string `json:"metainfo,omitempty"` Paused bool `json:"paused,omitempty"` PeerLimit int `json:"peer-limit,omitempty"` BandwidthPriority int `json:"bandwidthPriority,omitempty"` FilesWanted []*File `json:"files-wanted,omitempty"` FilesUnwanted []*File `json:"files-unwanted,omitempty"` PriorityHigh []*File `json:"priority-high,omitempty"` PriorityLow []*File `json:"priority-low,omitempty"` PriorityNormal []*File `json:"priority-normal,omitempty"` } type Add_Response struct { Torrent *Torrent `json:"torrent-added,omitempty"` } func (self *Client) AddTorrent( location string, path string, ) ( *Torrent, error, ) { if location == "" { return nil, fmt.Errorf("Transmission.AddTorrent(): location empty") } if path == "" { return nil, fmt.Errorf("Transmission.AddTorrent(): path empty") } if !strings.HasPrefix(path, "/") { return nil, fmt.Errorf("Transmission.AddTorrent(): path doesn't start with /") } request := &Request{} request.Method = "torrent-add" access := Add_Argument{} access.Filename = location access.DownloadDir = path request.Args = access var result *Response var err error for i := 0; i < 5; i++ { if result, err = self.Request(request); err == nil && result != nil { if result.Result == "success" { torrent := Add_Response{} if err2 := json.Unmarshal(result.Args, &torrent); err2 != nil { log.Printf("Transmission.AddTorrent(): failed to unmarshal %s | raw: %v\n", err2, result.Args) } else { return torrent.Torrent, nil } } else { return nil, fmt.Errorf("Transmission.AddTorrent(): failed to add: %s", result.Result) } } } return nil, fmt.Errorf("Transmission.AddTorrent(): failed to get torrents: %s", err) }
sabey/transmission
torrent_add.go
GO
bsd-3-clause
2,493
package main.data.core; public interface Function<A, B> { B apply(A a); }
nhibberd/search
src/main/data/core/Function.java
Java
bsd-3-clause
79
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.team649.frc2014.subsystems; import com.team649.frc2014.RobotMap; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; /** * * @author Kabi */ public class ClawRollerSubsystem extends Subsystem { private final SpeedController motor; public static final double ROLLER_SPIN_SHOOT_SPEED = 1; public static final double ROLLER_SPIN_INTAKE_SPEED = -.4; public static final double ROLLER_SPIN_PURGE_SPEED = .4; public static final double ROLLER_SPIN_OFF_SPEED = 0; public static final double ROLLER_SPIN_REALIGN_SPEED = -.2; public ClawRollerSubsystem() { motor = new Victor(RobotMap.CLAW_ROLLER.MOTOR); } protected void initDefaultCommand() { } public void runMotor(double speed) { motor.set(speed); } }
SaratogaMSET/649code2014
src/com/team649/frc2014/subsystems/ClawRollerSubsystem.java
Java
bsd-3-clause
1,047
module SpreeGridFaq class Engine < Rails::Engine engine_name 'spree_grid_faq' config.autoload_paths += %W(#{config.root}/lib) # use rspec for tests config.generators do |g| g.test_framework :rspec end def self.activate Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare &method(:activate).to_proc end end
ehoch/spree_grid_faq
lib/spree_grid_faq/engine.rb
Ruby
bsd-3-clause
486
<?php return array ( 'Search' => 'Pesquisar', );
LeonidLyalin/vova
common/humhub/protected/humhub/modules/search/messages/pt/base.php
PHP
bsd-3-clause
51
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/common/system/ime/tray_ime_chromeos.h" #include <vector> #include "ash/common/session/session_state_delegate.h" #include "ash/common/system/chromeos/ime_menu/ime_list_view.h" #include "ash/common/system/tray/hover_highlight_view.h" #include "ash/common/system/tray/system_tray.h" #include "ash/common/system/tray/system_tray_delegate.h" #include "ash/common/system/tray/system_tray_notifier.h" #include "ash/common/system/tray/tray_constants.h" #include "ash/common/system/tray/tray_details_view.h" #include "ash/common/system/tray/tray_item_more.h" #include "ash/common/system/tray/tray_item_view.h" #include "ash/common/system/tray/tray_utils.h" #include "ash/common/system/tray_accessibility.h" #include "ash/common/wm_shell.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "grit/ash_resources.h" #include "grit/ash_strings.h" #include "ui/accessibility/ax_enums.h" #include "ui/accessibility/ax_view_state.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/font.h" #include "ui/gfx/image/image.h" #include "ui/keyboard/keyboard_util.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/widget/widget.h" namespace ash { namespace tray { // A |HoverHighlightView| that uses bold or normal font depending on whether // it is selected. This view exposes itself as a checkbox to the accessibility // framework. class SelectableHoverHighlightView : public HoverHighlightView { public: SelectableHoverHighlightView(ViewClickListener* listener, const base::string16& label, bool selected) : HoverHighlightView(listener), selected_(selected) { AddLabel(label, gfx::ALIGN_LEFT, selected); } ~SelectableHoverHighlightView() override {} protected: // Overridden from views::View. void GetAccessibleState(ui::AXViewState* state) override { HoverHighlightView::GetAccessibleState(state); state->role = ui::AX_ROLE_CHECK_BOX; if (selected_) state->AddStateFlag(ui::AX_STATE_CHECKED); } private: bool selected_; DISALLOW_COPY_AND_ASSIGN(SelectableHoverHighlightView); }; class IMEDefaultView : public TrayItemMore { public: explicit IMEDefaultView(SystemTrayItem* owner, const base::string16& label) : TrayItemMore(owner, true) { ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); SetImage(bundle.GetImageNamed(IDR_AURA_UBER_TRAY_IME).ToImageSkia()); UpdateLabel(label); } ~IMEDefaultView() override {} void UpdateLabel(const base::string16& label) { SetLabel(label); SetAccessibleName(label); } private: DISALLOW_COPY_AND_ASSIGN(IMEDefaultView); }; class IMEDetailedView : public ImeListView { public: IMEDetailedView(SystemTrayItem* owner, LoginStatus login, bool show_keyboard_toggle) : ImeListView(owner, show_keyboard_toggle, ImeListView::HIDE_SINGLE_IME), login_(login) { SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate(); IMEInfoList list; delegate->GetAvailableIMEList(&list); IMEPropertyInfoList property_list; delegate->GetCurrentIMEProperties(&property_list); Update(list, property_list, show_keyboard_toggle, ImeListView::HIDE_SINGLE_IME); } ~IMEDetailedView() override {} void Update(const IMEInfoList& list, const IMEPropertyInfoList& property_list, bool show_keyboard_toggle, SingleImeBehavior single_ime_behavior) override { ImeListView::Update(list, property_list, show_keyboard_toggle, single_ime_behavior); if (login_ != LoginStatus::NOT_LOGGED_IN && login_ != LoginStatus::LOCKED && !WmShell::Get()->GetSessionStateDelegate()->IsInSecondaryLoginScreen()) AppendSettings(); AppendHeaderEntry(); } private: // ImeListView: void OnViewClicked(views::View* sender) override { ImeListView::OnViewClicked(sender); SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate(); if (sender == footer()->content()) { TransitionToDefaultView(); } else if (sender == settings_) { WmShell::Get()->RecordUserMetricsAction( UMA_STATUS_AREA_IME_SHOW_DETAILED); delegate->ShowIMESettings(); } } void AppendHeaderEntry() { CreateSpecialRow(IDS_ASH_STATUS_TRAY_IME, this); } void AppendSettings() { HoverHighlightView* container = new HoverHighlightView(this); container->AddLabel( ui::ResourceBundle::GetSharedInstance().GetLocalizedString( IDS_ASH_STATUS_TRAY_IME_SETTINGS), gfx::ALIGN_LEFT, false /* highlight */); AddChildView(container); settings_ = container; } LoginStatus login_; views::View* settings_; DISALLOW_COPY_AND_ASSIGN(IMEDetailedView); }; } // namespace tray TrayIME::TrayIME(SystemTray* system_tray) : SystemTrayItem(system_tray, UMA_IME), tray_label_(NULL), default_(NULL), detailed_(NULL), keyboard_suppressed_(false), is_visible_(true) { SystemTrayNotifier* tray_notifier = WmShell::Get()->system_tray_notifier(); tray_notifier->AddVirtualKeyboardObserver(this); tray_notifier->AddAccessibilityObserver(this); tray_notifier->AddIMEObserver(this); } TrayIME::~TrayIME() { SystemTrayNotifier* tray_notifier = WmShell::Get()->system_tray_notifier(); tray_notifier->RemoveIMEObserver(this); tray_notifier->RemoveAccessibilityObserver(this); tray_notifier->RemoveVirtualKeyboardObserver(this); } void TrayIME::OnKeyboardSuppressionChanged(bool suppressed) { keyboard_suppressed_ = suppressed; Update(); } void TrayIME::OnAccessibilityModeChanged( AccessibilityNotificationVisibility notify) { Update(); } void TrayIME::Update() { UpdateTrayLabel(current_ime_, ime_list_.size()); if (default_) { default_->SetVisible(ShouldDefaultViewBeVisible()); default_->UpdateLabel(GetDefaultViewLabel(ime_list_.size() > 1)); } if (detailed_) detailed_->Update(ime_list_, property_list_, ShouldShowKeyboardToggle(), ImeListView::HIDE_SINGLE_IME); } void TrayIME::UpdateTrayLabel(const IMEInfo& current, size_t count) { if (tray_label_) { bool visible = count > 1 && is_visible_; tray_label_->SetVisible(visible); // Do not change label before hiding because this change is noticeable. if (!visible) return; if (current.third_party) { tray_label_->label()->SetText(current.short_name + base::UTF8ToUTF16("*")); } else { tray_label_->label()->SetText(current.short_name); } SetTrayLabelItemBorder(tray_label_, system_tray()->shelf_alignment()); tray_label_->Layout(); } } bool TrayIME::ShouldShowKeyboardToggle() { return keyboard_suppressed_ && !WmShell::Get()->accessibility_delegate()->IsVirtualKeyboardEnabled(); } base::string16 TrayIME::GetDefaultViewLabel(bool show_ime_label) { if (show_ime_label) { IMEInfo current; WmShell::Get()->system_tray_delegate()->GetCurrentIME(&current); return current.name; } else { // Display virtual keyboard status instead. int id = keyboard::IsKeyboardEnabled() ? IDS_ASH_STATUS_TRAY_KEYBOARD_ENABLED : IDS_ASH_STATUS_TRAY_KEYBOARD_DISABLED; return ui::ResourceBundle::GetSharedInstance().GetLocalizedString(id); } } views::View* TrayIME::CreateTrayView(LoginStatus status) { CHECK(tray_label_ == NULL); tray_label_ = new TrayItemView(this); tray_label_->CreateLabel(); SetupLabelForTray(tray_label_->label()); // Hide IME tray when it is created, it will be updated when it is notified // of the IME refresh event. tray_label_->SetVisible(false); return tray_label_; } views::View* TrayIME::CreateDefaultView(LoginStatus status) { CHECK(default_ == NULL); default_ = new tray::IMEDefaultView(this, GetDefaultViewLabel(ime_list_.size() > 1)); default_->SetVisible(ShouldDefaultViewBeVisible()); return default_; } views::View* TrayIME::CreateDetailedView(LoginStatus status) { CHECK(detailed_ == NULL); detailed_ = new tray::IMEDetailedView(this, status, ShouldShowKeyboardToggle()); return detailed_; } void TrayIME::DestroyTrayView() { tray_label_ = NULL; } void TrayIME::DestroyDefaultView() { default_ = NULL; } void TrayIME::DestroyDetailedView() { detailed_ = NULL; } void TrayIME::UpdateAfterLoginStatusChange(LoginStatus status) {} void TrayIME::UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) { SetTrayLabelItemBorder(tray_label_, alignment); tray_label_->Layout(); } void TrayIME::OnIMERefresh() { // Caches the current ime state. SystemTrayDelegate* delegate = WmShell::Get()->system_tray_delegate(); ime_list_.clear(); property_list_.clear(); delegate->GetCurrentIME(&current_ime_); delegate->GetAvailableIMEList(&ime_list_); delegate->GetCurrentIMEProperties(&property_list_); Update(); } void TrayIME::OnIMEMenuActivationChanged(bool is_active) { is_visible_ = !is_active; if (is_visible_) OnIMERefresh(); else Update(); } bool TrayIME::ShouldDefaultViewBeVisible() { return is_visible_ && (ime_list_.size() > 1 || property_list_.size() > 1 || ShouldShowKeyboardToggle()); } } // namespace ash
danakj/chromium
ash/common/system/ime/tray_ime_chromeos.cc
C++
bsd-3-clause
9,556
/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ import { Suite } from './suite.js'; import { Spec } from './spec.js'; import { Test, TestResult } from './test.js'; /** * These are the events that represent the different stages of the reporting * lifecycle. */ export enum ReporterEvent { suiteStart = 'SuiteStart', suiteEnd = 'SuiteEnd', specStart = 'SpecStart', specEnd = 'SpecEnd', testStart = 'TestStart', testEnd = 'TestEnd', unexpectedError = 'UnexpectedError' }; /** * A reporter is an object that implements some callbacks associated with * reporting lifecycle stages of interest. The default reporter has none * of these callbacks implemented. */ export abstract class Reporter { /** * If set to true, the reporter will not dispatch lifecycle event details * to its associated callbacks. This is useful for disabling reporting for * some stretch of time (for example, when a test is isolated). */ disabled: boolean = false; /** * Dispatches an event's details to the appropriate lifecycle callback. */ report(eventName: ReporterEvent, ...args: any[]): boolean { const methodName = `on${eventName}` as keyof this; if (this.disabled || this[methodName] == null) { return false; } // TODO(dfreedm): make a argument mapping for each method of the reporter, someday (this[methodName] as any)(...args); return true; } /** * Invoked just before a suite begins iterating over specs and invoking tests. */ onSuiteStart?(suite: Suite): void; /** * Invoked after a suite has finished iterating over specs and invoking all * tests. */ onSuiteEnd?(suite: Suite): void; /** * Invoked before each spec in the suite, before ivoking tests. */ onSpecStart?(spec: Spec, suite: Suite): void; /** * Invoked for each spec in the suite, after all tests have been invoked. */ onSpecEnd?(spec: Spec, suite: Suite): void; /** * Invoked for each test, before its implementation is invoked. */ onTestStart?(test: Test, suite: Suite): void; /** * Invoked for each test, after its implementation has been invoked. Receives * the result of the test. */ onTestEnd?(result: TestResult, test: Test, suite: Suite): void; /** * Invoked when there is an out-of-band error, such as an internal exception * of the test runner or one of its related mixins. */ onUnexpectedError?(message: string, error: Error, suite: Suite): void; };
PolymerLabs/ristretto
src/reporter.ts
TypeScript
bsd-3-clause
2,969
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\apidoc\helpers; use phpDocumentor\Reflection\DocBlock\Type\Collection; use yii\apidoc\models\MethodDoc; use yii\apidoc\models\TypeDoc; /** * Class ApiMarkdownTrait * * @property TypeDoc $renderingContext */ trait ApiMarkdownTrait { /** * @marker [[ */ protected function parseApiLinks($text) { $context = $this->renderingContext; if (preg_match('/^\[\[([\w\d\\\\\(\):$]+)(\|[^\]]*)?\]\]/', $text, $matches)) { $offset = strlen($matches[0]); $object = $matches[1]; $title = (empty($matches[2]) || $matches[2] == '|') ? null : substr($matches[2], 1); if (($pos = strpos($object, '::')) !== false) { $typeName = substr($object, 0, $pos); $subjectName = substr($object, $pos + 2); if ($context !== null) { // Collection resolves relative types $typeName = (new Collection([$typeName], $context->phpDocContext))->__toString(); } /** @var $type TypeDoc */ $type = static::$renderer->apiContext->getType($typeName); if ($type === null) { static::$renderer->apiContext->errors[] = [ 'file' => ($context !== null) ? $context->sourceFile : null, 'message' => 'broken link to ' . $typeName . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''), ]; return [ ['brokenApiLink', '<span class="broken-link">' . $typeName . '::' . $subjectName . '</span>'], $offset ]; } else { if (($subject = $type->findSubject($subjectName)) !== null) { if ($title === null) { $title = $type->name . '::' . $subject->name; if ($subject instanceof MethodDoc) { $title .= '()'; } } return [ ['apiLink', static::$renderer->createSubjectLink($subject, $title)], $offset ]; } else { static::$renderer->apiContext->errors[] = [ 'file' => ($context !== null) ? $context->sourceFile : null, 'message' => 'broken link to ' . $type->name . '::' . $subjectName . (($context !== null) ? ' in ' . $context->name : ''), ]; return [ ['brokenApiLink', '<span class="broken-link">' . $type->name . '::' . $subjectName . '</span>'], $offset ]; } } } elseif ($context !== null && ($subject = $context->findSubject($object)) !== null) { return [ ['apiLink', static::$renderer->createSubjectLink($subject, $title)], $offset ]; } if ($context !== null) { // Collection resolves relative types $object = (new Collection([$object], $context->phpDocContext))->__toString(); } if (($type = static::$renderer->apiContext->getType($object)) !== null) { return [ ['apiLink', static::$renderer->createTypeLink($type, null, $title)], $offset ]; } elseif (strpos($typeLink = static::$renderer->createTypeLink($object, null, $title), '<a href') !== false) { return [ ['apiLink', $typeLink], $offset ]; } static::$renderer->apiContext->errors[] = [ 'file' => ($context !== null) ? $context->sourceFile : null, 'message' => 'broken link to ' . $object . (($context !== null) ? ' in ' . $context->name : ''), ]; return [ ['brokenApiLink', '<span class="broken-link">' . $object . '</span>'], $offset ]; } return [['text', '[['], 2]; } /** * Renders API link * @param array $block * @return string */ protected function renderApiLink($block) { return $block[1]; } /** * Renders API link that is broken i.e. points nowhere * @param array $block * @return string */ protected function renderBrokenApiLink($block) { return $block[1]; } /** * Consume lines for a blockquote element */ protected function consumeQuote($lines, $current) { $block = parent::consumeQuote($lines, $current); $blockTypes = [ 'warning', 'note', 'info', 'tip', ]; // check whether this is a special Info, Note, Warning, Tip block $content = $block[0]['content']; $first = reset($content); if (isset($first[0]) && $first[0] === 'paragraph') { $parfirst = reset($first['content']); if (isset($parfirst[0]) && $parfirst[0] === 'text') { foreach ($blockTypes as $type) { if (strncasecmp("$type: ", $parfirst[1], $len = strlen($type) + 2) === 0) { // remove block indicator $block[0]['content'][0]['content'][0][1] = substr($parfirst[1], $len); // add translated block indicator as bold text array_unshift($block[0]['content'][0]['content'], [ 'strong', [ ['text', $this->translateBlockType($type)], ], ]); $block[0]['blocktype'] = $type; break; } } } } return $block; } protected abstract function translateBlockType($type); /** * Renders a blockquote */ protected function renderQuote($block) { $class = ''; if (isset($block['blocktype'])) { $class = ' class="' . $block['blocktype'] . '"'; } return "<blockquote{$class}>" . $this->renderAbsy($block['content']) . "</blockquote>\n"; } }
Bladefidz/ocfa_yii
vendor/yiisoft/yii2-apidoc/helpers/ApiMarkdownTrait.php
PHP
bsd-3-clause
6,745
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 the OpenSimulator Project 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 DEVELOPERS ``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 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. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// This class stores and retrieves dynamic objects. /// </summary> /// <remarks> /// Experimental - DO NOT USE. Does not yet have namespace support. /// </remarks> public class DOMap { private IDictionary<string, object> m_map; private ReaderWriterLock m_mapRwLock = new ReaderWriterLock(); public void Add(string ns, string objName, object dynObj) { DAMap.ValidateNamespace(ns); m_mapRwLock.AcquireWriterLock(-1); try { if (m_map == null) m_map = new Dictionary<string, object>(); m_map.Add(objName, dynObj); } finally { m_mapRwLock.ReleaseWriterLock(); } } public bool ContainsKey(string key) { m_mapRwLock.AcquireReaderLock(-1); try { return Get(key) != null; } finally { m_mapRwLock.ReleaseReaderLock(); } } /// <summary> /// Get a dynamic object /// </summary> /// <remarks> /// Not providing an index method so that users can't casually overwrite each other's objects. /// </remarks> /// <param name='key'></param> public object Get(string key) { m_mapRwLock.AcquireReaderLock(-1); try { if (m_map == null) return null; else return m_map[key]; } finally { m_mapRwLock.ReleaseReaderLock(); } } public bool Remove(string key) { m_mapRwLock.AcquireWriterLock(-1); try { if (m_map == null) return false; else return m_map.Remove(key); } finally { m_mapRwLock.ReleaseWriterLock(); } } } }
ft-/arribasim-dev-extras
OpenSim/Framework/DOMap.cs
C#
bsd-3-clause
4,063
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/layers/picture_layer_impl.h" #include <algorithm> #include <cmath> #include <limits> #include <set> #include "base/time/time.h" #include "base/trace_event/trace_event_argument.h" #include "cc/base/math_util.h" #include "cc/debug/debug_colors.h" #include "cc/debug/micro_benchmark_impl.h" #include "cc/debug/traced_value.h" #include "cc/layers/append_quads_data.h" #include "cc/layers/solid_color_layer_impl.h" #include "cc/output/begin_frame_args.h" #include "cc/quads/checkerboard_draw_quad.h" #include "cc/quads/debug_border_draw_quad.h" #include "cc/quads/picture_draw_quad.h" #include "cc/quads/solid_color_draw_quad.h" #include "cc/quads/tile_draw_quad.h" #include "cc/tiles/tile_manager.h" #include "cc/tiles/tiling_set_raster_queue_all.h" #include "cc/trees/layer_tree_impl.h" #include "cc/trees/occlusion.h" #include "ui/gfx/geometry/quad_f.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" namespace { // This must be > 1 as we multiply or divide by this to find a new raster // scale during pinch. const float kMaxScaleRatioDuringPinch = 2.0f; // When creating a new tiling during pinch, snap to an existing // tiling's scale if the desired scale is within this ratio. const float kSnapToExistingTilingRatio = 1.2f; // Even for really wide viewports, at some point GPU raster should use // less than 4 tiles to fill the viewport. This is set to 256 as a // sane minimum for now, but we might want to tune this for low-end. const int kMinHeightForGpuRasteredTile = 256; // When making odd-sized tiles, round them up to increase the chances // of using the same tile size. const int kTileRoundUp = 64; } // namespace namespace cc { PictureLayerImpl::PictureLayerImpl( LayerTreeImpl* tree_impl, int id, bool is_mask, scoped_refptr<SyncedScrollOffset> scroll_offset) : LayerImpl(tree_impl, id, scroll_offset), twin_layer_(nullptr), tilings_(CreatePictureLayerTilingSet()), ideal_page_scale_(0.f), ideal_device_scale_(0.f), ideal_source_scale_(0.f), ideal_contents_scale_(0.f), raster_page_scale_(0.f), raster_device_scale_(0.f), raster_source_scale_(0.f), raster_contents_scale_(0.f), low_res_raster_contents_scale_(0.f), raster_source_scale_is_fixed_(false), was_screen_space_transform_animating_(false), only_used_low_res_last_append_quads_(false), is_mask_(is_mask), nearest_neighbor_(false) { layer_tree_impl()->RegisterPictureLayerImpl(this); } PictureLayerImpl::~PictureLayerImpl() { if (twin_layer_) twin_layer_->twin_layer_ = nullptr; layer_tree_impl()->UnregisterPictureLayerImpl(this); } const char* PictureLayerImpl::LayerTypeAsString() const { return "cc::PictureLayerImpl"; } scoped_ptr<LayerImpl> PictureLayerImpl::CreateLayerImpl( LayerTreeImpl* tree_impl) { return PictureLayerImpl::Create(tree_impl, id(), is_mask_, synced_scroll_offset()); } void PictureLayerImpl::PushPropertiesTo(LayerImpl* base_layer) { PictureLayerImpl* layer_impl = static_cast<PictureLayerImpl*>(base_layer); DCHECK_EQ(layer_impl->is_mask_, is_mask_); LayerImpl::PushPropertiesTo(base_layer); // Twin relationships should never change once established. DCHECK_IMPLIES(twin_layer_, twin_layer_ == layer_impl); DCHECK_IMPLIES(twin_layer_, layer_impl->twin_layer_ == this); // The twin relationship does not need to exist before the first // PushPropertiesTo from pending to active layer since before that the active // layer can not have a pile or tilings, it has only been created and inserted // into the tree at that point. twin_layer_ = layer_impl; layer_impl->twin_layer_ = this; layer_impl->SetNearestNeighbor(nearest_neighbor_); // Solid color layers have no tilings. DCHECK_IMPLIES(raster_source_->IsSolidColor(), tilings_->num_tilings() == 0); // The pending tree should only have a high res (and possibly low res) tiling. DCHECK_LE(tilings_->num_tilings(), layer_tree_impl()->create_low_res_tiling() ? 2u : 1u); layer_impl->set_gpu_raster_max_texture_size(gpu_raster_max_texture_size_); layer_impl->UpdateRasterSource(raster_source_, &invalidation_, tilings_.get()); DCHECK(invalidation_.IsEmpty()); // After syncing a solid color layer, the active layer has no tilings. DCHECK_IMPLIES(raster_source_->IsSolidColor(), layer_impl->tilings_->num_tilings() == 0); layer_impl->raster_page_scale_ = raster_page_scale_; layer_impl->raster_device_scale_ = raster_device_scale_; layer_impl->raster_source_scale_ = raster_source_scale_; layer_impl->raster_contents_scale_ = raster_contents_scale_; layer_impl->low_res_raster_contents_scale_ = low_res_raster_contents_scale_; layer_impl->SanityCheckTilingState(); // We always need to push properties. // See http://crbug.com/303943 // TODO(danakj): Stop always pushing properties since we don't swap tilings. needs_push_properties_ = true; } void PictureLayerImpl::AppendQuads(RenderPass* render_pass, AppendQuadsData* append_quads_data) { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK_IMPLIES(!raster_source_->GetSize().IsEmpty(), bounds() == raster_source_->GetSize()) << " bounds " << bounds().ToString() << " pile " << raster_source_->GetSize().ToString(); SharedQuadState* shared_quad_state = render_pass->CreateAndAppendSharedQuadState(); if (raster_source_->IsSolidColor()) { PopulateSharedQuadState(shared_quad_state); AppendDebugBorderQuad( render_pass, bounds(), shared_quad_state, append_quads_data); SolidColorLayerImpl::AppendSolidQuads( render_pass, draw_properties().occlusion_in_content_space, shared_quad_state, visible_layer_rect(), raster_source_->GetSolidColor(), append_quads_data); return; } float max_contents_scale = MaximumTilingContentsScale(); PopulateScaledSharedQuadState(shared_quad_state, max_contents_scale); Occlusion scaled_occlusion = draw_properties() .occlusion_in_content_space.GetOcclusionWithGivenDrawTransform( shared_quad_state->quad_to_target_transform); if (current_draw_mode_ == DRAW_MODE_RESOURCELESS_SOFTWARE) { AppendDebugBorderQuad( render_pass, shared_quad_state->quad_layer_bounds, shared_quad_state, append_quads_data, DebugColors::DirectPictureBorderColor(), DebugColors::DirectPictureBorderWidth(layer_tree_impl())); gfx::Rect geometry_rect = shared_quad_state->visible_quad_layer_rect; gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect(); gfx::Rect visible_geometry_rect = scaled_occlusion.GetUnoccludedContentRect(geometry_rect); if (visible_geometry_rect.IsEmpty()) return; gfx::Rect quad_content_rect = shared_quad_state->visible_quad_layer_rect; gfx::Size texture_size = quad_content_rect.size(); gfx::RectF texture_rect = gfx::RectF(texture_size); PictureDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<PictureDrawQuad>(); quad->SetNew(shared_quad_state, geometry_rect, opaque_rect, visible_geometry_rect, texture_rect, texture_size, nearest_neighbor_, RGBA_8888, quad_content_rect, max_contents_scale, raster_source_); ValidateQuadResources(quad); return; } AppendDebugBorderQuad(render_pass, shared_quad_state->quad_layer_bounds, shared_quad_state, append_quads_data); if (ShowDebugBorders()) { for (PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), max_contents_scale, shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_); iter; ++iter) { SkColor color; float width; if (*iter && iter->draw_info().IsReadyToDraw()) { TileDrawInfo::Mode mode = iter->draw_info().mode(); if (mode == TileDrawInfo::SOLID_COLOR_MODE) { color = DebugColors::SolidColorTileBorderColor(); width = DebugColors::SolidColorTileBorderWidth(layer_tree_impl()); } else if (mode == TileDrawInfo::OOM_MODE) { color = DebugColors::OOMTileBorderColor(); width = DebugColors::OOMTileBorderWidth(layer_tree_impl()); } else if (iter.resolution() == HIGH_RESOLUTION) { color = DebugColors::HighResTileBorderColor(); width = DebugColors::HighResTileBorderWidth(layer_tree_impl()); } else if (iter.resolution() == LOW_RESOLUTION) { color = DebugColors::LowResTileBorderColor(); width = DebugColors::LowResTileBorderWidth(layer_tree_impl()); } else if (iter->contents_scale() > max_contents_scale) { color = DebugColors::ExtraHighResTileBorderColor(); width = DebugColors::ExtraHighResTileBorderWidth(layer_tree_impl()); } else { color = DebugColors::ExtraLowResTileBorderColor(); width = DebugColors::ExtraLowResTileBorderWidth(layer_tree_impl()); } } else { color = DebugColors::MissingTileBorderColor(); width = DebugColors::MissingTileBorderWidth(layer_tree_impl()); } DebugBorderDrawQuad* debug_border_quad = render_pass->CreateAndAppendDrawQuad<DebugBorderDrawQuad>(); gfx::Rect geometry_rect = iter.geometry_rect(); gfx::Rect visible_geometry_rect = geometry_rect; debug_border_quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect, color, width); } } // Keep track of the tilings that were used so that tilings that are // unused can be considered for removal. last_append_quads_tilings_.clear(); // Ignore missing tiles outside of viewport for tile priority. This is // normally the same as draw viewport but can be independently overridden by // embedders like Android WebView with SetExternalDrawConstraints. gfx::Rect scaled_viewport_for_tile_priority = gfx::ScaleToEnclosingRect( viewport_rect_for_tile_priority_in_content_space_, max_contents_scale); size_t missing_tile_count = 0u; size_t on_demand_missing_tile_count = 0u; only_used_low_res_last_append_quads_ = true; for (PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), max_contents_scale, shared_quad_state->visible_quad_layer_rect, ideal_contents_scale_); iter; ++iter) { gfx::Rect geometry_rect = iter.geometry_rect(); gfx::Rect opaque_rect = contents_opaque() ? geometry_rect : gfx::Rect(); gfx::Rect visible_geometry_rect = scaled_occlusion.GetUnoccludedContentRect(geometry_rect); if (visible_geometry_rect.IsEmpty()) continue; append_quads_data->visible_layer_area += visible_geometry_rect.width() * visible_geometry_rect.height(); bool has_draw_quad = false; if (*iter && iter->draw_info().IsReadyToDraw()) { const TileDrawInfo& draw_info = iter->draw_info(); switch (draw_info.mode()) { case TileDrawInfo::RESOURCE_MODE: { gfx::RectF texture_rect = iter.texture_rect(); // The raster_contents_scale_ is the best scale that the layer is // trying to produce, even though it may not be ideal. Since that's // the best the layer can promise in the future, consider those as // complete. But if a tile is ideal scale, we don't want to consider // it incomplete and trying to replace it with a tile at a worse // scale. if (iter->contents_scale() != raster_contents_scale_ && iter->contents_scale() != ideal_contents_scale_ && geometry_rect.Intersects(scaled_viewport_for_tile_priority)) { append_quads_data->num_incomplete_tiles++; } TileDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<TileDrawQuad>(); quad->SetNew(shared_quad_state, geometry_rect, opaque_rect, visible_geometry_rect, draw_info.resource_id(), texture_rect, draw_info.resource_size(), draw_info.contents_swizzled(), nearest_neighbor_); ValidateQuadResources(quad); iter->draw_info().set_was_ever_used_to_draw(); has_draw_quad = true; break; } case TileDrawInfo::SOLID_COLOR_MODE: { SolidColorDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect, draw_info.solid_color(), false); ValidateQuadResources(quad); iter->draw_info().set_was_ever_used_to_draw(); has_draw_quad = true; break; } case TileDrawInfo::OOM_MODE: break; // Checkerboard. } } if (!has_draw_quad) { if (draw_checkerboard_for_missing_tiles()) { CheckerboardDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<CheckerboardDrawQuad>(); SkColor color = DebugColors::DefaultCheckerboardColor(); quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect, color, ideal_device_scale_); } else { SkColor color = SafeOpaqueBackgroundColor(); SolidColorDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); quad->SetNew(shared_quad_state, geometry_rect, visible_geometry_rect, color, false); ValidateQuadResources(quad); } if (geometry_rect.Intersects(scaled_viewport_for_tile_priority)) { append_quads_data->num_missing_tiles++; ++missing_tile_count; } append_quads_data->approximated_visible_content_area += visible_geometry_rect.width() * visible_geometry_rect.height(); append_quads_data->checkerboarded_visible_content_area += visible_geometry_rect.width() * visible_geometry_rect.height(); continue; } if (iter.resolution() != HIGH_RESOLUTION) { append_quads_data->approximated_visible_content_area += visible_geometry_rect.width() * visible_geometry_rect.height(); } // If we have a draw quad, but it's not low resolution, then // mark that we've used something other than low res to draw. if (iter.resolution() != LOW_RESOLUTION) only_used_low_res_last_append_quads_ = false; if (last_append_quads_tilings_.empty() || last_append_quads_tilings_.back() != iter.CurrentTiling()) { last_append_quads_tilings_.push_back(iter.CurrentTiling()); } } if (missing_tile_count) { TRACE_EVENT_INSTANT2("cc", "PictureLayerImpl::AppendQuads checkerboard", TRACE_EVENT_SCOPE_THREAD, "missing_tile_count", missing_tile_count, "on_demand_missing_tile_count", on_demand_missing_tile_count); } // Aggressively remove any tilings that are not seen to save memory. Note // that this is at the expense of doing cause more frequent re-painting. A // better scheme would be to maintain a tighter visible_layer_rect for the // finer tilings. CleanUpTilingsOnActiveLayer(last_append_quads_tilings_); } bool PictureLayerImpl::UpdateTiles(bool resourceless_software_draw) { if (!resourceless_software_draw) { visible_rect_for_tile_priority_ = visible_layer_rect(); } if (!CanHaveTilings()) { ideal_page_scale_ = 0.f; ideal_device_scale_ = 0.f; ideal_contents_scale_ = 0.f; ideal_source_scale_ = 0.f; SanityCheckTilingState(); return false; } // Remove any non-ideal tilings that were not used last time we generated // quads to save memory and processing time. Note that pending tree should // only have one or two tilings (high and low res), so only clean up the // active layer. This cleans it up here in case AppendQuads didn't run. // If it did run, this would not remove any additional tilings. if (layer_tree_impl()->IsActiveTree()) CleanUpTilingsOnActiveLayer(last_append_quads_tilings_); UpdateIdealScales(); if (!raster_contents_scale_ || ShouldAdjustRasterScale()) { RecalculateRasterScales(); AddTilingsForRasterScale(); } DCHECK(raster_page_scale_); DCHECK(raster_device_scale_); DCHECK(raster_source_scale_); DCHECK(raster_contents_scale_); DCHECK(low_res_raster_contents_scale_); was_screen_space_transform_animating_ = draw_properties().screen_space_transform_is_animating; if (draw_transform_is_animating()) raster_source_->SetShouldAttemptToUseDistanceFieldText(); double current_frame_time_in_seconds = (layer_tree_impl()->CurrentBeginFrameArgs().frame_time - base::TimeTicks()).InSecondsF(); UpdateViewportRectForTilePriorityInContentSpace(); // The tiling set can require tiles for activation any of the following // conditions are true: // - This layer produced a high-res or non-ideal-res tile last frame. // - We're in requires high res to draw mode. // - We're not in smoothness takes priority mode. // To put different, the tiling set can't require tiles for activation if // we're in smoothness mode and only used low-res or checkerboard to draw last // frame and we don't need high res to draw. // // The reason for this is that we should be able to activate sooner and get a // more up to date recording, so we don't run out of recording on the active // tree. bool can_require_tiles_for_activation = !only_used_low_res_last_append_quads_ || RequiresHighResToDraw() || !layer_tree_impl()->SmoothnessTakesPriority(); static const Occlusion kEmptyOcclusion; const Occlusion& occlusion_in_content_space = layer_tree_impl()->settings().use_occlusion_for_tile_prioritization ? draw_properties().occlusion_in_content_space : kEmptyOcclusion; // Pass |occlusion_in_content_space| for |occlusion_in_layer_space| since // they are the same space in picture layer, as contents scale is always 1. bool updated = tilings_->UpdateTilePriorities( viewport_rect_for_tile_priority_in_content_space_, ideal_contents_scale_, current_frame_time_in_seconds, occlusion_in_content_space, can_require_tiles_for_activation); return updated; } void PictureLayerImpl::UpdateViewportRectForTilePriorityInContentSpace() { // If visible_rect_for_tile_priority_ is empty or // viewport_rect_for_tile_priority is set to be different from the device // viewport, try to inverse project the viewport into layer space and use // that. Otherwise just use visible_rect_for_tile_priority_ gfx::Rect visible_rect_in_content_space = visible_rect_for_tile_priority_; gfx::Rect viewport_rect_for_tile_priority = layer_tree_impl()->ViewportRectForTilePriority(); if (visible_rect_in_content_space.IsEmpty() || layer_tree_impl()->DeviceViewport() != viewport_rect_for_tile_priority) { gfx::Transform view_to_layer(gfx::Transform::kSkipInitialization); if (screen_space_transform().GetInverse(&view_to_layer)) { // Transform from view space to content space. visible_rect_in_content_space = gfx::ToEnclosingRect(MathUtil::ProjectClippedRect( view_to_layer, viewport_rect_for_tile_priority)); // We have to allow for a viewport that is outside of the layer bounds in // order to compute tile priorities correctly for offscreen content that // is going to make it on screen. However, we also have to limit the // viewport since it can be very large due to screen_space_transforms. As // a heuristic, we clip to bounds padded by skewport_extrapolation_limit * // maximum tiling scale, since this should allow sufficient room for // skewport calculations. gfx::Rect padded_bounds(bounds()); int padding_amount = layer_tree_impl() ->settings() .skewport_extrapolation_limit_in_content_pixels * MaximumTilingContentsScale(); padded_bounds.Inset(-padding_amount, -padding_amount); visible_rect_in_content_space.Intersect(padded_bounds); } } viewport_rect_for_tile_priority_in_content_space_ = visible_rect_in_content_space; } PictureLayerImpl* PictureLayerImpl::GetPendingOrActiveTwinLayer() const { if (!twin_layer_ || !twin_layer_->IsOnActiveOrPendingTree()) return nullptr; return twin_layer_; } void PictureLayerImpl::UpdateRasterSource( scoped_refptr<RasterSource> raster_source, Region* new_invalidation, const PictureLayerTilingSet* pending_set) { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK_IMPLIES(!raster_source->GetSize().IsEmpty(), bounds() == raster_source->GetSize()) << " bounds " << bounds().ToString() << " pile " << raster_source->GetSize().ToString(); // The |raster_source_| is initially null, so have to check for that for the // first frame. bool could_have_tilings = raster_source_.get() && CanHaveTilings(); raster_source_.swap(raster_source); // The |new_invalidation| must be cleared before updating tilings since they // access the invalidation through the PictureLayerTilingClient interface. invalidation_.Clear(); invalidation_.Swap(new_invalidation); bool can_have_tilings = CanHaveTilings(); DCHECK_IMPLIES( pending_set, can_have_tilings == GetPendingOrActiveTwinLayer()->CanHaveTilings()); // Need to call UpdateTiles again if CanHaveTilings changed. if (could_have_tilings != can_have_tilings) layer_tree_impl()->set_needs_update_draw_properties(); if (!can_have_tilings) { RemoveAllTilings(); return; } // We could do this after doing UpdateTiles, which would avoid doing this for // tilings that are going to disappear on the pending tree (if scale changed). // But that would also be more complicated, so we just do it here for now. if (pending_set) { tilings_->UpdateTilingsToCurrentRasterSourceForActivation( raster_source_, pending_set, invalidation_, MinimumContentsScale(), MaximumContentsScale()); } else { tilings_->UpdateTilingsToCurrentRasterSourceForCommit( raster_source_, invalidation_, MinimumContentsScale(), MaximumContentsScale()); } } void PictureLayerImpl::UpdateCanUseLCDTextAfterCommit() { // This function is only allowed to be called after commit, due to it not // being smart about sharing tiles and because otherwise it would cause // flashes by switching out tiles in place that may be currently on screen. DCHECK(layer_tree_impl()->IsSyncTree()); // Don't allow the LCD text state to change once disabled. if (!RasterSourceUsesLCDText()) return; if (can_use_lcd_text() == RasterSourceUsesLCDText()) return; // Raster sources are considered const, so in order to update the state // a new one must be created and all tiles recreated. scoped_refptr<RasterSource> new_raster_source = raster_source_->CreateCloneWithoutLCDText(); raster_source_.swap(new_raster_source); // Synthetically invalidate everything. gfx::Rect bounds_rect(bounds()); invalidation_ = Region(bounds_rect); tilings_->UpdateRasterSourceDueToLCDChange(raster_source_, invalidation_); SetUpdateRect(bounds_rect); DCHECK(!RasterSourceUsesLCDText()); } bool PictureLayerImpl::RasterSourceUsesLCDText() const { return raster_source_ ? raster_source_->CanUseLCDText() : layer_tree_impl()->settings().can_use_lcd_text; } void PictureLayerImpl::NotifyTileStateChanged(const Tile* tile) { if (layer_tree_impl()->IsActiveTree()) { gfx::RectF layer_damage_rect = gfx::ScaleRect(tile->content_rect(), 1.f / tile->contents_scale()); AddDamageRect(layer_damage_rect); } if (tile->draw_info().NeedsRaster()) { PictureLayerTiling* tiling = tilings_->FindTilingWithScale(tile->contents_scale()); if (tiling) tiling->set_all_tiles_done(false); } } void PictureLayerImpl::DidBeginTracing() { raster_source_->DidBeginTracing(); } void PictureLayerImpl::ReleaseResources() { // Recreate tilings with new settings, since some of those might change when // we release resources. tilings_ = nullptr; ResetRasterScale(); } void PictureLayerImpl::RecreateResources() { tilings_ = CreatePictureLayerTilingSet(); // To avoid an edge case after lost context where the tree is up to date but // the tilings have not been managed, request an update draw properties // to force tilings to get managed. layer_tree_impl()->set_needs_update_draw_properties(); } skia::RefPtr<SkPicture> PictureLayerImpl::GetPicture() { return raster_source_->GetFlattenedPicture(); } Region PictureLayerImpl::GetInvalidationRegion() { // |invalidation_| gives the invalidation contained in the source frame, but // is not cleared after drawing from the layer. However, update_rect() is // cleared once the invalidation is drawn, which is useful for debugging // visualizations. This method intersects the two to give a more exact // representation of what was invalidated that is cleared after drawing. return IntersectRegions(invalidation_, update_rect()); } ScopedTilePtr PictureLayerImpl::CreateTile(float contents_scale, const gfx::Rect& content_rect) { int flags = 0; // We don't handle solid color masks, so we shouldn't bother analyzing those. // Otherwise, always analyze to maximize memory savings. if (!is_mask_) flags = Tile::USE_PICTURE_ANALYSIS; return layer_tree_impl()->tile_manager()->CreateTile( content_rect.size(), content_rect, contents_scale, id(), layer_tree_impl()->source_frame_number(), flags); } const Region* PictureLayerImpl::GetPendingInvalidation() { if (layer_tree_impl()->IsPendingTree()) return &invalidation_; if (layer_tree_impl()->IsRecycleTree()) return nullptr; DCHECK(layer_tree_impl()->IsActiveTree()); if (PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer()) return &twin_layer->invalidation_; return nullptr; } const PictureLayerTiling* PictureLayerImpl::GetPendingOrActiveTwinTiling( const PictureLayerTiling* tiling) const { PictureLayerImpl* twin_layer = GetPendingOrActiveTwinLayer(); if (!twin_layer) return nullptr; return twin_layer->tilings_->FindTilingWithScale(tiling->contents_scale()); } bool PictureLayerImpl::RequiresHighResToDraw() const { return layer_tree_impl()->RequiresHighResToDraw(); } gfx::Rect PictureLayerImpl::GetEnclosingRectInTargetSpace() const { return GetScaledEnclosingRectInTargetSpace(MaximumTilingContentsScale()); } gfx::Size PictureLayerImpl::CalculateTileSize( const gfx::Size& content_bounds) const { int max_texture_size = layer_tree_impl()->resource_provider()->max_texture_size(); if (is_mask_) { // Masks are not tiled, so if we can't cover the whole mask with one tile, // we shouldn't have such a tiling at all. DCHECK_LE(content_bounds.width(), max_texture_size); DCHECK_LE(content_bounds.height(), max_texture_size); return content_bounds; } int default_tile_width = 0; int default_tile_height = 0; if (layer_tree_impl()->use_gpu_rasterization()) { // For GPU rasterization, we pick an ideal tile size using the viewport // so we don't need any settings. The current approach uses 4 tiles // to cover the viewport vertically. int viewport_width = gpu_raster_max_texture_size_.width(); int viewport_height = gpu_raster_max_texture_size_.height(); default_tile_width = viewport_width; // Also, increase the height proportionally as the width decreases, and // pad by our border texels to make the tiles exactly match the viewport. int divisor = 4; if (content_bounds.width() <= viewport_width / 2) divisor = 2; if (content_bounds.width() <= viewport_width / 4) divisor = 1; default_tile_height = MathUtil::RoundUp(viewport_height, divisor) / divisor; // Grow default sizes to account for overlapping border texels. default_tile_width += 2 * PictureLayerTiling::kBorderTexels; default_tile_height += 2 * PictureLayerTiling::kBorderTexels; default_tile_height = std::max(default_tile_height, kMinHeightForGpuRasteredTile); } else { // For CPU rasterization we use tile-size settings. const LayerTreeSettings& settings = layer_tree_impl()->settings(); int max_untiled_content_width = settings.max_untiled_layer_size.width(); int max_untiled_content_height = settings.max_untiled_layer_size.height(); default_tile_width = settings.default_tile_size.width(); default_tile_height = settings.default_tile_size.height(); // If the content width is small, increase tile size vertically. // If the content height is small, increase tile size horizontally. // If both are less than the untiled-size, use a single tile. if (content_bounds.width() < default_tile_width) default_tile_height = max_untiled_content_height; if (content_bounds.height() < default_tile_height) default_tile_width = max_untiled_content_width; if (content_bounds.width() < max_untiled_content_width && content_bounds.height() < max_untiled_content_height) { default_tile_height = max_untiled_content_height; default_tile_width = max_untiled_content_width; } } int tile_width = default_tile_width; int tile_height = default_tile_height; // Clamp the tile width/height to the content width/height to save space. if (content_bounds.width() < default_tile_width) { tile_width = std::min(tile_width, content_bounds.width()); tile_width = MathUtil::RoundUp(tile_width, kTileRoundUp); tile_width = std::min(tile_width, default_tile_width); } if (content_bounds.height() < default_tile_height) { tile_height = std::min(tile_height, content_bounds.height()); tile_height = MathUtil::RoundUp(tile_height, kTileRoundUp); tile_height = std::min(tile_height, default_tile_height); } // Under no circumstance should we be larger than the max texture size. tile_width = std::min(tile_width, max_texture_size); tile_height = std::min(tile_height, max_texture_size); return gfx::Size(tile_width, tile_height); } void PictureLayerImpl::GetContentsResourceId(ResourceId* resource_id, gfx::Size* resource_size) const { // The bounds and the pile size may differ if the pile wasn't updated (ie. // PictureLayer::Update didn't happen). In that case the pile will be empty. DCHECK_IMPLIES(!raster_source_->GetSize().IsEmpty(), bounds() == raster_source_->GetSize()) << " bounds " << bounds().ToString() << " pile " << raster_source_->GetSize().ToString(); gfx::Rect content_rect(bounds()); PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), 1.f, content_rect, ideal_contents_scale_); // Mask resource not ready yet. if (!iter || !*iter) { *resource_id = 0; return; } // Masks only supported if they fit on exactly one tile. DCHECK(iter.geometry_rect() == content_rect) << "iter rect " << iter.geometry_rect().ToString() << " content rect " << content_rect.ToString(); const TileDrawInfo& draw_info = iter->draw_info(); if (!draw_info.IsReadyToDraw() || draw_info.mode() != TileDrawInfo::RESOURCE_MODE) { *resource_id = 0; return; } *resource_id = draw_info.resource_id(); *resource_size = draw_info.resource_size(); } void PictureLayerImpl::SetNearestNeighbor(bool nearest_neighbor) { if (nearest_neighbor_ == nearest_neighbor) return; nearest_neighbor_ = nearest_neighbor; NoteLayerPropertyChanged(); } PictureLayerTiling* PictureLayerImpl::AddTiling(float contents_scale) { DCHECK(CanHaveTilings()); DCHECK_GE(contents_scale, MinimumContentsScale()); DCHECK_LE(contents_scale, MaximumContentsScale()); DCHECK(raster_source_->HasRecordings()); return tilings_->AddTiling(contents_scale, raster_source_); } void PictureLayerImpl::RemoveAllTilings() { tilings_->RemoveAllTilings(); // If there are no tilings, then raster scales are no longer meaningful. ResetRasterScale(); } void PictureLayerImpl::AddTilingsForRasterScale() { // Reset all resolution enums on tilings, we'll be setting new values in this // function. tilings_->MarkAllTilingsNonIdeal(); PictureLayerTiling* high_res = tilings_->FindTilingWithScale(raster_contents_scale_); // We always need a high res tiling, so create one if it doesn't exist. if (!high_res) high_res = AddTiling(raster_contents_scale_); // Try and find a low res tiling. PictureLayerTiling* low_res = nullptr; if (raster_contents_scale_ == low_res_raster_contents_scale_) low_res = high_res; else low_res = tilings_->FindTilingWithScale(low_res_raster_contents_scale_); // Only create new low res tilings when the transform is static. This // prevents wastefully creating a paired low res tiling for every new high res // tiling during a pinch or a CSS animation. bool can_have_low_res = layer_tree_impl()->create_low_res_tiling(); bool needs_low_res = !low_res; bool is_pinching = layer_tree_impl()->PinchGestureActive(); bool is_animating = draw_properties().screen_space_transform_is_animating; if (can_have_low_res && needs_low_res && !is_pinching && !is_animating) low_res = AddTiling(low_res_raster_contents_scale_); // Set low-res if we have one. if (low_res && low_res != high_res) low_res->set_resolution(LOW_RESOLUTION); // Make sure we always have one high-res (even if high == low). high_res->set_resolution(HIGH_RESOLUTION); if (layer_tree_impl()->IsPendingTree()) { // On the pending tree, drop any tilings that are non-ideal since we don't // need them to activate anyway. tilings_->RemoveNonIdealTilings(); } SanityCheckTilingState(); } bool PictureLayerImpl::ShouldAdjustRasterScale() const { if (was_screen_space_transform_animating_ != draw_properties().screen_space_transform_is_animating) return true; if (draw_properties().screen_space_transform_is_animating && raster_contents_scale_ != ideal_contents_scale_ && ShouldAdjustRasterScaleDuringScaleAnimations()) return true; bool is_pinching = layer_tree_impl()->PinchGestureActive(); if (is_pinching && raster_page_scale_) { // We change our raster scale when it is: // - Higher than ideal (need a lower-res tiling available) // - Too far from ideal (need a higher-res tiling available) float ratio = ideal_page_scale_ / raster_page_scale_; if (raster_page_scale_ > ideal_page_scale_ || ratio > kMaxScaleRatioDuringPinch) return true; } if (!is_pinching) { // When not pinching, match the ideal page scale factor. if (raster_page_scale_ != ideal_page_scale_) return true; } // Always match the ideal device scale factor. if (raster_device_scale_ != ideal_device_scale_) return true; // When the source scale changes we want to match it, but not when animating // or when we've fixed the scale in place. if (!draw_properties().screen_space_transform_is_animating && !raster_source_scale_is_fixed_ && raster_source_scale_ != ideal_source_scale_) return true; if (raster_contents_scale_ > MaximumContentsScale()) return true; if (raster_contents_scale_ < MinimumContentsScale()) return true; return false; } void PictureLayerImpl::RecalculateRasterScales() { float old_raster_contents_scale = raster_contents_scale_; float old_raster_page_scale = raster_page_scale_; float old_raster_source_scale = raster_source_scale_; raster_device_scale_ = ideal_device_scale_; raster_page_scale_ = ideal_page_scale_; raster_source_scale_ = ideal_source_scale_; raster_contents_scale_ = ideal_contents_scale_; // If we're not animating, or leaving an animation, and the // ideal_source_scale_ changes, then things are unpredictable, and we fix // the raster_source_scale_ in place. if (old_raster_source_scale && !draw_properties().screen_space_transform_is_animating && !was_screen_space_transform_animating_ && old_raster_source_scale != ideal_source_scale_) raster_source_scale_is_fixed_ = true; // TODO(danakj): Adjust raster source scale closer to ideal source scale at // a throttled rate. Possibly make use of invalidation_.IsEmpty() on pending // tree. This will allow CSS scale changes to get re-rastered at an // appropriate rate. (crbug.com/413636) if (raster_source_scale_is_fixed_) { raster_contents_scale_ /= raster_source_scale_; raster_source_scale_ = 1.f; } // During pinch we completely ignore the current ideal scale, and just use // a multiple of the previous scale. bool is_pinching = layer_tree_impl()->PinchGestureActive(); if (is_pinching && old_raster_contents_scale) { // See ShouldAdjustRasterScale: // - When zooming out, preemptively create new tiling at lower resolution. // - When zooming in, approximate ideal using multiple of kMaxScaleRatio. bool zooming_out = old_raster_page_scale > ideal_page_scale_; float desired_contents_scale = old_raster_contents_scale; if (zooming_out) { while (desired_contents_scale > ideal_contents_scale_) desired_contents_scale /= kMaxScaleRatioDuringPinch; } else { while (desired_contents_scale < ideal_contents_scale_) desired_contents_scale *= kMaxScaleRatioDuringPinch; } raster_contents_scale_ = tilings_->GetSnappedContentsScale( desired_contents_scale, kSnapToExistingTilingRatio); raster_page_scale_ = raster_contents_scale_ / raster_device_scale_ / raster_source_scale_; } // If we're not re-rasterizing during animation, rasterize at the maximum // scale that will occur during the animation, if the maximum scale is // known. However we want to avoid excessive memory use. If the scale is // smaller than what we would choose otherwise, then it's always better off // for us memory-wise. But otherwise, we don't choose a scale at which this // layer's rastered content would become larger than the viewport. if (draw_properties().screen_space_transform_is_animating && !ShouldAdjustRasterScaleDuringScaleAnimations()) { bool can_raster_at_maximum_scale = false; bool should_raster_at_starting_scale = false; float maximum_scale = draw_properties().maximum_animation_contents_scale; float starting_scale = draw_properties().starting_animation_contents_scale; if (maximum_scale) { gfx::Size bounds_at_maximum_scale = gfx::ToCeiledSize( gfx::ScaleSize(raster_source_->GetSize(), maximum_scale)); int64 maximum_area = static_cast<int64>(bounds_at_maximum_scale.width()) * static_cast<int64>(bounds_at_maximum_scale.height()); gfx::Size viewport = layer_tree_impl()->device_viewport_size(); int64 viewport_area = static_cast<int64>(viewport.width()) * static_cast<int64>(viewport.height()); if (maximum_area <= viewport_area) can_raster_at_maximum_scale = true; } if (starting_scale && starting_scale > maximum_scale) { gfx::Size bounds_at_starting_scale = gfx::ToCeiledSize( gfx::ScaleSize(raster_source_->GetSize(), starting_scale)); int64 start_area = static_cast<int64>(bounds_at_starting_scale.width()) * static_cast<int64>(bounds_at_starting_scale.height()); gfx::Size viewport = layer_tree_impl()->device_viewport_size(); int64 viewport_area = static_cast<int64>(viewport.width()) * static_cast<int64>(viewport.height()); if (start_area <= viewport_area) should_raster_at_starting_scale = true; } // Use the computed scales for the raster scale directly, do not try to use // the ideal scale here. The current ideal scale may be way too large in the // case of an animation with scale, and will be constantly changing. if (should_raster_at_starting_scale) raster_contents_scale_ = starting_scale; else if (can_raster_at_maximum_scale) raster_contents_scale_ = maximum_scale; else raster_contents_scale_ = 1.f * ideal_page_scale_ * ideal_device_scale_; } raster_contents_scale_ = std::max(raster_contents_scale_, MinimumContentsScale()); raster_contents_scale_ = std::min(raster_contents_scale_, MaximumContentsScale()); DCHECK_GE(raster_contents_scale_, MinimumContentsScale()); DCHECK_LE(raster_contents_scale_, MaximumContentsScale()); // If this layer would create zero or one tiles at this content scale, // don't create a low res tiling. gfx::Size raster_bounds = gfx::ToCeiledSize( gfx::ScaleSize(raster_source_->GetSize(), raster_contents_scale_)); gfx::Size tile_size = CalculateTileSize(raster_bounds); bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() && tile_size.height() >= raster_bounds.height(); if (tile_size.IsEmpty() || tile_covers_bounds) { low_res_raster_contents_scale_ = raster_contents_scale_; return; } float low_res_factor = layer_tree_impl()->settings().low_res_contents_scale_factor; low_res_raster_contents_scale_ = std::max(raster_contents_scale_ * low_res_factor, MinimumContentsScale()); DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_); DCHECK_GE(low_res_raster_contents_scale_, MinimumContentsScale()); DCHECK_LE(low_res_raster_contents_scale_, MaximumContentsScale()); } void PictureLayerImpl::CleanUpTilingsOnActiveLayer( const std::vector<PictureLayerTiling*>& used_tilings) { DCHECK(layer_tree_impl()->IsActiveTree()); if (tilings_->num_tilings() == 0) return; float min_acceptable_high_res_scale = std::min( raster_contents_scale_, ideal_contents_scale_); float max_acceptable_high_res_scale = std::max( raster_contents_scale_, ideal_contents_scale_); PictureLayerImpl* twin = GetPendingOrActiveTwinLayer(); if (twin && twin->CanHaveTilings()) { min_acceptable_high_res_scale = std::min( min_acceptable_high_res_scale, std::min(twin->raster_contents_scale_, twin->ideal_contents_scale_)); max_acceptable_high_res_scale = std::max( max_acceptable_high_res_scale, std::max(twin->raster_contents_scale_, twin->ideal_contents_scale_)); } PictureLayerTilingSet* twin_set = twin ? twin->tilings_.get() : nullptr; tilings_->CleanUpTilings( min_acceptable_high_res_scale, max_acceptable_high_res_scale, used_tilings, layer_tree_impl()->create_low_res_tiling(), twin_set); DCHECK_GT(tilings_->num_tilings(), 0u); SanityCheckTilingState(); } float PictureLayerImpl::MinimumContentsScale() const { float setting_min = layer_tree_impl()->settings().minimum_contents_scale; // If the contents scale is less than 1 / width (also for height), // then it will end up having less than one pixel of content in that // dimension. Bump the minimum contents scale up in this case to prevent // this from happening. int min_dimension = std::min(raster_source_->GetSize().width(), raster_source_->GetSize().height()); if (!min_dimension) return setting_min; return std::max(1.f / min_dimension, setting_min); } float PictureLayerImpl::MaximumContentsScale() const { // Masks can not have tilings that would become larger than the // max_texture_size since they use a single tile for the entire // tiling. Other layers can have tilings of any scale. if (!is_mask_) return std::numeric_limits<float>::max(); int max_texture_size = layer_tree_impl()->resource_provider()->max_texture_size(); float max_scale_width = static_cast<float>(max_texture_size) / bounds().width(); float max_scale_height = static_cast<float>(max_texture_size) / bounds().height(); float max_scale = std::min(max_scale_width, max_scale_height); // We require that multiplying the layer size by the contents scale and // ceiling produces a value <= |max_texture_size|. Because for large layer // sizes floating point ambiguity may crop up, making the result larger or // smaller than expected, we use a slightly smaller floating point value for // the scale, to help ensure that the resulting content bounds will never end // up larger than |max_texture_size|. return nextafterf(max_scale, 0.f); } void PictureLayerImpl::ResetRasterScale() { raster_page_scale_ = 0.f; raster_device_scale_ = 0.f; raster_source_scale_ = 0.f; raster_contents_scale_ = 0.f; low_res_raster_contents_scale_ = 0.f; raster_source_scale_is_fixed_ = false; } bool PictureLayerImpl::CanHaveTilings() const { if (raster_source_->IsSolidColor()) return false; if (!DrawsContent()) return false; if (!raster_source_->HasRecordings()) return false; // If the |raster_source_| has a recording it should have non-empty bounds. DCHECK(!raster_source_->GetSize().IsEmpty()); if (MaximumContentsScale() < MinimumContentsScale()) return false; return true; } void PictureLayerImpl::SanityCheckTilingState() const { #if DCHECK_IS_ON() if (!CanHaveTilings()) { DCHECK_EQ(0u, tilings_->num_tilings()); return; } if (tilings_->num_tilings() == 0) return; // We should only have one high res tiling. DCHECK_EQ(1, tilings_->NumHighResTilings()); #endif } bool PictureLayerImpl::ShouldAdjustRasterScaleDuringScaleAnimations() const { return layer_tree_impl()->use_gpu_rasterization(); } float PictureLayerImpl::MaximumTilingContentsScale() const { float max_contents_scale = tilings_->GetMaximumContentsScale(); return std::max(max_contents_scale, MinimumContentsScale()); } scoped_ptr<PictureLayerTilingSet> PictureLayerImpl::CreatePictureLayerTilingSet() { const LayerTreeSettings& settings = layer_tree_impl()->settings(); return PictureLayerTilingSet::Create( GetTree(), this, settings.max_tiles_for_interest_area, layer_tree_impl()->use_gpu_rasterization() ? settings.gpu_rasterization_skewport_target_time_in_seconds : settings.skewport_target_time_in_seconds, settings.skewport_extrapolation_limit_in_content_pixels); } void PictureLayerImpl::UpdateIdealScales() { DCHECK(CanHaveTilings()); float min_contents_scale = MinimumContentsScale(); DCHECK_GT(min_contents_scale, 0.f); ideal_page_scale_ = IsAffectedByPageScale() ? layer_tree_impl()->current_page_scale_factor() : 1.f; ideal_device_scale_ = layer_tree_impl()->device_scale_factor(); ideal_contents_scale_ = std::max(draw_properties().ideal_contents_scale, min_contents_scale); ideal_source_scale_ = ideal_contents_scale_ / ideal_page_scale_ / ideal_device_scale_; } void PictureLayerImpl::GetDebugBorderProperties( SkColor* color, float* width) const { *color = DebugColors::TiledContentLayerBorderColor(); *width = DebugColors::TiledContentLayerBorderWidth(layer_tree_impl()); } void PictureLayerImpl::GetAllPrioritizedTilesForTracing( std::vector<PrioritizedTile>* prioritized_tiles) const { if (!tilings_) return; tilings_->GetAllPrioritizedTilesForTracing(prioritized_tiles); } void PictureLayerImpl::AsValueInto( base::trace_event::TracedValue* state) const { LayerImpl::AsValueInto(state); state->SetDouble("ideal_contents_scale", ideal_contents_scale_); state->SetDouble("geometry_contents_scale", MaximumTilingContentsScale()); state->BeginArray("tilings"); tilings_->AsValueInto(state); state->EndArray(); MathUtil::AddToTracedValue("tile_priority_rect", viewport_rect_for_tile_priority_in_content_space_, state); MathUtil::AddToTracedValue("visible_rect", visible_layer_rect(), state); state->BeginArray("pictures"); raster_source_->AsValueInto(state); state->EndArray(); state->BeginArray("invalidation"); invalidation_.AsValueInto(state); state->EndArray(); state->BeginArray("coverage_tiles"); for (PictureLayerTilingSet::CoverageIterator iter( tilings_.get(), 1.f, gfx::Rect(raster_source_->GetSize()), ideal_contents_scale_); iter; ++iter) { state->BeginDictionary(); MathUtil::AddToTracedValue("geometry_rect", iter.geometry_rect(), state); if (*iter) TracedValue::SetIDRef(*iter, state, "tile"); state->EndDictionary(); } state->EndArray(); } size_t PictureLayerImpl::GPUMemoryUsageInBytes() const { return tilings_->GPUMemoryUsageInBytes(); } void PictureLayerImpl::RunMicroBenchmark(MicroBenchmarkImpl* benchmark) { benchmark->RunOnLayer(this); } WhichTree PictureLayerImpl::GetTree() const { return layer_tree_impl()->IsActiveTree() ? ACTIVE_TREE : PENDING_TREE; } bool PictureLayerImpl::IsOnActiveOrPendingTree() const { return !layer_tree_impl()->IsRecycleTree(); } bool PictureLayerImpl::HasValidTilePriorities() const { return IsOnActiveOrPendingTree() && IsDrawnRenderSurfaceLayerListMember(); } } // namespace cc
SaschaMester/delicium
cc/layers/picture_layer_impl.cc
C++
bsd-3-clause
50,012
require 'spec_helper' describe 'OrderPreferencesBuilder' do # Factory order_with_line_items is incredibly slow.. let(:order) do order = create :order create_list :line_item, 2, order:order order.line_items.reload order.update! order end let!(:adjustment) { order.adjustments.create! label: 'Descuento', amount:-10.0, order: order} let(:payment) { create :payment } let(:callback_urls) { {success: 'http://example.com/success', pending: 'http://example.com/pending', failure: 'http://example.com/failure'}} let(:payer_data) { {email: 'jmperez@devartis.com'}} include ActionView::Helpers::TextHelper include ActionView::Helpers::SanitizeHelper include Spree::ProductsHelper context "Calling preferences_hash" do subject { Spree::MercadoPago::OrderPreferencesBuilder.new(order, payment, callback_urls, payer_data).preferences_hash } it 'should return external reference' do expect(subject).to include(external_reference:payment.identifier) end it 'should set callback urls' do expect(subject).to include(back_urls:callback_urls) end it 'should set payer data if brought' do expect(subject).to include(payer: payer_data) end it 'should set an item for every line item' do expect(subject).to include(:items) order.line_items.each do |line_item| expect(subject[:items]).to include({ title: line_item_description_text(line_item.variant.product.name), unit_price: line_item.price.to_f, quantity: line_item.quantity.to_f, currency_id: 'ARS' }) end end it 'should set its adjustments as items' do expect(subject[:items]).to include({ title: line_item_description_text(adjustment.label), unit_price: adjustment.amount.to_f, quantity: 1, currency_id: 'ARS' }) end it 'should only have line items and adjustments in items' do expect(subject[:items]).to have(order.line_items.count + order.adjustments.count).items end end end
devartis/Spree-Mercado-Pago-payment-method
spec/models/spree/mercado_pago/order_preferences_builder_spec.rb
Ruby
bsd-3-clause
2,062
#from django.conf import settings #settings.INSTALLED_APPS += ("mptt", "hvad", "galleries",)
marcopompili/django-market
django_market/__init__.py
Python
bsd-3-clause
94
package com.andymark.crosslink; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class UpdateJaguarPacket implements Message { private short[] uiMode = new short[20]; private short[] uiSetVoltage = new short[20]; @Override public ByteBuffer getMessage() { for (int i = 16; i < 20; i++) { uiMode[i] = (short) 0xffff; } uiSetVoltage[1] = (short) 0x1999; ByteBuffer buffer = ByteBuffer.allocate(86); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) 0xaaa0); // sig buffer.putShort((short) 86); // byte len for (short val : uiMode) { buffer.putShort(val); } for (short val : uiSetVoltage) { buffer.putShort(val); } short checksum = (short) Utilities.checksum(buffer, 0, 84); buffer.putShort(checksum); return buffer; } }
AndyMark/AMCrosslink-Java
src/com/andymark/crosslink/UpdateJaguarPacket.java
Java
bsd-3-clause
811
function installthis(id) { var answer = confirm('Are you sure ? '); if (answer){ //delete img... $.post(base_url+'/zfmodules/index/installmod/id/'+id, function(data){ window.location.reload(false); }); } } function installnotvalidthis(id) { var answer = confirm('Your module is not valid,\n if you continue, it\'s will be installed to another unique name,\n Are You sure ?'); if (answer){ //delete img... $.post(base_url+'/zfmodules/index/installmodtovalid/id/'+id, function(data){ window.location.reload(false); }); } }
samsonasik/zf_111_support_php532_with_modulewizard
public/themes/zend_prj/js/modules/modules.js
JavaScript
bsd-3-clause
751
from rdr_service.model.genomics import GenomicGCValidationMetrics, GenomicSetMember from rdr_service.tools.tool_libs.tool_base import cli_run, ToolBase tool_cmd = 'backfill-gvcf' tool_desc = 'Backfill the gVCF paths in genomic_gc_validation_metrics' class GVcfBackfillTool(ToolBase): def run(self): super(GVcfBackfillTool, self).run() # Get list of paths path_list = self.get_paths_from_file() for path in path_list: sample_id = self.get_sample_id_from_gvcf_path(path) metric = self.get_metric_from_sample_id(sample_id) self.update_metric_gvcf_path(metric, path) def get_paths_from_file(self): path_set = set() with open(self.args.input_file, encoding='utf-8-sig') as f: lines = f.readlines() for line in lines: path_set.add(line.strip()) return list(path_set) @staticmethod def get_sample_id_from_gvcf_path(path): # Based on naming convention: # gs://prod-genomics-data-northwest/Wgs_sample_raw_data/ # SS_VCF_research/UW_A100329930_21055000718_702252_v1.hard-filtered.gvcf.gz return path.split("_")[7] def get_metric_from_sample_id(self, sample_id): with self.get_session() as session: return session.query(GenomicGCValidationMetrics).join( GenomicSetMember, GenomicSetMember.id == GenomicGCValidationMetrics.genomicSetMemberId ).filter( GenomicSetMember.sampleId == sample_id ).one_or_none() def update_metric_gvcf_path(self, metric, path): if self.args.md5: metric.gvcfMd5Received = 1 metric.gvcfMd5Path = path else: metric.gvcfReceived = 1 metric.gvcfPath = path with self.get_session() as session: session.merge(metric) def add_additional_arguments(parser): parser.add_argument('--input-file', required=True, help='path of text file with list of gVCF paths') parser.add_argument('--md5', required=False, action="store_true", help='backfilling md5 files') def run(): return cli_run(tool_cmd, tool_desc, GVcfBackfillTool, add_additional_arguments)
all-of-us/raw-data-repository
rdr_service/tools/tool_libs/backfill_gvcf_paths.py
Python
bsd-3-clause
2,248
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This clang plugin checks various invariants of the Blink garbage // collection infrastructure. // // Checks that are implemented: // [currently none] #include "Config.h" #include "clang/AST/AST.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendPluginRegistry.h" using namespace clang; using std::string; namespace { struct BlinkGCPluginOptions { BlinkGCPluginOptions() { } }; // Main class containing checks for various invariants of the Blink // garbage collection infrastructure. class BlinkGCPluginConsumer : public ASTConsumer { public: BlinkGCPluginConsumer(CompilerInstance& instance, const BlinkGCPluginOptions& options) { } virtual void HandleTranslationUnit(ASTContext& context) { // FIXME: implement consistency checks. } }; class BlinkGCPluginAction : public PluginASTAction { public: BlinkGCPluginAction() { } protected: // Overridden from PluginASTAction: virtual ASTConsumer* CreateASTConsumer(CompilerInstance& instance, llvm::StringRef ref) { return new BlinkGCPluginConsumer(instance, options_); } virtual bool ParseArgs(const CompilerInstance& instance, const std::vector<string>& args) { bool parsed = true; for (size_t i = 0; i < args.size() && parsed; ++i) { if (args[i] == "enable-oilpan") { // TODO: Remove this once all transition types are eliminated. Config::set_oilpan_enabled(true); } else { parsed = false; llvm::errs() << "Unknown blink-gc-plugin argument: " << args[i] << "\n"; } } return parsed; } private: BlinkGCPluginOptions options_; }; } // namespace bool Config::oilpan_enabled_ = false; static FrontendPluginRegistry::Add<BlinkGCPluginAction> X("blink-gc-plugin", "Check Blink GC invariants");
ChromiumWebApps/chromium
tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp
C++
bsd-3-clause
2,082
using Shuttle.Core.Data; using Shuttle.Core.Infrastructure; namespace Shuttle.Scheduling { public class ScheduleQuery : IScheduleQuery { private readonly IDatabaseGateway _databaseGateway; private readonly IScheduleQueryFactory _queryFactory; public ScheduleQuery(IDatabaseGateway databaseGateway, IScheduleQueryFactory queryFactory) { Guard.AgainstNull(databaseGateway, "databaseGateway"); Guard.AgainstNull(queryFactory, "queryFactory"); _databaseGateway = databaseGateway; _queryFactory = queryFactory; } public bool HasScheduleStructures(DataSource source) { return _databaseGateway.GetScalarUsing<int>(source, _queryFactory.HasScheduleStructures()) == 1; } } }
yonglehou/shuttle-scheduling
Shuttle.Scheduling/DataAccess/Queries/ScheduleQuery.cs
C#
bsd-3-clause
703
#!/usr/bin/python2 """Syncs to a given Cobalt build id. Syncs current gclient instance to a given build id, as generated by "build_id.py" and stored on carbon-airlock-95823. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import json import os import shutil import subprocess import sys import requests _BUILD_ID_QUERY_URL = ( "https://carbon-airlock-95823.appspot.com/build_version/search") _BUILD_ID_QUERY_PARAMETER_NAME = "build_number" class SubprocessFailedException(Exception): """Exception for non-zero subprocess exits.""" def __init__(self, command): super(SubprocessFailedException, self).__init__() # pylint: disable=super-with-arguments self.command = command def __str__(self): return "Subprocess failed '{0}'".format(self.command) def _RunGitCommand(gitargs, **kwargs): """Runs a git command with "gitargs", returning the output splitlines(). Args: gitargs: Commandline args that follow 'git'. **kwargs: Keyword args for Popen. Returns: All of stdout, as an array of lines. Raises: SubprocessFailedException: if the exit code is nonzero. """ result_tuple = _RunGitCommandReturnExitCode(gitargs, **kwargs) if result_tuple[0] != 0: raise SubprocessFailedException(" ".join(["git"] + gitargs)) return result_tuple[1] def _RunGitCommandReturnExitCode(gitargs, **kwargs): """Runs a git command with "gitargs", returning the exit code and output. Args: gitargs: Commandline args that follow 'git'. **kwargs: Keyword args for Popen. Returns: Tuple of (exit code, all of stdout as an array of lines). """ popen_args = ["git"] + gitargs with subprocess.Popen(popen_args, stdout=subprocess.PIPE, **kwargs) as p: output = p.stdout.read().splitlines() return p.wait(), output def main(): dev_null = open(os.devnull, "w") # pylint: disable=consider-using-with arg_parser = argparse.ArgumentParser( description="Syncs to a given Cobalt build id") arg_parser.add_argument("buildid", nargs=1) arg_parser.add_argument( "--force", default=False, action="store_true", help="Deletes directories that don't match the requested format.") args = arg_parser.parse_args() r = requests.get( _BUILD_ID_QUERY_URL, params={_BUILD_ID_QUERY_PARAMETER_NAME: args.buildid[0]}) if not r.ok: print( "HTTP request failed\n{0} {1}\n{2}".format(r.status_code, r.reason, r.text), file=sys.stderr) return 1 # The response starts with a security-related close expression line outer_json = json.loads(r.text.splitlines()[1]) hashes = json.loads(outer_json["deps"]) git_root = os.getcwd() for relpath, rep_hash in hashes.items(): path = os.path.normpath(os.path.join(git_root, relpath)) if not os.path.exists(path): # No warning in this case, we will attempt to clone the repository in # the next pass through the repos. continue is_dirty = ( bool( _RunGitCommandReturnExitCode(["diff", "--no-ext-diff", "--quiet"], cwd=path, stderr=dev_null)[0]) or bool( _RunGitCommandReturnExitCode( ["diff", "--no-ext-diff", "--quiet", "--cached"], cwd=path, stderr=dev_null)[0])) if is_dirty: print("{0} is dirty, please resolve".format(relpath)) return 1 (requested_repo, _) = rep_hash.split("@") remote_url = _RunGitCommand(["config", "--get", "remote.origin.url"], cwd=path)[0].strip().decode("utf-8") if requested_repo.endswith(".git"): if remote_url + ".git" == requested_repo: print(("WARNING: You are syncing to {0} instead of {1}. While these " "point to the same repo, the differing extension will cause " "different build ids to be generated. If you need the same " "id, you'll need to specifically clone {0} (note the .git " "extension).").format(requested_repo, remote_url)) remote_url += ".git" if remote_url != requested_repo: if args.force and path != git_root: shutil.rmtree(path) else: print(("{0} exists but does not point to the requested repo for that " "path, {1}. Either replace that directory manually or run this " "script with --force. --force will not try to remove the top " "level repository.").format(path, requested_repo)) return 1 for relpath, rep_hash in hashes.items(): path = os.path.normpath(os.path.join(git_root, relpath)) # repo_hash has a repo path prefix like this: # 'https://chromium.googlesource.com/chromium/llvm-project/libcxx.git # @48198f9110397fff47fe7c37cbfa296be7d44d3d' (requested_repo, requested_hash) = rep_hash.split("@") if not os.path.exists(path): print("Missing path {0}, cloning from {1}.".format(path, requested_repo)) try: # The clone command will create all missing directories leading to the # path. If the clone is successful, we continue on as usual and let # the subsequent logic here checkout the appropriate git hash. _RunGitCommand(["clone", "-q", requested_repo, path]) except SubprocessFailedException: print("There was an error cloning the repository.") continue current_hash = _RunGitCommand(["rev-parse", "HEAD"], cwd=path)[0] if requested_hash == current_hash: continue symbolic_ref = None try: symbolic_ref = _RunGitCommand(["symbolic-ref", "--short", "-q", "HEAD"], cwd=path, stderr=dev_null)[0] except SubprocessFailedException: pass user_visible_commit = symbolic_ref if symbolic_ref else current_hash[0:7] print("{0} was at {1} now {2}".format(path, user_visible_commit, requested_hash[0:7])) _RunGitCommand(["checkout", "-q", "--detach", requested_hash], cwd=path) return 0 if __name__ == "__main__": try: sys.exit(main()) except SubprocessFailedException as ex: print(str(ex), file=sys.stderr) sys.exit(1)
youtube/cobalt
cobalt/build/sync_to_build_id.py
Python
bsd-3-clause
6,399
package ca.carleton.gcrc.couch.command; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.StringWriter; import java.util.Calendar; import org.json.JSONObject; import org.json.JSONTokener; import ca.carleton.gcrc.couch.command.impl.FileSetManifest; import ca.carleton.gcrc.couch.command.impl.PathComputer; import ca.carleton.gcrc.couch.command.impl.UpgradeOperations; import ca.carleton.gcrc.couch.command.impl.UpgradeOperationsBasic; import ca.carleton.gcrc.couch.command.impl.UpgradeOperationsNull; import ca.carleton.gcrc.couch.command.impl.UpgradeOperationsReporting; import ca.carleton.gcrc.couch.command.impl.UpgradeProcess; import ca.carleton.gcrc.couch.command.impl.UpgradeReport; import ca.carleton.gcrc.utils.StreamUtils; public class CommandUpgrade implements Command { @Override public String getCommandString() { return "upgrade"; } @Override public boolean matchesKeyword(String keyword) { if( getCommandString().equalsIgnoreCase(keyword) ) { return true; } return false; } @Override public boolean isDeprecated() { return false; } @Override public String[] getExpectedOptions() { return new String[]{ Options.OPTION_ATLAS_DIR ,Options.OPTION_NO_CONFIG ,Options.OPTION_TEST }; } @Override public boolean requiresAtlasDir() { return true; } @Override public void reportHelp(PrintStream ps) { ps.println("Nunaliit2 Atlas Framework - Upgrade Command"); ps.println(); ps.println("The upgrade command allows a user to modifies the files located in an atlas"); ps.println("so that they correspond to a different version of Nunaliit. This command"); ps.println("should be used when a newer version of Nunaliit is available and the"); ps.println("atlas creator wishes to use the newer version."); ps.println(); ps.println("Command Syntax:"); ps.println(" nunaliit upgrade <options>"); ps.println(); ps.println("options:"); ps.println(" "+Options.OPTION_TEST); ps.println(" Does not perform any changes. Simply print what would happen. Does "); ps.println(" not run 'config' command."); ps.println(); ps.println(" "+Options.OPTION_NO_CONFIG); ps.println(" Supresses the automatic 'config' command after completing upgrade"); ps.println(" process."); ps.println(); CommandHelp.reportGlobalOptions(ps,getExpectedOptions()); } @Override public void runCommand( GlobalSettings gs ,Options options ) throws Exception { if( options.getArguments().size() > 1 ){ throw new Exception("Unexpected argument: "+options.getArguments().get(1)); } // Pick up options boolean noConfig = false; if( null != options.getNoConfig() ){ noConfig = options.getNoConfig().booleanValue(); } boolean justTest = false; if( null != options.getTest() ){ justTest = options.getTest().booleanValue(); } File atlasDir = gs.getAtlasDir(); // Verify that content directory is available (contentDir includes new // versions for files under docs and htdocs) File contentDir = PathComputer.computeContentDir( gs.getInstallDir() ); if( null == contentDir || false == contentDir.exists() || false == contentDir.isDirectory() ){ throw new Exception("Unable to find content directory"); } // Verify that the installation directory is available (installationFilesDir includes // new versions of files under the templates directory. These are files that should not // be upgraded, just installed once). File installationFilesDir = PathComputer.computeTemplatesDir( gs.getInstallDir() ); if( null == installationFilesDir || false == installationFilesDir.exists() || false == installationFilesDir.isDirectory() ){ throw new Exception("Unable to find installation files directory"); } // Compute upgrade directory File upgradeCollisionDir = null; { Calendar calendar = Calendar.getInstance(); String name = String.format( "upgrade_%04d-%02d-%02d_%02d:%02d:%02d" ,calendar.get(Calendar.YEAR) ,(calendar.get(Calendar.MONTH)+1) ,calendar.get(Calendar.DAY_OF_MONTH) ,calendar.get(Calendar.HOUR_OF_DAY) ,calendar.get(Calendar.MINUTE) ,calendar.get(Calendar.SECOND) ); upgradeCollisionDir = new File(atlasDir, "upgrade/"+name); } // Figure out upgrade operations UpgradeOperations operations = null; if( justTest ) { operations = new UpgradeOperationsNull(); } else { operations = new UpgradeOperationsBasic( atlasDir ,contentDir ,upgradeCollisionDir ); } // Figure out reporting level UpgradeOperationsReporting reporting = new UpgradeOperationsReporting( atlasDir ,upgradeCollisionDir ,operations ,gs.getOutStream() ); if( justTest ) { reporting.setReportOperations(true); reporting.setReportCollisions(false); } // Compute installed file manifest FileSetManifest installedFileSetManifest = new FileSetManifest(); try { File configDir = new File(atlasDir,"config"); File manifestFile = new File(configDir,"nunaliit_manifest.json"); if( manifestFile.exists() ){ StringWriter sw = new StringWriter(); FileInputStream is = null; InputStreamReader isr = null; try { is = new FileInputStream(manifestFile); isr = new InputStreamReader(is, "UTF-8"); StreamUtils.copyStream(isr, sw); sw.flush(); JSONTokener tokener = new JSONTokener(sw.toString()); Object result = tokener.nextValue(); if( result instanceof JSONObject ){ JSONObject jsonManifest = (JSONObject)result; installedFileSetManifest = FileSetManifest.fromJSON(jsonManifest); } else { throw new Exception("Unexpected JSON found in manifext file: "+result.getClass().getName()); } } catch (Exception e) { throw new Exception("Error while reading file: "+manifestFile.getName(), e); } finally { if( null != isr ) { try { isr.close(); } catch (Exception e) { // Ignore } } if( null != is ) { try { is.close(); } catch (Exception e) { // Ignore } } } } } catch(Exception e) { throw new Exception("Unable to load installed file manifest",e); } // Upgrade content try { UpgradeProcess upgradeProcess = new UpgradeProcess(); upgradeProcess.setUpgradedFilesDir(contentDir); upgradeProcess.setInstallationFilesDir(installationFilesDir); upgradeProcess.setTargetDir(atlasDir); upgradeProcess.setInstalledManifest(installedFileSetManifest); UpgradeReport upgradeReport = upgradeProcess.computeUpgrade(); UpgradeProcess.performUpgrade( upgradeReport ,reporting ); } catch(Exception e) { throw new Exception("Unable to upgrade content",e); } // Perform configuration, unless disabled if( false == noConfig && false == justTest ){ CommandConfig config = new CommandConfig(); Options configOptions = new Options(); config.runCommand(gs, configOptions); } } }
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/CommandUpgrade.java
Java
bsd-3-clause
7,080
class LineItemController < ApplicationController end
voidstart/ror_depot_reboot_1
app/controllers/line_item_controller.rb
Ruby
bsd-3-clause
53
from models import * from django.db import connection import collections import time import calendar def GetCreditCardList(contactid): cards_list = [] orders = Orders.objects.all().filter(ocustomerid = contactid) cards_hash = {} for order in orders: if order.ocardno: if order.ocardno not in cards_hash: cards_hash[order.ocardno] = "Card Ending in %s" %order.ocardno[-4:] # Preparing Cards List cards_list = [] for key, value in cards_hash.items(): cards_list.append((key, value)) return cards_list def GenerateShippingCalander(): month = [['', '', '','','', '', ''], ['', '', '','','', '', ''], ['', '', '','','', '', ''], ['', '', '','','', '', ''], ['', '', '','','', '', ''], ['', '', '','','', '', ''], ] today = time.localtime().tm_mday start_time = time.strptime("2013/06/01", "%Y/%m/01") day = start_time.tm_mday wday = start_time.tm_wday last_day = calendar.monthrange(start_time.tm_year, start_time.tm_mon)[1] row_no = 0 while day <= last_day: cur_time = time.strptime(time.strftime("%Y/%m/" + str(day), start_time), "%Y/%m/%d") day = cur_time.tm_mday wday = cur_time.tm_wday script = '' bgcolor = "#FFFFFF" if day < today: bgcolor = "#999999" elif day == today: bgcolor = "#CC9966" elif day == today + 1: bgcolor = "#99CC00" script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time) elif day == today + 2: bgcolor = "#663366" script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time) elif day > today + 2: bgcolor = "#00CCCC" script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time) if day >= today: if wday == 6: bgcolor = "#DB9E9B" script = '' elif wday == 5: script = time.strftime("%m/" + str(day).zfill(2) + "/%Y", start_time) bgcolor = "#FFCC33" day_hash = {'wday': wday, 'day': day, 'bgcolor':bgcolor, 'script':script} month[row_no][wday] = day_hash if wday == 6: row_no += 1 day += 1 return month def GetPriorityShippingCharge(category_id): shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0] return shipping_cat_obj.priority_shipping def GetSaturdayShippingCharge(category_id): shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0] return shipping_cat_obj.saturday_delivery def GetAlaskaShippingCharge(category_id): shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0] return shipping_cat_obj.alaska_delivery class Error(object): def __init__(self): self.IsError = False self._error_number = 0 self._error_message = '' def RaiseError(self, p_message): self.IsError = True self._error_message = p_message def Error(self): self.IsError = False; msg = self._error_message self._error_message = "" return msg class StoreCredit(object): def __init__(self): self.id = 0 self.credit_value = 0.0 class MyShippingCategory(object): def __init__(self): self.id = -1 self.shipping_charge = 0.0 self.fuel_charge = 0.0 self.tax = 0.0 self.tax_value = 0.0 self.promotions = 0.0 self.shipping_value = 0.0 self.supplies_total = 0.0 self.freeshipping_diff = 0.0 self.shipping_items = [] class CartInfo(Error): '''Holds final order summary of the Cart''' def __init__(self): super(CartInfo, self).__init__() self.subtotal = 0.0 self.shipping_total = 0.0 self.fuelcharge_total = 0.0 self.tax_total = 0.0 self.promotions_total = 0 self.store_credit = 0.0 self.order_total = 0.0 self.is_storecredit_applied = False self.store_credit_id = 0 self.store_credit = 0.0 self.cc_approval_code = '' def ApplyStoreCredit(self, obj): self.store_credit_id = obj.id credit_value = obj.credit_value self.store_credit = credit_value if self.order_total >= self.store_credit: self.order_total -= self.store_credit self.store_credit = 0 elif self.order_total < self.store_credit and self.order_total > 0: self.store_credit -= self.order_total self.order_total = 0 def GetShippingCategoryID(self, catalog_id): #pc_object = ProductCategory.objects.get(catalogid=catalog_id) #psc_object = ProductShippingCategories.objects.get(product_category_id = pc_object.categoryid) cursor = connection.cursor() cursor.execute("SELECT psc.shipping_category_id, sc.category_name FROM product_shipping_categories psc " "inner join product_category pc on (psc.product_category_id = pc.categoryid) " "inner join shipping_category sc on (psc.shipping_category_id = sc.id)" "where product_category_id in (SELECT categoryid FROM product_category WHERE catalogid = %d) " %catalog_id) row = cursor.fetchone() cursor.close() shipping_category_id = row[0] shipping_category_name = row[1] return shipping_category_id, shipping_category_name def Add(self, cart_dict, catalog_id): items_dict = cart_dict # key is ItemID and value is CartItem object if catalog_id in items_dict.keys(): cart_item = items_dict[catalog_id] # Checking whether the one more item is allowed the the existing quantity. if (cart_item.quantity + 1) > cart_item.qoh: self.RaiseError("Quantity out of order. You can not add more items.") return items_dict cart_item.quantity += 1 items_dict[catalog_id] = cart_item else: cart_item = CartItem(catalog_id) if cart_item.qoh <= 0: self.RaiseError("Quantity is out of order") return cart_dict cart_item.shipping_category, cart_item.shipping_category_name = self.GetShippingCategoryID(catalog_id) cart_item.quantity = 1 items_dict[catalog_id] = cart_item return items_dict def Delete(self, cart_dict, catalog_id): del cart_dict[catalog_id] return cart_dict def Update(self, cart_dict, catalog_id, quantity): cart_item = cart_dict[catalog_id] if quantity <= 0: self.RaiseError("Quantity should be greater than 0 or remove from cart") return cart_dict if quantity <= cart_item.qoh: cart_item.quantity = quantity else: self.RaiseError("Quantity is out of order") return cart_dict return cart_dict def GetOrderValue(self, cart_dict): order_value = 0 for key, value in cart_dict.items(): value.CalculateTotals() order_value += value.subtotal return order_value def GetShippingCharge(self, category_id, shipping_value, state, excluded_zip_codes): shipping_charge = -1 fuel_charge = 0 free_shipping_diff = 0 shipping_cat_obj = ShippingCategory.objects.filter(id = category_id, status='ACTIVE')[0] fuel_charge = shipping_cat_obj.fuel_charge if shipping_cat_obj.is_free_shipping == 1: # Return 0 as shipping charge and also get fuel charge as Tuple shipping_charge = 0 return (shipping_charge, fuel_charge, free_shipping_diff) if shipping_cat_obj.flatrate_shipping_charge > 0.0: shipping_charge = shipping_cat_obj.flatrate_shipping_charge return (shipping_charge, fuel_charge, free_shipping_diff) # Fetching Rules. shipping_charge_objs = ShippingCharges.objects.filter(shipping_category_id = category_id, order_total_min__lte = shipping_value, order_total_max__gte = shipping_value, shipping_state = state) # Calculating shipping charge as per the rules. # If no rules, applying flat_rate shipping charge if shipping_charge_objs: shp_charge_obj = shipping_charge_objs[0] shipping_charge = shp_charge_obj.shipping_charge else: shipping_charge = shp_charge_obj.flatrate_shipping_charge # Calculating free shipping suggestion. if shipping_charge > 0: shipping_charge_objs = ShippingCharges.objects.filter(shipping_category_id = category_id, shipping_charge = 0, shipping_state = state) if shipping_charge_objs: shp_charge_obj = shipping_charge_objs[0] free_shipping_diff = (shp_charge_obj.order_total_min - shipping_value) else: free_shipping_diff = 0 return (shipping_charge, fuel_charge, free_shipping_diff) def GetItemsByShippingCategory(self, cart_dict): items_dict = cart_dict state = 'FL' excluded_zips = [] tax_list = Tax.objects.filter(tax_country = 'US', tax_state = state) if tax_list: tax = tax_list[0].tax_value1 else: tax = 7.0 # Dictionary contains shipping category id as a key and a list of items as values. shipping_categories_dict = {} shipping_cat_names_hash = {} # Collecting Category wise Items for key, item in items_dict.items(): item.CalculateTotals() shipping_category_id = item.shipping_category if item.shipping_category in shipping_categories_dict: shipping_categories_dict[item.shipping_category].append(item) else: shipping_categories_dict[item.shipping_category] = [item] shipping_cat_names_hash[item.shipping_category] = item.shipping_category_name # Calculating Shipping Charge, Fuel Charge and Tax for each category my_shipping_obj_list = [] for key, value in shipping_categories_dict.items(): shipping_category = MyShippingCategory() shipping_category.id = key shipping_category.name = shipping_cat_names_hash[key] shipping_category.shipping_items = value # Calculating Shipping Value for item in shipping_category.shipping_items: shipping_category.shipping_value += float(item.subtotal) (shipping_category.shipping_charge, shipping_category.fuel_charge, shipping_category.freeshipping_diff) = self.GetShippingCharge(shipping_category.id, shipping_category.shipping_value, state, excluded_zips) shipping_category.tax = tax shipping_category.tax_value = (shipping_category.shipping_value * shipping_category.tax)/100 shipping_category.supplies_total = (shipping_category.shipping_value + shipping_category.shipping_charge + shipping_category.fuel_charge + shipping_category.tax_value - shipping_category.promotions) self.subtotal += shipping_category.shipping_value self.shipping_total += shipping_category.shipping_charge self.fuelcharge_total += shipping_category.fuel_charge self.tax_total += shipping_category.tax_value self.promotions_total += shipping_category.promotions my_shipping_obj_list.append(shipping_category) self.order_total = self.subtotal + self.shipping_total + self.fuelcharge_total + self.tax_total - self.promotions_total # Applying Store Credit #if self.is_storecredit_applied: #od = collections.OrderedDict(sorted(shipping_categories_dict.items())) return my_shipping_obj_list def GetNumberOfItems(self, p_dict): cart_dict = p_dict; item_count = 0 for key, value in cart_dict.items(): item_count += value return item_count class CartItem(Error): def __init__(self, item_id=None): super(CartItem, self).__init__() self.catalog_id = -1 self.item_name = '' self.price = 0.0 self.saleprice = 0.0 self.quantity = 0 self.qoh = 0 # (Quantity on Hand) self.shipping_category = 0 self.shipping_category_name = '' self.shipping_charge = 0 self.tax_percent = 0.0 self.tax_value = 0.0 self.fuel_charge = 0.0 self.promotions = 0.0 self.is_reward_enabled = False self.reward_points = 0 self.thumbnail = '' self.image1 = '' self.image2 = '' self.image3 = '' self.extra_fied_3 = '' self.subtotal = 0.0 self.shipping_total = 0.0 self.fuel_charge_total = 0.0 self.promotions_total = 0.0 self.tax_total = 0.0 self.supplies_total = 0.0 if item_id: self.FillItem(item_id) return def CalculateTotals(self): if self.saleprice > 0: self.subtotal = self.saleprice * self.quantity else: self.subtotal = self.price * self.quantity self.shipping_total = 0.0 self.fuel_charge_total = 0.0 self.promotions_total = 0.0 self.tax_total = 0.0 self.supplies_total = 0.0 def FillItem(self, p_catalog_id): '''Fills the current class object with the data fetched from the DB. Returns: False if product not found. ''' # Fetching product from the DB. product_list = Products.objects.filter(catalogid=p_catalog_id) if not product_list: self.RaiseError("Item not found") return False product = product_list[0] #product = Products() self.catalog_id = product.catalogid self.item_name = product.name self.price = product.price self.saleprice = product.saleprice self.qoh = product.stock # (Quantity on Hand) # No need to fill the values. Will be calculated for every category. self.shipping_category = 0 self.shipping_charge = 0 self.tax_percent = 0.0 self.tax_value = 0.0 self.fuel_charge = 0.0 # Update this value when User is applied Coupon. self.promotions = 0.0 if product.reward_disable == 1: self.is_reward_enabled = False else: self.is_reward_enabled = True self.reward_points = product.reward_points self.thumbnail = product.thumbnail self.image1 = product.image1 self.image2 = product.image2 self.image3 = product.image3 self.extra_fied_3 = product.extra_field_3 #self.subtotal = 0.0 #self.shipping_total = 0.0 #self.fuel_charge_total = 0.0 #self.promotions_total = 0.0 #self.tax_total = 0.0 #self.supplies_total = 0.0 def Set(self, p_catalog_id, p_item_name, p_price, p_saleprice, p_quantity, p_qoh, p_shipping_category, p_shipping_charge, p_tax_percent, p_fuel_charge, p_promotions, p_is_rewards_enabled, p_reward_points, p_thumbnail, p_image1, p_image2, p_image3, p_extra_field_3=""): self.catalog_id = p_catalog_id self.item_name = p_item_name self.price = p_price self.saleprice = p_saleprice self.quantity = p_quantity self.qoh = p_qoh # (Quantity on Hand) self.shipping_category = p_shipping_category self.shipping_charge = p_shipping_charge self.tax_percent = p_tax_percent self.fuel_charge = p_fuel_charge self.promotions = p_promotions self.is_reward_enabled = p_is_rewards_enabled self.reward_points = p_reward_points self.thumbnail = p_thumbnail self.image1 = p_image1 self.image2 = p_image2 self.image3 = p_image3 self.extra_fied_3 = p_extra_fied_3 # # self.id = id # self.name = name # self.quantity = quantity # self.price = price # self.saleprice = saleprice # #self.fuelcharge = fuelcharge # self.fuelcharge = 2.99 * quantity # self.promotions = promotions # if saleprice <= 0 : # self.subtotal = price * quantity # else: # self.subtotal = saleprice * quantity # # self.shipping = shipping # self.tax = tax # self.taxvalue = float(self.subtotal) * float(tax)/float(100) # self.total = float(self.subtotal) + float(shipping) + self.taxvalue + self.fuelcharge - self.promotions # self.thumbnail = thumbnail # self.image1 = image1 # self.image2 = image2 # self.image3 = image3 # self.extra_field_3 = extra_field_3 # # if reward_disable == 0: # self.reward_points = reward_points # else: # self.reward_points = 0 # # product_category_list = ProductCategory.objects.filter(catalogid = id) # # logging.info(product_category_list[0].id) # if product_category_list: # category_id, category_name, parent_id = self.GetParentCategory(product_category_list[0].categoryid) # # (self.shipping, free_shipping_min_value) = self.GetShippingCharge(category_name, self.subtotal) # self.free_shipping_suggestion_val = free_shipping_min_value - self.subtotal # # # self.category_id = 0 # def GetParentCategory(self, category_id): # #SELECT category_name, category_parent from category where id = 4 # cursor = connection.cursor() # parent_id = 99999 # levels = 0 # while (parent_id > 0 and levels < 100): # cursor.execute("SELECT id, category_name, category_parent from category where id = %d" %category_id) # row = cursor.fetchone() # category_id = row[0] # category_name = row[1] # parent_id = row[2] # category_id = parent_id # levels += 1 # # return (category_id, category_name, parent_id) # # def GetShippingCharge(self, category_name, sub_total): # shipping_charge = 0.0 # free_shipping_min_value = -1 # if category_name.__contains__('Marine Life'): # free_shipping_min_value = 199 # if sub_total >= 00.01 and sub_total <= 98.99: # shipping_charge = 34.99 # elif sub_total >= 99.00 and sub_total <= 198.99: # shipping_charge = 24.99 # else: # shipping_charge = 0 # # elif category_name.__contains__('Live Goods'): # free_shipping_min_value = 199 # if sub_total >= 00.01 and sub_total <= 98.99: # shipping_charge = 34.99 # elif sub_total >= 99.00 and sub_total <= 198.99: # shipping_charge = 24.99 # else: # shipping_charge = 0 # # elif category_name.__contains__('Live Rock & Sand'): # free_shipping_min_value = 0 # if sub_total >= 00.01 and sub_total <= 98.99: # shipping_charge = 4.99 # elif sub_total >= 99.00 and sub_total <= 198.99: # shipping_charge = 4.99 # else: # shipping_charge = 4.99 # # elif category_name.__contains__('FastTrack Supplies'): # free_shipping_min_value = 0 # if sub_total >= 00.01 and sub_total <= 98.99: # shipping_charge = 4.99 # elif sub_total >= 99.00 and sub_total <= 198.99: # shipping_charge = 4.99 # else: # shipping_charge = 4.99 # # elif category_name.__contains__('Aquarium Supplies On Sale'): # free_shipping_min_value = 0 # if sub_total >= 00.01 and sub_total <= 98.99: # shipping_charge = 4.99 # elif sub_total >= 99.00 and sub_total <= 198.99: # shipping_charge = 4.99 # else: # shipping_charge = 4.99 # # return (shipping_charge, free_shipping_min_value)
hughsons/saltwaterfish
classes_bkp_0621.py
Python
bsd-3-clause
19,445
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # Download and build the data if it does not exist. import parlai.core.build_data as build_data import os def buildImage(opt): dpath = os.path.join(opt['datapath'], 'COCO-IMG') if not build_data.built(dpath): print('[building image data: ' + dpath + ']') build_data.remove_dir(dpath) build_data.make_dir(dpath) # download the image data. fname1 = 'train2014.zip' fname2 = 'val2014.zip' fname3 = 'test2014.zip' url = 'http://msvocds.blob.core.windows.net/coco2014/' build_data.download(dpath, url + fname1) build_data.download(dpath, url + fname2) build_data.download(dpath, url + fname3) build_data.untar(dpath, fname1, False) build_data.untar(dpath, fname2, False) build_data.untar(dpath, fname3, False) # Mark the data as built. build_data.mark_done(dpath) def build(opt): dpath = os.path.join(opt['datapath'], 'VQA-v2') if not build_data.built(dpath): print('[building data: ' + dpath + ']') build_data.remove_dir(dpath) build_data.make_dir(dpath) # Download the data. fname1 = 'v2_Questions_Train_mscoco.zip' fname2 = 'v2_Questions_Val_mscoco.zip' fname3 = 'v2_Questions_Test_mscoco.zip' fname4 = 'v2_Annotations_Val_mscoco.zip' fname5 = 'v2_Annotations_Train_mscoco.zip' url = 'http://visualqa.org/data/mscoco/vqa/' build_data.download(dpath, url + fname1) build_data.download(dpath, url + fname2) build_data.download(dpath, url + fname3) build_data.download(dpath, url + fname4) build_data.download(dpath, url + fname5) build_data.untar(dpath, fname1) build_data.untar(dpath, fname2) build_data.untar(dpath, fname3) build_data.untar(dpath, fname4) build_data.untar(dpath, fname5) # Mark the data as built. build_data.mark_done(dpath)
calee88/ParlAI
parlai/tasks/vqa_v2/build.py
Python
bsd-3-clause
2,271
class [scope]::RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :configure_account_update_params, only: [:update] # GET /resource/sign_up # def new # super # end # POST /resource # def create # super # end # GET /resource/edit # def edit # super # end # PUT /resource # def update # super # end # DELETE /resource # def destroy # super # end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. # def cancel # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_up_params # devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute]) # end # If you have extra params to permit, append them to the sanitizer. # def configure_account_update_params # devise_parameter_sanitizer.permit(:account_update, keys: [:attribute]) # end # The path used after sign up. # def after_sign_up_path_for(resource) # super(resource) # end # The path used after sign up for inactive accounts. # def after_inactive_sign_up_path_for(resource) # super(resource) # end end
danielsiebra/projeto_e_profissional
app/controllers/[scope]/registrations_controller.rb
Ruby
bsd-3-clause
1,404
--TEST-- radius_cvt_string() --INI-- display_errors=1 error_reporting=22527 --SKIPIF-- <?php if (!extension_loaded('radius')) echo 'SKIP: radius extension required'; ?> --FILE-- <?php var_dump(radius_cvt_string('127.0.0.1')); ?> --EXPECT-- string(9) "127.0.0.1"
LawnGnome/php-radius
tests/radius_cvt_string.phpt
PHP
bsd-3-clause
262
<?php namespace common\models\articles; use common\models\behaviors\HiddenBehavior; use common\models\scopes\ArticleScope; use common\models\traits\CacheTrait; use Yii; use yii\behaviors\TimestampBehavior; use yii\data\ActiveDataProvider; use yii\helpers\ArrayHelper; use yii\helpers\HtmlPurifier; use common\models\User; /** * This is the model class for table "a_article". * * @property integer $id * @property integer $user_id * @property string $title * @property string $description * @property string $text * @property integer $status * @property integer $hidden * @property integer $created_at * @property integer $updated_at * * @property Category[] $categories * @property User $user */ class Article extends \yii\db\ActiveRecord { use CacheTrait; public $categoriesNames; /** * @inheritdoc */ public static function tableName() { return 'a_article'; } /** * @inheritdoc */ public static function find() { return new ArticleScope(get_called_class()); } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), HiddenBehavior::className(), ]; } // values attribute 'status' const STATUS_NEW = 5; const STATUS_ON_MODERATION = 10; const STATUS_DELETED = 15; const STATUS_APPROVED = 20; /** * Available list of statuses attribute "status" * or get status name by index * @param null $index * @return array|string */ public static function statuses($index = null) { $statuses = [ self::STATUS_NEW => 'New', self::STATUS_ON_MODERATION => 'Moderation', self::STATUS_DELETED => 'Deleted', self::STATUS_APPROVED => 'Approved', ]; if ($index !== null) { if (!empty($statuses[$index])) { return $statuses[$index]; } else { return 'error status'; } } else { return $statuses; } } /** * Relation many-to-many. Article-Categories * @return $this */ public function getCategories() { return $this->hasMany(Category::className(), ['id' => 'category_id']) ->viaTable(ArticleCategory::tableName(), ['article_id' => 'id']); } /** * Relation User * @return $this */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); } // scenarios const SCENARIO_MODERATION = 'scenario_moderation'; const SCENARIO_AUTHOR_UPDATE = 'scenario_author_update'; const SCENARIO_SEARCH = 'scenario_search'; /** * @inheritdoc */ public function rules() { return [ [['user_id', 'title', 'description', 'text', 'hidden'], 'required', 'except' => self::SCENARIO_SEARCH], [['user_id'], 'integer'], ['status', 'integer', 'on' => self::SCENARIO_MODERATION], ['status', 'in', 'range' => array_keys(self::statuses()), 'on' => self::SCENARIO_MODERATION], [['title', 'description'], 'string', 'max' => 255], ['text', 'filter', 'filter' => function ($html) { return HtmlPurifier::process($html); }], ['categoriesNames', 'safe'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'user_id' => 'User ID', 'title' => 'Title', 'description' => 'Description', 'text' => 'Text', 'status' => 'Status', 'hidden' => 'Hidden', 'created_at' => 'Created At', 'updated_at' => 'Updated At', ]; } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = self::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if(!Yii::$app->getUser()->can('articleUpdate', $this)) { $query->approvedOrMy(); } $query->visibleOrMy(); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'id' => $this->id, 'user_id' => $this->user_id, 'status' => $this->status, ]); $query->andFilterWhere(['like', 'title', $this->title]) ->andFilterWhere(['like', 'description', $this->description]) ->andFilterWhere(['like', 'text', $this->text]); return $dataProvider; } /** * Get access update article * @return bool */ public function isEditAvailable() { return Yii::$app->user->can('articleUpdateOwner', $this) || Yii::$app->user->can('articleUpdate', $this); } /** * @inheritdoc */ public function afterFind() { $categoriesArticle = $this->categories; if ($categoriesArticle) { $this->categoriesNames = array_flip(ArrayHelper::map($categoriesArticle, 'id', 'name')); } parent::afterFind(); } /** * @inheritdoc */ public function afterSave($insert, $changedAttributes) { $articleCategories = ArticleCategory::getCache(ArticleCategory::find() ->where(['article_id' => $this->id]) ->indexBy('category_id'), false); $transaction = Yii::$app->db->beginTransaction(); try { ArticleCategory::deleteAll([ 'category_id' => array_diff_key($articleCategories, $this->categoriesNames), 'article_id' => $this->id ]); $addedCategories = array_diff_key($this->categoriesNames, $articleCategories); $insertData = []; foreach ($addedCategories as $addedCategoryId) { $insertData[] = [ 'article_id' => $this->id, 'category_id' => $addedCategoryId, ]; } if (!empty($insertData)) { Yii::$app->db->createCommand() ->batchInsert(ArticleCategory::tableName(), array_keys($insertData[0]), $insertData) ->execute(); } ArticleCategory::onInvalidateCache(); $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); throw $e; } parent::afterSave($insert, $changedAttributes); } }
bereznev/yii2-blog
common/models/articles/Article.php
PHP
bsd-3-clause
5,780
from django.core.exceptions import ImproperlyConfigured from django.db.models import F, fields from django.db.models.functions import Cast, Coalesce from django.utils.translation import gettext_lazy as _ from .conf import get_default_language, get_fallback_chain, get_modeltrans_setting from .utils import ( FallbackTransform, build_localized_fieldname, get_instance_field_value, get_language, ) try: # django==3.1 moved JSONField into django.db.models from django.db.models import JSONField from django.db.models.fields.json import KeyTextTransform except ImportError: from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform SUPPORTED_FIELDS = (fields.CharField, fields.TextField) DEFAULT_LANGUAGE = get_default_language() def translated_field_factory(original_field, language=None, *args, **kwargs): if not isinstance(original_field, SUPPORTED_FIELDS): raise ImproperlyConfigured( "{} is not supported by django-modeltrans.".format(original_field.__class__.__name__) ) class Specific(TranslatedVirtualField, original_field.__class__): pass Specific.__name__ = "Translated{}".format(original_field.__class__.__name__) return Specific(original_field, language, *args, **kwargs) class TranslatedVirtualField: """ A field representing a single field translated to a specific language. Arguments: original_field: The original field to be translated language: The language to translate to, or `None` to track the current active Django language. """ # Implementation inspired by HStoreVirtualMixin from: # https://github.com/djangonauts/django-hstore/blob/master/django_hstore/virtual.py def __init__(self, original_field, language=None, *args, **kwargs): # TODO: this feels like a big hack. self.__dict__.update(original_field.__dict__) self.original_field = original_field self.language = language self.blank = kwargs["blank"] self.null = kwargs["null"] self.concrete = False self._help_text = kwargs.pop("help_text", None) @property def original_name(self): return self.original_field.name @property def help_text(self): if self._help_text is not None: return self._help_text if get_modeltrans_setting("MODELTRANS_ADD_FIELD_HELP_TEXT") and self.language is None: return _("current language: {}").format(get_language()) def contribute_to_class(self, cls, name): self.model = cls self.attname = name self.name = name self.column = None # Use a translated verbose name: translated_field_name = _(self.original_field.verbose_name) if self.language is not None: translated_field_name += " ({})".format(self.language.upper()) self.verbose_name = translated_field_name setattr(cls, name, self) cls._meta.add_field(self, private=True) def db_type(self, connection): return None def get_instance_fallback_chain(self, instance, language): """ Return the fallback chain for the instance. Most of the time, it is just the configured fallback chain, but if the per-record-fallback feature is used, the value of the field is added (if not None). """ default = get_fallback_chain(language) i18n_field = instance._meta.get_field("i18n") if i18n_field.fallback_language_field: record_fallback_language = get_instance_field_value( instance, i18n_field.fallback_language_field ) if record_fallback_language: return (record_fallback_language, *default) return default def __get__(self, instance, instance_type=None): # This method is apparently called with instance=None from django. # django-hstor raises AttributeError here, but that doesn't solve our problem. if instance is None: return if "i18n" in instance.get_deferred_fields(): raise ValueError( "Getting translated values on a model fetched with defer('i18n') is not supported." ) language = self.get_language() original_value = getattr(instance, self.original_name) if language == DEFAULT_LANGUAGE and original_value: return original_value # Make sure we test for containment in a dict, not in None if instance.i18n is None: instance.i18n = {} field_name = build_localized_fieldname(self.original_name, language) # Just return the value if this is an explicit field (<name>_<lang>) if self.language is not None: return instance.i18n.get(field_name) # This is the _i18n version of the field, and the current language is not available, # so we walk the fallback chain: for fallback_language in (language,) + self.get_instance_fallback_chain(instance, language): if fallback_language == DEFAULT_LANGUAGE: if original_value: return original_value else: continue field_name = build_localized_fieldname(self.original_name, fallback_language) if field_name in instance.i18n and instance.i18n[field_name]: return instance.i18n.get(field_name) # finally, return the original field if all else fails. return getattr(instance, self.original_name) def __set__(self, instance, value): if instance.i18n is None: instance.i18n = {} language = self.get_language() if language == DEFAULT_LANGUAGE: setattr(instance, self.original_name, value) else: field_name = build_localized_fieldname(self.original_name, language) # if value is None, remove field from `i18n`. if value is None: instance.i18n.pop(field_name, None) else: instance.i18n[field_name] = value def get_field_name(self): """ Returns the field name for the current virtual field. The field name is ``<original_field_name>_<language>`` in case of a specific translation or ``<original_field_name>_i18n`` for the currently active language. """ if self.language is None: lang = "i18n" else: lang = self.get_language() return build_localized_fieldname(self.original_name, lang) def get_language(self): """ Returns the language for this field. In case of an explicit language (title_en), it returns "en", in case of `title_i18n`, it returns the currently active Django language. """ return self.language if self.language is not None else get_language() def output_field(self): """ The type of field used to Cast/Coalesce to. Mainly because a max_length argument is required for CharField until this PR is merged: https://github.com/django/django/pull/8758 """ Field = self.original_field.__class__ if isinstance(self.original_field, fields.CharField): return Field(max_length=self.original_field.max_length) return Field() def _localized_lookup(self, language, bare_lookup): if language == DEFAULT_LANGUAGE: return bare_lookup.replace(self.name, self.original_name) # When accessing a table directly, the i18_lookup will be just "i18n", while following relations # they are in the lookup first. i18n_lookup = bare_lookup.replace(self.name, "i18n") # To support per-row fallback languages, an F-expression is passed as language parameter. if isinstance(language, F): # abuse build_localized_fieldname without language to get "<field>_" field_prefix = build_localized_fieldname(self.original_name, "") return FallbackTransform(field_prefix, language, i18n_lookup) else: return KeyTextTransform( build_localized_fieldname(self.original_name, language), i18n_lookup ) def as_expression(self, bare_lookup, fallback=True): """ Compose an expression to get the value for this virtual field in a query. """ language = self.get_language() if language == DEFAULT_LANGUAGE: return F(self._localized_lookup(language, bare_lookup)) if not fallback: i18n_lookup = self._localized_lookup(language, bare_lookup) return Cast(i18n_lookup, self.output_field()) fallback_chain = get_fallback_chain(language) # First, add the current language to the list of lookups lookups = [self._localized_lookup(language, bare_lookup)] # Optionnally add the lookup for the per-row fallback language i18n_field = self.model._meta.get_field("i18n") if i18n_field.fallback_language_field: lookups.append( self._localized_lookup(F(i18n_field.fallback_language_field), bare_lookup) ) # and now, add the list of fallback languages to the lookup list for fallback_language in fallback_chain: lookups.append(self._localized_lookup(fallback_language, bare_lookup)) return Coalesce(*lookups, output_field=self.output_field()) class TranslationField(JSONField): """ This model field is used to store the translations in the translated model. Arguments: fields (iterable): List of model field names to make translatable. required_languages (iterable or dict): List of languages required for the model. If a dict is supplied, the keys must be translated field names with the value containing a list of required languages for that specific field. virtual_fields (bool): If `False`, do not add virtual fields to access translated values with. Set to `True` during migration from django-modeltranslation to prevent collisions with it's database fields while having the `i18n` field available. fallback_language_field: If not None, this should be the name of the field containing a language code to use as the first language in any fallback chain. For example: if you have a model instance with 'nl' as language_code, and set fallback_language_field='language_code', 'nl' will always be tried after the current language before any other language. """ description = "Translation storage for a model" def __init__( self, fields=None, required_languages=None, virtual_fields=True, fallback_language_field=None, *args, **kwargs, ): self.fields = fields or () self.required_languages = required_languages or () self.virtual_fields = virtual_fields self.fallback_language_field = fallback_language_field kwargs["editable"] = False kwargs["null"] = True super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["editable"] del kwargs["null"] kwargs["fields"] = self.fields kwargs["required_languages"] = self.required_languages kwargs["virtual_fields"] = self.virtual_fields return name, path, args, kwargs def get_translated_fields(self): """Return a generator for all translated fields.""" for field in self.model._meta.get_fields(): if isinstance(field, TranslatedVirtualField): yield field def contribute_to_class(self, cls, name): if name != "i18n": raise ImproperlyConfigured('{} must have name "i18n"'.format(self.__class__.__name__)) super().contribute_to_class(cls, name)
zostera/django-modeltrans
modeltrans/fields.py
Python
bsd-3-clause
12,105
package gengateway import ( "strings" "testing" "github.com/golang/protobuf/proto" protodescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/ilius/grpc-gateway/protoc-gen-grpc-gateway/descriptor" "github.com/ilius/grpc-gateway/protoc-gen-grpc-gateway/httprule" ) func crossLinkFixture(f *descriptor.File) *descriptor.File { for _, m := range f.Messages { m.File = f } for _, svc := range f.Services { svc.File = f for _, m := range svc.Methods { m.Service = svc for _, b := range m.Bindings { b.Method = m for _, param := range b.PathParams { param.Method = m } } } } return f } func TestApplyTemplateHeader(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Example"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } msg := &descriptor.Message{ DescriptorProto: msgdesc, } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), Dependency: []string{"a.example/b/c.proto", "a.example/d/e.proto"}, MessageType: []*protodescriptor.DescriptorProto{msgdesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "GET", Body: &descriptor.Body{FieldPath: nil}, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file)}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := "package example_pb\n"; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } func TestApplyTemplateRequestWithoutClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(false), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool sigWant string }{ { serverStreaming: false, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, }, { serverStreaming: true, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, }, } { meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file)}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := spec.sigWant; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `marshaler.NewDecoder(req.Body).Decode(&protoReq.GetNested().Bool)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `val, ok = pathParams["nested.int32"]`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `protoReq.GetNested().Int32, err = runtime.Int32P(val)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } } func TestApplyTemplateRequestWithClientStreaming(t *testing.T) { msgdesc := &protodescriptor.DescriptorProto{ Name: proto.String("ExampleMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("nested"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_MESSAGE.Enum(), TypeName: proto.String("NestedMessage"), Number: proto.Int32(1), }, }, } nesteddesc := &protodescriptor.DescriptorProto{ Name: proto.String("NestedMessage"), Field: []*protodescriptor.FieldDescriptorProto{ { Name: proto.String("int32"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_INT32.Enum(), Number: proto.Int32(1), }, { Name: proto.String("bool"), Label: protodescriptor.FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: protodescriptor.FieldDescriptorProto_TYPE_BOOL.Enum(), Number: proto.Int32(2), }, }, } meth := &protodescriptor.MethodDescriptorProto{ Name: proto.String("Echo"), InputType: proto.String("ExampleMessage"), OutputType: proto.String("ExampleMessage"), ClientStreaming: proto.Bool(true), } svc := &protodescriptor.ServiceDescriptorProto{ Name: proto.String("ExampleService"), Method: []*protodescriptor.MethodDescriptorProto{meth}, } for _, spec := range []struct { serverStreaming bool sigWant string }{ { serverStreaming: false, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {`, }, { serverStreaming: true, sigWant: `func request_ExampleService_Echo_0(ctx context.Context, marshaler runtime.Marshaler, client ExampleServiceClient, req *http.Request, pathParams map[string]string) (ExampleService_EchoClient, runtime.ServerMetadata, error) {`, }, } { meth.ServerStreaming = proto.Bool(spec.serverStreaming) msg := &descriptor.Message{ DescriptorProto: msgdesc, } nested := &descriptor.Message{ DescriptorProto: nesteddesc, } nestedField := &descriptor.Field{ Message: msg, FieldDescriptorProto: msg.GetField()[0], } intField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[0], } boolField := &descriptor.Field{ Message: nested, FieldDescriptorProto: nested.GetField()[1], } file := descriptor.File{ FileDescriptorProto: &protodescriptor.FileDescriptorProto{ Name: proto.String("example.proto"), Package: proto.String("example"), MessageType: []*protodescriptor.DescriptorProto{msgdesc, nesteddesc}, Service: []*protodescriptor.ServiceDescriptorProto{svc}, }, GoPkg: descriptor.GoPackage{ Path: "example.com/path/to/example/example.pb", Name: "example_pb", }, Messages: []*descriptor.Message{msg, nested}, Services: []*descriptor.Service{ { ServiceDescriptorProto: svc, Methods: []*descriptor.Method{ { MethodDescriptorProto: meth, RequestType: msg, ResponseType: msg, Bindings: []*descriptor.Binding{ { HTTPMethod: "POST", PathTmpl: httprule.Template{ Version: 1, OpCodes: []int{0, 0}, }, PathParams: []descriptor.Parameter{ { FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "int32", Target: intField, }, }), Target: intField, }, }, Body: &descriptor.Body{ FieldPath: descriptor.FieldPath([]descriptor.FieldPathComponent{ { Name: "nested", Target: nestedField, }, { Name: "bool", Target: boolField, }, }), }, }, }, }, }, }, }, } got, err := applyTemplate(param{File: crossLinkFixture(&file)}) if err != nil { t.Errorf("applyTemplate(%#v) failed with %v; want success", file, err) return } if want := spec.sigWant; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `marshaler.NewDecoder(req.Body)`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `func RegisterExampleServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } if want := `pattern_ExampleService_Echo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{0, 0}, []string(nil), ""))`; !strings.Contains(got, want) { t.Errorf("applyTemplate(%#v) = %s; want to contain %s", file, got, want) } } }
ilius/grpc-gateway
protoc-gen-grpc-gateway/gengateway/template_test.go
GO
bsd-3-clause
13,223
/* * Copyright (c) 2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * 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 the copyright holders 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. * * Authors: Stephan Diestelhorst <stephan.diestelhorst@arm.com> */ // hello /** * @file * Definition of a snoop filter. */ #include "base/misc.hh" #include "base/trace.hh" #include "debug/SnoopFilter.hh" #include "mem/snoop_filter.hh" #include "sim/system.hh" std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupRequest(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask req_port = portToMask(slave_port); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; SnoopMask interested = sf_item.holder | sf_item.requested; totRequests++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleRequests++; else hitMultiRequests++; } DPRINTF(SnoopFilter, "%s: SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); if (cpkt->needsResponse()) { if (!cpkt->memInhibitAsserted()) { // Max one request per address per port panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); // Mark in-flight requests to distinguish later on sf_item.requested |= req_port; } else { // NOTE: The memInhibit might have been asserted by a cache closer // to the CPU, already -> the response will not be seen by this // filter -> we do not need to keep the in-flight request, but make // sure that we know that that cluster has a copy panic_if(!(sf_item.holder & req_port), "Need to hold the value!"); DPRINTF(SnoopFilter, "%s: not marking request. SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency); } void SnoopFilter::updateRequest(const Packet* cpkt, const SlavePort& slave_port, bool will_retry) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask req_port = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x retry: %i\n", __func__, sf_item.requested, sf_item.holder, will_retry); if (will_retry) { // Unmark a request that will come again. sf_item.requested &= ~req_port; return; } // will_retry == false if (!cpkt->needsResponse()) { // Packets that will not evoke a response but still need updates of the // snoop filter; WRITEBACKs for now only if (cpkt->cmd == MemCmd::Writeback) { // make sure that the sender actually had the line panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); panic_if(!(sf_item.holder & req_port), "requester %x is not a "\ "holder :( SF value %x.%x\n", req_port, sf_item.requested, sf_item.holder); // Writebacks -> the sender does not have the line anymore sf_item.holder &= ~req_port; } else { assert(0 == "Handle non-writeback, here"); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } } std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupSnoop(const Packet* cpkt) { DPRINTF(SnoopFilter, "%s: packet addr 0x%x cmd %s\n", __func__, cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isRequest()); // Broadcast / filter upward snoops const bool filter_upward = true; // @todo: Make configurable if (!filter_upward) return snoopAll(lookupLatency); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); SnoopMask interested = (sf_item.holder | sf_item.requested); totSnoops++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleSnoops++; else hitMultiSnoops++; } assert(cpkt->isInvalidate() == cpkt->needsExclusive()); if (cpkt->isInvalidate() && !sf_item.requested) { // Early clear of the holder, if no other request is currently going on // @todo: This should possibly be updated even though we do not filter // upward snoops sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x interest: %x \n", __func__, sf_item.requested, sf_item.holder, interested); return snoopSelected(maskToPortList(interested), lookupLatency); } void SnoopFilter::updateSnoopResponse(const Packet* cpkt, const SlavePort& rsp_port, const SlavePort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask rsp_mask = portToMask(rsp_port); SnoopMask req_mask = portToMask(req_port); SnoopItem& sf_item = cachedLocations[line_addr]; assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // The source should have the line panic_if(!(sf_item.holder & rsp_mask), "SF value %x.%x does not have "\ "the line\n", sf_item.requested, sf_item.holder); // The destination should have had a request in panic_if(!(sf_item.requested & req_mask), "SF value %x.%x missing "\ "the original request\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) { DPRINTF(SnoopFilter, "%s: dropping %x because needs: %i shared: %i "\ "SF val: %x.%x\n", __func__, rsp_mask, cpkt->needsExclusive(), cpkt->sharedAsserted(), sf_item.requested, sf_item.holder); sf_item.holder &= ~rsp_mask; // The snoop filter does not see any ACKs from non-responding sharers // that have been invalidated :( So below assert would be nice, but.. //assert(sf_item.holder == 0); sf_item.holder = 0; } assert(cpkt->cmd != MemCmd::Writeback); sf_item.holder |= req_mask; sf_item.requested &= ~req_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateSnoopForward(const Packet* cpkt, const SlavePort& rsp_port, const MasterPort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopItem& sf_item = cachedLocations[line_addr]; SnoopMask rsp_mask M5_VAR_USED = portToMask(rsp_port); assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Remote (to this snoop filter) snoops update the filter already when they // arrive from below, because we may not see any response. if (cpkt->needsExclusive()) { // If the request to this snoop response hit an in-flight transaction, // the holder was not reset -> no assertion & do that here, now! //assert(sf_item.holder == 0); sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateResponse(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask slave_mask = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; assert(cpkt->isResponse()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Make sure we have seen the actual request, too panic_if(!(sf_item.requested & slave_mask), "SF value %x.%x missing "\ "request bit\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) sf_item.holder = 0; sf_item.holder |= slave_mask; sf_item.requested &= ~slave_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::regStats() { totRequests .name(name() + ".tot_requests") .desc("Total number of requests made to the snoop filter."); hitSingleRequests .name(name() + ".hit_single_requests") .desc("Number of requests hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiRequests .name(name() + ".hit_multi_requests") .desc("Number of requests hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); totSnoops .name(name() + ".tot_snoops") .desc("Total number of snoops made to the snoop filter."); hitSingleSnoops .name(name() + ".hit_single_snoops") .desc("Number of snoops hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiSnoops .name(name() + ".hit_multi_snoops") .desc("Number of snoops hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); } SnoopFilter * SnoopFilterParams::create() { return new SnoopFilter(this); }
SteveXiSong/ECE757-SnoopingPredictions
src/mem/snoop_filter.cc
C++
bsd-3-clause
13,192
/* * $Id: GridAttributeDialog.java,v 1.2 2006/01/19 14:45:50 luca Exp $ * * This software is provided by NOAA for full, free and open release. It is * understood by the recipient/user that NOAA assumes no liability for any * errors contained in the code. Although this software is released without * conditions or restrictions in its use, it is expected that appropriate * credit be given to its author and to the National Oceanic and Atmospheric * Administration should the software be included by the recipient as an * element in other product development. */ package gov.noaa.pmel.sgt.swing.prop; import javax.swing.*; import java.awt.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumn; import javax.swing.event.TableModelEvent; import java.util.Vector; import java.io.File; import java.io.Reader; import java.io.BufferedReader; import java.io.FileReader; import java.io.StreamTokenizer; import gov.noaa.pmel.sgt.GridCartesianRenderer; import gov.noaa.pmel.sgt.GridAttribute; import gov.noaa.pmel.sgt.ContourLineAttribute; import gov.noaa.pmel.sgt.DefaultContourLineAttribute; import gov.noaa.pmel.sgt.ContourLevels; import gov.noaa.pmel.sgt.ColorMap; import gov.noaa.pmel.sgt.IndexedColor; import gov.noaa.pmel.sgt.swing.ColorSwatchIcon; import gov.noaa.pmel.sgt.IndexedColorMap; import gov.noaa.pmel.sgt.LinearTransform; import gov.noaa.pmel.sgt.JPane; import gov.noaa.pmel.sgt.ContourLevelNotFoundException; import gov.noaa.pmel.sgt.dm.SGTGrid; import gov.noaa.pmel.util.Range2D; import java.awt.event.*; import it.unitn.ing.rista.util.Misc; /** * Edits the <code>GridAttribute</code>. This dialog does not make a * copy of the attribute so changes "Applied" will cause * <code>sgt</code> to redraw the plot using the properties * immediately unless a <code>JPane</code> was supplied. * * <p> Example of <code>GridAttributeDialog</code> use: * <pre> * JPane pane_; * CartesianRenderer rend = ((CartesianGraph)pane_.getFirstLayer().getGraph()).getRenderer(); * ... * GridAttributeDialog gad = new GridAttributeDialog(); * gad.setJPane(pane_); * gad.setGridCartesianRenderer((GridCartesianRenderer)rend); * gad.setVisible(true); * </pre> * * @author Donald Denbo * @version $Revision: 1.2 $, $Date: 2006/01/19 14:45:50 $ * @since 2.0 * @see NewLevelsDialog * @see ContourLineAttributeDialog * @see DefaultContourLineAttributeDialog */ public class GridAttributeDialog extends JDialog { private GridAttribute attr_; private ContourLevels conLevels_; private ColorMap colorMap_; private JPane[] paneList_ = null; private int contourLevelIndex_ = 0; private int colorMapIndex_ = 1; private JTable conLevelTable_; private ConLevelTableModel conLevelModel_; private SGTGrid grid_ = null; private JToggleButton[] colorButtons_ = new JToggleButton[256]; /** * Constructor. */ public GridAttributeDialog(Frame parent) { super(parent); try { jbInit(); pack(); } catch(Exception ex) { ex.printStackTrace(); } } void jbInit() throws Exception { getContentPane().setLayout(new BorderLayout(0,0)); setSize(516,374); setVisible(false); mainPanel.setPreferredSize(new Dimension(516, 36)); getContentPane().add(TabbedPane, "Center"); ContourLevelsPanel.setLayout(new BorderLayout(0,0)); TabbedPane.add(ContourLevelsPanel, "ContourLevelsPanel"); ContourLevelsPanel.setBounds(2,27,511,271); ContourLevelsPanel.setVisible(false); ContourLevelsPanel.add(gridScrollPane, "Center"); controlPanel.setLayout(new GridBagLayout()); ContourLevelsPanel.add(controlPanel, "East"); JPanel1.setBorder(titledBorder1); JPanel1.setLayout(new GridBagLayout()); controlPanel.add(JPanel1, new GridBagConstraints(0,1,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,0,0,0),0,0)); editButton.setToolTipText("Edit attribute of selected level."); editButton.setText("Edit Attribute"); editButton.setActionCommand("Change Value"); JPanel1.add(editButton, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,0,5),0,0)); aboveButton.setToolTipText("Insert level above selected level."); aboveButton.setText("Insert Level Above"); aboveButton.setActionCommand("Before Item"); JPanel1.add(aboveButton, new GridBagConstraints(0,1,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,0,5),0,0)); belowButton.setToolTipText("Insert level below selected level."); belowButton.setText("Insert Level Below"); belowButton.setActionCommand("After Item"); JPanel1.add(belowButton, new GridBagConstraints(0,2,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,0,5),0,0)); deleteButton.setToolTipText("Delete the selected level."); deleteButton.setText("Delete Level"); deleteButton.setActionCommand("Delete Item"); JPanel1.add(deleteButton, new GridBagConstraints(0,3,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(2,5,2,5),0,0)); JPanel4.setBorder(titledBorder4); JPanel4.setLayout(new GridBagLayout()); controlPanel.add(JPanel4, new GridBagConstraints(0,3,1,1,0.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,0,0,0),0,0)); defaultButton.setToolTipText("Edit default attributes."); defaultButton.setText("Edit Default Attributes"); defaultButton.setActionCommand("Edit Default Attributes"); JPanel4.add(defaultButton, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(2,5,2,5),0,0)); sortButton.setToolTipText("Sort levels by value."); sortButton.setText("Sort Levels"); sortButton.setActionCommand("Sort"); controlPanel.add(sortButton, new GridBagConstraints(0,4,1,1,0.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(5,5,5,5),0,0)); newConLevelButton.setToolTipText("Create new contour level set."); newConLevelButton.setText("New..."); newConLevelButton.setActionCommand("New..."); controlPanel.add(newConLevelButton, new GridBagConstraints(0,0,1,1,1.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(5,5,0,5),0,0)); ColorMapPanel.setLayout(new BorderLayout(0,0)); TabbedPane.add(ColorMapPanel, "ColorMapPanel"); ColorMapPanel.setBounds(2,27,511,271); ColorMapPanel.setVisible(false); colorControlPanel.setLayout(new GridBagLayout()); ColorMapPanel.add(colorControlPanel, "East"); colorMapPanel.setBorder(titledBorder2); colorMapPanel.setLayout(new GridBagLayout()); colorControlPanel.add(colorMapPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0)); newColorMapButton.setToolTipText("Create new color map."); newColorMapButton.setText("New..."); newColorMapButton.setActionCommand("New..."); colorMapPanel.add(newColorMapButton, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)); loadColorMapButton.setToolTipText("Load color map from disk."); loadColorMapButton.setText("Load..."); loadColorMapButton.setActionCommand("Load..."); colorMapPanel.add(loadColorMapButton, new GridBagConstraints(0,1,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)); saveColorMapButton.setToolTipText("Save color map to disk."); saveColorMapButton.setText("Save..."); saveColorMapButton.setActionCommand("Save..."); colorMapPanel.add(saveColorMapButton, new GridBagConstraints(0,2,1,1,0.0,0.0, GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL,new Insets(0,0,0,0),0,0)); colorPanel.setLayout(new CardLayout(0,0)); ColorMapPanel.add(colorPanel, "Center"); CLIndexedPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); colorPanel.add("CLIndexed", CLIndexedPanel); CLTransformPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); colorPanel.add("CLTransform", CLTransformPanel); CLTransformPanel.setVisible(false); IndexedPanel.setLayout(new GridBagLayout()); colorPanel.add("Indexed", IndexedPanel); IndexedPanel.setVisible(false); colorButtonsPanel.setLayout(new GridLayout(16,16,1,1)); IndexedPanel.add(colorButtonsPanel, new GridBagConstraints(0,0,1,1,1.0,1.0, GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0)); TransformPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); colorPanel.add("Transform", TransformPanel); TransformPanel.setVisible(false); TabbedPane.setSelectedComponent(ContourLevelsPanel); TabbedPane.setSelectedIndex(0); TabbedPane.setTitleAt(0,"Contour Levels"); TabbedPane.setTitleAt(1,"Color Map"); buttonPanel.setBorder(etchedBorder1); buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,5,5)); getContentPane().add(buttonPanel, "South"); okButton.setText("OK"); okButton.setActionCommand("OK"); buttonPanel.add(okButton); applyButton.setText("Apply"); applyButton.setActionCommand("Apply"); buttonPanel.add(applyButton); cancelButton.setText("Cancel"); cancelButton.setActionCommand("Cancel"); buttonPanel.add(cancelButton); mainPanel.setLayout(new GridBagLayout()); getContentPane().add(mainPanel, "North"); JLabel5.setText("Grid Style:"); mainPanel.add(JLabel5, new GridBagConstraints(0,0,1,1,0.0,0.0, GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(5,5,0,5),0,0)); gridStyleComboBox.setModel(stringComboBoxModel1); mainPanel.add(gridStyleComboBox, new GridBagConstraints(1,0,1,1,0.0,0.0, GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(5,5,5,5),0,0)); { String[] tempString = new String[5]; tempString[0] = "RASTER"; tempString[1] = "AREA_FILL"; tempString[2] = "CONTOUR"; tempString[3] = "RASTER_CONTOUR"; tempString[4] = "AREA_FILL_CONTOUR"; for(int i=0; i < tempString.length; i++) { stringComboBoxModel1.addElement(tempString[i]); } } gridStyleComboBox.setSelectedIndex(0); setTitle("GridAttribute Properties"); SymWindow aSymWindow = new SymWindow(); this.addWindowListener(aSymWindow); SymAction lSymAction = new SymAction(); cancelButton.addActionListener(lSymAction); okButton.addActionListener(lSymAction); applyButton.addActionListener(lSymAction); gridStyleComboBox.addActionListener(lSymAction); newConLevelButton.addActionListener(lSymAction); newColorMapButton.addActionListener(lSymAction); loadColorMapButton.addActionListener(lSymAction); editButton.addActionListener(lSymAction); aboveButton.addActionListener(lSymAction); belowButton.addActionListener(lSymAction); deleteButton.addActionListener(lSymAction); sortButton.addActionListener(lSymAction); saveColorMapButton.addActionListener(lSymAction); defaultButton.addActionListener(lSymAction); makeColorToggleButtons(); } private void makeColorToggleButtons() { Insets insets = new Insets(0,0,0,0); ButtonGroup bg = new ButtonGroup(); ColorSwatchIcon csi = null; for(int i=0; i < 256; i++) { JToggleButton tb = new JToggleButton(""); if(System.getProperty("mrj.version") == null || !UIManager.getSystemLookAndFeelClassName().equals(UIManager.getLookAndFeel().getClass().getName())) tb.setMargin(insets); csi = new ColorSwatchIcon(Color.white, 8, 8); tb.setIcon(csi); colorButtons_[i] = tb; colorButtonsPanel.add(tb); bg.add(tb); } } /** Used internally. */ public void addNotify() { // Record the size of the window prior to calling parents addNotify. Dimension d = getSize(); super.addNotify(); if (fComponentsAdjusted) return; // Adjust components according to the insets Insets ins = getInsets(); setSize(ins.left + ins.right + d.width, ins.top + ins.bottom + d.height); Component components[] = getContentPane().getComponents(); for (int i = 0; i < components.length; i++) { Point p = components[i].getLocation(); p.translate(ins.left, ins.top); components[i].setLocation(p); } fComponentsAdjusted = true; } // Used for addNotify check. boolean fComponentsAdjusted = false; /** * Constructor. */ public GridAttributeDialog(String title) { this(); setTitle(title); } /** * Default constructor. */ public GridAttributeDialog() { this((Frame)null); } /** * Make the dialog visible. */ public void setVisible(boolean b) { if(b) { setLocation(50, 50); } super.setVisible(b); } class SymWindow extends java.awt.event.WindowAdapter { public void windowClosing(java.awt.event.WindowEvent event) { Object object = event.getSource(); if (object == GridAttributeDialog.this) GridAttributeDialog_WindowClosing(event); } } void GridAttributeDialog_WindowClosing(java.awt.event.WindowEvent event) { dispose(); } //{{DECLARE_CONTROLS javax.swing.JTabbedPane TabbedPane = new javax.swing.JTabbedPane(); javax.swing.JPanel ContourLevelsPanel = new javax.swing.JPanel(); javax.swing.JScrollPane gridScrollPane = new javax.swing.JScrollPane(); javax.swing.JPanel controlPanel = new javax.swing.JPanel(); javax.swing.JPanel JPanel1 = new javax.swing.JPanel(); javax.swing.JButton editButton = new javax.swing.JButton(); javax.swing.JButton aboveButton = new javax.swing.JButton(); javax.swing.JButton belowButton = new javax.swing.JButton(); javax.swing.JButton deleteButton = new javax.swing.JButton(); javax.swing.JPanel JPanel4 = new javax.swing.JPanel(); javax.swing.JButton defaultButton = new javax.swing.JButton(); javax.swing.JButton sortButton = new javax.swing.JButton(); javax.swing.JButton newConLevelButton = new javax.swing.JButton(); javax.swing.JPanel ColorMapPanel = new javax.swing.JPanel(); javax.swing.JPanel colorControlPanel = new javax.swing.JPanel(); javax.swing.JPanel colorMapPanel = new javax.swing.JPanel(); javax.swing.JButton newColorMapButton = new javax.swing.JButton(); javax.swing.JButton loadColorMapButton = new javax.swing.JButton(); javax.swing.JButton saveColorMapButton = new javax.swing.JButton(); javax.swing.JPanel colorPanel = new javax.swing.JPanel(); javax.swing.JPanel CLIndexedPanel = new javax.swing.JPanel(); javax.swing.JPanel CLTransformPanel = new javax.swing.JPanel(); javax.swing.JPanel IndexedPanel = new javax.swing.JPanel(); javax.swing.JPanel colorButtonsPanel = new javax.swing.JPanel(); javax.swing.JPanel TransformPanel = new javax.swing.JPanel(); javax.swing.JPanel buttonPanel = new javax.swing.JPanel(); javax.swing.JButton okButton = new javax.swing.JButton(); javax.swing.JButton applyButton = new javax.swing.JButton(); javax.swing.JButton cancelButton = new javax.swing.JButton(); javax.swing.JPanel mainPanel = new javax.swing.JPanel(); javax.swing.JLabel JLabel5 = new javax.swing.JLabel(); javax.swing.JComboBox gridStyleComboBox = new javax.swing.JComboBox(); javax.swing.border.EtchedBorder etchedBorder1 = new javax.swing.border.EtchedBorder(); DefaultComboBoxModel stringComboBoxModel1 = new DefaultComboBoxModel(); javax.swing.border.EtchedBorder etchedBorder2 = new javax.swing.border.EtchedBorder(); javax.swing.border.TitledBorder titledBorder1 = new javax.swing.border.TitledBorder("Contour Level"); javax.swing.border.EmptyBorder emptyBorder1 = new javax.swing.border.EmptyBorder(5,0,0,0); javax.swing.border.TitledBorder titledBorder4 = new javax.swing.border.TitledBorder("Default Attributes"); javax.swing.border.TitledBorder titledBorder2 = new javax.swing.border.TitledBorder("Color Map"); //}} class SymAction implements java.awt.event.ActionListener { public void actionPerformed(java.awt.event.ActionEvent event) { Object object = event.getSource(); if (object == cancelButton) cancelButton_actionPerformed(event); else if (object == okButton) okButton_actionPerformed(event); else if (object == applyButton) applyButton_actionPerformed(event); else if (object == gridStyleComboBox) gridStyleComboBox_actionPerformed(event); if (object == newConLevelButton) newConLevelButton_actionPerformed(event); if (object == newColorMapButton) newColorMapButton_actionPerformed(event); else if (object == loadColorMapButton) loadColorMapButton_actionPerformed(event); else if (object == editButton) editButton_actionPerformed(event); else if (object == aboveButton) aboveButton_actionPerformed(event); else if (object == belowButton) belowButton_actionPerformed(event); else if (object == deleteButton) deleteButton_actionPerformed(event); else if (object == sortButton) sortButton_actionPerformed(event); else if (object == saveColorMapButton) saveColorMapButton_actionPerformed(event); else if (object == defaultButton) defaultButton_actionPerformed(event); } } void cancelButton_actionPerformed(java.awt.event.ActionEvent event) { this.setVisible(false); } void okButton_actionPerformed(java.awt.event.ActionEvent event) { updateGridAttribute(); this.setVisible(false); } void applyButton_actionPerformed(java.awt.event.ActionEvent event) { updateGridAttribute(); } /** * Set the parent <code>JPane</code>. This reference to * <code>JPane</code> is used to enable/disable * {@link gov.noaa.pmel.sgt.JPane#setBatch(boolean) batching} so * multiple property changes are made at one time. */ public void setJPane(JPane pane) { paneList_ = new JPane[1]; paneList_[0] = pane; } /** * Get the first parent pane. */ public JPane getJPane() { if(paneList_ != null) { return paneList_[0]; } else { return null; } } /** * Set the parent <code>JPane</code>s. These references to * <code>JPane</code> are used to enable/disable * {@link gov.noaa.pmel.sgt.JPane#setBatch(boolean) batching} so * multiple property changes are made at one time. A second * <code>JPane</code> is often used for a <code>ColorKey</code>. */ public void setJPaneList(JPane[] list) { paneList_ = list; } /** Get an array of parent panes. */ public JPane[] getJPaneList() { return paneList_; } /** * Set the <code>GridCartesianRenderer</code>. Specifying the * renderer give <code>GridAttributeDialog</code> a reference to the * data and <code>GridAttribute</code> allowing automated * computation of <code>ColorMap</code> and * <code>ContourLevels</code> ranges. * * @see #setGridAttribute(GridAttribute) */ public void setGridCartesianRenderer(GridCartesianRenderer render) { grid_ = render.getGrid(); setGridAttribute((GridAttribute)render.getAttribute()); } /** * Set the <code>GridAttribute</code>. */ public void setGridAttribute(GridAttribute attr) { attr_ = attr; colorMap_ = attr.getColorMap(); conLevels_ = attr.getContourLevels(); // // style // int style = attr_.getStyle(); gridStyleComboBox.setSelectedIndex(style); // // contour ? // enableContourLevels(style); initContourLevels(); // // raster ? // enableColorMap(style); initColorMap(); // setCurrentTab(); } private void enableContourLevels(int style) { boolean isContour = (style == GridAttribute.CONTOUR || style == GridAttribute.RASTER_CONTOUR || style == GridAttribute.AREA_FILL_CONTOUR); TabbedPane.setEnabledAt(contourLevelIndex_, isContour); Component[] list = ContourLevelsPanel.getComponents(); boolean clExists = conLevels_ != null; for(int i=0; i < list.length; i++) { list[i].setEnabled(clExists); } newConLevelButton.setEnabled(true); } private void enableColorMap(int style) { boolean isRaster = style != GridAttribute.CONTOUR; TabbedPane.setEnabledAt(colorMapIndex_, isRaster); Component[] list = ColorMapPanel.getComponents(); boolean cmExists = colorMap_ != null; for(int i=0; i < list.length; i++) { list[i].setEnabled(cmExists); } newColorMapButton.setEnabled(true); } private void setCurrentTab() { if(!TabbedPane.isEnabledAt(TabbedPane.getSelectedIndex())) { // // change to other tab // if(TabbedPane.getSelectedIndex() == colorMapIndex_) { TabbedPane.setSelectedIndex(contourLevelIndex_); } else { TabbedPane.setSelectedIndex(colorMapIndex_); } } } private void initContourLevels() { createConLevelTable(); } private void initColorMap() { ColorSwatchIcon csi; int i; if(colorMap_ instanceof IndexedColor) { int maxindx = ((IndexedColor)colorMap_).getMaximumIndex(); for(i=0; i <= maxindx; i++) { csi = new ColorSwatchIcon((IndexedColor)colorMap_, i, 8); colorButtons_[i].setIcon(csi); colorButtons_[i].setEnabled(true); } for(i=maxindx+1; i < 256; i++) { csi = new ColorSwatchIcon(Color.white, 8, 8); colorButtons_[i].setIcon(csi); colorButtons_[i].setEnabled(false); } ((CardLayout)colorPanel.getLayout()).show(colorPanel, "Indexed"); } } void updateGridAttribute() { if(paneList_ != null) { for(int i=0; i < paneList_.length; i++) { paneList_[i].setBatch(true, "GridAttributeDialog"); } } updateConLevels(); attr_.setContourLevels(conLevels_); attr_.setColorMap(colorMap_); attr_.setStyle(gridStyleComboBox.getSelectedIndex()); if(paneList_ != null) { for(int i=0; i < paneList_.length; i++) { paneList_[i].setBatch(false, "GridAttributeDialog"); } } } /** * Test entry point. */ public static void main(String[] args) { Range2D range = new Range2D(-20.0f, 45.0f, 5.0f); ContourLevels clevels = ContourLevels.getDefault(range); GridAttribute attr = new GridAttribute(clevels); GridAttributeDialog la = new GridAttributeDialog(); la.setGridAttribute(attr); la.setTitle("Test GridAttribute Dialog"); la.setVisible(true); } void gridStyleComboBox_actionPerformed(java.awt.event.ActionEvent event) { int style = gridStyleComboBox.getSelectedIndex(); // enableContourLevels(style); enableColorMap(style); setCurrentTab(); // } void newConLevelButton_actionPerformed(java.awt.event.ActionEvent event) { NewLevelsDialog nld = new NewLevelsDialog(); int result = nld.showDialog(grid_); if(result == NewLevelsDialog.OK_RESPONSE) { Range2D range = nld.getRange(); conLevels_ = ContourLevels.getDefault(range); initContourLevels(); } } void newColorMapButton_actionPerformed(java.awt.event.ActionEvent event) { // // this will be replaced by a specialized dialog // // // define default colormap (ps.64) // int[] red = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 23, 39, 55, 71, 87,103, 119,135,151,167,183,199,215,231, 247,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,246,228,211,193,175,158,140}; int[] green = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 27, 43, 59, 75, 91,107, 123,139,155,171,187,203,219,235, 251,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,247,231,215,199,183,167,151, 135,119,103, 87, 71, 55, 39, 23, 7, 0, 0, 0, 0, 0, 0, 0}; int[] blue = { 0,143,159,175,191,207,223,239, 255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255, 255,247,231,215,199,183,167,151, 135,119,103, 87, 71, 55, 39, 23, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // colorMap_ = new IndexedColorMap(red, green, blue); ((IndexedColorMap)colorMap_).setTransform(new LinearTransform(0.0, (double)red.length, 0.0, 1.0)); initColorMap(); } void loadColorMapButton_actionPerformed(ActionEvent event) { int[] r = new int[256]; int[] g = new int[256]; int[] b = new int[256]; int lastindx = -1; File file = null; StreamTokenizer st = null; JFileChooser chooser = new JFileChooser("C:/local/pal"); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); try { Reader rdr = new BufferedReader(new FileReader(file)); st = new StreamTokenizer(rdr); } catch (java.io.FileNotFoundException e) { System.out.println(e); return; } try { st.nextToken(); while(st.ttype != StreamTokenizer.TT_EOF) { lastindx++; if(st.ttype == StreamTokenizer.TT_NUMBER) { r[lastindx] = (int)st.nval; st.nextToken(); g[lastindx] = (int)st.nval; st.nextToken(); b[lastindx] = (int)st.nval; } if(st.nextToken() == StreamTokenizer.TT_EOL) st.nextToken(); } } catch (java.io.IOException e) { System.out.println(e); } int[] red = new int[lastindx+1]; int[] green = new int[lastindx+1]; int[] blue = new int[lastindx+1]; for(int i=0; i <= lastindx; i++) { red[i] = r[i]; green[i] = g[i]; blue[i] = b[i]; } colorMap_ = new IndexedColorMap(red, green, blue); ((IndexedColorMap)colorMap_).setTransform(new LinearTransform(0.0, (double)red.length, 0.0, 1.0)); initColorMap(); } } void editButton_actionPerformed(java.awt.event.ActionEvent event) { ContourLineAttribute attr; int index = conLevelTable_.getSelectedRow(); if(index < 0) return; ContourLineAttributeDialog clad = new ContourLineAttributeDialog(); attr = (ContourLineAttribute) ((ContourLineAttribute)conLevelModel_.getValueAt(index,1)).copy(); int result = clad.showDialog(attr); if(result == ContourLineAttributeDialog.OK_RESPONSE) { attr = clad.getContourLineAttribute(); conLevelModel_.setValueAt(attr, index, 1); } } void aboveButton_actionPerformed(java.awt.event.ActionEvent event) { int index = conLevelTable_.getSelectedRow(); if(index < 0) return; conLevelModel_.insert(index, new Double(0.0), new ContourLineAttribute(ContourLineAttribute.SOLID)); } void belowButton_actionPerformed(java.awt.event.ActionEvent event) { int index = conLevelTable_.getSelectedRow(); if(index < 0) return; conLevelModel_.insert(index + 1, new Double(0.0), new ContourLineAttribute(ContourLineAttribute.SOLID)); } void deleteButton_actionPerformed(java.awt.event.ActionEvent event) { int index = conLevelTable_.getSelectedRow(); if(index < 0) return; conLevelModel_.remove(index); } void sortButton_actionPerformed(java.awt.event.ActionEvent event) { conLevelModel_.sort(); } void defaultButton_actionPerformed(java.awt.event.ActionEvent event) { DefaultContourLineAttribute attr; DefaultContourLineAttributeDialog dclad = new DefaultContourLineAttributeDialog(); attr = conLevels_.getDefaultContourLineAttribute(); int result = dclad.showDialog((DefaultContourLineAttribute)attr.copy()); if(result == DefaultContourLineAttributeDialog.OK_RESPONSE) { attr = dclad.getDefaultContourLineAttribute(); conLevels_.setDefaultContourLineAttribute(attr); } } void saveColorMapButton_actionPerformed(java.awt.event.ActionEvent event) { // to do: code goes here. } void createConLevelTable() { Double val; ContourLineAttribute attr; conLevelModel_ = new ConLevelTableModel(); conLevelTable_ = new JTable(conLevelModel_); conLevelTable_.setSize(1000,1000); ListSelectionModel lsm = conLevelTable_.getSelectionModel(); lsm.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); TableColumn tc; tc = conLevelTable_.getColumnModel().getColumn(0); tc.setPreferredWidth(250); tc = conLevelTable_.getColumnModel().getColumn(1); tc.setPreferredWidth(750); gridScrollPane.getViewport().add(conLevelTable_); // if(conLevels_ == null) return; int size = conLevels_.size(); for(int i=0; i < size; i++) { try { val = new Double(conLevels_.getLevel(i)); attr = conLevels_.getContourLineAttribute(i); conLevelModel_.add(val, attr); } catch (ContourLevelNotFoundException e) { System.out.println(e); } } } private void updateConLevels() { if(conLevels_ == null) return; ContourLevels cl = new ContourLevels(); Double val; ContourLineAttribute attr; conLevelModel_.sort(); int size = conLevelModel_.getRowCount(); for(int i=0; i < size; i++) { val = (Double)conLevelModel_.getValueAt(i,0); attr = (ContourLineAttribute)conLevelModel_.getValueAt(i,1); cl.addLevel(val.doubleValue(), attr); } cl.setDefaultContourLineAttribute(conLevels_.getDefaultContourLineAttribute()); conLevels_ = cl; } class ConLevelTableModel extends AbstractTableModel { Vector values = new Vector(); Vector attr = new Vector(); String[] titles = {"Value", "Attribute"}; public void add(Double val, ContourLineAttribute cla) { values.addElement(val); attr.addElement(cla); } public void insert(int row, Double val, ContourLineAttribute cla) { values.insertElementAt(val, row); attr.insertElementAt(cla, row); fireTableChanged(new TableModelEvent(this, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT)); } public void remove(int row) { values.removeElementAt(row); attr.removeElementAt(row); fireTableChanged(new TableModelEvent(this, row, row, TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE)); } public void sort() { // // use brain-dead bubble sort (there will be few lines) // int i, temp; int size = values.size(); Double a, b; int[] index = new int[size]; boolean flipped = true; for(i=0; i < size; i++) { index[i] = i; } while(flipped) { flipped = false; for(i=0; i < size-1; i++) { a = (Double)values.elementAt(index[i]); b = (Double)values.elementAt(index[i+1]); if(a.doubleValue() > b.doubleValue()) { // if(a.compareTo(b) > 0) { // jdk1.2 temp = index[i]; index[i] = index[i+1]; index[i+1] = temp; flipped = true; } } } Vector oldValues = values; Vector oldAttr = attr; values = new Vector(size); attr = new Vector(size); for(i=0; i < size; i++) { values.addElement(oldValues.elementAt(index[i])); attr.addElement(oldAttr.elementAt(index[i])); } fireTableChanged(new TableModelEvent(this)); } public Object getValueAt(int row, int col) { if(col == 0) { return values.elementAt(row); } else { return attr.elementAt(row); } } public void setValueAt(Object obj, int row, int col) { if(col == 0) { if(obj instanceof Double) { values.setElementAt(obj, row); } else if(obj instanceof String) { values.setElementAt(new Double((String)obj), row); } } else { attr.setElementAt(obj, row); } fireTableCellUpdated(row, col); } public int getRowCount() { return values.size(); } public int getColumnCount() { return 2; } public String getColumnName(int col) { return titles[col]; } public boolean isCellEditable(int row, int col) { return col == 0; } } }
luttero/Maud
src/gov/noaa/pmel/sgt/swing/prop/GridAttributeDialog.java
Java
bsd-3-clause
32,899
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/proxy_service_v8.h" #include "base/logging.h" #include "base/thread_task_runner_handle.h" #include "base/threading/thread_checker.h" #include "net/proxy/network_delegate_error_observer.h" #include "net/proxy/proxy_resolver.h" #include "net/proxy/proxy_resolver_factory.h" #include "net/proxy/proxy_resolver_v8_tracing_wrapper.h" #include "net/proxy/proxy_service.h" namespace net { // static ProxyService* CreateProxyServiceUsingV8ProxyResolver( ProxyConfigService* proxy_config_service, ProxyScriptFetcher* proxy_script_fetcher, scoped_ptr<DhcpProxyScriptFetcher> dhcp_proxy_script_fetcher, HostResolver* host_resolver, NetLog* net_log, NetworkDelegate* network_delegate) { DCHECK(proxy_config_service); DCHECK(proxy_script_fetcher); DCHECK(dhcp_proxy_script_fetcher); DCHECK(host_resolver); ProxyService* proxy_service = new ProxyService( proxy_config_service, make_scoped_ptr(new ProxyResolverFactoryV8TracingWrapper( host_resolver, net_log, base::Bind(&NetworkDelegateErrorObserver::Create, network_delegate, base::ThreadTaskRunnerHandle::Get()))), net_log); // Configure fetchers to use for PAC script downloads and auto-detect. proxy_service->SetProxyScriptFetchers(proxy_script_fetcher, dhcp_proxy_script_fetcher.Pass()); return proxy_service; } } // namespace net
Chilledheart/chromium
net/proxy/proxy_service_v8.cc
C++
bsd-3-clause
1,609
<?php /** * PradoBase class file. * * This is the file that establishes the PRADO component model * and error handling mechanism. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.pradosoft.com/ * @copyright Copyright &copy; 2005-2011 PradoSoft * @license http://www.pradosoft.com/license/ * @version $Id: PradoBase.php 3168 2012-06-25 10:43:31Z ctrlaltca $ * @package System */ /** * Defines the PRADO framework installation path. */ if(!defined('PRADO_DIR')) define('PRADO_DIR',dirname(__FILE__)); /** * Defines the default permission for writable directories and files */ if(!defined('PRADO_CHMOD')) define('PRADO_CHMOD',0777); /** * PradoBase class. * * PradoBase implements a few fundamental static methods. * * To use the static methods, Use Prado as the class name rather than PradoBase. * PradoBase is meant to serve as the base class of Prado. The latter might be * rewritten for customization. * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id: PradoBase.php 3168 2012-06-25 10:43:31Z ctrlaltca $ * @package System * @since 3.0 */ class PradoBase { /** * File extension for Prado class files. */ const CLASS_FILE_EXT='.php'; /** * @var array list of path aliases */ private static $_aliases=array('System'=>PRADO_DIR); /** * @var array list of namespaces currently in use */ private static $_usings=array(); /** * @var TApplication the application instance */ private static $_application=null; /** * @var TLogger logger instance */ private static $_logger=null; /** * @var array list of class exists checks */ protected static $classExists = array(); /** * @return string the version of Prado framework */ public static function getVersion() { return '3.2.0'; } /** * Initializes error handlers. * This method set error and exception handlers to be functions * defined in this class. */ public static function initErrorHandlers() { /** * Sets error handler to be Prado::phpErrorHandler */ set_error_handler(array('PradoBase','phpErrorHandler')); /** * Sets exception handler to be Prado::exceptionHandler */ set_exception_handler(array('PradoBase','exceptionHandler')); } /** * Class autoload loader. * This method is provided to be invoked within an __autoload() magic method. * @param string class name */ public static function autoload($className) { include_once($className.self::CLASS_FILE_EXT); if(!class_exists($className,false) && !interface_exists($className,false)) self::fatalError("Class file for '$className' cannot be found."); } /** * @param integer the type of "powered logo". Valid values include 0 and 1. * @return string a string that can be displayed on your Web page showing powered-by-PRADO information */ public static function poweredByPrado($logoType=0) { $logoName=$logoType==1?'powered2':'powered'; if(self::$_application!==null) { $am=self::$_application->getAssetManager(); $url=$am->publishFilePath(self::getPathOfNamespace('System.'.$logoName,'.gif')); } else $url='http://www.pradosoft.com/images/'.$logoName.'.gif'; return '<a title="Powered by PRADO" href="http://www.pradosoft.com/" target="_blank"><img src="'.$url.'" style="border-width:0px;" alt="Powered by PRADO" /></a>'; } /** * PHP error handler. * This method should be registered as PHP error handler using * {@link set_error_handler}. The method throws an exception that * contains the error information. * @param integer the level of the error raised * @param string the error message * @param string the filename that the error was raised in * @param integer the line number the error was raised at */ public static function phpErrorHandler($errno,$errstr,$errfile,$errline) { if(error_reporting() & $errno) throw new TPhpErrorException($errno,$errstr,$errfile,$errline); } /** * Default exception handler. * This method should be registered as default exception handler using * {@link set_exception_handler}. The method tries to use the errorhandler * module of the Prado application to handle the exception. * If the application or the module does not exist, it simply echoes the * exception. * @param Exception exception that is not caught */ public static function exceptionHandler($exception) { if(self::$_application!==null && ($errorHandler=self::$_application->getErrorHandler())!==null) { $errorHandler->handleError(null,$exception); } else { echo $exception; } exit(1); } /** * Stores the application instance in the class static member. * This method helps implement a singleton pattern for TApplication. * Repeated invocation of this method or the application constructor * will cause the throw of an exception. * This method should only be used by framework developers. * @param TApplication the application instance * @throws TInvalidOperationException if this method is invoked twice or more. */ public static function setApplication($application) { if(self::$_application!==null) throw new TInvalidOperationException('prado_application_singleton_required'); self::$_application=$application; } /** * @return TApplication the application singleton, null if the singleton has not be created yet. */ public static function getApplication() { return self::$_application; } /** * @return string the path of the framework */ public static function getFrameworkPath() { return PRADO_DIR; } /** * Serializes a data. * The original PHP serialize function has a bug that may not serialize * properly an object. * @param mixed data to be serialized * @return string the serialized data */ public static function serialize($data) { return serialize($data); } /** * Unserializes a data. * The original PHP unserialize function has a bug that may not unserialize * properly an object. * @param string data to be unserialized * @return mixed unserialized data, null if unserialize failed */ public static function unserialize($str) { return unserialize($str); } /** * Creates a component with the specified type. * A component type can be either the component class name * or a namespace referring to the path of the component class file. * For example, 'TButton', 'System.Web.UI.WebControls.TButton' are both * valid component type. * This method can also pass parameters to component constructors. * All parameters passed to this method except the first one (the component type) * will be supplied as component constructor parameters. * @param string component type * @return TComponent component instance of the specified type * @throws TInvalidDataValueException if the component type is unknown */ public static function createComponent($type) { if(!isset(self::$classExists[$type])) self::$classExists[$type] = class_exists($type, false); if( !isset(self::$_usings[$type]) && !self::$classExists[$type]) { self::using($type); self::$classExists[$type] = class_exists($type, false); } if( ($pos = strrpos($type, '.')) !== false) $type = substr($type,$pos+1); if(($n=func_num_args())>1) { $args = func_get_args(); switch($n) { case 2: return new $type($args[1]); break; case 3: return new $type($args[1], $args[2]); break; case 4: return new $type($args[1], $args[2], $args[3]); break; case 5: return new $type($args[1], $args[2], $args[3], $args[4]); break; default: $s='$args[1]'; for($i=2;$i<$n;++$i) $s.=",\$args[$i]"; eval("\$component=new $type($s);"); return $component; break; } } else return new $type; } /** * Uses a namespace. * A namespace ending with an asterisk '*' refers to a directory, otherwise it represents a PHP file. * If the namespace corresponds to a directory, the directory will be appended * to the include path. If the namespace corresponds to a file, it will be included (include_once). * @param string namespace to be used * @param boolean whether to check the existence of the class after the class file is included * @throws TInvalidDataValueException if the namespace is invalid */ public static function using($namespace,$checkClassExistence=true) { if(isset(self::$_usings[$namespace]) || class_exists($namespace,false)) return; if(($pos=strrpos($namespace,'.'))===false) // a class name { try { include_once($namespace.self::CLASS_FILE_EXT); } catch(Exception $e) { if($checkClassExistence && !class_exists($namespace,false)) throw new TInvalidOperationException('prado_component_unknown',$namespace,$e->getMessage()); else throw $e; } } else if(($path=self::getPathOfNamespace($namespace,self::CLASS_FILE_EXT))!==null) { $className=substr($namespace,$pos+1); if($className==='*') // a directory { self::$_usings[$namespace]=$path; set_include_path(get_include_path().PATH_SEPARATOR.$path); } else // a file { self::$_usings[$namespace]=$path; if(!$checkClassExistence || !class_exists($className,false)) { try { include_once($path); } catch(Exception $e) { if($checkClassExistence && !class_exists($className,false)) throw new TInvalidOperationException('prado_component_unknown',$className,$e->getMessage()); else throw $e; } } } } else throw new TInvalidDataValueException('prado_using_invalid',$namespace); } /** * Translates a namespace into a file path. * The first segment of the namespace is considered as a path alias * which is replaced with the actual path. The rest segments are * subdirectory names appended to the aliased path. * If the namespace ends with an asterisk '*', it represents a directory; * Otherwise it represents a file whose extension name is specified by the second parameter (defaults to empty). * Note, this method does not ensure the existence of the resulting file path. * @param string namespace * @param string extension to be appended if the namespace refers to a file * @return string file path corresponding to the namespace, null if namespace is invalid */ public static function getPathOfNamespace($namespace, $ext='') { if(self::CLASS_FILE_EXT === $ext || empty($ext)) { if(isset(self::$_usings[$namespace])) return self::$_usings[$namespace]; if(isset(self::$_aliases[$namespace])) return self::$_aliases[$namespace]; } $segs = explode('.',$namespace); $alias = array_shift($segs); if(null !== ($file = array_pop($segs)) && null !== ($root = self::getPathOfAlias($alias))) return rtrim($root.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR ,$segs),'/\\').(($file === '*') ? '' : DIRECTORY_SEPARATOR.$file.$ext); return null; } /** * @param string alias to the path * @return string the path corresponding to the alias, null if alias not defined. */ public static function getPathOfAlias($alias) { return isset(self::$_aliases[$alias])?self::$_aliases[$alias]:null; } protected static function getPathAliases() { return self::$_aliases; } /** * @param string alias to the path * @param string the path corresponding to the alias * @throws TInvalidOperationException if the alias is already defined * @throws TInvalidDataValueException if the path is not a valid file path */ public static function setPathOfAlias($alias,$path) { if(isset(self::$_aliases[$alias])) throw new TInvalidOperationException('prado_alias_redefined',$alias); else if(($rp=realpath($path))!==false && is_dir($rp)) { if(strpos($alias,'.')===false) self::$_aliases[$alias]=$rp; else throw new TInvalidDataValueException('prado_aliasname_invalid',$alias); } else throw new TInvalidDataValueException('prado_alias_invalid',$alias,$path); } /** * Fatal error handler. * This method displays an error message together with the current call stack. * The application will exit after calling this method. * @param string error message */ public static function fatalError($msg) { echo '<h1>Fatal Error</h1>'; echo '<p>'.$msg.'</p>'; if(!function_exists('debug_backtrace')) return; echo '<h2>Debug Backtrace</h2>'; echo '<pre>'; $index=-1; foreach(debug_backtrace() as $t) { $index++; if($index==0) // hide the backtrace of this function continue; echo '#'.$index.' '; if(isset($t['file'])) echo basename($t['file']) . ':' . $t['line']; else echo '<PHP inner-code>'; echo ' -- '; if(isset($t['class'])) echo $t['class'] . $t['type']; echo $t['function'] . '('; if(isset($t['args']) && sizeof($t['args']) > 0) { $count=0; foreach($t['args'] as $item) { if(is_string($item)) { $str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES); if (strlen($item) > 70) echo "'". substr($str, 0, 70) . "...'"; else echo "'" . $str . "'"; } else if (is_int($item) || is_float($item)) echo $item; else if (is_object($item)) echo get_class($item); else if (is_array($item)) echo 'array(' . count($item) . ')'; else if (is_bool($item)) echo $item ? 'true' : 'false'; else if ($item === null) echo 'NULL'; else if (is_resource($item)) echo get_resource_type($item); $count++; if (count($t['args']) > $count) echo ', '; } } echo ")\n"; } echo '</pre>'; exit(1); } /** * Returns a list of user preferred languages. * The languages are returned as an array. Each array element * represents a single language preference. The languages are ordered * according to user preferences. The first language is the most preferred. * @return array list of user preferred languages. */ public static function getUserLanguages() { static $languages=null; if($languages===null) { if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $languages[0]='en'; else { $languages=array(); foreach(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']) as $language) { $array=explode(';q=',trim($language)); $languages[trim($array[0])]=isset($array[1])?(float)$array[1]:1.0; } arsort($languages); $languages=array_keys($languages); if(empty($languages)) $languages[0]='en'; } } return $languages; } /** * Returns the most preferred language by the client user. * @return string the most preferred language by the client user, defaults to English. */ public static function getPreferredLanguage() { static $language=null; if($language===null) { $langs=Prado::getUserLanguages(); $lang=explode('-',$langs[0]); if(empty($lang[0]) || !ctype_alpha($lang[0])) $language='en'; else $language=$lang[0]; } return $language; } /** * Writes a log message. * This method wraps {@link log()} by checking the application mode. * When the application is in Debug mode, debug backtrace information is appended * to the message and the message is logged at DEBUG level. * When the application is in Performance mode, this method does nothing. * Otherwise, the message is logged at INFO level. * @param string message to be logged * @param string category of the message * @param (string|TControl) control of the message * @see log, getLogger */ public static function trace($msg,$category='Uncategorized',$ctl=null) { if(self::$_application && self::$_application->getMode()===TApplicationMode::Performance) return; if(!self::$_application || self::$_application->getMode()===TApplicationMode::Debug) { $trace=debug_backtrace(); if(isset($trace[0]['file']) && isset($trace[0]['line'])) $msg.=" (line {$trace[0]['line']}, {$trace[0]['file']})"; $level=TLogger::DEBUG; } else $level=TLogger::INFO; self::log($msg,$level,$category,$ctl); } /** * Logs a message. * Messages logged by this method may be retrieved via {@link TLogger::getLogs} * and may be recorded in different media, such as file, email, database, using * {@link TLogRouter}. * @param string message to be logged * @param integer level of the message. Valid values include * TLogger::DEBUG, TLogger::INFO, TLogger::NOTICE, TLogger::WARNING, * TLogger::ERROR, TLogger::ALERT, TLogger::FATAL. * @param string category of the message * @param (string|TControl) control of the message */ public static function log($msg,$level=TLogger::INFO,$category='Uncategorized',$ctl=null) { if(self::$_logger===null) self::$_logger=new TLogger; self::$_logger->log($msg,$level,$category,$ctl); } /** * @return TLogger message logger */ public static function getLogger() { if(self::$_logger===null) self::$_logger=new TLogger; return self::$_logger; } /** * Converts a variable into a string representation. * This method achieves the similar functionality as var_dump and print_r * but is more robust when handling complex objects such as PRADO controls. * @param mixed variable to be dumped * @param integer maximum depth that the dumper should go into the variable. Defaults to 10. * @param boolean whether to syntax highlight the output. Defaults to false. * @return string the string representation of the variable */ public static function varDump($var,$depth=10,$highlight=false) { Prado::using('System.Util.TVarDumper'); return TVarDumper::dump($var,$depth,$highlight); } /** * Localize a text to the locale/culture specified in the globalization handler. * @param string text to be localized. * @param array a set of parameters to substitute. * @param string a different catalogue to find the localize text. * @param string the input AND output charset. * @return string localized text. * @see TTranslate::formatter() * @see TTranslate::init() */ public static function localize($text, $parameters=array(), $catalogue=null, $charset=null) { Prado::using('System.I18N.Translation'); $app = Prado::getApplication()->getGlobalization(false); $params = array(); foreach($parameters as $key => $value) $params['{'.$key.'}'] = $value; //no translation handler provided if($app===null || ($config = $app->getTranslationConfiguration())===null) return strtr($text, $params); if ($catalogue===null) $catalogue=isset($config['catalogue'])?$config['catalogue']:'messages'; Translation::init($catalogue); //globalization charset $appCharset = $app===null ? '' : $app->getCharset(); //default charset $defaultCharset = ($app===null) ? 'UTF-8' : $app->getDefaultCharset(); //fall back if(empty($charset)) $charset = $appCharset; if(empty($charset)) $charset = $defaultCharset; return Translation::formatter($catalogue)->format($text,$params,$catalogue,$charset); } } /** * Includes the classes essential for PradoBase class */ PradoBase::using('System.TComponent'); PradoBase::using('System.Exceptions.TException'); PradoBase::using('System.Util.TLogger');
wiccano/WDEPRDO
framework/PradoBase.php
PHP
bsd-3-clause
19,078
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !cgo,!windows,!plan9 android vita package user import ( "errors" "fmt" "os" "runtime" "strconv" ) func init() { groupImplemented = false } func current() (*User, error) { u := &User{ Uid: currentUID(), Gid: currentGID(), Username: os.Getenv("USER"), Name: "", // ignored HomeDir: os.Getenv("HOME"), } // On NaCL and Android, return a dummy user instead of failing. switch runtime.GOOS { case "nacl": if u.Uid == "" { u.Uid = "1" } if u.Username == "" { u.Username = "nacl" } if u.HomeDir == "" { u.HomeDir = "/" } case "android": if u.Uid == "" { u.Uid = "1" } if u.Username == "" { u.Username = "android" } if u.HomeDir == "" { u.HomeDir = "/sdcard" } } // cgo isn't available, but if we found the minimum information // without it, use it: if u.Uid != "" && u.Username != "" && u.HomeDir != "" { return u, nil } return u, fmt.Errorf("user: Current not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } func listGroups(*User) ([]string, error) { if runtime.GOOS == "android" { return nil, errors.New("user: GroupIds not implemented on Android") } return nil, errors.New("user: GroupIds requires cgo") } func currentUID() string { if id := os.Getuid(); id >= 0 { return strconv.Itoa(id) } // Note: Windows returns -1, but this file isn't used on // Windows anyway, so this empty return path shouldn't be // used. return "" } func currentGID() string { if id := os.Getgid(); id >= 0 { return strconv.Itoa(id) } return "" }
codestation/go
src/os/user/lookup_stubs.go
GO
bsd-3-clause
1,709
package main import "fmt" import "time" type Ball struct{ hits int } func main() { table := make(chan *Ball) go player("ping", table) go player("pong", table) table <- new(Ball) // game on; toss the ball time.Sleep(1 * time.Second) <-table // game over; grab the ball panic("show the stack") } func player(name string, table chan *Ball) { for { ball := <-table ball.hits++ fmt.Println(name, ball.hits) time.Sleep(100 * time.Millisecond) table <- ball } }
immortal/sandbox
go/goroutine/ping-pong/main.go
GO
bsd-3-clause
480
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.03.15 at 01:54:55 PM MEZ // // Based on the XML schmema: TigerXMLHeader.xsd // Reference: http://www.coli.uni-saarland.de/projects/salsa/ // package tigerxml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for headType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="headType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="meta" type="{}metaType" minOccurs="0"/> * &lt;element name="annotation" type="{}annotationType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="external" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "headType", propOrder = { "meta", "annotation" }) public class Head { protected Meta meta; protected Annotation annotation; @XmlAttribute @XmlSchemaType(name = "anyURI") protected String external; /** * Gets the value of the meta property. * * @return * possible object is * {@link Meta } * */ public Meta getMeta() { return meta; } /** * Sets the value of the meta property. * * @param value * allowed object is * {@link Meta } * */ public void setMeta(Meta value) { this.meta = value; } /** * Gets the value of the annotation property. * * @return * possible object is * {@link Annotation } * */ public Annotation getAnnotation() { if (annotation == null) { annotation = new Annotation(); } return annotation; } /** * Sets the value of the annotation property. * * @param value * allowed object is * {@link Annotation } * */ public void setAnnotation(Annotation value) { this.annotation = value; } /** * Gets the value of the external property. * * @return * possible object is * {@link String } * */ public String getExternal() { return external; } /** * Sets the value of the external property. * * @param value * allowed object is * {@link String } * */ public void setExternal(String value) { this.external = value; } }
svoos/CorpusConverter
src/main/java/tigerxml/Head.java
Java
bsd-3-clause
3,131
package main // Single sender // Multiple receivers - round-robin // Durable // Delayed acknowledgment import ( "fmt" "time" "github.com/streadway/amqp" ) const ( broker = "amqp://localhost" queue1 = "gs3-queue" // Should queue persist beyond broker restart? durable = true // Should queue be deleted once all clients have disconnected? autoDelete = false exclusive = false nowait = false nolocal = false // not supported autoAck = false ) func main() { conn, err := amqp.Dial(broker) if err != nil { fmt.Printf("Couldn't open amqp connection: %v\n", err) return } defer conn.Close() chn, err := conn.Channel() if err != nil { fmt.Printf("Couldn't open amqp channel: %v\n", err) return } defer chn.Close() qq, err := chn.QueueDeclare(queue1, durable, autoDelete, exclusive, nowait, nil) if err != nil { fmt.Printf("Couldn't open amqp queue: %v\n", err) return } fmt.Printf("Queue declared: %s (%d, %d)\n", qq.Name, qq.Consumers, qq.Messages) recv, err := chn.Consume(queue1, "", autoAck, exclusive, nolocal, nowait, nil) if err != nil { fmt.Printf("Couldn't open amqp queue for receiving: %v\n", err) return } var msg amqp.Delivery lastAckd := 0 i := 1 go func() { for { if len(msg.Body) > 0 && lastAckd < i { fmt.Printf("acking up to %d\n", i) msg.Ack(true) lastAckd = i } time.Sleep(5000 * time.Millisecond) } }() for msg = range recv { fmt.Printf("[%03d] msg: %v\n", i, msg) i++ } fmt.Printf("messages done...\n") }
dterei/Scraps
amqp/gs3/recv.go
GO
bsd-3-clause
1,522
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import collections import itertools from contextlib import contextmanager import six from cryptography import utils from cryptography.exceptions import ( InternalError, UnsupportedAlgorithm, _Reasons ) from cryptography.hazmat.backends.interfaces import ( CMACBackend, CipherBackend, DERSerializationBackend, DSABackend, EllipticCurveBackend, HMACBackend, HashBackend, PBKDF2HMACBackend, PEMSerializationBackend, RSABackend, X509Backend ) from cryptography.hazmat.backends.openssl.ciphers import ( _AESCTRCipherContext, _CipherContext ) from cryptography.hazmat.backends.openssl.cmac import _CMACContext from cryptography.hazmat.backends.openssl.dsa import ( _DSAParameters, _DSAPrivateKey, _DSAPublicKey ) from cryptography.hazmat.backends.openssl.ec import ( _EllipticCurvePrivateKey, _EllipticCurvePublicKey ) from cryptography.hazmat.backends.openssl.hashes import _HashContext from cryptography.hazmat.backends.openssl.hmac import _HMACContext from cryptography.hazmat.backends.openssl.rsa import ( _RSAPrivateKey, _RSAPublicKey ) from cryptography.hazmat.backends.openssl.x509 import ( _Certificate, _CertificateSigningRequest ) from cryptography.hazmat.bindings.openssl.binding import Binding from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa from cryptography.hazmat.primitives.asymmetric.padding import ( MGF1, OAEP, PKCS1v15, PSS ) from cryptography.hazmat.primitives.ciphers.algorithms import ( AES, ARC4, Blowfish, CAST5, Camellia, IDEA, SEED, TripleDES ) from cryptography.hazmat.primitives.ciphers.modes import ( CBC, CFB, CFB8, CTR, ECB, GCM, OFB ) _MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"]) _OpenSSLError = collections.namedtuple("_OpenSSLError", ["code", "lib", "func", "reason"]) @utils.register_interface(CipherBackend) @utils.register_interface(CMACBackend) @utils.register_interface(DERSerializationBackend) @utils.register_interface(DSABackend) @utils.register_interface(EllipticCurveBackend) @utils.register_interface(HashBackend) @utils.register_interface(HMACBackend) @utils.register_interface(PBKDF2HMACBackend) @utils.register_interface(RSABackend) @utils.register_interface(PEMSerializationBackend) @utils.register_interface(X509Backend) class Backend(object): """ OpenSSL API binding interfaces. """ name = "openssl" def __init__(self): self._binding = Binding() self._ffi = self._binding.ffi self._lib = self._binding.lib self._binding.init_static_locks() # adds all ciphers/digests for EVP self._lib.OpenSSL_add_all_algorithms() # registers available SSL/TLS ciphers and digests self._lib.SSL_library_init() # loads error strings for libcrypto and libssl functions self._lib.SSL_load_error_strings() self._cipher_registry = {} self._register_default_ciphers() self.activate_osrandom_engine() def activate_builtin_random(self): # Obtain a new structural reference. e = self._lib.ENGINE_get_default_RAND() if e != self._ffi.NULL: self._lib.ENGINE_unregister_RAND(e) # Reset the RNG to use the new engine. self._lib.RAND_cleanup() # decrement the structural reference from get_default_RAND res = self._lib.ENGINE_finish(e) assert res == 1 def activate_osrandom_engine(self): # Unregister and free the current engine. self.activate_builtin_random() # Fetches an engine by id and returns it. This creates a structural # reference. e = self._lib.ENGINE_by_id(self._lib.Cryptography_osrandom_engine_id) assert e != self._ffi.NULL # Initialize the engine for use. This adds a functional reference. res = self._lib.ENGINE_init(e) assert res == 1 # Set the engine as the default RAND provider. res = self._lib.ENGINE_set_default_RAND(e) assert res == 1 # Decrement the structural ref incremented by ENGINE_by_id. res = self._lib.ENGINE_free(e) assert res == 1 # Decrement the functional ref incremented by ENGINE_init. res = self._lib.ENGINE_finish(e) assert res == 1 # Reset the RNG to use the new engine. self._lib.RAND_cleanup() def openssl_version_text(self): """ Friendly string name of the loaded OpenSSL library. This is not necessarily the same version as it was compiled against. Example: OpenSSL 1.0.1e 11 Feb 2013 """ return self._ffi.string( self._lib.SSLeay_version(self._lib.SSLEAY_VERSION) ).decode("ascii") def create_hmac_ctx(self, key, algorithm): return _HMACContext(self, key, algorithm) def hash_supported(self, algorithm): digest = self._lib.EVP_get_digestbyname(algorithm.name.encode("ascii")) return digest != self._ffi.NULL def hmac_supported(self, algorithm): return self.hash_supported(algorithm) def create_hash_ctx(self, algorithm): return _HashContext(self, algorithm) def cipher_supported(self, cipher, mode): if self._evp_cipher_supported(cipher, mode): return True elif isinstance(mode, CTR) and isinstance(cipher, AES): return True else: return False def _evp_cipher_supported(self, cipher, mode): try: adapter = self._cipher_registry[type(cipher), type(mode)] except KeyError: return False evp_cipher = adapter(self, cipher, mode) return self._ffi.NULL != evp_cipher def register_cipher_adapter(self, cipher_cls, mode_cls, adapter): if (cipher_cls, mode_cls) in self._cipher_registry: raise ValueError("Duplicate registration for: {0} {1}.".format( cipher_cls, mode_cls) ) self._cipher_registry[cipher_cls, mode_cls] = adapter def _register_default_ciphers(self): for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8]: self.register_cipher_adapter( AES, mode_cls, GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") ) for mode_cls in [CBC, CTR, ECB, OFB, CFB]: self.register_cipher_adapter( Camellia, mode_cls, GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") ) for mode_cls in [CBC, CFB, CFB8, OFB]: self.register_cipher_adapter( TripleDES, mode_cls, GetCipherByName("des-ede3-{mode.name}") ) self.register_cipher_adapter( TripleDES, ECB, GetCipherByName("des-ede3") ) for mode_cls in [CBC, CFB, OFB, ECB]: self.register_cipher_adapter( Blowfish, mode_cls, GetCipherByName("bf-{mode.name}") ) for mode_cls in [CBC, CFB, OFB, ECB]: self.register_cipher_adapter( SEED, mode_cls, GetCipherByName("seed-{mode.name}") ) for cipher_cls, mode_cls in itertools.product( [CAST5, IDEA], [CBC, OFB, CFB, ECB], ): self.register_cipher_adapter( cipher_cls, mode_cls, GetCipherByName("{cipher.name}-{mode.name}") ) self.register_cipher_adapter( ARC4, type(None), GetCipherByName("rc4") ) self.register_cipher_adapter( AES, GCM, GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") ) def create_symmetric_encryption_ctx(self, cipher, mode): if (isinstance(mode, CTR) and isinstance(cipher, AES) and not self._evp_cipher_supported(cipher, mode)): # This is needed to provide support for AES CTR mode in OpenSSL # 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5 # extended life ends 2020). return _AESCTRCipherContext(self, cipher, mode) else: return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT) def create_symmetric_decryption_ctx(self, cipher, mode): if (isinstance(mode, CTR) and isinstance(cipher, AES) and not self._evp_cipher_supported(cipher, mode)): # This is needed to provide support for AES CTR mode in OpenSSL # 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5 # extended life ends 2020). return _AESCTRCipherContext(self, cipher, mode) else: return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT) def pbkdf2_hmac_supported(self, algorithm): if self._lib.Cryptography_HAS_PBKDF2_HMAC: return self.hmac_supported(algorithm) else: # OpenSSL < 1.0.0 has an explicit PBKDF2-HMAC-SHA1 function, # so if the PBKDF2_HMAC function is missing we only support # SHA1 via PBKDF2_HMAC_SHA1. return isinstance(algorithm, hashes.SHA1) def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations, key_material): buf = self._ffi.new("char[]", length) if self._lib.Cryptography_HAS_PBKDF2_HMAC: evp_md = self._lib.EVP_get_digestbyname( algorithm.name.encode("ascii")) assert evp_md != self._ffi.NULL res = self._lib.PKCS5_PBKDF2_HMAC( key_material, len(key_material), salt, len(salt), iterations, evp_md, length, buf ) assert res == 1 else: if not isinstance(algorithm, hashes.SHA1): raise UnsupportedAlgorithm( "This version of OpenSSL only supports PBKDF2HMAC with " "SHA1.", _Reasons.UNSUPPORTED_HASH ) res = self._lib.PKCS5_PBKDF2_HMAC_SHA1( key_material, len(key_material), salt, len(salt), iterations, length, buf ) assert res == 1 return self._ffi.buffer(buf)[:] def _err_string(self, code): err_buf = self._ffi.new("char[]", 256) self._lib.ERR_error_string_n(code, err_buf, 256) return self._ffi.string(err_buf, 256)[:] def _consume_errors(self): errors = [] while True: code = self._lib.ERR_get_error() if code == 0: break lib = self._lib.ERR_GET_LIB(code) func = self._lib.ERR_GET_FUNC(code) reason = self._lib.ERR_GET_REASON(code) errors.append(_OpenSSLError(code, lib, func, reason)) return errors def _unknown_error(self, error): return InternalError( "Unknown error code {0} from OpenSSL, " "you should probably file a bug. {1}.".format( error.code, self._err_string(error.code) ) ) def _bn_to_int(self, bn): assert bn != self._ffi.NULL if six.PY3: # Python 3 has constant time from_bytes, so use that. bn_num_bytes = (self._lib.BN_num_bits(bn) + 7) // 8 bin_ptr = self._ffi.new("unsigned char[]", bn_num_bytes) bin_len = self._lib.BN_bn2bin(bn, bin_ptr) # A zero length means the BN has value 0 assert bin_len >= 0 assert bin_ptr != self._ffi.NULL return int.from_bytes(self._ffi.buffer(bin_ptr)[:bin_len], "big") else: # Under Python 2 the best we can do is hex() hex_cdata = self._lib.BN_bn2hex(bn) assert hex_cdata != self._ffi.NULL hex_str = self._ffi.string(hex_cdata) self._lib.OPENSSL_free(hex_cdata) return int(hex_str, 16) def _int_to_bn(self, num, bn=None): """ Converts a python integer to a BIGNUM. The returned BIGNUM will not be garbage collected (to support adding them to structs that take ownership of the object). Be sure to register it for GC if it will be discarded after use. """ assert bn is None or bn != self._ffi.NULL if bn is None: bn = self._ffi.NULL if six.PY3: # Python 3 has constant time to_bytes, so use that. binary = num.to_bytes(int(num.bit_length() / 8.0 + 1), "big") bn_ptr = self._lib.BN_bin2bn(binary, len(binary), bn) assert bn_ptr != self._ffi.NULL return bn_ptr else: # Under Python 2 the best we can do is hex() hex_num = hex(num).rstrip("L").lstrip("0x").encode("ascii") or b"0" bn_ptr = self._ffi.new("BIGNUM **") bn_ptr[0] = bn res = self._lib.BN_hex2bn(bn_ptr, hex_num) assert res != 0 assert bn_ptr[0] != self._ffi.NULL return bn_ptr[0] def generate_rsa_private_key(self, public_exponent, key_size): rsa._verify_rsa_parameters(public_exponent, key_size) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) bn = self._int_to_bn(public_exponent) bn = self._ffi.gc(bn, self._lib.BN_free) res = self._lib.RSA_generate_key_ex( rsa_cdata, key_size, bn, self._ffi.NULL ) assert res == 1 evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPrivateKey(self, rsa_cdata, evp_pkey) def generate_rsa_parameters_supported(self, public_exponent, key_size): return (public_exponent >= 3 and public_exponent & 1 != 0 and key_size >= 512) def load_rsa_private_numbers(self, numbers): rsa._check_private_key_components( numbers.p, numbers.q, numbers.d, numbers.dmp1, numbers.dmq1, numbers.iqmp, numbers.public_numbers.e, numbers.public_numbers.n ) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) rsa_cdata.p = self._int_to_bn(numbers.p) rsa_cdata.q = self._int_to_bn(numbers.q) rsa_cdata.d = self._int_to_bn(numbers.d) rsa_cdata.dmp1 = self._int_to_bn(numbers.dmp1) rsa_cdata.dmq1 = self._int_to_bn(numbers.dmq1) rsa_cdata.iqmp = self._int_to_bn(numbers.iqmp) rsa_cdata.e = self._int_to_bn(numbers.public_numbers.e) rsa_cdata.n = self._int_to_bn(numbers.public_numbers.n) res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL) assert res == 1 evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPrivateKey(self, rsa_cdata, evp_pkey) def load_rsa_public_numbers(self, numbers): rsa._check_public_key_components(numbers.e, numbers.n) rsa_cdata = self._lib.RSA_new() assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) rsa_cdata.e = self._int_to_bn(numbers.e) rsa_cdata.n = self._int_to_bn(numbers.n) res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL) assert res == 1 evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPublicKey(self, rsa_cdata, evp_pkey) def _rsa_cdata_to_evp_pkey(self, rsa_cdata): evp_pkey = self._lib.EVP_PKEY_new() assert evp_pkey != self._ffi.NULL evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) res = self._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata) assert res == 1 return evp_pkey def _bytes_to_bio(self, data): """ Return a _MemoryBIO namedtuple of (BIO, char*). The char* is the storage for the BIO and it must stay alive until the BIO is finished with. """ data_char_p = self._ffi.new("char[]", data) bio = self._lib.BIO_new_mem_buf( data_char_p, len(data) ) assert bio != self._ffi.NULL return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_char_p) def _create_mem_bio(self): """ Creates an empty memory BIO. """ bio_method = self._lib.BIO_s_mem() assert bio_method != self._ffi.NULL bio = self._lib.BIO_new(bio_method) assert bio != self._ffi.NULL bio = self._ffi.gc(bio, self._lib.BIO_free) return bio def _read_mem_bio(self, bio): """ Reads a memory BIO. This only works on memory BIOs. """ buf = self._ffi.new("char **") buf_len = self._lib.BIO_get_mem_data(bio, buf) assert buf_len > 0 assert buf[0] != self._ffi.NULL bio_data = self._ffi.buffer(buf[0], buf_len)[:] return bio_data def _evp_pkey_to_private_key(self, evp_pkey): """ Return the appropriate type of PrivateKey given an evp_pkey cdata pointer. """ key_type = evp_pkey.type if key_type == self._lib.EVP_PKEY_RSA: rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) return _RSAPrivateKey(self, rsa_cdata, evp_pkey) elif key_type == self._lib.EVP_PKEY_DSA: dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey) assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) return _DSAPrivateKey(self, dsa_cdata, evp_pkey) elif (self._lib.Cryptography_HAS_EC == 1 and key_type == self._lib.EVP_PKEY_EC): ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) else: raise UnsupportedAlgorithm("Unsupported key type.") def _evp_pkey_to_public_key(self, evp_pkey): """ Return the appropriate type of PublicKey given an evp_pkey cdata pointer. """ key_type = evp_pkey.type if key_type == self._lib.EVP_PKEY_RSA: rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey) assert rsa_cdata != self._ffi.NULL rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) return _RSAPublicKey(self, rsa_cdata, evp_pkey) elif key_type == self._lib.EVP_PKEY_DSA: dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey) assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) return _DSAPublicKey(self, dsa_cdata, evp_pkey) elif (self._lib.Cryptography_HAS_EC == 1 and key_type == self._lib.EVP_PKEY_EC): ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) else: raise UnsupportedAlgorithm("Unsupported key type.") def _pem_password_cb(self, password): """ Generate a pem_password_cb function pointer that copied the password to OpenSSL as required and returns the number of bytes copied. typedef int pem_password_cb(char *buf, int size, int rwflag, void *userdata); Useful for decrypting PKCS8 files and so on. Returns a tuple of (cdata function pointer, callback function). """ def pem_password_cb(buf, size, writing, userdata): pem_password_cb.called += 1 if not password: pem_password_cb.exception = TypeError( "Password was not given but private key is encrypted." ) return 0 elif len(password) < size: pw_buf = self._ffi.buffer(buf, size) pw_buf[:len(password)] = password return len(password) else: pem_password_cb.exception = ValueError( "Passwords longer than {0} bytes are not supported " "by this backend.".format(size - 1) ) return 0 pem_password_cb.called = 0 pem_password_cb.exception = None return ( self._ffi.callback("int (char *, int, int, void *)", pem_password_cb), pem_password_cb ) def _mgf1_hash_supported(self, algorithm): if self._lib.Cryptography_HAS_MGF1_MD: return self.hash_supported(algorithm) else: return isinstance(algorithm, hashes.SHA1) def rsa_padding_supported(self, padding): if isinstance(padding, PKCS1v15): return True elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): return self._mgf1_hash_supported(padding._mgf._algorithm) elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): return isinstance(padding._mgf._algorithm, hashes.SHA1) else: return False def generate_dsa_parameters(self, key_size): if key_size not in (1024, 2048, 3072): raise ValueError( "Key size must be 1024 or 2048 or 3072 bits.") if (self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f and key_size > 1024): raise ValueError( "Key size must be 1024 because OpenSSL < 1.0.0 doesn't " "support larger key sizes.") ctx = self._lib.DSA_new() assert ctx != self._ffi.NULL ctx = self._ffi.gc(ctx, self._lib.DSA_free) res = self._lib.DSA_generate_parameters_ex( ctx, key_size, self._ffi.NULL, 0, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) assert res == 1 return _DSAParameters(self, ctx) def generate_dsa_private_key(self, parameters): ctx = self._lib.DSA_new() assert ctx != self._ffi.NULL ctx = self._ffi.gc(ctx, self._lib.DSA_free) ctx.p = self._lib.BN_dup(parameters._dsa_cdata.p) ctx.q = self._lib.BN_dup(parameters._dsa_cdata.q) ctx.g = self._lib.BN_dup(parameters._dsa_cdata.g) self._lib.DSA_generate_key(ctx) evp_pkey = self._dsa_cdata_to_evp_pkey(ctx) return _DSAPrivateKey(self, ctx, evp_pkey) def generate_dsa_private_key_and_parameters(self, key_size): parameters = self.generate_dsa_parameters(key_size) return self.generate_dsa_private_key(parameters) def load_dsa_private_numbers(self, numbers): dsa._check_dsa_private_numbers(numbers) parameter_numbers = numbers.public_numbers.parameter_numbers dsa_cdata = self._lib.DSA_new() assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) dsa_cdata.p = self._int_to_bn(parameter_numbers.p) dsa_cdata.q = self._int_to_bn(parameter_numbers.q) dsa_cdata.g = self._int_to_bn(parameter_numbers.g) dsa_cdata.pub_key = self._int_to_bn(numbers.public_numbers.y) dsa_cdata.priv_key = self._int_to_bn(numbers.x) evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata) return _DSAPrivateKey(self, dsa_cdata, evp_pkey) def load_dsa_public_numbers(self, numbers): dsa._check_dsa_parameters(numbers.parameter_numbers) dsa_cdata = self._lib.DSA_new() assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) dsa_cdata.p = self._int_to_bn(numbers.parameter_numbers.p) dsa_cdata.q = self._int_to_bn(numbers.parameter_numbers.q) dsa_cdata.g = self._int_to_bn(numbers.parameter_numbers.g) dsa_cdata.pub_key = self._int_to_bn(numbers.y) evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata) return _DSAPublicKey(self, dsa_cdata, evp_pkey) def load_dsa_parameter_numbers(self, numbers): dsa._check_dsa_parameters(numbers) dsa_cdata = self._lib.DSA_new() assert dsa_cdata != self._ffi.NULL dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free) dsa_cdata.p = self._int_to_bn(numbers.p) dsa_cdata.q = self._int_to_bn(numbers.q) dsa_cdata.g = self._int_to_bn(numbers.g) return _DSAParameters(self, dsa_cdata) def _dsa_cdata_to_evp_pkey(self, dsa_cdata): evp_pkey = self._lib.EVP_PKEY_new() assert evp_pkey != self._ffi.NULL evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) res = self._lib.EVP_PKEY_set1_DSA(evp_pkey, dsa_cdata) assert res == 1 return evp_pkey def dsa_hash_supported(self, algorithm): if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f: return isinstance(algorithm, hashes.SHA1) else: return self.hash_supported(algorithm) def dsa_parameters_supported(self, p, q, g): if self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f: return utils.bit_length(p) <= 1024 and utils.bit_length(q) <= 160 else: return True def cmac_algorithm_supported(self, algorithm): return ( self._lib.Cryptography_HAS_CMAC == 1 and self.cipher_supported( algorithm, CBC(b"\x00" * algorithm.block_size) ) ) def create_cmac_ctx(self, algorithm): return _CMACContext(self, algorithm) def load_pem_private_key(self, data, password): return self._load_key( self._lib.PEM_read_bio_PrivateKey, self._evp_pkey_to_private_key, data, password, ) def load_pem_public_key(self, data): mem_bio = self._bytes_to_bio(data) evp_pkey = self._lib.PEM_read_bio_PUBKEY( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if evp_pkey != self._ffi.NULL: evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) return self._evp_pkey_to_public_key(evp_pkey) else: # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still # need to check to see if it is a pure PKCS1 RSA public key (not # embedded in a subjectPublicKeyInfo) self._consume_errors() res = self._lib.BIO_reset(mem_bio.bio) assert res == 1 rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if rsa_cdata != self._ffi.NULL: rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPublicKey(self, rsa_cdata, evp_pkey) else: self._handle_key_loading_error() def load_der_private_key(self, data, password): # OpenSSL has a function called d2i_AutoPrivateKey that can simplify # this. Unfortunately it doesn't properly support PKCS8 on OpenSSL # 0.9.8 so we can't use it. Instead we sequentially try to load it 3 # different ways. First we'll try to load it as a traditional key bio_data = self._bytes_to_bio(data) key = self._evp_pkey_from_der_traditional_key(bio_data, password) if not key: # Okay so it's not a traditional key. Let's try # PKCS8 unencrypted. OpenSSL 0.9.8 can't load unencrypted # PKCS8 keys using d2i_PKCS8PrivateKey_bio so we do this instead. # Reset the memory BIO so we can read the data again. res = self._lib.BIO_reset(bio_data.bio) assert res == 1 key = self._evp_pkey_from_der_unencrypted_pkcs8(bio_data, password) if key: return self._evp_pkey_to_private_key(key) else: # Finally we try to load it with the method that handles encrypted # PKCS8 properly. return self._load_key( self._lib.d2i_PKCS8PrivateKey_bio, self._evp_pkey_to_private_key, data, password, ) def _evp_pkey_from_der_traditional_key(self, bio_data, password): key = self._lib.d2i_PrivateKey_bio(bio_data.bio, self._ffi.NULL) if key != self._ffi.NULL: key = self._ffi.gc(key, self._lib.EVP_PKEY_free) if password is not None: raise TypeError( "Password was given but private key is not encrypted." ) return key else: self._consume_errors() return None def _evp_pkey_from_der_unencrypted_pkcs8(self, bio_data, password): info = self._lib.d2i_PKCS8_PRIV_KEY_INFO_bio( bio_data.bio, self._ffi.NULL ) info = self._ffi.gc(info, self._lib.PKCS8_PRIV_KEY_INFO_free) if info != self._ffi.NULL: key = self._lib.EVP_PKCS82PKEY(info) assert key != self._ffi.NULL key = self._ffi.gc(key, self._lib.EVP_PKEY_free) if password is not None: raise TypeError( "Password was given but private key is not encrypted." ) return key else: self._consume_errors() return None def load_der_public_key(self, data): mem_bio = self._bytes_to_bio(data) evp_pkey = self._lib.d2i_PUBKEY_bio(mem_bio.bio, self._ffi.NULL) if evp_pkey != self._ffi.NULL: evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) return self._evp_pkey_to_public_key(evp_pkey) else: # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still # need to check to see if it is a pure PKCS1 RSA public key (not # embedded in a subjectPublicKeyInfo) self._consume_errors() res = self._lib.BIO_reset(mem_bio.bio) assert res == 1 rsa_cdata = self._lib.d2i_RSAPublicKey_bio( mem_bio.bio, self._ffi.NULL ) if rsa_cdata != self._ffi.NULL: rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata) return _RSAPublicKey(self, rsa_cdata, evp_pkey) else: self._handle_key_loading_error() def load_pem_x509_certificate(self, data): mem_bio = self._bytes_to_bio(data) x509 = self._lib.PEM_read_bio_X509( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if x509 == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load certificate") x509 = self._ffi.gc(x509, self._lib.X509_free) return _Certificate(self, x509) def load_der_x509_certificate(self, data): mem_bio = self._bytes_to_bio(data) x509 = self._lib.d2i_X509_bio(mem_bio.bio, self._ffi.NULL) if x509 == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load certificate") x509 = self._ffi.gc(x509, self._lib.X509_free) return _Certificate(self, x509) def load_pem_x509_csr(self, data): mem_bio = self._bytes_to_bio(data) x509_req = self._lib.PEM_read_bio_X509_REQ( mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL ) if x509_req == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load request") x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free) return _CertificateSigningRequest(self, x509_req) def load_der_x509_csr(self, data): mem_bio = self._bytes_to_bio(data) x509_req = self._lib.d2i_X509_REQ_bio(mem_bio.bio, self._ffi.NULL) if x509_req == self._ffi.NULL: self._consume_errors() raise ValueError("Unable to load request") x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free) return _CertificateSigningRequest(self, x509_req) def _load_key(self, openssl_read_func, convert_func, data, password): mem_bio = self._bytes_to_bio(data) password_callback, password_func = self._pem_password_cb(password) evp_pkey = openssl_read_func( mem_bio.bio, self._ffi.NULL, password_callback, self._ffi.NULL ) if evp_pkey == self._ffi.NULL: if password_func.exception is not None: errors = self._consume_errors() assert errors raise password_func.exception else: self._handle_key_loading_error() evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) if password is not None and password_func.called == 0: raise TypeError( "Password was given but private key is not encrypted.") assert ( (password is not None and password_func.called == 1) or password is None ) return convert_func(evp_pkey) def _handle_key_loading_error(self): errors = self._consume_errors() if not errors: raise ValueError("Could not unserialize key data.") elif errors[0][1:] in ( ( self._lib.ERR_LIB_EVP, self._lib.EVP_F_EVP_DECRYPTFINAL_EX, self._lib.EVP_R_BAD_DECRYPT ), ( self._lib.ERR_LIB_PKCS12, self._lib.PKCS12_F_PKCS12_PBE_CRYPT, self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR, ) ): raise ValueError("Bad decrypt. Incorrect password?") elif errors[0][1:] in ( ( self._lib.ERR_LIB_PEM, self._lib.PEM_F_PEM_GET_EVP_CIPHER_INFO, self._lib.PEM_R_UNSUPPORTED_ENCRYPTION ), ( self._lib.ERR_LIB_EVP, self._lib.EVP_F_EVP_PBE_CIPHERINIT, self._lib.EVP_R_UNKNOWN_PBE_ALGORITHM ) ): raise UnsupportedAlgorithm( "PEM data is encrypted with an unsupported cipher", _Reasons.UNSUPPORTED_CIPHER ) elif any( error[1:] == ( self._lib.ERR_LIB_EVP, self._lib.EVP_F_EVP_PKCS82PKEY, self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM ) for error in errors ): raise UnsupportedAlgorithm( "Unsupported public key algorithm.", _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ) else: assert errors[0][1] in ( self._lib.ERR_LIB_EVP, self._lib.ERR_LIB_PEM, self._lib.ERR_LIB_ASN1, ) raise ValueError("Could not unserialize key data.") def elliptic_curve_supported(self, curve): if self._lib.Cryptography_HAS_EC != 1: return False try: curve_nid = self._elliptic_curve_to_nid(curve) except UnsupportedAlgorithm: curve_nid = self._lib.NID_undef ctx = self._lib.EC_GROUP_new_by_curve_name(curve_nid) if ctx == self._ffi.NULL: errors = self._consume_errors() assert ( curve_nid == self._lib.NID_undef or errors[0][1:] == ( self._lib.ERR_LIB_EC, self._lib.EC_F_EC_GROUP_NEW_BY_CURVE_NAME, self._lib.EC_R_UNKNOWN_GROUP ) ) return False else: assert curve_nid != self._lib.NID_undef self._lib.EC_GROUP_free(ctx) return True def elliptic_curve_signature_algorithm_supported( self, signature_algorithm, curve ): if self._lib.Cryptography_HAS_EC != 1: return False # We only support ECDSA right now. if not isinstance(signature_algorithm, ec.ECDSA): return False # Before 0.9.8m OpenSSL can't cope with digests longer than the curve. if ( self._lib.OPENSSL_VERSION_NUMBER < 0x009080df and curve.key_size < signature_algorithm.algorithm.digest_size * 8 ): return False return self.elliptic_curve_supported(curve) def generate_elliptic_curve_private_key(self, curve): """ Generate a new private key on the named curve. """ if self.elliptic_curve_supported(curve): curve_nid = self._elliptic_curve_to_nid(curve) ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) res = self._lib.EC_KEY_generate_key(ec_cdata) assert res == 1 res = self._lib.EC_KEY_check_key(ec_cdata) assert res == 1 evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) else: raise UnsupportedAlgorithm( "Backend object does not support {0}.".format(curve.name), _Reasons.UNSUPPORTED_ELLIPTIC_CURVE ) def load_elliptic_curve_private_numbers(self, numbers): public = numbers.public_numbers curve_nid = self._elliptic_curve_to_nid(public.curve) ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) ec_cdata = self._ec_key_set_public_key_affine_coordinates( ec_cdata, public.x, public.y) res = self._lib.EC_KEY_set_private_key( ec_cdata, self._int_to_bn(numbers.private_value)) assert res == 1 evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey) def load_elliptic_curve_public_numbers(self, numbers): curve_nid = self._elliptic_curve_to_nid(numbers.curve) ec_cdata = self._lib.EC_KEY_new_by_curve_name(curve_nid) assert ec_cdata != self._ffi.NULL ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free) ec_cdata = self._ec_key_set_public_key_affine_coordinates( ec_cdata, numbers.x, numbers.y) evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) def _ec_cdata_to_evp_pkey(self, ec_cdata): evp_pkey = self._lib.EVP_PKEY_new() assert evp_pkey != self._ffi.NULL evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free) res = self._lib.EVP_PKEY_set1_EC_KEY(evp_pkey, ec_cdata) assert res == 1 def _elliptic_curve_to_nid(self, curve): """ Get the NID for a curve name. """ curve_aliases = { "secp192r1": "prime192v1", "secp256r1": "prime256v1" } curve_name = curve_aliases.get(curve.name, curve.name) curve_nid = self._lib.OBJ_sn2nid(curve_name.encode()) if curve_nid == self._lib.NID_undef: raise UnsupportedAlgorithm( "{0} is not a supported elliptic curve".format(curve.name), _Reasons.UNSUPPORTED_ELLIPTIC_CURVE ) return curve_nid @contextmanager def _tmp_bn_ctx(self): bn_ctx = self._lib.BN_CTX_new() assert bn_ctx != self._ffi.NULL bn_ctx = self._ffi.gc(bn_ctx, self._lib.BN_CTX_free) self._lib.BN_CTX_start(bn_ctx) try: yield bn_ctx finally: self._lib.BN_CTX_end(bn_ctx) def _ec_key_determine_group_get_set_funcs(self, ctx): """ Given an EC_KEY determine the group and what methods are required to get/set point coordinates. """ assert ctx != self._ffi.NULL nid_two_field = self._lib.OBJ_sn2nid(b"characteristic-two-field") assert nid_two_field != self._lib.NID_undef group = self._lib.EC_KEY_get0_group(ctx) assert group != self._ffi.NULL method = self._lib.EC_GROUP_method_of(group) assert method != self._ffi.NULL nid = self._lib.EC_METHOD_get_field_type(method) assert nid != self._lib.NID_undef if nid == nid_two_field and self._lib.Cryptography_HAS_EC2M: set_func = self._lib.EC_POINT_set_affine_coordinates_GF2m get_func = self._lib.EC_POINT_get_affine_coordinates_GF2m else: set_func = self._lib.EC_POINT_set_affine_coordinates_GFp get_func = self._lib.EC_POINT_get_affine_coordinates_GFp assert set_func and get_func return set_func, get_func, group def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y): """ This is a port of EC_KEY_set_public_key_affine_coordinates that was added in 1.0.1. Sets the public key point in the EC_KEY context to the affine x and y values. """ if x < 0 or y < 0: raise ValueError( "Invalid EC key. Both x and y must be non-negative." ) set_func, get_func, group = ( self._ec_key_determine_group_get_set_funcs(ctx) ) point = self._lib.EC_POINT_new(group) assert point != self._ffi.NULL point = self._ffi.gc(point, self._lib.EC_POINT_free) bn_x = self._int_to_bn(x) bn_y = self._int_to_bn(y) with self._tmp_bn_ctx() as bn_ctx: check_x = self._lib.BN_CTX_get(bn_ctx) check_y = self._lib.BN_CTX_get(bn_ctx) res = set_func(group, point, bn_x, bn_y, bn_ctx) assert res == 1 res = get_func(group, point, check_x, check_y, bn_ctx) assert res == 1 res = self._lib.BN_cmp(bn_x, check_x) assert res == 0 res = self._lib.BN_cmp(bn_y, check_y) assert res == 0 res = self._lib.EC_KEY_set_public_key(ctx, point) assert res == 1 res = self._lib.EC_KEY_check_key(ctx) if res != 1: self._consume_errors() raise ValueError("Invalid EC key.") return ctx def _private_key_bytes(self, encoding, format, encryption_algorithm, evp_pkey, cdata): if not isinstance(encoding, serialization.Encoding): raise TypeError("encoding must be an item from the Encoding enum") if not isinstance(format, serialization.PrivateFormat): raise TypeError( "format must be an item from the PrivateFormat enum" ) if not isinstance(encryption_algorithm, serialization.KeySerializationEncryption): raise TypeError( "Encryption algorithm must be a KeySerializationEncryption " "instance" ) if isinstance(encryption_algorithm, serialization.NoEncryption): password = b"" passlen = 0 evp_cipher = self._ffi.NULL elif isinstance(encryption_algorithm, serialization.BestAvailableEncryption): # This is a curated value that we will update over time. evp_cipher = self._lib.EVP_get_cipherbyname( b"aes-256-cbc" ) password = encryption_algorithm.password passlen = len(password) if passlen > 1023: raise ValueError( "Passwords longer than 1023 bytes are not supported by " "this backend" ) else: raise ValueError("Unsupported encryption type") if encoding is serialization.Encoding.PEM: if format is serialization.PrivateFormat.PKCS8: write_bio = self._lib.PEM_write_bio_PKCS8PrivateKey key = evp_pkey elif format is serialization.PrivateFormat.TraditionalOpenSSL: if evp_pkey.type == self._lib.EVP_PKEY_RSA: write_bio = self._lib.PEM_write_bio_RSAPrivateKey elif evp_pkey.type == self._lib.EVP_PKEY_DSA: write_bio = self._lib.PEM_write_bio_DSAPrivateKey elif (self._lib.Cryptography_HAS_EC == 1 and evp_pkey.type == self._lib.EVP_PKEY_EC): write_bio = self._lib.PEM_write_bio_ECPrivateKey key = cdata elif encoding is serialization.Encoding.DER: if format is serialization.PrivateFormat.TraditionalOpenSSL: if not isinstance( encryption_algorithm, serialization.NoEncryption ): raise ValueError( "Encryption is not supported for DER encoded " "traditional OpenSSL keys" ) return self._private_key_bytes_traditional_der( evp_pkey.type, cdata ) elif format is serialization.PrivateFormat.PKCS8: write_bio = self._lib.i2d_PKCS8PrivateKey_bio key = evp_pkey bio = self._create_mem_bio() res = write_bio( bio, key, evp_cipher, password, passlen, self._ffi.NULL, self._ffi.NULL ) assert res == 1 return self._read_mem_bio(bio) def _private_key_bytes_traditional_der(self, key_type, cdata): if key_type == self._lib.EVP_PKEY_RSA: write_bio = self._lib.i2d_RSAPrivateKey_bio elif (self._lib.Cryptography_HAS_EC == 1 and key_type == self._lib.EVP_PKEY_EC): write_bio = self._lib.i2d_ECPrivateKey_bio elif key_type == self._lib.EVP_PKEY_DSA: write_bio = self._lib.i2d_DSAPrivateKey_bio bio = self._create_mem_bio() res = write_bio(bio, cdata) assert res == 1 return self._read_mem_bio(bio) def _public_key_bytes(self, encoding, format, evp_pkey, cdata): if not isinstance(encoding, serialization.Encoding): raise TypeError("encoding must be an item from the Encoding enum") if not isinstance(format, serialization.PublicFormat): raise TypeError( "format must be an item from the PublicFormat enum" ) if format is serialization.PublicFormat.SubjectPublicKeyInfo: if encoding is serialization.Encoding.PEM: write_bio = self._lib.PEM_write_bio_PUBKEY elif encoding is serialization.Encoding.DER: write_bio = self._lib.i2d_PUBKEY_bio key = evp_pkey elif format is serialization.PublicFormat.PKCS1: # Only RSA is supported here. assert evp_pkey.type == self._lib.EVP_PKEY_RSA if encoding is serialization.Encoding.PEM: write_bio = self._lib.PEM_write_bio_RSAPublicKey elif encoding is serialization.Encoding.DER: write_bio = self._lib.i2d_RSAPublicKey_bio key = cdata bio = self._create_mem_bio() res = write_bio(bio, key) assert res == 1 return self._read_mem_bio(bio) class GetCipherByName(object): def __init__(self, fmt): self._fmt = fmt def __call__(self, backend, cipher, mode): cipher_name = self._fmt.format(cipher=cipher, mode=mode).lower() return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii")) backend = Backend()
sholsapp/cryptography
src/cryptography/hazmat/backends/openssl/backend.py
Python
bsd-3-clause
49,028
$(function(){ function openPanel(){ require(['panel']); $('#admin_link').hide(); } if($.cookie('grass_panel')){ openPanel(); } $('#admin_link').on('click', function(e){ e.preventDefault(); openPanel(); }); }); require.config({ baseUrl: 'media/scripts', paths: { // 'doT': 'vendor/dot', 'riotjs': 'vendor/riot+compiler', 'panel': 'admin/panel', 'text': 'vendor/text' }, shim: { riotjs: { exports: 'riot' } } }); var riot; function loadCss(url) { var link = document.createElement("link"); link.type = "text/css"; link.rel = "stylesheet"; link.href = url; document.getElementsByTagName("head")[0].appendChild(link); }
grnrbt/grass
web/media/scripts/link.js
JavaScript
bsd-3-clause
781
<?php use yii\helpers\Html; use kartik\grid\GridView; use yii\widgets\ActiveForm; use yii\bootstrap\Modal; use yii\widgets\Pjax; /* @var $this yii\web\View */ /* @var $searchModel app\modules\fct\models\FctSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'ผู้ป่วยในระบบ FCT'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="fct-index"> <!-- <h1><?= Html::encode($this->title) ?></h1>--> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <!-- <p> <?= Html::a('Create Fct', ['create'], ['class' => 'btn btn-success']) ?> </p>--> <div class="panel panel-success"> <div class="panel-heading"> รายชื่อผู้ป่วย</div> <div class="panel-body"> <?php Pjax::begin(['id' => 'fct_id']); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, //'filterModel' => $searchModel, 'formatter' => ['class' => 'yii\i18n\Formatter', 'nullDisplay' => '-'], 'striped' => false, 'hover' => true, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //'id', //'fcttype_id', //'pass', //'colour_id', 'senddate', 'cid', //'hn', // 'an', 'ptname', //'birthday', [ 'attribute' => 'sex', 'format' => 'html', 'value' => function($model, $key, $index, $column) { return $model->sex == 1 ? "<span style=\"color:green;\">ชาย</span>" : "<span style=\"color:red;\">หญิง</span>"; } ], // 'ptage', // 'diage', // 'pps', // 'pain', // 'painnote', // 'cc', // 'pi', // 'bt', // 'pr', // 'rr', // 'bp', // 'drugallergy', // 'admit', // 'dc', // 'or', // 'ordate', // 'disease', // 'receive', 'address', // 'ptcate', // 'hossub', // 'tra', // 'retng', // 'retfo', // 'colobag', // 'lesion', // 'lesioncare', // 'recov', // 'recovcare', // 'oxygen', // 'lr01', // 'lr02', // 'lr03', // 'lr04', // 'lr05', // 'lr06', // 'lr07', // 'lr08', // 'lr09', // 'lr10', // 'lrl01', // 'lrl02', // 'lrl03', // 'lrl04', // 'lrl05', // 'lrl06', // 'lrl07', // 'lrl08', // 'lr', // 'lrl09', // 'lrl10', // 'lrl11', // 'lrl12', // 'lrl13', // 'other', // 'appdate', // 'doctorapp', // 'appdate2', // 'doctorapp2', // 'appdate3', // 'doctorapp3', // 'windpipe', // 'insulin', // 'equip', // 'depart', // 'hosin', // 'officer', // 'confirm', // 'confirmfct', //'tmbpart', 'phone', //'bloodgrp', // [ // 'class' => 'kartik\grid\BooleanColumn', // 'attribute' => 'send', // ], // [ // 'class' => 'kartik\grid\BooleanColumn', // 'attribute' => 'okcase', // ], [ 'class' => 'yii\grid\ActionColumn', 'options' => ['style' => 'width:100px;'], 'template' => '<div class="btn-group btn-group-sm" role="group" aria-label="...">{update}</div>', 'buttons' => [ // 'view'=>function($url,$model,$key){ // return Html::a('<i class="glyphicon glyphicon-search"></i>',$url,['class'=>'btn btn-default']); // }, 'update' => function($url, $model, $key) { return Html::a('<i class="glyphicon glyphicon-pencil"></i> ', ['/fct/fcthhc/update', 'id' => $model->id], [ 'class' => 'activity-update-link btn btn-info', 'title' => 'บันทึก', // 'data-toggle' => 'modal', // 'data-target' => '#activity-modal', // 'data-id' => $key, // 'data-pjax' => '0', ]); }, // // 'delete'=>function($url,$model,$key){ // return Html::a('<i class="glyphicon glyphicon-trash"></i>', $url,[ // 'title' => Yii::t('yii', 'Delete'), // 'data-confirm' => Yii::t('yii', 'คุณต้องการลบไฟล์นี้?'), // 'data-method' => 'post', // 'data-pjax' => '0', // 'class'=>'btn btn-default' // ]); // } ] ], ], ]); ?> <?php Pjax::end() ?> </div> </div> </div> <?php Modal::begin([ 'id' => 'activity-modal', 'header' => '<h4 class="modal-title"></h4>', 'size' => 'modal-lg', 'footer' => '<a href="#" class="btn btn-primary" data-dismiss="modal">ปิด</a>', ]); Modal::end(); ?> <?php $this->registerJs(' function init_click_handlers(){ $(".activity-update-link").click(function(e) { var fID = $(this).closest("tr").data("key"); $.get( "?r=fct/fcthhc/update", { fct_id: fID }, function (data) { $("#activity-modal").find(".modal-body").html(data); $(".modal-body").html(data); $(".modal-title").html("รับผู้ป่วยที่มีความเสี่ยงเข้าระบบ"); $("#activity-modal").modal("show"); } ); }); } init_click_handlers(); //first run $("#fct_id").on("pjax:success", function() { init_click_handlers(); //reactivate links in grid after pjax update });'); ?>
inamjung/fct
modules/fct/views/fct/indexcaseok.php
PHP
bsd-3-clause
8,182
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package RobotCode2014.commands.manipulator; import RobotCode2014.commands.CommandBase; /** * * @author me */ public class PitchAccelerationCommand extends CommandBase { public PitchAccelerationCommand() { } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { manipPitch.updatePitchSpeed(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
HarkerRobo/robocode14
src/RobotCode2014/commands/manipulator/PitchAccelerationCommand.java
Java
bsd-3-clause
1,076
<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ namespace Nette\DI; use Nette; use Nette\Utils\Validators; use Nette\Utils\Strings; use Nette\PhpGenerator\Helpers as PhpHelpers; use ReflectionClass; /** * Basic container builder. */ class ContainerBuilder extends Nette\Object { const THIS_SERVICE = 'self', THIS_CONTAINER = 'container'; /** @var array */ public $parameters = array(); /** @var string */ private $className = 'Container'; /** @var ServiceDefinition[] */ private $definitions = array(); /** @var array of alias => service */ private $aliases = array(); /** @var array for auto-wiring */ private $classes; /** @var string[] of classes excluded from auto-wiring */ private $excludedClasses = array(); /** @var array of file names */ private $dependencies = array(); /** @var Nette\PhpGenerator\ClassType[] */ private $generatedClasses = array(); /** @var string */ /*private in 5.4*/public $currentService; /** * Adds new service definition. * @param string * @return ServiceDefinition */ public function addDefinition($name, ServiceDefinition $definition = NULL) { if (!is_string($name) || !$name) { // builder is not ready for falsy names such as '0' throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name))); } $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; if (isset($this->definitions[$name])) { throw new Nette\InvalidStateException("Service '$name' has already been added."); } return $this->definitions[$name] = $definition ?: new ServiceDefinition; } /** * Removes the specified service definition. * @param string * @return void */ public function removeDefinition($name) { $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; unset($this->definitions[$name]); if ($this->classes) { foreach ($this->classes as & $tmp) { foreach ($tmp as & $names) { $names = array_values(array_diff($names, array($name))); } } } } /** * Gets the service definition. * @param string * @return ServiceDefinition */ public function getDefinition($name) { $service = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; if (!isset($this->definitions[$service])) { throw new MissingServiceException("Service '$name' not found."); } return $this->definitions[$service]; } /** * Gets all service definitions. * @return ServiceDefinition[] */ public function getDefinitions() { return $this->definitions; } /** * Does the service definition or alias exist? * @param string * @return bool */ public function hasDefinition($name) { $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name; return isset($this->definitions[$name]); } /** * @param string * @param string */ public function addAlias($alias, $service) { if (!is_string($alias) || !$alias) { // builder is not ready for falsy names such as '0' throw new Nette\InvalidArgumentException(sprintf('Alias name must be a non-empty string, %s given.', gettype($alias))); } elseif (!is_string($service) || !$service) { // builder is not ready for falsy names such as '0' throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service))); } elseif (isset($this->aliases[$alias])) { throw new Nette\InvalidStateException("Alias '$alias' has already been added."); } elseif (isset($this->definitions[$alias])) { throw new Nette\InvalidStateException("Service '$alias' has already been added."); } $this->aliases[$alias] = $service; } /** * Removes the specified alias. * @return void */ public function removeAlias($alias) { unset($this->aliases[$alias]); } /** * Gets all service aliases. * @return array */ public function getAliases() { return $this->aliases; } /** * @return self */ public function setClassName($name) { $this->className = (string) $name; return $this; } /** * @return string */ public function getClassName() { return $this->className; } /********************* class resolving ****************d*g**/ /** * Resolves service name by type. * @param string class or interface * @return string|NULL service name or NULL * @throws ServiceCreationException */ public function getByType($class) { $class = ltrim($class, '\\'); if ($this->currentService !== NULL) { $curClass = $this->definitions[$this->currentService]->getClass(); if ($curClass === $class || is_subclass_of($curClass, $class)) { return $this->currentService; } } if (empty($this->classes[$class][TRUE])) { self::checkCase($class); return; } elseif (count($this->classes[$class][TRUE]) === 1) { return $this->classes[$class][TRUE][0]; } else { throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $this->classes[$class][TRUE])); } } /** * Gets the service names and definitions of the specified type. * @param string * @return ServiceDefinition[] */ public function findByType($class) { $class = ltrim($class, '\\'); self::checkCase($class); $found = array(); if (!empty($this->classes[$class])) { foreach (call_user_func_array('array_merge', $this->classes[$class]) as $name) { $found[$name] = $this->definitions[$name]; } } return $found; } /** * Gets the service objects of the specified tag. * @param string * @return array of [service name => tag attributes] */ public function findByTag($tag) { $found = array(); foreach ($this->definitions as $name => $def) { if (($tmp = $def->getTag($tag)) !== NULL) { $found[$name] = $tmp; } } return $found; } /** * Creates a list of arguments using autowiring. * @return array */ public function autowireArguments($class, $method, array $arguments) { $rc = new ReflectionClass($class); if (!$rc->hasMethod($method)) { if (!Nette\Utils\Arrays::isList($arguments)) { throw new ServiceCreationException("Unable to pass specified arguments to $class::$method()."); } return $arguments; } $rm = $rc->getMethod($method); if (!$rm->isPublic()) { throw new ServiceCreationException("$class::$method() is not callable."); } $this->addDependency($rm->getFileName()); return Helpers::autowireArguments($rm, $arguments, $this); } /** * Generates $dependencies, $classes and normalizes class names. * @return array * @internal */ public function prepareClassList() { unset($this->definitions[self::THIS_CONTAINER]); $this->addDefinition(self::THIS_CONTAINER)->setClass('Nette\DI\Container'); $this->classes = FALSE; foreach ($this->definitions as $name => $def) { // prepare generated factories if ($def->getImplement()) { $this->resolveImplement($def, $name); } if ($def->isDynamic()) { if (!$def->getClass()) { throw new ServiceCreationException("Class is missing in definition of service '$name'."); } $def->setFactory(NULL); continue; } // complete class-factory pairs if (!$def->getEntity()) { if (!$def->getClass()) { throw new ServiceCreationException("Class and factory are missing in definition of service '$name'."); } $def->setFactory($def->getClass(), ($factory = $def->getFactory()) ? $factory->arguments : array()); } // auto-disable autowiring for aliases if (($alias = $this->getServiceName($def->getFactory()->getEntity())) && (!$def->getImplement() || (!Strings::contains($alias, '\\') && $this->definitions[$alias]->getImplement())) ) { $def->setAutowired(FALSE); } } // resolve and check classes foreach ($this->definitions as $name => $def) { $this->resolveServiceClass($name); } // build auto-wiring list $excludedClasses = array(); foreach ($this->excludedClasses as $class) { self::checkCase($class); $excludedClasses += class_parents($class) + class_implements($class) + array($class => $class); } $this->classes = array(); foreach ($this->definitions as $name => $def) { if ($class = $def->getImplement() ?: $def->getClass()) { foreach (class_parents($class) + class_implements($class) + array($class) as $parent) { $this->classes[$parent][$def->isAutowired() && empty($excludedClasses[$parent])][] = (string) $name; } } } foreach ($this->classes as $class => $foo) { $rc = new ReflectionClass($class); $this->addDependency($rc->getFileName()); } } private function resolveImplement(ServiceDefinition $def, $name) { $interface = $def->getImplement(); if (!interface_exists($interface)) { throw new ServiceCreationException("Interface $interface used in service '$name' not found."); } self::checkCase($interface); $rc = new ReflectionClass($interface); $method = $rc->hasMethod('create') ? $rc->getMethod('create') : ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL); if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) { throw new ServiceCreationException("Interface $interface used in service '$name' must have just one non-static method create() or get()."); } $def->setImplementType($methodName = $rc->hasMethod('create') ? 'create' : 'get'); if (!$def->getClass() && !$def->getEntity()) { $returnType = PhpReflection::getReturnType($method); if (!$returnType) { throw new ServiceCreationException("Method $interface::$methodName() used in service '$name' has no @return annotation."); } elseif (!class_exists($returnType)) { throw new ServiceCreationException("Check a @return annotation of the $interface::$methodName() method used in service '$name', class '$returnType' cannot be found."); } $def->setClass($returnType); } if ($methodName === 'get') { if ($method->getParameters()) { throw new ServiceCreationException("Method $interface::get() used in service '$name' must have no arguments."); } if (!$def->getEntity()) { $def->setFactory('@\\' . ltrim($def->getClass(), '\\')); } elseif (!$this->getServiceName($def->getFactory()->getEntity())) { throw new ServiceCreationException("Invalid factory in service '$name' definition."); } } if (!$def->parameters) { $ctorParams = array(); if (!$def->getEntity()) { $def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : array()); } if (($class = $this->resolveEntityClass($def->getFactory(), array($name => 1))) && ($rc = new ReflectionClass($class)) && ($ctor = $rc->getConstructor()) ) { foreach ($ctor->getParameters() as $param) { $ctorParams[$param->getName()] = $param; } } foreach ($method->getParameters() as $param) { $hint = PhpReflection::getParameterType($param); if (isset($ctorParams[$param->getName()])) { $arg = $ctorParams[$param->getName()]; if ($hint !== PhpReflection::getParameterType($arg)) { throw new ServiceCreationException("Type hint for \${$param->getName()} in $interface::$methodName() doesn't match type hint in $class constructor."); } $def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName()); } elseif (!$def->getSetup()) { $hint = Nette\Utils\ObjectMixin::getSuggestion(array_keys($ctorParams), $param->getName()); throw new ServiceCreationException("Unused parameter \${$param->getName()} when implementing method $interface::$methodName()" . ($hint ? ", did you mean \${$hint}?" : '.')); } $paramDef = $hint . ' ' . $param->getName(); if ($param->isOptional()) { $def->parameters[$paramDef] = $param->getDefaultValue(); } else { $def->parameters[] = $paramDef; } } } } /** @return string|NULL */ private function resolveServiceClass($name, $recursive = array()) { if (isset($recursive[$name])) { throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($recursive)))); } $recursive[$name] = TRUE; $def = $this->definitions[$name]; $class = $def->getFactory() ? $this->resolveEntityClass($def->getFactory()->getEntity(), $recursive) : NULL; // call always to check entities if ($class = $def->getClass() ?: $class) { $def->setClass($class); if (!class_exists($class) && !interface_exists($class)) { throw new ServiceCreationException("Type $class used in service '$name' not found or is not class or interface."); } self::checkCase($class); } elseif ($def->isAutowired()) { trigger_error("Type of service '$name' is unknown.", E_USER_NOTICE); } return $class; } /** @return string|NULL */ private function resolveEntityClass($entity, $recursive = array()) { $entity = $this->normalizeEntity($entity instanceof Statement ? $entity->getEntity() : $entity); if (is_array($entity)) { if (($service = $this->getServiceName($entity[0])) || $entity[0] instanceof Statement) { $entity[0] = $this->resolveEntityClass($entity[0], $recursive); if (!$entity[0]) { return; } elseif (isset($this->definitions[$service]) && $this->definitions[$service]->getImplement()) { // @Implement::create return $entity[1] === 'create' ? $this->resolveServiceClass($service, $recursive) : NULL; } } try { $reflection = Nette\Utils\Callback::toReflection($entity[0] === '' ? $entity[1] : $entity); $refClass = $reflection instanceof \ReflectionMethod ? $reflection->getDeclaringClass() : NULL; } catch (\ReflectionException $e) { } if (isset($e) || ($refClass && (!$reflection->isPublic() || (PHP_VERSION_ID >= 50400 && $refClass->isTrait() && !$reflection->isStatic()) ))) { $name = array_slice(array_keys($recursive), -1); throw new ServiceCreationException(sprintf("Factory '%s' used in service '%s' is not callable.", Nette\Utils\Callback::toString($entity), $name[0])); } return PhpReflection::getReturnType($reflection); } elseif ($service = $this->getServiceName($entity)) { // alias or factory if (Strings::contains($service, '\\')) { // @\Class return ltrim($service, '\\'); } return $this->definitions[$service]->getImplement() ?: $this->resolveServiceClass($service, $recursive); } elseif (is_string($entity)) { if (!class_exists($entity) || !($rc = new ReflectionClass($entity)) || !$rc->isInstantiable()) { $name = array_slice(array_keys($recursive), -1); throw new ServiceCreationException("Class $entity used in service '$name[0]' not found or is not instantiable."); } return ltrim($entity, '\\'); } } private function checkCase($class) { if ((class_exists($class) || interface_exists($class)) && ($rc = new ReflectionClass($class)) && $class !== $rc->getName()) { throw new ServiceCreationException("Case mismatch on class name '$class', correct name is '{$rc->getName()}'."); } } /** * @param string[] * @return self */ public function addExcludedClasses(array $classes) { $this->excludedClasses = array_merge($this->excludedClasses, $classes); return $this; } /** * Adds a file to the list of dependencies. * @return self * @internal */ public function addDependency($file) { $this->dependencies[$file] = TRUE; return $this; } /** * Returns the list of dependent files. * @return array */ public function getDependencies() { unset($this->dependencies[FALSE]); return array_keys($this->dependencies); } /********************* code generator ****************d*g**/ /** * Generates PHP classes. First class is the container. * @return Nette\PhpGenerator\ClassType[] */ public function generateClasses($className = NULL, $parentName = NULL) { $this->prepareClassList(); $this->generatedClasses = array(); $this->className = $className ?: $this->className; $containerClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType($this->className); $containerClass->setExtends($parentName ?: 'Nette\DI\Container'); $containerClass->addMethod('__construct') ->addBody('parent::__construct(?);', array($this->parameters)); $definitions = $this->definitions; ksort($definitions); $meta = $containerClass->addProperty('meta') ->setVisibility('protected') ->setValue(array(Container::TYPES => $this->classes)); foreach ($definitions as $name => $def) { $meta->value[Container::SERVICES][$name] = $def->getClass() ?: NULL; foreach ($def->getTags() as $tag => $value) { $meta->value[Container::TAGS][$tag][$name] = $value; } } foreach ($definitions as $name => $def) { try { $name = (string) $name; $methodName = Container::getMethodName($name); if (!PhpHelpers::isIdentifier($methodName)) { throw new ServiceCreationException('Name contains invalid characters.'); } $containerClass->addMethod($methodName) ->addComment('@return ' . ($def->getImplement() ?: $def->getClass())) ->setBody($name === self::THIS_CONTAINER ? 'return $this;' : $this->generateService($name)) ->setParameters($def->getImplement() ? array() : $this->convertParameters($def->parameters)); } catch (\Exception $e) { throw new ServiceCreationException("Service '$name': " . $e->getMessage(), NULL, $e); } } $aliases = $this->aliases; ksort($aliases); $meta->value[Container::ALIASES] = $aliases; return $this->generatedClasses; } /** * Generates body of service method. * @return string */ private function generateService($name) { $this->currentService = NULL; $def = $this->definitions[$name]; if ($def->isDynamic()) { return PhpHelpers::formatArgs('throw new Nette\\DI\\ServiceCreationException(?);', array("Unable to create dynamic service '$name', it must be added using addService()") ); } $entity = $def->getFactory()->getEntity(); $serviceRef = $this->getServiceName($entity); $factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementType() !== 'create' ? new Statement(array('@' . self::THIS_CONTAINER, 'getService'), array($serviceRef)) : $def->getFactory(); $code = '$service = ' . $this->formatStatement($factory) . ";\n"; $this->currentService = $name; if (($class = $def->getClass()) && !$serviceRef && $class !== $entity && !(is_string($entity) && preg_match('#^[\w\\\\]+\z#', $entity) && is_subclass_of($entity, $class)) ) { $code .= PhpHelpers::formatArgs("if (!\$service instanceof $class) {\n" . "\tthrow new Nette\\UnexpectedValueException(?);\n}\n", array("Unable to create service '$name', value returned by factory is not $class type.") ); } foreach ($def->getSetup() as $setup) { if (is_string($setup->getEntity()) && strpbrk($setup->getEntity(), ':@?\\') === FALSE) { // auto-prepend @self $setup->setEntity(array('@self', $setup->getEntity())); } $code .= $this->formatStatement($setup) . ";\n"; } $this->currentService = NULL; $code .= 'return $service;'; if (!$def->getImplement()) { return $code; } $factoryClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType; $factoryClass->setName(str_replace(array('\\', '.'), '_', "{$this->className}_{$def->getImplement()}Impl_{$name}")) ->addImplement($def->getImplement()) ->setFinal(TRUE); $factoryClass->addProperty('container') ->setVisibility('private'); $factoryClass->addMethod('__construct') ->addBody('$this->container = $container;') ->addParameter('container') ->setTypeHint($this->className); $factoryClass->addMethod($def->getImplementType()) ->setParameters($this->convertParameters($def->parameters)) ->setBody(str_replace('$this', '$this->container', $code)) ->setReturnType(PHP_VERSION_ID >= 70000 ? $def->getClass() : NULL); return "return new {$factoryClass->getName()}(\$this);"; } /** * Converts parameters from ServiceDefinition to PhpGenerator. * @return Nette\PhpGenerator\Parameter[] */ private function convertParameters(array $parameters) { $res = array(); foreach ($parameters as $k => $v) { $tmp = explode(' ', is_int($k) ? $v : $k); $param = $res[] = new Nette\PhpGenerator\Parameter; $param->setName(end($tmp)); if (!is_int($k)) { $param = $param->setOptional(TRUE)->setDefaultValue($v); } if (isset($tmp[1])) { $param->setTypeHint($tmp[0]); } } return $res; } /** * Formats PHP code for class instantiating, function calling or property setting in PHP. * @return string * @internal */ public function formatStatement(Statement $statement) { $entity = $this->normalizeEntity($statement->getEntity()); $arguments = $statement->arguments; if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal return $this->formatPhp($entity, $arguments); } elseif ($service = $this->getServiceName($entity)) { // factory calling $params = array(); foreach ($this->definitions[$service]->parameters as $k => $v) { $params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v)); } $rm = new \ReflectionFunction(create_function(implode(', ', $params), '')); $arguments = Helpers::autowireArguments($rm, $arguments, $this); return $this->formatPhp('$this->?(?*)', array(Container::getMethodName($service), $arguments)); } elseif ($entity === 'not') { // operator return $this->formatPhp('!?', array($arguments[0])); } elseif (is_string($entity)) { // class name $rc = new ReflectionClass($entity); if ($constructor = $rc->getConstructor()) { $this->addDependency($constructor->getFileName()); $arguments = Helpers::autowireArguments($constructor, $arguments, $this); } elseif ($arguments) { throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor."); } return $this->formatPhp("new $entity" . ($arguments ? '(?*)' : ''), array($arguments)); } elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) { throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity))); } elseif (!preg_match('#^\$?' . PhpHelpers::PHP_IDENT . '\z#', $entity[1])) { throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given."); } elseif ($entity[0] === '') { // globalFunc return $this->formatPhp("$entity[1](?*)", array($arguments)); } elseif ($entity[0] instanceof Statement) { $inner = $this->formatPhp('?', array($entity[0])); if (substr($inner, 0, 4) === 'new ') { $inner = PHP_VERSION_ID < 50400 ? "current(array($inner))" : "($inner)"; } return $this->formatPhp("$inner->?(?*)", array($entity[1], $arguments)); } elseif (Strings::contains($entity[1], '$')) { // property setter Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'"); if ($this->getServiceName($entity[0])) { return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0])); } else { return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0])); } } elseif ($service = $this->getServiceName($entity[0])) { // service method $class = $this->definitions[$service]->getImplement(); if (!$class || !method_exists($class, $entity[1])) { $class = $this->definitions[$service]->getClass(); } if ($class) { $arguments = $this->autowireArguments($class, $entity[1], $arguments); } return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments)); } else { // static method $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments); return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments)); } } /** * Formats PHP statement. * @return string * @internal */ public function formatPhp($statement, $args) { $that = $this; array_walk_recursive($args, function (& $val) use ($that) { if ($val instanceof Statement) { $val = ContainerBuilder::literal($that->formatStatement($val)); } elseif ($val === $that) { $val = ContainerBuilder::literal('$this'); } elseif ($val instanceof ServiceDefinition) { $val = '@' . current(array_keys($that->getDefinitions(), $val, TRUE)); } if (!is_string($val)) { return; } elseif (substr($val, 0, 2) === '@@') { $val = substr($val, 1); } elseif (substr($val, 0, 1) === '@' && strlen($val) > 1) { $pair = explode('::', $val, 2); $name = $that->getServiceName($pair[0]); if (isset($pair[1]) && preg_match('#^[A-Z][A-Z0-9_]*\z#', $pair[1], $m)) { $val = $that->getDefinition($name)->getClass() . '::' . $pair[1]; } else { if ($name === ContainerBuilder::THIS_CONTAINER) { $val = '$this'; } elseif ($name === $that->currentService) { $val = '$service'; } else { $val = $that->formatStatement(new Statement(array('@' . ContainerBuilder::THIS_CONTAINER, 'getService'), array($name))); } $val .= (isset($pair[1]) ? PhpHelpers::formatArgs('->?', array($pair[1])) : ''); } $val = ContainerBuilder::literal($val); } }); return PhpHelpers::formatArgs($statement, $args); } /** * Expands %placeholders% in strings. * @return mixed * @deprecated */ public function expand($value) { return Helpers::expand($value, $this->parameters); } /** * @return Nette\PhpGenerator\PhpLiteral */ public static function literal($phpCode) { return new Nette\PhpGenerator\PhpLiteral($phpCode); } /** @internal */ public function normalizeEntity($entity) { if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method] $entity = explode('::', $entity); } if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...] $entity[0] = '@' . current(array_keys($this->definitions, $entity[0], TRUE)); } elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName $entity = '@' . current(array_keys($this->definitions, $entity, TRUE)); } elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...] $entity[0] = '@' . self::THIS_CONTAINER; } return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc], Statement } /** * Converts @service or @\Class -> service name and checks its existence. * @return string of FALSE, if argument is not service name * @internal */ public function getServiceName($arg) { $arg = $this->normalizeEntity($arg); if (!is_string($arg) || !preg_match('#^@[\w\\\\.].*\z#', $arg)) { return FALSE; } $service = substr($arg, 1); if ($service === self::THIS_SERVICE) { $service = $this->currentService; } if (Strings::contains($service, '\\')) { if ($this->classes === FALSE) { // may be disabled by prepareClassList return $service; } $res = $this->getByType($service); if (!$res) { throw new ServiceCreationException("Reference to missing service of type $service."); } return $res; } $service = isset($this->aliases[$service]) ? $this->aliases[$service] : $service; if (!isset($this->definitions[$service])) { throw new ServiceCreationException("Reference to missing service '$service'."); } return $service; } }
kivi8/ars-poetica
vendor/nette/di/src/DI/ContainerBuilder.php
PHP
bsd-3-clause
27,588
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package org.cagrid.gaards.dorian.federation; import gov.nih.nci.cagrid.common.Utils; import java.util.Arrays; public class ReportUtils { public static String generateReport(TrustedIdP original, TrustedIdP updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the Trusted IdP, " + original.getName() + " (" + original.getId() + "): \n"); int count = 0; if ((Utils.clean(updated.getDisplayName()) != null) && (!updated.getDisplayName().equals(original.getDisplayName()))) { count = count + 1; sb.append(count + ". Display Name changed from " + original.getDisplayName() + " to " + updated.getDisplayName() + ".\n"); } if ((Utils.clean(updated.getUserPolicyClass()) != null) && (!updated.getUserPolicyClass().equals(original.getUserPolicyClass()))) { count = count + 1; sb.append(count + ". User policy changed from " + original.getUserPolicyClass() + " to " + updated.getUserPolicyClass() + ".\n"); } if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to " + updated.getStatus().getValue() + ".\n"); } if ((Utils.clean(updated.getIdPCertificate()) != null) && (!updated.getIdPCertificate().equals(original.getIdPCertificate()))) { count = count + 1; sb.append(count + ". Signing certificate changed.\n"); } if (updated.getAuthenticationServiceURL() == null) { updated.setAuthenticationServiceURL(""); } if (!updated.getAuthenticationServiceURL().equals(original.getAuthenticationServiceURL())) { count = count + 1; sb.append(count + ". Authentication Service URL changed from " + original.getAuthenticationServiceURL() + " to " + updated.getAuthenticationServiceURL() + ".\n"); } if (updated.getAuthenticationServiceIdentity() == null) { updated.setAuthenticationServiceIdentity(""); } if (!updated.getAuthenticationServiceIdentity().equals(original.getAuthenticationServiceIdentity())) { count = count + 1; sb.append(count + ". Authentication Service Identity changed from " + original.getAuthenticationServiceIdentity() + " to " + updated.getAuthenticationServiceIdentity() + ".\n"); } if ((updated.getUserIdAttributeDescriptor() != null) && (!updated.getUserIdAttributeDescriptor().equals(original.getUserIdAttributeDescriptor()))) { count = count + 1; sb.append(count + ". User Id Attribute changed from " + original.getUserIdAttributeDescriptor().getNamespaceURI() + ":" + original.getUserIdAttributeDescriptor().getName() + " to " + updated.getUserIdAttributeDescriptor().getNamespaceURI() + ":" + updated.getUserIdAttributeDescriptor().getName() + ".\n"); } if ((updated.getFirstNameAttributeDescriptor() != null) && (!updated.getFirstNameAttributeDescriptor().equals(original.getFirstNameAttributeDescriptor()))) { count = count + 1; sb.append(count + ". First Name Attribute changed from " + original.getFirstNameAttributeDescriptor().getNamespaceURI() + ":" + original.getFirstNameAttributeDescriptor().getName() + " to " + updated.getFirstNameAttributeDescriptor().getNamespaceURI() + ":" + updated.getFirstNameAttributeDescriptor().getName() + ".\n"); } if ((updated.getLastNameAttributeDescriptor() != null) && (!updated.getLastNameAttributeDescriptor().equals(original.getLastNameAttributeDescriptor()))) { count = count + 1; sb.append(count + ". Last Name Attribute changed from " + original.getLastNameAttributeDescriptor().getNamespaceURI() + ":" + original.getLastNameAttributeDescriptor().getName() + " to " + updated.getLastNameAttributeDescriptor().getNamespaceURI() + ":" + updated.getLastNameAttributeDescriptor().getName() + ".\n"); } if ((updated.getEmailAttributeDescriptor() != null) && (!updated.getEmailAttributeDescriptor().equals(original.getEmailAttributeDescriptor()))) { count = count + 1; sb.append(count + ". Email Attribute changed from " + original.getEmailAttributeDescriptor().getNamespaceURI() + ":" + original.getEmailAttributeDescriptor().getName() + " to " + updated.getEmailAttributeDescriptor().getNamespaceURI() + ":" + updated.getEmailAttributeDescriptor().getName() + ".\n"); } if (!Arrays.equals(original.getAuthenticationMethod(), updated.getAuthenticationMethod())) { count = count + 1; sb.append(count + ". Authentication methods changed from ("); boolean first = true; if (original.getAuthenticationMethod() != null) { for (int i = 0; i < original.getAuthenticationMethod().length; i++) { if (!first) { sb.append(", "); } sb.append(original.getAuthenticationMethod(i)); first = false; } } sb.append(") to ("); first = true; if (updated.getAuthenticationMethod() != null) { for (int i = 0; i < updated.getAuthenticationMethod().length; i++) { if (!first) { sb.append(", "); } sb.append(updated.getAuthenticationMethod(i)); first = false; } } sb.append(")."); } return sb.toString(); } public static String generateReport(GridUser original, GridUser updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the Grid user, " + original.getGridId() + ": \n"); int count = 0; if ((updated.getFirstName() != null) && (!updated.getFirstName().equals(original.getFirstName()))) { count = count + 1; sb.append(count + ". First Name changed from " + original.getFirstName() + " to " + updated.getFirstName() + ".\n"); } if ((updated.getLastName() != null) && (!updated.getLastName().equals(original.getLastName()))) { count = count + 1; sb.append(count + ". Last Name changed from " + original.getLastName() + " to " + updated.getLastName() + ".\n"); } if ((updated.getEmail() != null) && (!updated.getEmail().equals(original.getEmail()))) { count = count + 1; sb.append(count + ". Email changed from " + original.getEmail() + " to " + updated.getEmail() + ".\n"); } if ((updated.getUserStatus() != null) && (!updated.getUserStatus().equals(original.getUserStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getUserStatus().getValue() + " to " + updated.getUserStatus().getValue() + ".\n"); } return sb.toString(); } public static String generateReport(HostCertificateRecord original, HostCertificateRecord updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the host certificate, " + original.getHost() + "(" + original.getId() + "): \n"); int count = 0; if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to " + updated.getStatus().getValue() + ".\n"); } if ((updated.getOwner() != null) && (!updated.getOwner().equals(original.getOwner()))) { count = count + 1; sb.append(count + ". Owner changed from " + original.getOwner() + " to " + updated.getOwner() + ".\n"); } return sb.toString(); } public static String generateReport(UserCertificateRecord original, UserCertificateRecord updated) { StringBuffer sb = new StringBuffer(); sb.append("The following changes were made to the user certificate, " + original.getSerialNumber() + ": \n"); int count = 0; if ((updated.getStatus() != null) && (!updated.getStatus().equals(original.getStatus()))) { count = count + 1; sb.append(count + ". Status changed from " + original.getStatus().getValue() + " to " + updated.getStatus().getValue() + ".\n"); } if ((updated.getNotes() != null) && (!updated.getNotes().equals(original.getNotes()))) { count = count + 1; sb.append(count + ". Notes updated.\n"); } return sb.toString(); } }
NCIP/cagrid-core
caGrid/projects/dorian/src/org/cagrid/gaards/dorian/federation/ReportUtils.java
Java
bsd-3-clause
9,870
//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for inline asm statements. // //===----------------------------------------------------------------------===// #include "clang/AST/ExprCXX.h" #include "clang/AST/GlobalDecl.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/MC/MCParser/MCAsmParser.h" using namespace clang; using namespace sema; /// Remove the upper-level LValueToRValue cast from an expression. static void removeLValueToRValueCast(Expr *E) { Expr *Parent = E; Expr *ExprUnderCast = nullptr; SmallVector<Expr *, 8> ParentsToUpdate; while (true) { ParentsToUpdate.push_back(Parent); if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) { Parent = ParenE->getSubExpr(); continue; } Expr *Child = nullptr; CastExpr *ParentCast = dyn_cast<CastExpr>(Parent); if (ParentCast) Child = ParentCast->getSubExpr(); else return; if (auto *CastE = dyn_cast<CastExpr>(Child)) if (CastE->getCastKind() == CK_LValueToRValue) { ExprUnderCast = CastE->getSubExpr(); // LValueToRValue cast inside GCCAsmStmt requires an explicit cast. ParentCast->setSubExpr(ExprUnderCast); break; } Parent = Child; } // Update parent expressions to have same ValueType as the underlying. assert(ExprUnderCast && "Should be reachable only if LValueToRValue cast was found!"); auto ValueKind = ExprUnderCast->getValueKind(); for (Expr *E : ParentsToUpdate) E->setValueKind(ValueKind); } /// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension) /// and fix the argument with removing LValueToRValue cast from the expression. static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument, Sema &S) { if (!S.getLangOpts().HeinousExtensions) { S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue) << BadArgument->getSourceRange(); } else { S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue) << BadArgument->getSourceRange(); } removeLValueToRValueCast(BadArgument); } /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently /// ignore "noop" casts in places where an lvalue is required by an inline asm. /// We emulate this behavior when -fheinous-gnu-extensions is specified, but /// provide a strong guidance to not use it. /// /// This method checks to see if the argument is an acceptable l-value and /// returns false if it is a case we can handle. static bool CheckAsmLValue(Expr *E, Sema &S) { // Type dependent expressions will be checked during instantiation. if (E->isTypeDependent()) return false; if (E->isLValue()) return false; // Cool, this is an lvalue. // Okay, this is not an lvalue, but perhaps it is the result of a cast that we // are supposed to allow. const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); if (E != E2 && E2->isLValue()) { emitAndFixInvalidAsmCastLValue(E2, E, S); // Accept, even if we emitted an error diagnostic. return false; } // None of the above, just randomly invalid non-lvalue. return true; } /// isOperandMentioned - Return true if the specified operand # is mentioned /// anywhere in the decomposed asm string. static bool isOperandMentioned(unsigned OpNo, ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) { for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; if (!Piece.isOperand()) continue; // If this is a reference to the input and if the input was the smaller // one, then we have to reject this asm. if (Piece.getOperandNo() == OpNo) return true; } return false; } static bool CheckNakedParmReference(Expr *E, Sema &S) { FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext); if (!Func) return false; if (!Func->hasAttr<NakedAttr>()) return false; SmallVector<Expr*, 4> WorkList; WorkList.push_back(E); while (WorkList.size()) { Expr *E = WorkList.pop_back_val(); if (isa<CXXThisExpr>(E)) { S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref); S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); return true; } if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { if (isa<ParmVarDecl>(DRE->getDecl())) { S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref); S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); return true; } } for (Stmt *Child : E->children()) { if (Expr *E = dyn_cast_or_null<Expr>(Child)) WorkList.push_back(E); } } return false; } /// Returns true if given expression is not compatible with inline /// assembly's memory constraint; false otherwise. static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E, TargetInfo::ConstraintInfo &Info, bool is_input_expr) { enum { ExprBitfield = 0, ExprVectorElt, ExprGlobalRegVar, ExprSafeType } EType = ExprSafeType; // Bitfields, vector elements and global register variables are not // compatible. if (E->refersToBitField()) EType = ExprBitfield; else if (E->refersToVectorElement()) EType = ExprVectorElt; else if (E->refersToGlobalRegisterVar()) EType = ExprGlobalRegVar; if (EType != ExprSafeType) { S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint) << EType << is_input_expr << Info.getConstraintStr() << E->getSourceRange(); return true; } return false; } // Extracting the register name from the Expression value, // if there is no register name to extract, returns "" static StringRef extractRegisterName(const Expr *Expression, const TargetInfo &Target) { Expression = Expression->IgnoreImpCasts(); if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) { // Handle cases where the expression is a variable const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl()); if (Variable && Variable->getStorageClass() == SC_Register) { if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>()) if (Target.isValidGCCRegisterName(Attr->getLabel())) return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true); } } return ""; } // Checks if there is a conflict between the input and output lists with the // clobbers list. If there's a conflict, returns the location of the // conflicted clobber, else returns nullptr static SourceLocation getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints, StringLiteral **Clobbers, int NumClobbers, unsigned NumLabels, const TargetInfo &Target, ASTContext &Cont) { llvm::StringSet<> InOutVars; // Collect all the input and output registers from the extended asm // statement in order to check for conflicts with the clobber list for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) { StringRef Constraint = Constraints[i]->getString(); StringRef InOutReg = Target.getConstraintRegister( Constraint, extractRegisterName(Exprs[i], Target)); if (InOutReg != "") InOutVars.insert(InOutReg); } // Check for each item in the clobber list if it conflicts with the input // or output for (int i = 0; i < NumClobbers; ++i) { StringRef Clobber = Clobbers[i]->getString(); // We only check registers, therefore we don't check cc and memory // clobbers if (Clobber == "cc" || Clobber == "memory") continue; Clobber = Target.getNormalizedGCCRegisterName(Clobber, true); // Go over the output's registers we collected if (InOutVars.count(Clobber)) return Clobbers[i]->getBeginLoc(); } return SourceLocation(); } StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg constraints, MultiExprArg Exprs, Expr *asmString, MultiExprArg clobbers, unsigned NumLabels, SourceLocation RParenLoc) { unsigned NumClobbers = clobbers.size(); StringLiteral **Constraints = reinterpret_cast<StringLiteral**>(constraints.data()); StringLiteral *AsmString = cast<StringLiteral>(asmString); StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data()); SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; // The parser verifies that there is a string literal here. assert(AsmString->isAscii()); FunctionDecl *FD = dyn_cast<FunctionDecl>(getCurLexicalContext()); llvm::StringMap<bool> FeatureMap; Context.getFunctionFeatureMap(FeatureMap, FD); for (unsigned i = 0; i != NumOutputs; i++) { StringLiteral *Literal = Constraints[i]; assert(Literal->isAscii()); StringRef OutputName; if (Names[i]) OutputName = Names[i]->getName(); TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); if (!Context.getTargetInfo().validateOutputConstraint(Info)) { targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_output_constraint) << Info.getConstraintStr(); return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } ExprResult ER = CheckPlaceholderExpr(Exprs[i]); if (ER.isInvalid()) return StmtError(); Exprs[i] = ER.get(); // Check that the output exprs are valid lvalues. Expr *OutputExpr = Exprs[i]; // Referring to parameters is not allowed in naked functions. if (CheckNakedParmReference(OutputExpr, *this)) return StmtError(); // Check that the output expression is compatible with memory constraint. if (Info.allowsMemory() && checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false)) return StmtError(); OutputConstraintInfos.push_back(Info); // If this is dependent, just continue. if (OutputExpr->isTypeDependent()) continue; Expr::isModifiableLvalueResult IsLV = OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr); switch (IsLV) { case Expr::MLV_Valid: // Cool, this is an lvalue. break; case Expr::MLV_ArrayType: // This is OK too. break; case Expr::MLV_LValueCast: { const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context); emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this); // Accept, even if we emitted an error diagnostic. break; } case Expr::MLV_IncompleteType: case Expr::MLV_IncompleteVoidType: if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(), diag::err_dereference_incomplete_type)) return StmtError(); LLVM_FALLTHROUGH; default: return StmtError(Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_lvalue_in_output) << OutputExpr->getSourceRange()); } unsigned Size = Context.getTypeSize(OutputExpr->getType()); if (!Context.getTargetInfo().validateOutputSize( FeatureMap, Literal->getString(), Size)) { targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size) << Info.getConstraintStr(); return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } } SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { StringLiteral *Literal = Constraints[i]; assert(Literal->isAscii()); StringRef InputName; if (Names[i]) InputName = Names[i]->getName(); TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos, Info)) { targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint) << Info.getConstraintStr(); return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } ExprResult ER = CheckPlaceholderExpr(Exprs[i]); if (ER.isInvalid()) return StmtError(); Exprs[i] = ER.get(); Expr *InputExpr = Exprs[i]; // Referring to parameters is not allowed in naked functions. if (CheckNakedParmReference(InputExpr, *this)) return StmtError(); // Check that the input expression is compatible with memory constraint. if (Info.allowsMemory() && checkExprMemoryConstraintCompat(*this, InputExpr, Info, true)) return StmtError(); // Only allow void types for memory constraints. if (Info.allowsMemory() && !Info.allowsRegister()) { if (CheckAsmLValue(InputExpr, *this)) return StmtError(Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_lvalue_in_input) << Info.getConstraintStr() << InputExpr->getSourceRange()); } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) { if (!InputExpr->isValueDependent()) { Expr::EvalResult EVResult; if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) { // For compatibility with GCC, we also allow pointers that would be // integral constant expressions if they were cast to int. llvm::APSInt IntResult; if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(), Context)) if (!Info.isValidAsmImmediate(IntResult)) return StmtError(Diag(InputExpr->getBeginLoc(), diag::err_invalid_asm_value_for_constraint) << IntResult.toString(10) << Info.getConstraintStr() << InputExpr->getSourceRange()); } } } else { ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); if (Result.isInvalid()) return StmtError(); Exprs[i] = Result.get(); } if (Info.allowsRegister()) { if (InputExpr->getType()->isVoidType()) { return StmtError( Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input) << InputExpr->getType() << Info.getConstraintStr() << InputExpr->getSourceRange()); } } InputConstraintInfos.push_back(Info); const Type *Ty = Exprs[i]->getType().getTypePtr(); if (Ty->isDependentType()) continue; if (!Ty->isVoidType() || !Info.allowsMemory()) if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(), diag::err_dereference_incomplete_type)) return StmtError(); unsigned Size = Context.getTypeSize(Ty); if (!Context.getTargetInfo().validateInputSize(FeatureMap, Literal->getString(), Size)) return StmtResult( targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size) << Info.getConstraintStr()); } // Check that the clobbers are valid. for (unsigned i = 0; i != NumClobbers; i++) { StringLiteral *Literal = Clobbers[i]; assert(Literal->isAscii()); StringRef Clobber = Literal->getString(); if (!Context.getTargetInfo().isValidClobber(Clobber)) { targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name) << Clobber; return new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); } } GCCAsmStmt *NS = new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names, Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, NumLabels, RParenLoc); // Validate the asm string, ensuring it makes sense given the operands we // have. SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces; unsigned DiagOffs; if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) << AsmString->getSourceRange(); return NS; } // Validate constraints and modifiers. for (unsigned i = 0, e = Pieces.size(); i != e; ++i) { GCCAsmStmt::AsmStringPiece &Piece = Pieces[i]; if (!Piece.isOperand()) continue; // Look for the correct constraint index. unsigned ConstraintIdx = Piece.getOperandNo(); unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs(); // Labels are the last in the Exprs list. if (NS->isAsmGoto() && ConstraintIdx >= NumOperands) continue; // Look for the (ConstraintIdx - NumOperands + 1)th constraint with // modifier '+'. if (ConstraintIdx >= NumOperands) { unsigned I = 0, E = NS->getNumOutputs(); for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I) if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) { ConstraintIdx = I; break; } assert(I != E && "Invalid operand number should have been caught in " " AnalyzeAsmString"); } // Now that we have the right indexes go ahead and check. StringLiteral *Literal = Constraints[ConstraintIdx]; const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr(); if (Ty->isDependentType() || Ty->isIncompleteType()) continue; unsigned Size = Context.getTypeSize(Ty); std::string SuggestedModifier; if (!Context.getTargetInfo().validateConstraintModifier( Literal->getString(), Piece.getModifier(), Size, SuggestedModifier)) { targetDiag(Exprs[ConstraintIdx]->getBeginLoc(), diag::warn_asm_mismatched_size_modifier); if (!SuggestedModifier.empty()) { auto B = targetDiag(Piece.getRange().getBegin(), diag::note_asm_missing_constraint_modifier) << SuggestedModifier; SuggestedModifier = "%" + SuggestedModifier + Piece.getString(); B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier); } } } // Validate tied input operands for type mismatches. unsigned NumAlternatives = ~0U; for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) { TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; StringRef ConstraintStr = Info.getConstraintStr(); unsigned AltCount = ConstraintStr.count(',') + 1; if (NumAlternatives == ~0U) { NumAlternatives = AltCount; } else if (NumAlternatives != AltCount) { targetDiag(NS->getOutputExpr(i)->getBeginLoc(), diag::err_asm_unexpected_constraint_alternatives) << NumAlternatives << AltCount; return NS; } } SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(), ~0U); for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; StringRef ConstraintStr = Info.getConstraintStr(); unsigned AltCount = ConstraintStr.count(',') + 1; if (NumAlternatives == ~0U) { NumAlternatives = AltCount; } else if (NumAlternatives != AltCount) { targetDiag(NS->getInputExpr(i)->getBeginLoc(), diag::err_asm_unexpected_constraint_alternatives) << NumAlternatives << AltCount; return NS; } // If this is a tied constraint, verify that the output and input have // either exactly the same type, or that they are int/ptr operands with the // same size (int/long, int*/long, are ok etc). if (!Info.hasTiedOperand()) continue; unsigned TiedTo = Info.getTiedOperand(); unsigned InputOpNo = i+NumOutputs; Expr *OutputExpr = Exprs[TiedTo]; Expr *InputExpr = Exprs[InputOpNo]; // Make sure no more than one input constraint matches each output. assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range"); if (InputMatchedToOutput[TiedTo] != ~0U) { targetDiag(NS->getInputExpr(i)->getBeginLoc(), diag::err_asm_input_duplicate_match) << TiedTo; targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(), diag::note_asm_input_duplicate_first) << TiedTo; return NS; } InputMatchedToOutput[TiedTo] = i; if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) continue; QualType InTy = InputExpr->getType(); QualType OutTy = OutputExpr->getType(); if (Context.hasSameType(InTy, OutTy)) continue; // All types can be tied to themselves. // Decide if the input and output are in the same domain (integer/ptr or // floating point. enum AsmDomain { AD_Int, AD_FP, AD_Other } InputDomain, OutputDomain; if (InTy->isIntegerType() || InTy->isPointerType()) InputDomain = AD_Int; else if (InTy->isRealFloatingType()) InputDomain = AD_FP; else InputDomain = AD_Other; if (OutTy->isIntegerType() || OutTy->isPointerType()) OutputDomain = AD_Int; else if (OutTy->isRealFloatingType()) OutputDomain = AD_FP; else OutputDomain = AD_Other; // They are ok if they are the same size and in the same domain. This // allows tying things like: // void* to int* // void* to int if they are the same size. // double to long double if they are the same size. // uint64_t OutSize = Context.getTypeSize(OutTy); uint64_t InSize = Context.getTypeSize(InTy); if (OutSize == InSize && InputDomain == OutputDomain && InputDomain != AD_Other) continue; // If the smaller input/output operand is not mentioned in the asm string, // then we can promote the smaller one to a larger input and the asm string // won't notice. bool SmallerValueMentioned = false; // If this is a reference to the input and if the input was the smaller // one, then we have to reject this asm. if (isOperandMentioned(InputOpNo, Pieces)) { // This is a use in the asm string of the smaller operand. Since we // codegen this by promoting to a wider value, the asm will get printed // "wrong". SmallerValueMentioned |= InSize < OutSize; } if (isOperandMentioned(TiedTo, Pieces)) { // If this is a reference to the output, and if the output is the larger // value, then it's ok because we'll promote the input to the larger type. SmallerValueMentioned |= OutSize < InSize; } // If the smaller value wasn't mentioned in the asm string, and if the // output was a register, just extend the shorter one to the size of the // larger one. if (!SmallerValueMentioned && InputDomain != AD_Other && OutputConstraintInfos[TiedTo].allowsRegister()) continue; // Either both of the operands were mentioned or the smaller one was // mentioned. One more special case that we'll allow: if the tied input is // integer, unmentioned, and is a constant, then we'll allow truncating it // down to the size of the destination. if (InputDomain == AD_Int && OutputDomain == AD_Int && !isOperandMentioned(InputOpNo, Pieces) && InputExpr->isEvaluatable(Context)) { CastKind castKind = (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get(); Exprs[InputOpNo] = InputExpr; NS->setInputExpr(i, InputExpr); continue; } targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types) << InTy << OutTy << OutputExpr->getSourceRange() << InputExpr->getSourceRange(); return NS; } // Check for conflicts between clobber list and input or output lists SourceLocation ConstraintLoc = getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers, NumLabels, Context.getTargetInfo(), Context); if (ConstraintLoc.isValid()) targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber); // Check for duplicate asm operand name between input, output and label lists. typedef std::pair<StringRef , Expr *> NamedOperand; SmallVector<NamedOperand, 4> NamedOperandList; for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i) if (Names[i]) NamedOperandList.emplace_back( std::make_pair(Names[i]->getName(), Exprs[i])); // Sort NamedOperandList. std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(), [](const NamedOperand &LHS, const NamedOperand &RHS) { return LHS.first < RHS.first; }); // Find adjacent duplicate operand. SmallVector<NamedOperand, 4>::iterator Found = std::adjacent_find(begin(NamedOperandList), end(NamedOperandList), [](const NamedOperand &LHS, const NamedOperand &RHS) { return LHS.first == RHS.first; }); if (Found != NamedOperandList.end()) { Diag((Found + 1)->second->getBeginLoc(), diag::error_duplicate_asm_operand_name) << (Found + 1)->first; Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name) << Found->first; return StmtError(); } if (NS->isAsmGoto()) setFunctionHasBranchIntoScope(); return NS; } void Sema::FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info) { QualType T = Res->getType(); Expr::EvalResult Eval; if (T->isFunctionType() || T->isDependentType()) return Info.setLabel(Res); if (Res->isRValue()) { bool IsEnum = isa<clang::EnumType>(T); if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Res)) if (DRE->getDecl()->getKind() == Decl::EnumConstant) IsEnum = true; if (IsEnum && Res->EvaluateAsRValue(Eval, Context)) return Info.setEnum(Eval.Val.getInt().getSExtValue()); return Info.setLabel(Res); } unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); unsigned Type = Size; if (const auto *ATy = Context.getAsArrayType(T)) Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity(); bool IsGlobalLV = false; if (Res->EvaluateAsLValue(Eval, Context)) IsGlobalLV = Eval.isGlobalLValue(); Info.setVar(Res, IsGlobalLV, Size, Type); } ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext) { if (IsUnevaluatedContext) PushExpressionEvaluationContext( ExpressionEvaluationContext::UnevaluatedAbstract, ReuseLambdaContextDecl); ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id, /*trailing lparen*/ false, /*is & operand*/ false, /*CorrectionCandidateCallback=*/nullptr, /*IsInlineAsmIdentifier=*/ true); if (IsUnevaluatedContext) PopExpressionEvaluationContext(); if (!Result.isUsable()) return Result; Result = CheckPlaceholderExpr(Result.get()); if (!Result.isUsable()) return Result; // Referring to parameters is not allowed in naked functions. if (CheckNakedParmReference(Result.get(), *this)) return ExprError(); QualType T = Result.get()->getType(); if (T->isDependentType()) { return Result; } // Any sort of function type is fine. if (T->isFunctionType()) { return Result; } // Otherwise, it needs to be a complete type. if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) { return ExprError(); } return Result; } bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc) { Offset = 0; SmallVector<StringRef, 2> Members; Member.split(Members, "."); NamedDecl *FoundDecl = nullptr; // MS InlineAsm uses 'this' as a base if (getLangOpts().CPlusPlus && Base.equals("this")) { if (const Type *PT = getCurrentThisType().getTypePtrOrNull()) FoundDecl = PT->getPointeeType()->getAsTagDecl(); } else { LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(), LookupOrdinaryName); if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult()) FoundDecl = BaseResult.getFoundDecl(); } if (!FoundDecl) return true; for (StringRef NextMember : Members) { const RecordType *RT = nullptr; if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl)) RT = VD->getType()->getAs<RecordType>(); else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) { MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); // MS InlineAsm often uses struct pointer aliases as a base QualType QT = TD->getUnderlyingType(); if (const auto *PT = QT->getAs<PointerType>()) QT = PT->getPointeeType(); RT = QT->getAs<RecordType>(); } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl)) RT = TD->getTypeForDecl()->getAs<RecordType>(); else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl)) RT = TD->getType()->getAs<RecordType>(); if (!RT) return true; if (RequireCompleteType(AsmLoc, QualType(RT, 0), diag::err_asm_incomplete_type)) return true; LookupResult FieldResult(*this, &Context.Idents.get(NextMember), SourceLocation(), LookupMemberName); if (!LookupQualifiedName(FieldResult, RT->getDecl())) return true; if (!FieldResult.isSingleResult()) return true; FoundDecl = FieldResult.getFoundDecl(); // FIXME: Handle IndirectFieldDecl? FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl); if (!FD) return true; const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl()); unsigned i = FD->getFieldIndex(); CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i)); Offset += (unsigned)Result.getQuantity(); } return false; } ExprResult Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member, SourceLocation AsmLoc) { QualType T = E->getType(); if (T->isDependentType()) { DeclarationNameInfo NameInfo; NameInfo.setLoc(AsmLoc); NameInfo.setName(&Context.Idents.get(Member)); return CXXDependentScopeMemberExpr::Create( Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(), SourceLocation(), /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr); } const RecordType *RT = T->getAs<RecordType>(); // FIXME: Diagnose this as field access into a scalar type. if (!RT) return ExprResult(); LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc, LookupMemberName); if (!LookupQualifiedName(FieldResult, RT->getDecl())) return ExprResult(); // Only normal and indirect field results will work. ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl()); if (!FD) FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl()); if (!FD) return ExprResult(); // Make an Expr to thread through OpDecl. ExprResult Result = BuildMemberReferenceExpr( E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(), SourceLocation(), nullptr, FieldResult, nullptr, nullptr); return Result; } StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc) { bool IsSimple = (NumOutputs != 0 || NumInputs != 0); setFunctionHasBranchProtectedScope(); MSAsmStmt *NS = new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple, /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs, Constraints, Exprs, AsmString, Clobbers, EndLoc); return NS; } LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate) { LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName), Location); if (Label->isMSAsmLabel()) { // If we have previously created this label implicitly, mark it as used. Label->markUsed(Context); } else { // Otherwise, insert it, but only resolve it if we have seen the label itself. std::string InternalName; llvm::raw_string_ostream OS(InternalName); // Create an internal name for the label. The name should not be a valid // mangled name, and should be unique. We use a dot to make the name an // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a // unique label is generated each time this blob is emitted, even after // inlining or LTO. OS << "__MSASMLABEL_.${:uid}__"; for (char C : ExternalLabelName) { OS << C; // We escape '$' in asm strings by replacing it with "$$" if (C == '$') OS << '$'; } Label->setMSAsmLabel(OS.str()); } if (AlwaysCreate) { // The label might have been created implicitly from a previously encountered // goto statement. So, for both newly created and looked up labels, we mark // them as resolved. Label->setMSAsmLabelResolved(); } // Adjust their location for being able to generate accurate diagnostics. Label->setLocation(Location); return Label; }
endlessm/chromium-browser
third_party/llvm/clang/lib/Sema/SemaStmtAsm.cpp
C++
bsd-3-clause
36,063
/** * Copyright (c) 2009-2016, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * SPI, tests. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 1.28 */ package com.rultor.spi;
dalifreire/rultor
src/test/java/com/rultor/spi/package-info.java
Java
bsd-3-clause
1,692
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/privacy/dlp/v2beta1/dlp.proto package com.google.privacy.dlp.v2beta1; /** * <pre> * Description of the information type (infoType). * </pre> * * Protobuf type {@code google.privacy.dlp.v2beta1.InfoTypeDescription} */ public final class InfoTypeDescription extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.privacy.dlp.v2beta1.InfoTypeDescription) InfoTypeDescriptionOrBuilder { private static final long serialVersionUID = 0L; // Use InfoTypeDescription.newBuilder() to construct. private InfoTypeDescription(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private InfoTypeDescription() { name_ = ""; displayName_ = ""; categories_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private InfoTypeDescription( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); displayName_ = s; break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { categories_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta1.CategoryDescription>(); mutable_bitField0_ |= 0x00000004; } categories_.add( input.readMessage(com.google.privacy.dlp.v2beta1.CategoryDescription.parser(), extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { categories_ = java.util.Collections.unmodifiableList(categories_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2beta1.InfoTypeDescription.class, com.google.privacy.dlp.v2beta1.InfoTypeDescription.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DISPLAY_NAME_FIELD_NUMBER = 2; private volatile java.lang.Object displayName_; /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CATEGORIES_FIELD_NUMBER = 3; private java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> categories_; /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> getCategoriesList() { return categories_; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<? extends com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> getCategoriesOrBuilderList() { return categories_; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public int getCategoriesCount() { return categories_.size(); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription getCategories(int index) { return categories_.get(index); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder getCategoriesOrBuilder( int index) { return categories_.get(index); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!getDisplayNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_); } for (int i = 0; i < categories_.size(); i++) { output.writeMessage(3, categories_.get(i)); } unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!getDisplayNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_); } for (int i = 0; i < categories_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, categories_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.privacy.dlp.v2beta1.InfoTypeDescription)) { return super.equals(obj); } com.google.privacy.dlp.v2beta1.InfoTypeDescription other = (com.google.privacy.dlp.v2beta1.InfoTypeDescription) obj; boolean result = true; result = result && getName() .equals(other.getName()); result = result && getDisplayName() .equals(other.getDisplayName()); result = result && getCategoriesList() .equals(other.getCategoriesList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER; hash = (53 * hash) + getDisplayName().hashCode(); if (getCategoriesCount() > 0) { hash = (37 * hash) + CATEGORIES_FIELD_NUMBER; hash = (53 * hash) + getCategoriesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.privacy.dlp.v2beta1.InfoTypeDescription prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Description of the information type (infoType). * </pre> * * Protobuf type {@code google.privacy.dlp.v2beta1.InfoTypeDescription} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2beta1.InfoTypeDescription) com.google.privacy.dlp.v2beta1.InfoTypeDescriptionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2beta1.InfoTypeDescription.class, com.google.privacy.dlp.v2beta1.InfoTypeDescription.Builder.class); } // Construct using com.google.privacy.dlp.v2beta1.InfoTypeDescription.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getCategoriesFieldBuilder(); } } public Builder clear() { super.clear(); name_ = ""; displayName_ = ""; if (categoriesBuilder_ == null) { categories_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { categoriesBuilder_.clear(); } return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.privacy.dlp.v2beta1.DlpProto.internal_static_google_privacy_dlp_v2beta1_InfoTypeDescription_descriptor; } public com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstanceForType() { return com.google.privacy.dlp.v2beta1.InfoTypeDescription.getDefaultInstance(); } public com.google.privacy.dlp.v2beta1.InfoTypeDescription build() { com.google.privacy.dlp.v2beta1.InfoTypeDescription result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.privacy.dlp.v2beta1.InfoTypeDescription buildPartial() { com.google.privacy.dlp.v2beta1.InfoTypeDescription result = new com.google.privacy.dlp.v2beta1.InfoTypeDescription(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.name_ = name_; result.displayName_ = displayName_; if (categoriesBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004)) { categories_ = java.util.Collections.unmodifiableList(categories_); bitField0_ = (bitField0_ & ~0x00000004); } result.categories_ = categories_; } else { result.categories_ = categoriesBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.privacy.dlp.v2beta1.InfoTypeDescription) { return mergeFrom((com.google.privacy.dlp.v2beta1.InfoTypeDescription)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.privacy.dlp.v2beta1.InfoTypeDescription other) { if (other == com.google.privacy.dlp.v2beta1.InfoTypeDescription.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getDisplayName().isEmpty()) { displayName_ = other.displayName_; onChanged(); } if (categoriesBuilder_ == null) { if (!other.categories_.isEmpty()) { if (categories_.isEmpty()) { categories_ = other.categories_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureCategoriesIsMutable(); categories_.addAll(other.categories_); } onChanged(); } } else { if (!other.categories_.isEmpty()) { if (categoriesBuilder_.isEmpty()) { categoriesBuilder_.dispose(); categoriesBuilder_ = null; categories_ = other.categories_; bitField0_ = (bitField0_ & ~0x00000004); categoriesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCategoriesFieldBuilder() : null; } else { categoriesBuilder_.addAllMessages(other.categories_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.privacy.dlp.v2beta1.InfoTypeDescription parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.privacy.dlp.v2beta1.InfoTypeDescription) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <pre> * Internal name of the infoType. * </pre> * * <code>string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object displayName_ = ""; /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public Builder setDisplayName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } displayName_ = value; onChanged(); return this; } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public Builder clearDisplayName() { displayName_ = getDefaultInstance().getDisplayName(); onChanged(); return this; } /** * <pre> * Human readable form of the infoType name. * </pre> * * <code>string display_name = 2;</code> */ public Builder setDisplayNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); displayName_ = value; onChanged(); return this; } private java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> categories_ = java.util.Collections.emptyList(); private void ensureCategoriesIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { categories_ = new java.util.ArrayList<com.google.privacy.dlp.v2beta1.CategoryDescription>(categories_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> categoriesBuilder_; /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription> getCategoriesList() { if (categoriesBuilder_ == null) { return java.util.Collections.unmodifiableList(categories_); } else { return categoriesBuilder_.getMessageList(); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public int getCategoriesCount() { if (categoriesBuilder_ == null) { return categories_.size(); } else { return categoriesBuilder_.getCount(); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription getCategories(int index) { if (categoriesBuilder_ == null) { return categories_.get(index); } else { return categoriesBuilder_.getMessage(index); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder setCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription value) { if (categoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCategoriesIsMutable(); categories_.set(index, value); onChanged(); } else { categoriesBuilder_.setMessage(index, value); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder setCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.set(index, builderForValue.build()); onChanged(); } else { categoriesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories(com.google.privacy.dlp.v2beta1.CategoryDescription value) { if (categoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCategoriesIsMutable(); categories_.add(value); onChanged(); } else { categoriesBuilder_.addMessage(value); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription value) { if (categoriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCategoriesIsMutable(); categories_.add(index, value); onChanged(); } else { categoriesBuilder_.addMessage(index, value); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories( com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.add(builderForValue.build()); onChanged(); } else { categoriesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addCategories( int index, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder builderForValue) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.add(index, builderForValue.build()); onChanged(); } else { categoriesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder addAllCategories( java.lang.Iterable<? extends com.google.privacy.dlp.v2beta1.CategoryDescription> values) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, categories_); onChanged(); } else { categoriesBuilder_.addAllMessages(values); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder clearCategories() { if (categoriesBuilder_ == null) { categories_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { categoriesBuilder_.clear(); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public Builder removeCategories(int index) { if (categoriesBuilder_ == null) { ensureCategoriesIsMutable(); categories_.remove(index); onChanged(); } else { categoriesBuilder_.remove(index); } return this; } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder getCategoriesBuilder( int index) { return getCategoriesFieldBuilder().getBuilder(index); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder getCategoriesOrBuilder( int index) { if (categoriesBuilder_ == null) { return categories_.get(index); } else { return categoriesBuilder_.getMessageOrBuilder(index); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<? extends com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> getCategoriesOrBuilderList() { if (categoriesBuilder_ != null) { return categoriesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(categories_); } } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder addCategoriesBuilder() { return getCategoriesFieldBuilder().addBuilder( com.google.privacy.dlp.v2beta1.CategoryDescription.getDefaultInstance()); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public com.google.privacy.dlp.v2beta1.CategoryDescription.Builder addCategoriesBuilder( int index) { return getCategoriesFieldBuilder().addBuilder( index, com.google.privacy.dlp.v2beta1.CategoryDescription.getDefaultInstance()); } /** * <pre> * List of categories this infoType belongs to. * </pre> * * <code>repeated .google.privacy.dlp.v2beta1.CategoryDescription categories = 3;</code> */ public java.util.List<com.google.privacy.dlp.v2beta1.CategoryDescription.Builder> getCategoriesBuilderList() { return getCategoriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder> getCategoriesFieldBuilder() { if (categoriesBuilder_ == null) { categoriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.privacy.dlp.v2beta1.CategoryDescription, com.google.privacy.dlp.v2beta1.CategoryDescription.Builder, com.google.privacy.dlp.v2beta1.CategoryDescriptionOrBuilder>( categories_, ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); categories_ = null; } return categoriesBuilder_; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2beta1.InfoTypeDescription) } // @@protoc_insertion_point(class_scope:google.privacy.dlp.v2beta1.InfoTypeDescription) private static final com.google.privacy.dlp.v2beta1.InfoTypeDescription DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.privacy.dlp.v2beta1.InfoTypeDescription(); } public static com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<InfoTypeDescription> PARSER = new com.google.protobuf.AbstractParser<InfoTypeDescription>() { public InfoTypeDescription parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new InfoTypeDescription(input, extensionRegistry); } }; public static com.google.protobuf.Parser<InfoTypeDescription> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<InfoTypeDescription> getParserForType() { return PARSER; } public com.google.privacy.dlp.v2beta1.InfoTypeDescription getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
pongad/api-client-staging
generated/java/proto-google-cloud-dlp-v2beta1/src/main/java/com/google/privacy/dlp/v2beta1/InfoTypeDescription.java
Java
bsd-3-clause
37,925
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/filters/vpx_video_decoder.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <string> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/feature_list.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" #include "base/sys_byteorder.h" #include "base/trace_event/trace_event.h" #include "media/base/bind_to_current_loop.h" #include "media/base/decoder_buffer.h" #include "media/base/limits.h" #include "media/base/media_switches.h" #include "media/base/video_aspect_ratio.h" #include "media/filters/frame_buffer_pool.h" #include "third_party/libvpx/source/libvpx/vpx/vp8dx.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_frame_buffer.h" #include "third_party/libyuv/include/libyuv/convert.h" #include "third_party/libyuv/include/libyuv/planar_functions.h" namespace media { // Returns the number of threads. static int GetVpxVideoDecoderThreadCount(const VideoDecoderConfig& config) { // vp8a doesn't really need more threads. int desired_threads = limits::kMinVideoDecodeThreads; // For VP9 decoding increase the number of decode threads to equal the // maximum number of tiles possible for higher resolution streams. if (config.codec() == VideoCodec::kVP9) { const int width = config.coded_size().width(); if (width >= 3840) desired_threads = 16; else if (width >= 2560) desired_threads = 8; else if (width >= 1280) desired_threads = 4; } return VideoDecoder::GetRecommendedThreadCount(desired_threads); } static std::unique_ptr<vpx_codec_ctx> InitializeVpxContext( const VideoDecoderConfig& config) { auto context = std::make_unique<vpx_codec_ctx>(); vpx_codec_dec_cfg_t vpx_config = {0}; vpx_config.w = config.coded_size().width(); vpx_config.h = config.coded_size().height(); vpx_config.threads = GetVpxVideoDecoderThreadCount(config); vpx_codec_err_t status = vpx_codec_dec_init(context.get(), config.codec() == VideoCodec::kVP9 ? vpx_codec_vp9_dx() : vpx_codec_vp8_dx(), &vpx_config, 0 /* flags */); if (status == VPX_CODEC_OK) return context; DLOG(ERROR) << "vpx_codec_dec_init() failed: " << vpx_codec_error(context.get()); return nullptr; } static int32_t GetVP9FrameBuffer(void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) { DCHECK(user_priv); DCHECK(fb); FrameBufferPool* pool = static_cast<FrameBufferPool*>(user_priv); fb->data = pool->GetFrameBuffer(min_size, &fb->priv); fb->size = min_size; return fb->data ? 0 : VPX_CODEC_MEM_ERROR; } static int32_t ReleaseVP9FrameBuffer(void* user_priv, vpx_codec_frame_buffer* fb) { DCHECK(user_priv); DCHECK(fb); if (!fb->priv) return -1; FrameBufferPool* pool = static_cast<FrameBufferPool*>(user_priv); pool->ReleaseFrameBuffer(fb->priv); return 0; } // static SupportedVideoDecoderConfigs VpxVideoDecoder::SupportedConfigs() { SupportedVideoDecoderConfigs supported_configs; supported_configs.emplace_back(/*profile_min=*/VP8PROFILE_ANY, /*profile_max=*/VP8PROFILE_ANY, /*coded_size_min=*/kDefaultSwDecodeSizeMin, /*coded_size_max=*/kDefaultSwDecodeSizeMax, /*allow_encrypted=*/false, /*require_encrypted=*/false); supported_configs.emplace_back(/*profile_min=*/VP9PROFILE_PROFILE0, /*profile_max=*/VP9PROFILE_PROFILE2, /*coded_size_min=*/kDefaultSwDecodeSizeMin, /*coded_size_max=*/kDefaultSwDecodeSizeMax, /*allow_encrypted=*/false, /*require_encrypted=*/false); return supported_configs; } VpxVideoDecoder::VpxVideoDecoder(OffloadState offload_state) : bind_callbacks_(offload_state == OffloadState::kNormal) { DETACH_FROM_SEQUENCE(sequence_checker_); } VpxVideoDecoder::~VpxVideoDecoder() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CloseDecoder(); } VideoDecoderType VpxVideoDecoder::GetDecoderType() const { return VideoDecoderType::kVpx; } void VpxVideoDecoder::Initialize(const VideoDecoderConfig& config, bool /* low_delay */, CdmContext* /* cdm_context */, InitCB init_cb, const OutputCB& output_cb, const WaitingCB& /* waiting_cb */) { DVLOG(1) << __func__ << ": " << config.AsHumanReadableString(); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(config.IsValidConfig()); CloseDecoder(); InitCB bound_init_cb = bind_callbacks_ ? BindToCurrentLoop(std::move(init_cb)) : std::move(init_cb); if (config.is_encrypted()) { std::move(bound_init_cb).Run(StatusCode::kEncryptedContentUnsupported); return; } if (!ConfigureDecoder(config)) { std::move(bound_init_cb).Run(StatusCode::kDecoderFailedInitialization); return; } // Success! config_ = config; state_ = DecoderState::kNormal; output_cb_ = output_cb; std::move(bound_init_cb).Run(OkStatus()); } void VpxVideoDecoder::Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) { DVLOG(3) << __func__ << ": " << buffer->AsHumanReadableString(); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(buffer); DCHECK(decode_cb); DCHECK_NE(state_, DecoderState::kUninitialized) << "Called Decode() before successful Initialize()"; DecodeCB bound_decode_cb = bind_callbacks_ ? BindToCurrentLoop(std::move(decode_cb)) : std::move(decode_cb); if (state_ == DecoderState::kError) { std::move(bound_decode_cb).Run(DecodeStatus::DECODE_ERROR); return; } if (state_ == DecoderState::kDecodeFinished) { std::move(bound_decode_cb).Run(DecodeStatus::OK); return; } if (state_ == DecoderState::kNormal && buffer->end_of_stream()) { state_ = DecoderState::kDecodeFinished; std::move(bound_decode_cb).Run(DecodeStatus::OK); return; } scoped_refptr<VideoFrame> video_frame; if (!VpxDecode(buffer.get(), &video_frame)) { state_ = DecoderState::kError; std::move(bound_decode_cb).Run(DecodeStatus::DECODE_ERROR); return; } // We might get a successful VpxDecode but not a frame if only a partial // decode happened. if (video_frame) { video_frame->metadata().power_efficient = false; output_cb_.Run(video_frame); } // VideoDecoderShim expects |decode_cb| call after |output_cb_|. std::move(bound_decode_cb).Run(DecodeStatus::OK); } void VpxVideoDecoder::Reset(base::OnceClosure reset_cb) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); state_ = DecoderState::kNormal; if (bind_callbacks_) BindToCurrentLoop(std::move(reset_cb)).Run(); else std::move(reset_cb).Run(); // Allow Initialize() to be called on another thread now. DETACH_FROM_SEQUENCE(sequence_checker_); } bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig& config) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (config.codec() != VideoCodec::kVP8 && config.codec() != VideoCodec::kVP9) return false; #if BUILDFLAG(ENABLE_FFMPEG_VIDEO_DECODERS) // When enabled, ffmpeg handles VP8 that doesn't have alpha, and // VpxVideoDecoder will handle VP8 with alpha. FFvp8 is being deprecated. // See http://crbug.com/992235. if (base::FeatureList::IsEnabled(kFFmpegDecodeOpaqueVP8) && config.codec() == VideoCodec::kVP8 && config.alpha_mode() == VideoDecoderConfig::AlphaMode::kIsOpaque) { return false; } #endif DCHECK(!vpx_codec_); vpx_codec_ = InitializeVpxContext(config); if (!vpx_codec_) return false; // Configure VP9 to decode on our buffers to skip a data copy on // decoding. For YV12A-VP9, we use our buffers for the Y, U and V planes and // copy the A plane. if (config.codec() == VideoCodec::kVP9) { DCHECK(vpx_codec_get_caps(vpx_codec_->iface) & VPX_CODEC_CAP_EXTERNAL_FRAME_BUFFER); DCHECK(!memory_pool_); memory_pool_ = new FrameBufferPool(); if (vpx_codec_set_frame_buffer_functions( vpx_codec_.get(), &GetVP9FrameBuffer, &ReleaseVP9FrameBuffer, memory_pool_.get())) { DLOG(ERROR) << "Failed to configure external buffers. " << vpx_codec_error(vpx_codec_.get()); return false; } vpx_codec_err_t status = vpx_codec_control(vpx_codec_.get(), VP9D_SET_LOOP_FILTER_OPT, 1); if (status != VPX_CODEC_OK) { DLOG(ERROR) << "Failed to enable VP9D_SET_LOOP_FILTER_OPT. " << vpx_codec_error(vpx_codec_.get()); return false; } } if (config.alpha_mode() == VideoDecoderConfig::AlphaMode::kIsOpaque) return true; DCHECK(!vpx_codec_alpha_); vpx_codec_alpha_ = InitializeVpxContext(config); return !!vpx_codec_alpha_; } void VpxVideoDecoder::CloseDecoder() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Note: The vpx_codec_destroy() calls below don't release the memory // allocated for vpx_codec_ctx, they just release internal allocations, so we // still need std::unique_ptr to release the structure memory. if (vpx_codec_) vpx_codec_destroy(vpx_codec_.get()); if (vpx_codec_alpha_) vpx_codec_destroy(vpx_codec_alpha_.get()); vpx_codec_.reset(); vpx_codec_alpha_.reset(); if (memory_pool_) { memory_pool_->Shutdown(); memory_pool_ = nullptr; } } void VpxVideoDecoder::Detach() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!bind_callbacks_); CloseDecoder(); DETACH_FROM_SEQUENCE(sequence_checker_); } bool VpxVideoDecoder::VpxDecode(const DecoderBuffer* buffer, scoped_refptr<VideoFrame>* video_frame) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(video_frame); DCHECK(!buffer->end_of_stream()); { TRACE_EVENT1("media", "vpx_codec_decode", "buffer", buffer->AsHumanReadableString()); vpx_codec_err_t status = vpx_codec_decode(vpx_codec_.get(), buffer->data(), buffer->data_size(), nullptr /* user_priv */, 0 /* deadline */); if (status != VPX_CODEC_OK) { DLOG(ERROR) << "vpx_codec_decode() error: " << vpx_codec_err_to_string(status); return false; } } // Gets pointer to decoded data. vpx_codec_iter_t iter = NULL; const vpx_image_t* vpx_image = vpx_codec_get_frame(vpx_codec_.get(), &iter); if (!vpx_image) { *video_frame = nullptr; return true; } const vpx_image_t* vpx_image_alpha = nullptr; const auto alpha_decode_status = DecodeAlphaPlane(vpx_image, &vpx_image_alpha, buffer); if (alpha_decode_status == kAlphaPlaneError) { return false; } else if (alpha_decode_status == kNoAlphaPlaneData) { *video_frame = nullptr; return true; } if (!CopyVpxImageToVideoFrame(vpx_image, vpx_image_alpha, video_frame)) return false; if (vpx_image_alpha && config_.codec() == VideoCodec::kVP8) { libyuv::CopyPlane(vpx_image_alpha->planes[VPX_PLANE_Y], vpx_image_alpha->stride[VPX_PLANE_Y], (*video_frame)->visible_data(VideoFrame::kAPlane), (*video_frame)->stride(VideoFrame::kAPlane), (*video_frame)->visible_rect().width(), (*video_frame)->visible_rect().height()); } (*video_frame)->set_timestamp(buffer->timestamp()); (*video_frame)->set_hdr_metadata(config_.hdr_metadata()); // Prefer the color space from the config if available. It generally comes // from the color tag which is more expressive than the vp8 and vp9 bitstream. if (config_.color_space_info().IsSpecified()) { (*video_frame) ->set_color_space(config_.color_space_info().ToGfxColorSpace()); return true; } auto primaries = gfx::ColorSpace::PrimaryID::INVALID; auto transfer = gfx::ColorSpace::TransferID::INVALID; auto matrix = gfx::ColorSpace::MatrixID::INVALID; auto range = vpx_image->range == VPX_CR_FULL_RANGE ? gfx::ColorSpace::RangeID::FULL : gfx::ColorSpace::RangeID::LIMITED; switch (vpx_image->cs) { case VPX_CS_BT_601: case VPX_CS_SMPTE_170: primaries = gfx::ColorSpace::PrimaryID::SMPTE170M; transfer = gfx::ColorSpace::TransferID::SMPTE170M; matrix = gfx::ColorSpace::MatrixID::SMPTE170M; break; case VPX_CS_SMPTE_240: primaries = gfx::ColorSpace::PrimaryID::SMPTE240M; transfer = gfx::ColorSpace::TransferID::SMPTE240M; matrix = gfx::ColorSpace::MatrixID::SMPTE240M; break; case VPX_CS_BT_709: primaries = gfx::ColorSpace::PrimaryID::BT709; transfer = gfx::ColorSpace::TransferID::BT709; matrix = gfx::ColorSpace::MatrixID::BT709; break; case VPX_CS_BT_2020: primaries = gfx::ColorSpace::PrimaryID::BT2020; if (vpx_image->bit_depth >= 12) transfer = gfx::ColorSpace::TransferID::BT2020_12; else if (vpx_image->bit_depth >= 10) transfer = gfx::ColorSpace::TransferID::BT2020_10; else transfer = gfx::ColorSpace::TransferID::BT709; matrix = gfx::ColorSpace::MatrixID::BT2020_NCL; // is this right? break; case VPX_CS_SRGB: primaries = gfx::ColorSpace::PrimaryID::BT709; transfer = gfx::ColorSpace::TransferID::IEC61966_2_1; matrix = gfx::ColorSpace::MatrixID::GBR; break; default: break; } // TODO(ccameron): Set a color space even for unspecified values. if (primaries != gfx::ColorSpace::PrimaryID::INVALID) { (*video_frame) ->set_color_space(gfx::ColorSpace(primaries, transfer, matrix, range)); } return true; } VpxVideoDecoder::AlphaDecodeStatus VpxVideoDecoder::DecodeAlphaPlane( const struct vpx_image* vpx_image, const struct vpx_image** vpx_image_alpha, const DecoderBuffer* buffer) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!vpx_codec_alpha_ || buffer->side_data_size() < 8) { return kAlphaPlaneProcessed; } // First 8 bytes of side data is |side_data_id| in big endian. const uint64_t side_data_id = base::NetToHost64( *(reinterpret_cast<const uint64_t*>(buffer->side_data()))); if (side_data_id != 1) { return kAlphaPlaneProcessed; } // Try and decode buffer->side_data() minus the first 8 bytes as a full // frame. { TRACE_EVENT1("media", "vpx_codec_decode_alpha", "buffer", buffer->AsHumanReadableString()); vpx_codec_err_t status = vpx_codec_decode(vpx_codec_alpha_.get(), buffer->side_data() + 8, buffer->side_data_size() - 8, nullptr /* user_priv */, 0 /* deadline */); if (status != VPX_CODEC_OK) { DLOG(ERROR) << "vpx_codec_decode() failed for the alpha: " << vpx_codec_error(vpx_codec_.get()); return kAlphaPlaneError; } } vpx_codec_iter_t iter_alpha = NULL; *vpx_image_alpha = vpx_codec_get_frame(vpx_codec_alpha_.get(), &iter_alpha); if (!(*vpx_image_alpha)) { return kNoAlphaPlaneData; } if ((*vpx_image_alpha)->d_h != vpx_image->d_h || (*vpx_image_alpha)->d_w != vpx_image->d_w) { DLOG(ERROR) << "The alpha plane dimensions are not the same as the " "image dimensions."; return kAlphaPlaneError; } return kAlphaPlaneProcessed; } bool VpxVideoDecoder::CopyVpxImageToVideoFrame( const struct vpx_image* vpx_image, const struct vpx_image* vpx_image_alpha, scoped_refptr<VideoFrame>* video_frame) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(vpx_image); VideoPixelFormat codec_format; switch (vpx_image->fmt) { case VPX_IMG_FMT_I420: codec_format = vpx_image_alpha ? PIXEL_FORMAT_I420A : PIXEL_FORMAT_I420; break; case VPX_IMG_FMT_I422: codec_format = PIXEL_FORMAT_I422; break; case VPX_IMG_FMT_I444: codec_format = PIXEL_FORMAT_I444; break; case VPX_IMG_FMT_I42016: switch (vpx_image->bit_depth) { case 10: codec_format = PIXEL_FORMAT_YUV420P10; break; case 12: codec_format = PIXEL_FORMAT_YUV420P12; break; default: DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth; return false; } break; case VPX_IMG_FMT_I42216: switch (vpx_image->bit_depth) { case 10: codec_format = PIXEL_FORMAT_YUV422P10; break; case 12: codec_format = PIXEL_FORMAT_YUV422P12; break; default: DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth; return false; } break; case VPX_IMG_FMT_I44416: switch (vpx_image->bit_depth) { case 10: codec_format = PIXEL_FORMAT_YUV444P10; break; case 12: codec_format = PIXEL_FORMAT_YUV444P12; break; default: DLOG(ERROR) << "Unsupported bit depth: " << vpx_image->bit_depth; return false; } break; default: DLOG(ERROR) << "Unsupported pixel format: " << vpx_image->fmt; return false; } // The mixed |w|/|d_h| in |coded_size| is intentional. Setting the correct // coded width is necessary to allow coalesced memory access, which may avoid // frame copies. Setting the correct coded height however does not have any // benefit, and only risk copying too much data. const gfx::Size coded_size(vpx_image->w, vpx_image->d_h); const gfx::Size visible_size(vpx_image->d_w, vpx_image->d_h); // Compute natural size by scaling visible size by *pixel* aspect ratio. Note // that we could instead use vpx_image r_w and r_h, but doing so would allow // pixel aspect ratio to change on a per-frame basis which would make // vpx_video_decoder inconsistent with decoders where changes to // pixel aspect ratio are not surfaced (e.g. Android MediaCodec). const gfx::Size natural_size = config_.aspect_ratio().GetNaturalSize(gfx::Rect(visible_size)); if (memory_pool_) { DCHECK_EQ(VideoCodec::kVP9, config_.codec()); if (vpx_image_alpha) { size_t alpha_plane_size = vpx_image_alpha->stride[VPX_PLANE_Y] * vpx_image_alpha->d_h; uint8_t* alpha_plane = memory_pool_->AllocateAlphaPlaneForFrameBuffer( alpha_plane_size, vpx_image->fb_priv); if (!alpha_plane) // In case of OOM, abort copy. return false; libyuv::CopyPlane(vpx_image_alpha->planes[VPX_PLANE_Y], vpx_image_alpha->stride[VPX_PLANE_Y], alpha_plane, vpx_image_alpha->stride[VPX_PLANE_Y], vpx_image_alpha->d_w, vpx_image_alpha->d_h); *video_frame = VideoFrame::WrapExternalYuvaData( codec_format, coded_size, gfx::Rect(visible_size), natural_size, vpx_image->stride[VPX_PLANE_Y], vpx_image->stride[VPX_PLANE_U], vpx_image->stride[VPX_PLANE_V], vpx_image_alpha->stride[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_U], vpx_image->planes[VPX_PLANE_V], alpha_plane, kNoTimestamp); } else { *video_frame = VideoFrame::WrapExternalYuvData( codec_format, coded_size, gfx::Rect(visible_size), natural_size, vpx_image->stride[VPX_PLANE_Y], vpx_image->stride[VPX_PLANE_U], vpx_image->stride[VPX_PLANE_V], vpx_image->planes[VPX_PLANE_Y], vpx_image->planes[VPX_PLANE_U], vpx_image->planes[VPX_PLANE_V], kNoTimestamp); } if (!(*video_frame)) return false; video_frame->get()->AddDestructionObserver( memory_pool_->CreateFrameCallback(vpx_image->fb_priv)); return true; } *video_frame = frame_pool_.CreateFrame(codec_format, visible_size, gfx::Rect(visible_size), natural_size, kNoTimestamp); if (!(*video_frame)) return false; for (int plane = 0; plane < 3; plane++) { libyuv::CopyPlane( vpx_image->planes[plane], vpx_image->stride[plane], (*video_frame)->visible_data(plane), (*video_frame)->stride(plane), (*video_frame)->row_bytes(plane), (*video_frame)->rows(plane)); } return true; } } // namespace media
nwjs/chromium.src
media/filters/vpx_video_decoder.cc
C++
bsd-3-clause
21,197
"""Workflow for uploading many many many log files at once.""" from __future__ import absolute_import import os from os.path import isfile, getsize import logging import re import luigi import psycopg2 import pandas as pd # import sqlalchemy try: from .pylog_parse import LogFile except: from pylog_parse import LogFile logger = logging.getLogger(__name__) class LogTask(luigi.Task): """Base task for log workflow.""" path = luigi.Parameter() logtype = luigi.Parameter() _conf = luigi.configuration.get_config() _conf.reload() _password = _conf.get('postgres', 'password') _host = _conf.get('postgres', 'host') _port = _conf.get('postgres', 'port') _database = _conf.get('pylog', 'database') _user = _conf.get('postgres', 'user') _url = """postgresql://{u}:{p}@{h}:{port}/{db}""".format(u=_user, p=_password, h=_host, port=_port, db=_database) @property def url(self): """Postgresql url property.""" return self._url def folder_size(path): """Return size of folder at path.""" return sum(getsize(f) for f in os.listdir('.') if isfile(f)) def list_directory_files(path, folders=False): """Yield all filenames in a path.""" for f in os.listdir(path): if f[0] == '.': continue current_path = os.path.join(path, f) if folders is False: if os.path.isfile(current_path): if os.path.getsize(current_path) != 0: yield current_path else: file_ext = os.path.splitext(f)[1] if file_ext == '' or file_ext == '/': yield current_path def get_subfolders(path): for f in list_directory_files(path, folders=True): file_ext = os.path.splitext(f)[1] if file_ext == ''or file_ext == '/': yield f def get_sublogs(path): for f in list_directory_files(path): file_ext = os.path.splitext(f)[1] if file_ext == '.log': yield f class CheckLogPath(luigi.ExternalTask): path = luigi.Parameter() def output(self): return luigi.LocalTarget(path=self.path) class UploadLogs(LogTask): def requires(self): return CheckLogPath(path=self.path) def output(self): groups = re.search(r'2015.(\d{2}).(\d{2})', self.path).groups() csv = '/home/ubuntu/elb2/2015-{m}-{d}.csv'.format(m=groups[0], d=groups[1]) return luigi.LocalTarget(path=csv) def run(self): conn = psycopg2.connect(self.url) log = LogFile(path=self.path, log_type=self.logtype) cursor = conn.cursor() cursor.close() log.to_csv(self.output().path, con=conn, copy=True) if os.path.exists(self.output().path): df = pd.DataFrame({'length': log.length}, index=[0]) os.remove(self.output().path) df.to_csv(self.output().path, index=False) # Only keep head of csv class LogPaths(LogTask): def requires(self): log_files = [f for f in get_sublogs(self.path)] subfolders = [f for f in get_subfolders(self.path)] logger.debug('Path: {p}'.format(p=self.path)) logger.debug('Subfolders: {s}'.format(s=subfolders)) logger.debug('Subfiles: {f}'.format(f=log_files)) for fold in subfolders: sub = [f for f in get_subfolders(fold)] files = [f for f in get_sublogs(fold)] if len(sub) > 0: logger.info('Subfolders of {f}: {s}'.format(f=fold, s=sub)) yield LogPaths(path=fold, logtype=self.logtype) elif len(files) > 0: yield UploadLogs(path=fold, logtype=self.logtype) for f in log_files: yield UploadLogs(path=f, logtype=self.logtype) def run(self): total_length = 0 for f in self.input(): total_length = total_length + pd.read_csv(f.path()).iloc[0][0] logger.info('AllFilesLength: {l}'.format(l=total_length)) if __name__ == '__main__': luigi.run()
sethmenghi/pylog_parse
pylog_parse/workflow.py
Python
bsd-3-clause
4,335
namespace NHibernate.ZMQLogPublisher { using System.Collections.Concurrent; using System.Collections.Generic; using ZMQ; public class SocketManager { private readonly Context context; private ConcurrentDictionary<string, Socket> sockets; private object synclock = new object(); private bool terminated; public SocketManager() { this.context = new Context(1); this.sockets = new ConcurrentDictionary<string, Socket>(); } public bool Terminated { get { return this.terminated; } } public Context Context { get { return this.context; } } public Socket CreateSocketForKey(string loggerKey, SocketType socketType) { return this.sockets.GetOrAdd( loggerKey, key => { var socket = this.Context.Socket(socketType); this.sockets.TryAdd(loggerKey, socket); return socket; }); } public void Terminate() { this.terminated = true; foreach (var socket in sockets.Values) { lock (this.synclock) { socket.Dispose(); } } sockets.Clear(); this.Context.Dispose(); } } }
seif/NHibernate.ZMQLogPublisher
src/NHibernate.ZMQLogPublisher/SocketManager.cs
C#
bsd-3-clause
1,545
//====================================================================== //----------------------------------------------------------------------- /** * @file syntax_tests.cpp * @brief syntax test * * @author t.shirayanagi * @par copyright * Copyright (C) 2013-2021, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #include "pred_tests.hpp" #include <limits> namespace syntax_tests { #ifndef IUTEST_NO_VARIADIC_MACROS template<int A, int B>struct T { template<typename U> static U call(U v) { return v; } }; #endif IUTEST_PRAGMA_WARN_PUSH() IUTEST_PRAGMA_WARN_DISABLE_DANGLING_ELSE() IUTEST_PRAGMA_WARN_DISABLE_FLOAT_CONVERSION() IUTEST(SyntaxTest, True) { if( bool b = true ) IUTEST_ASSERT_TRUE(b) << b; if( bool b = true ) IUTEST_EXPECT_TRUE(b) << b; if( bool b = true ) IUTEST_INFORM_TRUE(b) << b; if( bool b = true ) IUTEST_ASSUME_TRUE(b) << b; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicTrue) { if( bool b = true ) IUTEST_ASSERT_TRUE(T<0, 0>::call(b)) << b; if( bool b = true ) IUTEST_EXPECT_TRUE(T<0, 0>::call(b)) << b; if( bool b = true ) IUTEST_INFORM_TRUE(T<0, 0>::call(b)) << b; if( bool b = true ) IUTEST_ASSUME_TRUE(T<0, 0>::call(b)) << b; } #endif IUTEST(SyntaxTest, False) { if( bool b = false ) IUTEST_ASSERT_FALSE(b) << b; if( bool b = false ) IUTEST_EXPECT_FALSE(b) << b; if( bool b = false ) IUTEST_INFORM_FALSE(b) << b; if( bool b = false ) IUTEST_ASSUME_FALSE(b) << b; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicFalse) { if( bool b = false ) IUTEST_ASSERT_FALSE(T<0, 0>::call(b)) << b; if( bool b = false ) IUTEST_EXPECT_FALSE(T<0, 0>::call(b)) << b; if( bool b = false ) IUTEST_INFORM_FALSE(T<0, 0>::call(b)) << b; if( bool b = false ) IUTEST_ASSUME_FALSE(T<0, 0>::call(b)) << b; } #endif IUTEST(SyntaxTest, EQ) { if( int x = 1 ) IUTEST_ASSERT_EQ(1, x) << x; if( int x = 1 ) IUTEST_EXPECT_EQ(1, x) << x; if( int x = 1 ) IUTEST_INFORM_EQ(1, x) << x; if( int x = 1 ) IUTEST_ASSUME_EQ(1, x) << x; } IUTEST(SyntaxTest, EQ_COLLECTIONS) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 2, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_EQ_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; } IUTEST(SyntaxTest, NE_COLLECTIONS) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 5, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_NE_COLLECTIONS(a, a+(sizeof(a)/sizeof(a[0])), b, b+(sizeof(b)/sizeof(b[0]))) << size; } IUTEST(SyntaxTest, EQ_RANGE) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 2, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_EQ_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_EQ_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_EQ_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_EQ_RANGE(a, b) << size; } IUTEST(SyntaxTest, NE_RANGE) { int a[] = { 0, 1, 2, 3, 4 }; int b[] = { 0, 1, 0, 3, 4 }; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSERT_NE_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_EXPECT_NE_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_INFORM_NE_RANGE(a, b) << size; if( int size = (sizeof(a)/sizeof(a[0])) ) IUTEST_ASSUME_NE_RANGE(a, b) << size; } IUTEST(SyntaxTest, NE) { if( int x = 1 ) IUTEST_ASSERT_NE(0, x) << x; if( int x = 1 ) IUTEST_EXPECT_NE(0, x) << x; if( int x = 1 ) IUTEST_INFORM_NE(0, x) << x; if( int x = 1 ) IUTEST_ASSUME_NE(0, x) << x; } IUTEST(SyntaxTest, LT) { if( int x = 1 ) IUTEST_ASSERT_LT(0, x) << x; if( int x = 1 ) IUTEST_EXPECT_LT(0, x) << x; if( int x = 1 ) IUTEST_INFORM_LT(0, x) << x; if( int x = 1 ) IUTEST_ASSUME_LT(0, x) << x; } IUTEST(SyntaxTest, LE) { if( int x = 1 ) IUTEST_ASSERT_LE(1, x) << x; if( int x = 1 ) IUTEST_EXPECT_LE(1, x) << x; if( int x = 1 ) IUTEST_INFORM_LE(1, x) << x; if( int x = 1 ) IUTEST_ASSUME_LE(1, x) << x; } IUTEST(SyntaxTest, GT) { if( int x = 1 ) IUTEST_ASSERT_GT(2, x) << x; if( int x = 1 ) IUTEST_EXPECT_GT(2, x) << x; if( int x = 1 ) IUTEST_INFORM_GT(2, x) << x; if( int x = 1 ) IUTEST_ASSUME_GT(2, x) << x; } IUTEST(SyntaxTest, GE) { if( int x = 1 ) IUTEST_ASSERT_GE(1, x) << x; if( int x = 1 ) IUTEST_EXPECT_GE(1, x) << x; if( int x = 1 ) IUTEST_INFORM_GE(1, x) << x; if( int x = 1 ) IUTEST_ASSUME_GE(1, x) << x; } IUTEST(SyntaxTest, Float) { if( float f = 1.0f ) IUTEST_ASSERT_FLOAT_EQ(1.0f, f) << f; if( float f = 1.0f ) IUTEST_EXPECT_FLOAT_EQ(1.0f, f) << f; if( float f = 1.0f ) IUTEST_INFORM_FLOAT_EQ(1.0f, f) << f; if( float f = 1.0f ) IUTEST_ASSUME_FLOAT_EQ(1.0f, f) << f; } IUTEST(SyntaxTest, Double) { if( double d = 1.0 ) IUTEST_ASSERT_DOUBLE_EQ(1.0, d) << d; if( double d = 1.0 ) IUTEST_EXPECT_DOUBLE_EQ(1.0, d) << d; if( double d = 1.0 ) IUTEST_INFORM_DOUBLE_EQ(1.0, d) << d; if( double d = 1.0 ) IUTEST_ASSUME_DOUBLE_EQ(1.0, d) << d; } #if IUTEST_HAS_LONG_DOUBLE IUTEST(SyntaxTest, LongDouble) { if( long double d = 1.0l ) IUTEST_ASSERT_LONG_DOUBLE_EQ(1.0l, d) << d; if( long double d = 1.0l ) IUTEST_EXPECT_LONG_DOUBLE_EQ(1.0l, d) << d; if( long double d = 1.0l ) IUTEST_INFORM_LONG_DOUBLE_EQ(1.0l, d) << d; if( long double d = 1.0l ) IUTEST_ASSUME_LONG_DOUBLE_EQ(1.0l, d) << d; } #endif IUTEST(SyntaxTest, Complex) { ::std::complex<float> c(1.0f, 1.0f); if( float d = 1.0 ) IUTEST_ASSERT_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; if( float d = 1.0 ) IUTEST_EXPECT_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; if( float d = 1.0 ) IUTEST_INFORM_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; if( float d = 1.0 ) IUTEST_ASSUME_COMPLEX_EQ(::std::complex<float>(d, d), c) << c; } IUTEST(SyntaxTest, Near) { if( int x = 1 ) IUTEST_ASSERT_NEAR(0, x, 2) << x; if( int x = 1 ) IUTEST_EXPECT_NEAR(0, x, 2) << x; if( int x = 1 ) IUTEST_INFORM_NEAR(0, x, 2) << x; if( int x = 1 ) IUTEST_ASSUME_NEAR(0, x, 2) << x; } IUTEST(SyntaxTest, AlmostEq) { if( int x = 1 ) IUTEST_ASSERT_ALMOST_EQ(1, x); if( int x = 1 ) IUTEST_EXPECT_ALMOST_EQ(1, x); if( int x = 1 ) IUTEST_INFORM_ALMOST_EQ(1, x); if( int x = 1 ) IUTEST_ASSUME_ALMOST_EQ(1, x); } IUTEST(SyntaxTest, AlmostFloatEq) { if( float x = 1.0f ) IUTEST_ASSERT_ALMOST_EQ(1.0f, x); if( float x = 1.0f ) IUTEST_EXPECT_ALMOST_EQ(1.0f, x); if( float x = 1.0f ) IUTEST_INFORM_ALMOST_EQ(1.0f, x); if( float x = 1.0f ) IUTEST_ASSUME_ALMOST_EQ(1.0f, x); } IUTEST(SyntaxTest, AlmostDoubleEq) { if( double x = 1.0 ) IUTEST_ASSERT_ALMOST_EQ(1.0, x); if( double x = 1.0 ) IUTEST_EXPECT_ALMOST_EQ(1.0, x); if( double x = 1.0 ) IUTEST_INFORM_ALMOST_EQ(1.0, x); if( double x = 1.0 ) IUTEST_ASSUME_ALMOST_EQ(1.0, x); } #if IUTEST_HAS_LONG_DOUBLE IUTEST(SyntaxTest, AlmostLongDoubleEq) { if( long double x = 1.0l ) IUTEST_ASSERT_ALMOST_EQ(1.0l, x); if( long double x = 1.0l ) IUTEST_EXPECT_ALMOST_EQ(1.0l, x); if( long double x = 1.0l ) IUTEST_INFORM_ALMOST_EQ(1.0l, x); if( long double x = 1.0l ) IUTEST_ASSUME_ALMOST_EQ(1.0l, x); } #endif IUTEST(SyntaxTest, AlmostComplexEq) { ::std::complex<double> c(1.0, 0.0); if( double x = 1.0 ) IUTEST_ASSERT_ALMOST_EQ(c, x); if( double x = 1.0 ) IUTEST_EXPECT_ALMOST_EQ(x, c); if( double x = 1.0 ) IUTEST_INFORM_ALMOST_EQ(::std::complex<double>(x, x), c); if( double x = 1.0 ) IUTEST_ASSUME_ALMOST_EQ(c, ::std::complex<double>(x, x)); } IUTEST(SyntaxTest, Null) { int* p = NULL; if( int x = 1 ) IUTEST_ASSERT_NULL(p) << x; if( int x = 1 ) IUTEST_EXPECT_NULL(p) << x; if( int x = 1 ) IUTEST_INFORM_NULL(p) << x; if( int x = 1 ) IUTEST_ASSUME_NULL(p) << x; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicNull) { int* p = NULL; if( int x = 1 ) IUTEST_ASSERT_NULL(T<0, 0>::call(p)) << x; if( int x = 1 ) IUTEST_EXPECT_NULL(T<0, 0>::call(p)) << x; if( int x = 1 ) IUTEST_INFORM_NULL(T<0, 0>::call(p)) << x; if( int x = 1 ) IUTEST_ASSUME_NULL(T<0, 0>::call(p)) << x; } #endif IUTEST(SyntaxTest, NotNull) { if( void* p = this ) IUTEST_ASSERT_NOTNULL(p) << p; if( void* p = this ) IUTEST_EXPECT_NOTNULL(p) << p; if( void* p = this ) IUTEST_INFORM_NOTNULL(p) << p; if( void* p = this ) IUTEST_ASSUME_NOTNULL(p) << p; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicNotNull) { if( void* p = this ) IUTEST_ASSERT_NOTNULL(T<0, 0>::call(p)) << p; if( void* p = this ) IUTEST_EXPECT_NOTNULL(T<0, 0>::call(p)) << p; if( void* p = this ) IUTEST_INFORM_NOTNULL(T<0, 0>::call(p)) << p; if( void* p = this ) IUTEST_ASSUME_NOTNULL(T<0, 0>::call(p)) << p; } #endif IUTEST(SyntaxTest, Same) { int v = 0; if( int* p = &v ) IUTEST_ASSERT_SAME(v, *p) << p; if( int* p = &v ) IUTEST_EXPECT_SAME(v, *p) << p; if( int* p = &v ) IUTEST_INFORM_SAME(v, *p) << p; if( int* p = &v ) IUTEST_ASSUME_SAME(v, *p) << p; } IUTEST(SyntaxTest, StrEq) { const char test[] = "test"; if( const char* p = "test" ) IUTEST_ASSERT_STREQ(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STREQ(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STREQ(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STREQ(p, test) << p; } IUTEST(SyntaxTest, StrNe) { const char test[] = "Test"; if( const char* p = "test" ) IUTEST_ASSERT_STRNE(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STRNE(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STRNE(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STRNE(p, test) << p; } IUTEST(SyntaxTest, StrCaseEq) { const char test[] = "Test"; if( const char* p = "test" ) IUTEST_ASSERT_STRCASEEQ(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STRCASEEQ(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STRCASEEQ(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STRCASEEQ(p, test) << p; } IUTEST(SyntaxTest, StrCaseNe) { const char test[] = "host"; if( const char* p = "test" ) IUTEST_ASSERT_STRCASENE(p, test) << p; if( const char* p = "test" ) IUTEST_EXPECT_STRCASENE(p, test) << p; if( const char* p = "test" ) IUTEST_INFORM_STRCASENE(p, test) << p; if( const char* p = "test" ) IUTEST_ASSUME_STRCASENE(p, test) << p; } IUTEST(SyntaxTest, StrLn) { const char test[] = "test"; if( int len = 4 ) IUTEST_ASSERT_STRLNEQ(len, test) << len; if( int len = 4 ) IUTEST_EXPECT_STRLNEQ(len, test) << len; if( int len = 4 ) IUTEST_INFORM_STRLNEQ(len, test) << len; if( int len = 4 ) IUTEST_ASSUME_STRLNEQ(len, test) << len; } IUTEST(SyntaxTest, Nan) { float fnan = ::std::numeric_limits<float>::quiet_NaN(); double dnan = ::std::numeric_limits<double>::quiet_NaN(); if( fnan ) IUTEST_ASSERT_NAN(fnan) << fnan; if( fnan ) IUTEST_EXPECT_NAN(fnan) << fnan; if( dnan ) IUTEST_INFORM_NAN(dnan) << dnan; if( dnan ) IUTEST_ASSUME_NAN(dnan) << dnan; } #if defined(IUTEST_OS_WINDOWS) IUTEST(SyntaxTest, HResultSucceeded) { if( int x=1 ) IUTEST_ASSERT_HRESULT_SUCCEEDED(0) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_SUCCEEDED(0) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_SUCCEEDED(0) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_SUCCEEDED(0) << x; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicHResultSucceeded) { if( int x=1 ) IUTEST_ASSERT_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_SUCCEEDED(T<0, 0>::call(0)) << x; } #endif IUTEST(SyntaxTest, HResultFailed) { if( int x=1 ) IUTEST_ASSERT_HRESULT_FAILED(-1) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_FAILED(-1) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_FAILED(-1) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_FAILED(-1) << x; } #ifndef IUTEST_NO_VARIADIC_MACROS IUTEST(SyntaxTest, VariadicHResultFailed) { if( int x=1 ) IUTEST_ASSERT_HRESULT_FAILED(T<0, 0>::call(-1)) << x; if( int x=1 ) IUTEST_EXPECT_HRESULT_FAILED(T<0, 0>::call(-1)) << x; if( int x=1 ) IUTEST_INFORM_HRESULT_FAILED(T<0, 0>::call(-1)) << x; if( int x=1 ) IUTEST_ASSUME_HRESULT_FAILED(T<0, 0>::call(-1)) << x; } #endif #endif IUTEST(SyntaxTest, Skip) { if( int x = 1 ) IUTEST_SKIP() << x; } IUTEST(SyntaxTest, Pred1) { if( int x=1 ) IUTEST_ASSERT_PRED1(IsOdd, x) << x; if( int x=1 ) IUTEST_EXPECT_PRED1(IsOdd, x) << x; if( int x=1 ) IUTEST_INFORM_PRED1(IsOdd, x) << x; if( int x=1 ) IUTEST_ASSUME_PRED1(IsOdd, x) << x; } IUTEST(SyntaxTest, Pred2) { if( int x=1 ) IUTEST_ASSERT_PRED2(IsGreater, 3, x) << x; if( int x=1 ) IUTEST_EXPECT_PRED2(IsGreater, 3, x) << x; if( int x=1 ) IUTEST_INFORM_PRED2(IsGreater, 3, x) << x; if( int x=1 ) IUTEST_ASSUME_PRED2(IsGreater, 3, x) << x; } IUTEST(SyntaxTest, Pred3) { if( int x=1 ) IUTEST_ASSERT_PRED3(PredTest3, 0, x, 2) << x; if( int x=1 ) IUTEST_EXPECT_PRED3(PredTest3, 0, x, 2) << x; if( int x=1 ) IUTEST_INFORM_PRED3(PredTest3, 0, x, 2) << x; if( int x=1 ) IUTEST_ASSUME_PRED3(PredTest3, 0, x, 2) << x; } IUTEST(SyntaxTest, Pred4) { if( int x=1 ) IUTEST_ASSERT_PRED4(PredTest4, 0, x, 2, 3) << x; if( int x=1 ) IUTEST_EXPECT_PRED4(PredTest4, 0, x, 2, 3) << x; if( int x=1 ) IUTEST_INFORM_PRED4(PredTest4, 0, x, 2, 3) << x; if( int x=1 ) IUTEST_ASSUME_PRED4(PredTest4, 0, x, 2, 3) << x; } IUTEST(SyntaxTest, Pred5) { if( int x=1 ) IUTEST_ASSERT_PRED5(PredTest5, 0, x, 2, 3, 4) << x; if( int x=1 ) IUTEST_EXPECT_PRED5(PredTest5, 0, x, 2, 3, 4) << x; if( int x=1 ) IUTEST_INFORM_PRED5(PredTest5, 0, x, 2, 3, 4) << x; if( int x=1 ) IUTEST_ASSUME_PRED5(PredTest5, 0, x, 2, 3, 4) << x; } #if IUTEST_HAS_MATCHERS IUTEST(SyntaxTest, That) { if( int x=1 ) IUTEST_ASSERT_THAT(x, ::iutest::Eq(1)) << x; if( int x=1 ) IUTEST_EXPECT_THAT(x, ::iutest::Le(1)) << x; if( int x=1 ) IUTEST_INFORM_THAT(x, ::iutest::Ge(1)) << x; if( int x=1 ) IUTEST_ASSUME_THAT(x, ::iutest::Ne(0)) << x; } struct X { int a, b; X(int _a, int _b) : a(_a), b(_b) {} int GetA() const { return a; } }; int X2(int value) { return value*2; } IUTEST(SyntaxTest, Matcher) { ::std::vector<int> v; v.push_back(0); v.push_back(1); v.push_back(2); int a[3] = { 0, 1, 2 }; int b[4] = { 0, 1, 2, 3 }; X x(0, 1); int z=1; IUTEST_EXPECT_THAT(a, ::iutest::Contains(0)); IUTEST_EXPECT_THAT(a, ::iutest::Contains(::iutest::Lt(10))); #if IUTEST_HAS_MATCHER_EACH IUTEST_EXPECT_THAT(a, ::iutest::Each(::iutest::Le(10))); IUTEST_EXPECT_THAT(a, ::iutest::Each(::iutest::_)); IUTEST_EXPECT_THAT(a, ::iutest::Each(::iutest::A<int>())); #endif IUTEST_EXPECT_THAT(&x, ::iutest::Field(&X::a, 0)); IUTEST_EXPECT_THAT(x, ::iutest::Field(&X::a, 0)); IUTEST_EXPECT_THAT(&x, ::iutest::Property(&X::GetA, 0)); IUTEST_EXPECT_THAT(x, ::iutest::Property(&X::GetA, 0)); IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray(a)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArray(a)); #if !defined(IUTEST_USE_GMOCK) || (GMOCK_VER >= 0x01070000) IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray(v)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArray(v)); #endif IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray(b, 3)); #if IUTEST_HAS_INITIALIZER_LIST IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArray({0, 1, 2})); #endif IUTEST_EXPECT_THAT(1, ::iutest::ResultOf(X2, 2)); IUTEST_EXPECT_THAT(1, ::iutest::ResultOf(X2, ::iutest::Gt(1))); IUTEST_EXPECT_THAT(z, ::iutest::TypedEq<int>(1.0)); } #if IUTEST_HAS_MATCHER_ELEMENTSAREARRAYFORWARD IUTEST(SyntaxTest, ElementsAreArrayForward) { ::std::vector<int> v; v.push_back(0); v.push_back(1); v.push_back(2); int a[3] = { 0, 1, 2 }; int b[4] = { 0, 1, 2, 3 }; IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward(a)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArrayForward(a)); IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward(v)); IUTEST_EXPECT_THAT(v, ::iutest::ElementsAreArrayForward(v)); IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward(b, 1)); #if IUTEST_HAS_INITIALIZER_LIST IUTEST_EXPECT_THAT(a, ::iutest::ElementsAreArrayForward({0, 1, 2})); #endif } #endif #if IUTEST_HAS_MATCHER_REGEX IUTEST(SyntaxTest, MatcherRegex) { ::std::string s = "greeeeeen"; IUTEST_EXPECT_THAT(s, ::iutest::MatchesRegex("gre+n")); IUTEST_EXPECT_THAT("hogeeeeeet", ::iutest::MatchesRegex("hoge+t")); IUTEST_EXPECT_THAT(s, ::iutest::ContainsRegex("e")); IUTEST_EXPECT_THAT("hogeeeeeet", ::iutest::ContainsRegex("hoge+")); } #endif IUTEST(SyntaxTest, MatcherPredicate) { IUTEST_EXPECT_TRUE(::iutest::Value(2, 2)); IUTEST_EXPECT_TRUE(::iutest::Value(2, ::iutest::Eq(2))); } #if IUTEST_HAS_MATCHER_ALLOF_AND_ANYOF IUTEST(SyntaxTest, AllOf) { #if IUTEST_HAS_MATCHER_VARIADIC IUTEST_EXPECT_THAT("9347812650", ::iutest::AllOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") , ::iutest::HasSubstr("0") )); #else IUTEST_EXPECT_THAT("9347812650", ::iutest::AllOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") )); #endif } IUTEST(SyntaxTest, AnyOf) { #if IUTEST_HAS_MATCHER_VARIADIC IUTEST_EXPECT_THAT("hoge7", ::iutest::AnyOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") , ::iutest::HasSubstr("0") )); #else IUTEST_EXPECT_THAT("hoge7", ::iutest::AnyOf( ::iutest::HasSubstr("0") , ::iutest::HasSubstr("1") , ::iutest::HasSubstr("2") , ::iutest::HasSubstr("3") , ::iutest::HasSubstr("4") , ::iutest::HasSubstr("5") , ::iutest::HasSubstr("6") , ::iutest::HasSubstr("7") , ::iutest::HasSubstr("8") , ::iutest::HasSubstr("9") )); #endif } #endif #endif #if !defined(IUTEST_USE_GTEST) #if !defined(IUTEST_NO_VARIADIC_MACROS) #if IUTEST_HAS_VARIADIC_TEMPLATES IUTEST(SyntaxTest, VariadicPred) { if( int x=1 ) IUTEST_ASSERT_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_EXPECT_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_INFORM_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_ASSUME_PRED(PredTest6, 0, x, 2, 3, 4, 5) << x; } #endif IUTEST(SyntaxTest, VariadicPredFormat) { if( int x=1 ) IUTEST_ASSERT_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_EXPECT_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_INFORM_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; if( int x=1 ) IUTEST_ASSUME_PRED_FORMAT(Pred6Formater, 0, x, 2, 3, 4, 5) << x; } #endif #endif #if IUTEST_HAS_EXCEPTIONS static void ExceptionFunction(int i) { switch( i ) { case 0: return; case 1: throw 2; case 2: throw ::std::bad_exception(); case 3: throw "error"; case 4: throw ::std::string("error"); case 5: throw 0.1f; default: break; } } IUTEST(SyntaxTest, ExceptionThrow) { if( int x = 2 ) IUTEST_ASSERT_THROW(ExceptionFunction(x), ::std::bad_exception) << x; if( int x = 2 ) IUTEST_EXPECT_THROW(ExceptionFunction(x), ::std::bad_exception) << x; if( int x = 2 ) IUTEST_INFORM_THROW(ExceptionFunction(x), ::std::bad_exception) << x; if( int x = 2 ) IUTEST_ASSUME_THROW(ExceptionFunction(x), ::std::bad_exception) << x; } IUTEST(SyntaxTest, ExceptionAnyThrow) { if( int x = 1 ) IUTEST_ASSERT_ANY_THROW(throw ::std::bad_exception()) << x; if( int x = 1 ) IUTEST_EXPECT_ANY_THROW(throw ::std::bad_exception()) << x; if( int x = 1 ) IUTEST_INFORM_ANY_THROW(throw ::std::bad_exception()) << x; if( int x = 1 ) IUTEST_ASSUME_ANY_THROW(throw ::std::bad_exception()) << x; } IUTEST(SyntaxTest, ExceptionNoThrow) { if( int x = 1 ) IUTEST_ASSERT_NO_THROW((void)x) << x; if( int x = 1 ) IUTEST_EXPECT_NO_THROW((void)x) << x; if( int x = 1 ) IUTEST_INFORM_NO_THROW((void)x) << x; if( int x = 1 ) IUTEST_ASSUME_NO_THROW((void)x) << x; } IUTEST(SyntaxTest, ExceptionValueEQ) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_EQ(throw 1, int, x) << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_EQ(throw 1, int, x) << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_EQ(throw 1, int, x) << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_EQ(throw 1, int, x) << x; } IUTEST(SyntaxTest, ExceptionValueNE) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_NE(throw 2, int, x) << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_NE(throw 2, int, x) << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_NE(throw 2, int, x) << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_NE(throw 2, int, x) << x; } IUTEST(SyntaxTest, ExceptionValueSTREQ) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_STREQ(throw "error", const char *, "error") << x; } IUTEST(SyntaxTest, ExceptionValueSTRCASEEQ) { if( int x = 1 ) IUTEST_ASSERT_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; if( int x = 1 ) IUTEST_EXPECT_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; if( int x = 1 ) IUTEST_INFORM_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; if( int x = 1 ) IUTEST_ASSUME_THROW_VALUE_STRCASEEQ(throw "error", const char *, "Error") << x; } IUTEST(SyntaxTest, ExceptionValueFormat) { if( float x = 0.1f ) IUTEST_ASSERT_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; if( float x = 0.1f ) IUTEST_EXPECT_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; if( float x = 0.1f ) IUTEST_INFORM_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; if( float x = 0.1f ) IUTEST_ASSUME_THROW_PRED_FORMAT2(::iutest::internal::CmpHelperFloatingPointEQ<float> , ExceptionFunction(5), float, x) << x; } class exception_test { public: explicit exception_test(const ::std::vector<int>&) { IUTEST_SUPPRESS_UNREACHABLE_CODE_WARNING(throw ::std::exception()); } }; IUTEST(SyntaxTest, ExceptionVectorConstructor) { ::std::vector<int> a; IUTEST_ASSERT_THROW(exception_test(a), ::std::exception); } #endif #if !defined(IUTEST_USE_GTEST) && defined(__WANDBOX__) IUTEST(SyntaxTest, ShowFeature) { ::iutest::detail::iuOptionMessage::ShowFeature(); } IUTEST(SyntaxTest, ShowSpec) { ::iutest::detail::iuOptionMessage::ShowSpec(); } #endif #if IUTEST_HAS_TYPED_TEST template<typename T> class TypedPrintToTest : public ::iutest::Test {}; typedef ::iutest::Types<char, unsigned char, short, unsigned short, int, unsigned int, long, unsigned long, int*> PrintStringTestTypes; IUTEST_TYPED_TEST_SUITE(TypedPrintToTest, PrintStringTestTypes); IUTEST_TYPED_TEST(TypedPrintToTest, Print) { TypeParam a = 0; TypeParam& b = a; const TypeParam c = a; const volatile TypeParam d = a; IUTEST_SUCCEED() << ::iutest::PrintToString(a); IUTEST_SUCCEED() << ::iutest::PrintToString(b); IUTEST_SUCCEED() << ::iutest::PrintToString(c); IUTEST_SUCCEED() << ::iutest::PrintToString(d); } #endif IUTEST(PrintToTest, RawArray) { { unsigned char a[3] = {0, 1, 2}; const unsigned char b[3] = {0, 1, 2}; const volatile unsigned char c[3] = {0, 1, 2}; volatile unsigned char d[3] = {0, 1, 2}; IUTEST_SUCCEED() << ::iutest::PrintToString(a); IUTEST_SUCCEED() << ::iutest::PrintToString(b); IUTEST_SUCCEED() << ::iutest::PrintToString(c); IUTEST_SUCCEED() << ::iutest::PrintToString(d); } { char a[3] = {0, 1, 2}; const char b[3] = {0, 1, 2}; const volatile char c[3] = {0, 1, 2}; volatile char d[3] = {0, 1, 2}; IUTEST_SUCCEED() << ::iutest::PrintToString(a); IUTEST_SUCCEED() << ::iutest::PrintToString(b); IUTEST_SUCCEED() << ::iutest::PrintToString(c); IUTEST_SUCCEED() << ::iutest::PrintToString(d); } } #if IUTEST_HAS_IOMANIP IUTEST(PrintToTest, Iomanip) { IUTEST_SUCCEED() << ::std::endl; IUTEST_SUCCEED() << ::std::ends; } #endif #if IUTEST_HAS_CHAR16_T IUTEST(PrintToTest, U16String) { IUTEST_SUCCEED() << u"test"; } #if IUTEST_HAS_CXX_HDR_STRING_VIEW IUTEST(PrintToTest, U16StringStringView) { ::std::u16string_view view = u"Hello"; IUTEST_SUCCEED() << view; } #endif #endif #if IUTEST_HAS_CHAR32_T IUTEST(PrintToTest, U32String) { IUTEST_SUCCEED() << U"TEST"; } #if IUTEST_HAS_CXX_HDR_STRING_VIEW IUTEST(PrintToTest, U32StringStringView) { ::std::u32string_view view = U"Hello"; IUTEST_SUCCEED() << view; } #endif #endif #if defined(__WANDBOX__) #if IUTEST_HAS_PARAM_TEST class ValuesTest : public ::iutest::TestWithParam<int> {}; IUTEST_P(ValuesTest, Test) { } IUTEST_INSTANTIATE_TEST_SUITE_P( X1, ValuesTest, ::iutest::Values(1) ); IUTEST_INSTANTIATE_TEST_SUITE_P( X2, ValuesTest, ::iutest::Values(1, 2) ); #if IUTEST_HAS_VARIADIC_VALUES IUTEST_INSTANTIATE_TEST_SUITE_P( X51, ValuesTest , ::iutest::Values( IUTEST_PP_ENUM_PARAMS(51, IUTEST_PP_EMPTY()) ) ); #endif #endif #endif IUTEST_PRAGMA_WARN_POP() } // end of namespace syntax_tests
srz-zumix/iutest
test/syntax_tests.cpp
C++
bsd-3-clause
29,693
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/services/gcm/gcm_profile_service_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/channel_info.h" #include "chrome/test/base/testing_profile.h" #include "components/gcm_driver/gcm_profile_service.h" #if defined(OS_CHROMEOS) #include "chromeos/dbus/dbus_thread_manager.h" #endif #include "components/gcm_driver/fake_gcm_app_handler.h" #include "components/gcm_driver/fake_gcm_client.h" #include "components/gcm_driver/fake_gcm_client_factory.h" #include "components/gcm_driver/gcm_client.h" #include "components/gcm_driver/gcm_client_factory.h" #include "components/gcm_driver/gcm_driver.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace gcm { namespace { const char kTestAppID[] = "TestApp"; const char kUserID[] = "user"; std::unique_ptr<KeyedService> BuildGCMProfileService( content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); base::SequencedWorkerPool* worker_pool = content::BrowserThread::GetBlockingPool(); scoped_refptr<base::SequencedTaskRunner> blocking_task_runner( worker_pool->GetSequencedTaskRunnerWithShutdownBehavior( worker_pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)); return base::WrapUnique(new gcm::GCMProfileService( profile->GetPrefs(), profile->GetPath(), profile->GetRequestContext(), chrome::GetChannel(), std::unique_ptr<ProfileIdentityProvider>(new ProfileIdentityProvider( SigninManagerFactory::GetForProfile(profile), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), LoginUIServiceFactory::GetShowLoginPopupCallbackForProfile(profile))), std::unique_ptr<gcm::GCMClientFactory>(new gcm::FakeGCMClientFactory( content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO))), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::IO), blocking_task_runner)); } } // namespace class GCMProfileServiceTest : public testing::Test { protected: GCMProfileServiceTest(); ~GCMProfileServiceTest() override; // testing::Test: void SetUp() override; void TearDown() override; FakeGCMClient* GetGCMClient() const; void CreateGCMProfileService(); void RegisterAndWaitForCompletion(const std::vector<std::string>& sender_ids); void UnregisterAndWaitForCompletion(); void SendAndWaitForCompletion(const OutgoingMessage& message); void RegisterCompleted(const base::Closure& callback, const std::string& registration_id, GCMClient::Result result); void UnregisterCompleted(const base::Closure& callback, GCMClient::Result result); void SendCompleted(const base::Closure& callback, const std::string& message_id, GCMClient::Result result); GCMDriver* driver() const { return gcm_profile_service_->driver(); } std::string registration_id() const { return registration_id_; } GCMClient::Result registration_result() const { return registration_result_; } GCMClient::Result unregistration_result() const { return unregistration_result_; } std::string send_message_id() const { return send_message_id_; } GCMClient::Result send_result() const { return send_result_; } private: content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<TestingProfile> profile_; GCMProfileService* gcm_profile_service_; std::unique_ptr<FakeGCMAppHandler> gcm_app_handler_; std::string registration_id_; GCMClient::Result registration_result_; GCMClient::Result unregistration_result_; std::string send_message_id_; GCMClient::Result send_result_; DISALLOW_COPY_AND_ASSIGN(GCMProfileServiceTest); }; GCMProfileServiceTest::GCMProfileServiceTest() : gcm_profile_service_(NULL), gcm_app_handler_(new FakeGCMAppHandler), registration_result_(GCMClient::UNKNOWN_ERROR), send_result_(GCMClient::UNKNOWN_ERROR) { } GCMProfileServiceTest::~GCMProfileServiceTest() { } FakeGCMClient* GCMProfileServiceTest::GetGCMClient() const { return static_cast<FakeGCMClient*>( gcm_profile_service_->driver()->GetGCMClientForTesting()); } void GCMProfileServiceTest::SetUp() { #if defined(OS_CHROMEOS) // Create a DBus thread manager setter for its side effect. // Ignore the return value. chromeos::DBusThreadManager::GetSetterForTesting(); #endif TestingProfile::Builder builder; profile_ = builder.Build(); } void GCMProfileServiceTest::TearDown() { gcm_profile_service_->driver()->RemoveAppHandler(kTestAppID); } void GCMProfileServiceTest::CreateGCMProfileService() { gcm_profile_service_ = static_cast<GCMProfileService*>( GCMProfileServiceFactory::GetInstance()->SetTestingFactoryAndUse( profile_.get(), &BuildGCMProfileService)); gcm_profile_service_->driver()->AddAppHandler( kTestAppID, gcm_app_handler_.get()); } void GCMProfileServiceTest::RegisterAndWaitForCompletion( const std::vector<std::string>& sender_ids) { base::RunLoop run_loop; gcm_profile_service_->driver()->Register( kTestAppID, sender_ids, base::Bind(&GCMProfileServiceTest::RegisterCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } void GCMProfileServiceTest::UnregisterAndWaitForCompletion() { base::RunLoop run_loop; gcm_profile_service_->driver()->Unregister( kTestAppID, base::Bind(&GCMProfileServiceTest::UnregisterCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } void GCMProfileServiceTest::SendAndWaitForCompletion( const OutgoingMessage& message) { base::RunLoop run_loop; gcm_profile_service_->driver()->Send( kTestAppID, kUserID, message, base::Bind(&GCMProfileServiceTest::SendCompleted, base::Unretained(this), run_loop.QuitClosure())); run_loop.Run(); } void GCMProfileServiceTest::RegisterCompleted( const base::Closure& callback, const std::string& registration_id, GCMClient::Result result) { registration_id_ = registration_id; registration_result_ = result; callback.Run(); } void GCMProfileServiceTest::UnregisterCompleted( const base::Closure& callback, GCMClient::Result result) { unregistration_result_ = result; callback.Run(); } void GCMProfileServiceTest::SendCompleted( const base::Closure& callback, const std::string& message_id, GCMClient::Result result) { send_message_id_ = message_id; send_result_ = result; callback.Run(); } TEST_F(GCMProfileServiceTest, RegisterAndUnregister) { CreateGCMProfileService(); std::vector<std::string> sender_ids; sender_ids.push_back("sender"); RegisterAndWaitForCompletion(sender_ids); std::string expected_registration_id = FakeGCMClient::GenerateGCMRegistrationID(sender_ids); EXPECT_EQ(expected_registration_id, registration_id()); EXPECT_EQ(GCMClient::SUCCESS, registration_result()); UnregisterAndWaitForCompletion(); EXPECT_EQ(GCMClient::SUCCESS, unregistration_result()); } TEST_F(GCMProfileServiceTest, Send) { CreateGCMProfileService(); OutgoingMessage message; message.id = "1"; message.data["key1"] = "value1"; SendAndWaitForCompletion(message); EXPECT_EQ(message.id, send_message_id()); EXPECT_EQ(GCMClient::SUCCESS, send_result()); } } // namespace gcm
danakj/chromium
chrome/browser/services/gcm/gcm_profile_service_unittest.cc
C++
bsd-3-clause
8,567
/** * @decription mock file config * * 该文件实现路由的配置,在没有test准备好的情况下可以直接走这个mock数据 * key: 为要匹配的路由 * value: 为对应的参数配置 * method: get或者post,router的方法 * filename: 对应的mock文件 */ module.exports = { '/api/realtime': { method: "post", filename: "realtime.js" } };
changfuguo/vuejs-boilerplate
server/config/route.js
JavaScript
bsd-3-clause
383
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill_assistant/browser/selector.h" #include "base/macros.h" #include "components/autofill_assistant/browser/service.pb.h" #include "testing/gmock/include/gmock/gmock.h" namespace autofill_assistant { namespace { TEST(SelectorTest, FromProto) { ElementReferenceProto proto; proto.add_selectors("a"); proto.add_selectors("b"); proto.set_inner_text_pattern("c"); proto.set_value_pattern("d"); proto.set_visibility_requirement(MUST_BE_VISIBLE); proto.set_pseudo_type(PseudoType::BEFORE); Selector selector(proto); EXPECT_THAT(selector.selectors, testing::ElementsAre("a", "b")); EXPECT_TRUE(selector.must_be_visible); EXPECT_EQ("c", selector.inner_text_pattern); EXPECT_EQ("d", selector.value_pattern); EXPECT_EQ(PseudoType::BEFORE, selector.pseudo_type); } TEST(SelectorTest, ToProto) { Selector selector; selector.selectors.emplace_back("a"); selector.selectors.emplace_back("b"); selector.inner_text_pattern = "c"; selector.value_pattern = "d"; selector.must_be_visible = true; selector.pseudo_type = PseudoType::BEFORE; ElementReferenceProto proto = selector.ToElementReferenceProto(); EXPECT_THAT(proto.selectors(), testing::ElementsAre("a", "b")); EXPECT_EQ("c", proto.inner_text_pattern()); EXPECT_EQ("d", proto.value_pattern()); EXPECT_EQ(MUST_BE_VISIBLE, proto.visibility_requirement()); EXPECT_EQ(PseudoType::BEFORE, proto.pseudo_type()); } TEST(SelectorTest, Comparison) { EXPECT_FALSE(Selector({"a"}) == Selector({"b"})); EXPECT_LT(Selector({"a"}), Selector({"b"})); EXPECT_TRUE(Selector({"a"}) == Selector({"a"})); EXPECT_FALSE(Selector({"a"}, PseudoType::BEFORE) == Selector({"a"}, PseudoType::AFTER)); EXPECT_LT(Selector({"a"}, PseudoType::BEFORE), Selector({"a"}, PseudoType::AFTER)); EXPECT_LT(Selector({"a"}, PseudoType::BEFORE), Selector({"b"})); EXPECT_TRUE(Selector({"a"}, PseudoType::BEFORE) == Selector({"a"}, PseudoType::BEFORE)); EXPECT_FALSE(Selector({"a"}) == Selector({"a"}).MustBeVisible()); EXPECT_LT(Selector({"a"}), Selector({"a"}).MustBeVisible()); EXPECT_TRUE(Selector({"a"}).MustBeVisible() == Selector({"a"}).MustBeVisible()); EXPECT_FALSE(Selector({"a"}).MatchingInnerText("a") == Selector({"a"}).MatchingInnerText("b")); EXPECT_LT(Selector({"a"}).MatchingInnerText("a"), Selector({"a"}).MatchingInnerText("b")); EXPECT_TRUE(Selector({"a"}).MatchingInnerText("a") == Selector({"a"}).MatchingInnerText("a")); EXPECT_FALSE(Selector({"a"}).MatchingValue("a") == Selector({"a"}).MatchingValue("b")); EXPECT_LT(Selector({"a"}).MatchingValue("a"), Selector({"a"}).MatchingValue("b")); EXPECT_TRUE(Selector({"a"}).MatchingValue("a") == Selector({"a"}).MatchingValue("a")); } } // namespace } // namespace autofill_assistant
endlessm/chromium-browser
components/autofill_assistant/browser/selector_unittest.cc
C++
bsd-3-clause
3,076
using System; using SevenDigital.Messaging.MessageReceiving; namespace SevenDigital.Messaging { /// <summary> /// A receiver node source that can produce competitive or co-operative consumers /// </summary> public interface IReceiver { /// <summary> /// Map handlers to a listener on a named endpoint. /// All other listeners on this endpoint will compete for messages /// (i.e. only one listener will get a given message) /// </summary> IReceiverNode TakeFrom(Endpoint endpoint, Action<IMessageBinding> bindings); /// <summary> /// Map handlers to a listener on a unique endpoint. /// All listeners mapped this way will receive all messages. /// </summary> IReceiverNode Listen(Action<IMessageBinding> bindings); } /// <summary> /// Interface for binding message types to handlers /// </summary> public interface IMessageBinding: IBinding { /// <summary> /// Handle a message type. Must complete With&lt;&gt;() to bind to a handler. /// </summary> IHandlerBinding<TMessage> Handle<TMessage>() where TMessage:IMessage; } /// <summary> /// Interface for binding message types to handlers /// </summary> public interface IHandlerBinding<TMessage>where TMessage:IMessage { /// <summary> /// Bind a handler to the selected message /// </summary> IMessageBinding With<THandler>() where THandler : IHandle<TMessage>; } /// <summary> /// Control methods for IReceiver. /// Seperated to simplify receiver interface. /// </summary> public interface IReceiverControl: IDisposable { /// <summary> /// Close all receiver nodes that have been created /// </summary> void Shutdown(); /// <summary> /// Unregister a node from the shutdown list /// </summary> void Remove(IReceiverNode node); /// <summary> /// Set maximum concurrent handlers per receiver node /// </summary> void SetConcurrentHandlers(int max); /// <summary> /// Set purging policy. If true, all waiting messages are DELETED when a handler is registered. /// This setting is meant for integration tests. /// Default is false. /// </summary> bool PurgeOnConnect { get; set; } /// <summary> /// Set cleanup policy. If true, all endpoints generated in integration mode /// are deleted when the receiver is disposed. /// Default is false. /// </summary> bool DeleteIntegrationEndpointsOnShutdown { get; set; } } }
i-e-b/SevenDigital.Messaging
src/SevenDigital.Messaging/IReceiver.cs
C#
bsd-3-clause
2,465
<?php namespace Base\Form\Hydrator; use Zend\Stdlib\Hydrator\HydratorInterface; use Base\Constants as C; class User implements HydratorInterface { public function extract($object) { $filter = function($value) { return !(($value === null) || ($value === '')); }; $data = array( 'user_id' => $object->getUserId(), 'username' => $object->getUserName(), 'email' => $object->getEmail(), 'display_name' => $object->getDisplayName(), 'password' => $object->getPassword(), 'state' => $object->getState(), ); $result = array_filter($data, $filter); // var_dump(__METHOD__, 'EXT_OBJ', $object, 'EXT_RES', $result); return $result; } public function hydrate(array $data, $object) { (!isset($data['user_id']) || $this->isEmpty($data['user_id'])) ? : $object->setUserId($data['user_id']); (!isset($data['username']) || $this->isEmpty($data['username'])) ? : $object->setUserName($data['username']); (!isset($data['email']) || $this->isEmpty($data['email'])) ? : $object->setEmail($data['email']); (!isset($data['display_name']) || $this->isEmpty($data['display_name'])) ? : $object->setDisplayName($data['display_name']); (!isset($data['password']) || $this->isEmpty($data['password'])) ? : $object->setPassword($data['password']); (!isset($data['state']) || $this->isEmpty($data['state'])) ? : $object->setState($data['state']); // var_dump(__METHOD__, 'HYD_SRCDATA', $data, 'HYD_RES', $object); return $object; } private function isEmpty($value) { return (($value === null) || ($value === '')); } }
fhsctv/ctv2base
module/Base/src/Base/Form/Hydrator/User.php
PHP
bsd-3-clause
1,947