max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
14,668
<filename>ios/web/public/test/fakes/fake_web_frame.h // Copyright 2018 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. #ifndef IOS_WEB_PUBLIC_TEST_FAKES_FAKE_WEB_FRAME_H_ #define IOS_WEB_PUBLIC_TEST_FAKES_FAKE_WEB_FRAME_H_ #include <memory> #include <vector> #include "base/callback_forward.h" #include "ios/web/public/js_messaging/web_frame.h" namespace web { // Frame id constants which can be used to initialize FakeWebFrame. // Frame ids are base16 string of 128 bit numbers. extern const char kMainFakeFrameId[]; extern const char kInvalidFrameId[]; extern const char kChildFakeFrameId[]; extern const char kChildFakeFrameId2[]; // A fake web frame to use for testing. class FakeWebFrame : public WebFrame { public: // Creates a web frame. |frame_id| must be a string representing a valid // hexadecimal number. static std::unique_ptr<FakeWebFrame> Create(const std::string& frame_id, bool is_main_frame, GURL security_origin); // Creates a web frame representing the main frame with a frame id of // |kMainFakeFrameId|. static std::unique_ptr<FakeWebFrame> CreateMainWebFrame(GURL security_origin); // Creates a web frame representing the main frame with a frame id of // |kChildFakeFrameId|. static std::unique_ptr<FakeWebFrame> CreateChildWebFrame( GURL security_origin); // Returns the most recent JavaScript handler call made to this frame. virtual std::string GetLastJavaScriptCall() const = 0; // Returns |javascript_calls|. Use LastJavaScriptCall() if possible. virtual const std::vector<std::string>& GetJavaScriptCallHistory() = 0; // Sets the browser state associated with this frame. virtual void set_browser_state(BrowserState* browser_state) = 0; // Sets |js_result| that will be passed into callback for |name| function // call. The same result will be pass regardless of call arguments. // NOTE: The caller is responsible for keeping |js_result| alive for as // long as this instance lives. virtual void AddJsResultForFunctionCall(base::Value* js_result, const std::string& function_name) = 0; virtual void set_force_timeout(bool force_timeout) = 0; // Sets return value |can_call_function_| of CanCallJavaScriptFunction(), // which defaults to true. virtual void set_can_call_function(bool can_call_function) = 0; // Sets a callback to be called at the start of |CallJavaScriptFunction()| if // |CanCallJavaScriptFunction()| returns true. virtual void set_call_java_script_function_callback( base::RepeatingClosure callback) = 0; }; } // namespace web #endif // IOS_WEB_PUBLIC_TEST_FAKES_FAKE_WEB_FRAME_H_
971
301
<gh_stars>100-1000 { "config": { "abort": { "single_instance_allowed": "Slechts een enkele configuratie van Mail en pakketten is toegestaan." }, "error": { "communication": "Kan geen verbinding maken met of inloggen op de mailserver. Controleer het logboek voor details.", "invalid_path": "Bewaar de afbeeldingen in een andere map.", "ffmpeg_not_found": "Generate MP4 requires ffmpeg" }, "step": { "user": { "data": { "host": "Gastheer", "password": "<PASSWORD>", "port": "Haven", "username": "Gebruikersnaam" }, "description": "Voer de verbindingsgegevens van uw mailserver in.", "title": "Mail en pakketten (stap 1 van 2)" }, "config_2": { "data": { "folder": "E-mailmap", "scan_interval": "Scaninterval (minuten)", "image_path": "Afbeeldingspad", "gif_duration": "Beeldduur (seconden)", "image_security": "Bestandsnaam willekeurige afbeelding", "generate_mp4": "Maak mp4 van afbeeldingen", "resources": "Sensors List", "imap_timeout": "Time in seconds before connection timeout (seconds, minimum 10)", "amazon_fwds": "Amazon fowarded email addresses", "allow_external": "Create image for notification apps" }, "description": "Voltooi de configuratie door het volgende aan te passen op basis van uw e-mailstructuur en Home Assistant-installatie. \n\n Voor meer informatie over de [E-mail en pakketten integratie] (https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) opties bekijk de [configuratie, sjablonen , en automatisering sectie] (https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) op GitHub.", "title": "Mail en pakketten (stap 2 van 2)" } }, "title": "Mail and Packages" }, "options": { "error": { "communication": "Kan geen verbinding maken met of inloggen op de mailserver. Controleer het logboek voor details.", "invalid_path": "Bewaar de afbeeldingen in een andere map.", "ffmpeg_not_found": "Generate MP4 requires ffmpeg" }, "step": { "init": { "data": { "host": "Gastheer", "password": "<PASSWORD>", "port": "Haven", "username": "Gebruikersnaam" }, "description": "Voer de verbindingsgegevens van uw mailserver in.", "title": "Mail en pakketten (stap 1 van 2)" }, "options_2": { "data": { "folder": "E-mailmap", "scan_interval": "Scaninterval (minuten)", "image_path": "Afbeeldingspad", "gif_duration": "Beeldduur (seconden)", "image_security": "Bestandsnaam willekeurige afbeelding", "generate_mp4": "Maak mp4 van afbeeldingen", "resources": "Sensoren lijst", "imap_timeout": "Tijd in seconden voordat verbinding wordt verbroken (seconden, minimaal 10)", "amazon_fwds": "Amazon forwarded email addresses", "allow_external": "Maak een afbeelding voor meldings-apps" }, "description": "Voltooi de configuratie door het volgende aan te passen op basis van uw e-mailstructuur en Home Assistant-installatie. \n\n Voor meer informatie over de [E-mail en pakketten integratie](https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) opties bekijk de [configuratie, sjablonen , en automatisering sectie](https://github.com/moralmunky/Home-Assistant-Mail-And-Packages/wiki/Configuration-and-Email-Settings#configuration) op GitHub.", "title": "Mail en pakketten (stap 2 van 2)" } } } }
2,196
749
/* AUTHOR : <NAME> (angelo12 AT vt DOT edu) PROJECT : Hybrid Rendering Engine LICENSE : This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) DATE : 2018-10-04 */ #include "debugUtils.h" #include <cstdio> #include <string> //Determine what OpenGL error you are facing specifically GLenum HREUtils::glCheckError_(const char *file, int line){ GLenum errorCode; while((errorCode = glGetError()) != GL_NO_ERROR){ std::string error; switch(errorCode){ case GL_INVALID_ENUM: error = "Invalid Enum"; break; case GL_INVALID_VALUE: error = "Invalid value"; break; case GL_INVALID_OPERATION: error = "Invalid operation"; break; case GL_STACK_OVERFLOW: error = "stack overflow"; break; case GL_STACK_UNDERFLOW: error = "stack underflow"; break; case GL_OUT_OF_MEMORY: error = "out of memory"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "invalid framebuffer operation"; break; } printf("%s, | %s ( %d ) \n", error.c_str(), file, line); } return errorCode; } //Finding the max sizes for compute units void HREUtils::printComputeSizes(){ int work_grp_cnt[3]; int work_grp_size[3]; //Counts glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0, &work_grp_cnt[0]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1, &work_grp_cnt[1]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2, &work_grp_cnt[2]); //Sizes glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0, &work_grp_size[0]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, &work_grp_size[1]); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2, &work_grp_size[2]); printf("max global (total) work group size x:%i y:%i z:%i\n", work_grp_cnt[0], work_grp_cnt[1], work_grp_cnt[2]); printf("max local (in one shader) work group sizes x:%i y:%i z:%i\n", work_grp_size[0], work_grp_size[1], work_grp_size[2]); }
911
1,886
<gh_stars>1000+ // [AsmJit] // Machine Code Generation for C++. // // [License] // Zlib - See LICENSE.md file in the package. #include "./asmjit.h" using namespace asmjit; // ============================================================================ // [DumpCpu] // ============================================================================ struct DumpCpuFeature { uint32_t feature; const char* name; }; static const char* hostArch() noexcept { switch (ArchInfo::kIdHost) { case ArchInfo::kIdX86: return "X86"; case ArchInfo::kIdX64: return "X64"; case ArchInfo::kIdA32: return "ARM32"; case ArchInfo::kIdA64: return "ARM64"; default: return "Unknown"; } } static void dumpFeatures(const CpuInfo& cpu, const DumpCpuFeature* data, size_t count) noexcept { for (size_t i = 0; i < count; i++) if (cpu.hasFeature(data[i].feature)) INFO(" %s", data[i].name); } static void dumpCpu(void) noexcept { const CpuInfo& cpu = CpuInfo::host(); INFO("Host CPU:"); INFO(" Vendor : %s", cpu.vendor()); INFO(" Brand : %s", cpu.brand()); INFO(" Model ID : %u", cpu.modelId()); INFO(" Brand ID : %u", cpu.brandId()); INFO(" Family ID : %u", cpu.familyId()); INFO(" Stepping : %u", cpu.stepping()); INFO(" Processor Type : %u", cpu.processorType()); INFO(" Max logical Processors : %u", cpu.maxLogicalProcessors()); INFO(" Cache-Line Size : %u", cpu.cacheLineSize()); INFO(" HW-Thread Count : %u", cpu.hwThreadCount()); INFO(""); // -------------------------------------------------------------------------- // [X86] // -------------------------------------------------------------------------- #if ASMJIT_ARCH_X86 static const DumpCpuFeature x86FeaturesList[] = { { x86::Features::kNX , "NX" }, { x86::Features::kMT , "MT" }, { x86::Features::k3DNOW , "3DNOW" }, { x86::Features::k3DNOW2 , "3DNOW2" }, { x86::Features::kADX , "ADX" }, { x86::Features::kAESNI , "AESNI" }, { x86::Features::kALTMOVCR8 , "ALTMOVCR8" }, { x86::Features::kAVX , "AVX" }, { x86::Features::kAVX2 , "AVX2" }, { x86::Features::kAVX512_4FMAPS , "AVX512_4FMAPS" }, { x86::Features::kAVX512_4VNNIW , "AVX512_4VNNIW" }, { x86::Features::kAVX512_BITALG , "AVX512_BITALG" }, { x86::Features::kAVX512_BW , "AVX512_BW" }, { x86::Features::kAVX512_CDI , "AVX512_CDI" }, { x86::Features::kAVX512_DQ , "AVX512_DQ" }, { x86::Features::kAVX512_ERI , "AVX512_ERI" }, { x86::Features::kAVX512_F , "AVX512_F" }, { x86::Features::kAVX512_IFMA , "AVX512_IFMA" }, { x86::Features::kAVX512_PFI , "AVX512_PFI" }, { x86::Features::kAVX512_VBMI , "AVX512_VBMI" }, { x86::Features::kAVX512_VBMI2 , "AVX512_VBMI2" }, { x86::Features::kAVX512_VL , "AVX512_VL" }, { x86::Features::kAVX512_VNNI , "AVX512_VNNI" }, { x86::Features::kAVX512_VPOPCNTDQ, "AVX512_VPOPCNTDQ" }, { x86::Features::kBMI , "BMI" }, { x86::Features::kBMI2 , "BMI2" }, { x86::Features::kCLFLUSH , "CLFLUSH" }, { x86::Features::kCLFLUSHOPT , "CLFLUSHOPT" }, { x86::Features::kCLWB , "CLWB" }, { x86::Features::kCLZERO , "CLZERO" }, { x86::Features::kCMOV , "CMOV" }, { x86::Features::kCMPXCHG16B , "CMPXCHG16B" }, { x86::Features::kCMPXCHG8B , "CMPXCHG8B" }, { x86::Features::kERMS , "ERMS" }, { x86::Features::kF16C , "F16C" }, { x86::Features::kFMA , "FMA" }, { x86::Features::kFMA4 , "FMA4" }, { x86::Features::kFPU , "FPU" }, { x86::Features::kFSGSBASE , "FSGSBASE" }, { x86::Features::kFXSR , "FXSR" }, { x86::Features::kFXSROPT , "FXSROPT" }, { x86::Features::kGEODE , "GEODE" }, { x86::Features::kGFNI , "GFNI" }, { x86::Features::kHLE , "HLE" }, { x86::Features::kI486 , "I486" }, { x86::Features::kLAHFSAHF , "LAHFSAHF" }, { x86::Features::kLWP , "LWP" }, { x86::Features::kLZCNT , "LZCNT" }, { x86::Features::kMMX , "MMX" }, { x86::Features::kMMX2 , "MMX2" }, { x86::Features::kMONITOR , "MONITOR" }, { x86::Features::kMONITORX , "MONITORX" }, { x86::Features::kMOVBE , "MOVBE" }, { x86::Features::kMPX , "MPX" }, { x86::Features::kMSR , "MSR" }, { x86::Features::kMSSE , "MSSE" }, { x86::Features::kOSXSAVE , "OSXSAVE" }, { x86::Features::kPCLMULQDQ , "PCLMULQDQ" }, { x86::Features::kPCOMMIT , "PCOMMIT" }, { x86::Features::kPOPCNT , "POPCNT" }, { x86::Features::kPREFETCHW , "PREFETCHW" }, { x86::Features::kPREFETCHWT1 , "PREFETCHWT1" }, { x86::Features::kRDRAND , "RDRAND" }, { x86::Features::kRDSEED , "RDSEED" }, { x86::Features::kRDTSC , "RDTSC" }, { x86::Features::kRDTSCP , "RDTSCP" }, { x86::Features::kRTM , "RTM" }, { x86::Features::kSHA , "SHA" }, { x86::Features::kSKINIT , "SKINIT" }, { x86::Features::kSMAP , "SMAP" }, { x86::Features::kSMEP , "SMEP" }, { x86::Features::kSMX , "SMX" }, { x86::Features::kSSE , "SSE" }, { x86::Features::kSSE2 , "SSE2" }, { x86::Features::kSSE3 , "SSE3" }, { x86::Features::kSSE4_1 , "SSE4.1" }, { x86::Features::kSSE4_2 , "SSE4.2" }, { x86::Features::kSSE4A , "SSE4A" }, { x86::Features::kSSSE3 , "SSSE3" }, { x86::Features::kSVM , "SVM" }, { x86::Features::kTBM , "TBM" }, { x86::Features::kTSX , "TSX" }, { x86::Features::kVAES , "VAES" }, { x86::Features::kVMX , "VMX" }, { x86::Features::kVPCLMULQDQ , "VPCLMULQDQ" }, { x86::Features::kXOP , "XOP" }, { x86::Features::kXSAVE , "XSAVE" }, { x86::Features::kXSAVEC , "XSAVEC" }, { x86::Features::kXSAVEOPT , "XSAVEOPT" }, { x86::Features::kXSAVES , "XSAVES" } }; INFO("X86 Features:"); dumpFeatures(cpu, x86FeaturesList, ASMJIT_ARRAY_SIZE(x86FeaturesList)); INFO(""); #endif // -------------------------------------------------------------------------- // [ARM] // -------------------------------------------------------------------------- #if ASMJIT_ARCH_ARM static const DumpCpuFeature armFeaturesList[] = { { arm::Features::kARMv6 , "ARMv6" }, { arm::Features::kARMv7 , "ARMv7" }, { arm::Features::kARMv8 , "ARMv8" }, { arm::Features::kTHUMB , "THUMB" }, { arm::Features::kTHUMBv2 , "THUMBv2" }, { arm::Features::kVFP2 , "VFPv2" }, { arm::Features::kVFP3 , "VFPv3" }, { arm::Features::kVFP4 , "VFPv4" }, { arm::Features::kVFP_D32 , "VFP D32" }, { arm::Features::kNEON , "NEON" }, { arm::Features::kDSP , "DSP" }, { arm::Features::kIDIV , "IDIV" }, { arm::Features::kAES , "AES" }, { arm::Features::kCRC32 , "CRC32" }, { arm::Features::kSHA1 , "SHA1" }, { arm::Features::kSHA256 , "SHA256" }, { arm::Features::kATOMIC64 , "ATOMIC64" } }; INFO("ARM Features:"); dumpFeatures(cpu, armFeaturesList, ASMJIT_ARRAY_SIZE(armFeaturesList)); INFO(""); #endif } // ============================================================================ // [DumpSizeOf] // ============================================================================ static void dumpSizeOf(void) noexcept { #define DUMP_TYPE(...) \ INFO(" %-26s: %u", #__VA_ARGS__, uint32_t(sizeof(__VA_ARGS__))) INFO("Size of C++ types:"); DUMP_TYPE(int8_t); DUMP_TYPE(int16_t); DUMP_TYPE(int32_t); DUMP_TYPE(int64_t); DUMP_TYPE(int); DUMP_TYPE(long); DUMP_TYPE(size_t); DUMP_TYPE(intptr_t); DUMP_TYPE(float); DUMP_TYPE(double); DUMP_TYPE(void*); INFO(""); INFO("Size of base classes:"); DUMP_TYPE(BaseAssembler); DUMP_TYPE(BaseEmitter); DUMP_TYPE(CodeBuffer); DUMP_TYPE(CodeHolder); DUMP_TYPE(ConstPool); DUMP_TYPE(LabelEntry); DUMP_TYPE(RelocEntry); DUMP_TYPE(Section); DUMP_TYPE(String); DUMP_TYPE(Target); DUMP_TYPE(Zone); DUMP_TYPE(ZoneAllocator); DUMP_TYPE(ZoneBitVector); DUMP_TYPE(ZoneHashNode); DUMP_TYPE(ZoneHash<ZoneHashNode>); DUMP_TYPE(ZoneList<int>); DUMP_TYPE(ZoneVector<int>); INFO(""); INFO("Size of operand classes:"); DUMP_TYPE(Operand); DUMP_TYPE(BaseReg); DUMP_TYPE(BaseMem); DUMP_TYPE(Imm); DUMP_TYPE(Label); INFO(""); INFO("Size of function classes:"); DUMP_TYPE(CallConv); DUMP_TYPE(FuncFrame); DUMP_TYPE(FuncValue); DUMP_TYPE(FuncDetail); DUMP_TYPE(FuncSignature); DUMP_TYPE(FuncArgsAssignment); INFO(""); #ifndef ASMJIT_NO_BUILDER INFO("Size of builder classes:"); DUMP_TYPE(BaseBuilder); DUMP_TYPE(BaseNode); DUMP_TYPE(InstNode); DUMP_TYPE(InstExNode); DUMP_TYPE(AlignNode); DUMP_TYPE(LabelNode); DUMP_TYPE(EmbedDataNode); DUMP_TYPE(EmbedLabelNode); DUMP_TYPE(ConstPoolNode); DUMP_TYPE(CommentNode); DUMP_TYPE(SentinelNode); INFO(""); #endif #ifndef ASMJIT_NO_COMPILER INFO("Size of compiler classes:"); DUMP_TYPE(BaseCompiler); DUMP_TYPE(FuncNode); DUMP_TYPE(FuncRetNode); DUMP_TYPE(FuncCallNode); INFO(""); #endif #ifdef ASMJIT_BUILD_X86 INFO("Size of x86-specific classes:"); DUMP_TYPE(x86::Assembler); #ifndef ASMJIT_NO_BUILDER DUMP_TYPE(x86::Builder); #endif #ifndef ASMJIT_NO_COMPILER DUMP_TYPE(x86::Compiler); #endif DUMP_TYPE(x86::InstDB::InstInfo); DUMP_TYPE(x86::InstDB::CommonInfo); DUMP_TYPE(x86::InstDB::OpSignature); DUMP_TYPE(x86::InstDB::InstSignature); INFO(""); #endif #undef DUMP_TYPE } // ============================================================================ // [Main] // ============================================================================ static void onBeforeRun(void) noexcept { dumpCpu(); dumpSizeOf(); } int main(int argc, const char* argv[]) { #if defined(ASMJIT_BUILD_DEBUG) const char buildType[] = "Debug"; #else const char buildType[] = "Release"; #endif INFO("AsmJit Unit-Test v%u.%u.%u [Arch=%s] [Mode=%s]\n\n", unsigned((ASMJIT_LIBRARY_VERSION >> 16) ), unsigned((ASMJIT_LIBRARY_VERSION >> 8) & 0xFF), unsigned((ASMJIT_LIBRARY_VERSION ) & 0xFF), hostArch(), buildType ); return BrokenAPI::run(argc, argv, onBeforeRun); }
6,588
647
#pragma message ( "checkpoint_map.hh has moved to trick/checkpoint_map.hh" ) #include "trick/checkpoint_map.hh"
41
575
// Copyright 2020 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 "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_proxy_configurator.h" #include <memory> #include "base/run_loop.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_features.h" #include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_params.h" #include "content/public/test/browser_task_environment.h" #include "google_apis/google_api_keys.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/base/host_port_pair.h" #include "net/http/http_request_headers.h" #include "net/proxy_resolution/proxy_config.h" #include "services/network/public/mojom/network_context.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" class TestCustomProxyConfigClient : public network::mojom::CustomProxyConfigClient { public: explicit TestCustomProxyConfigClient( mojo::PendingReceiver<network::mojom::CustomProxyConfigClient> pending_receiver) : receiver_(this, std::move(pending_receiver)) {} // network::mojom::CustomProxyConfigClient: void OnCustomProxyConfigUpdated( network::mojom::CustomProxyConfigPtr proxy_config) override { config_ = std::move(proxy_config); } void MarkProxiesAsBad(base::TimeDelta bypass_duration, const net::ProxyList& bad_proxies, MarkProxiesAsBadCallback callback) override {} void ClearBadProxiesCache() override {} network::mojom::CustomProxyConfigPtr config_; private: mojo::Receiver<network::mojom::CustomProxyConfigClient> receiver_; }; class PrefetchProxyProxyConfiguratorTest : public testing::Test { public: PrefetchProxyProxyConfiguratorTest() = default; ~PrefetchProxyProxyConfiguratorTest() override = default; network::mojom::CustomProxyConfigPtr LatestProxyConfig() { return std::move(config_client_->config_); } void VerifyLatestProxyConfig(const GURL& proxy_url, const net::HttpRequestHeaders& headers) { auto config = LatestProxyConfig(); ASSERT_TRUE(config); EXPECT_EQ(config->rules.type, net::ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME); EXPECT_FALSE(config->should_override_existing_config); EXPECT_FALSE(config->allow_non_idempotent_methods); EXPECT_EQ(config->connect_tunnel_headers.ToString(), headers.ToString()); EXPECT_EQ(config->rules.proxies_for_http.size(), 0U); EXPECT_EQ(config->rules.proxies_for_ftp.size(), 0U); ASSERT_EQ(config->rules.proxies_for_https.size(), 1U); EXPECT_EQ(GURL(config->rules.proxies_for_https.Get().ToURI()), proxy_url); } PrefetchProxyProxyConfigurator* configurator() { if (!configurator_) { // Lazy construct and init so that any changed field trials can be used. configurator_ = std::make_unique<PrefetchProxyProxyConfigurator>(); mojo::Remote<network::mojom::CustomProxyConfigClient> client_remote; config_client_ = std::make_unique<TestCustomProxyConfigClient>( client_remote.BindNewPipeAndPassReceiver()); configurator_->AddCustomProxyConfigClient(std::move(client_remote)); configurator_->SetClockForTesting(task_environment_.GetMockClock()); base::RunLoop().RunUntilIdle(); } return configurator_.get(); } void FastForwardBy(base::TimeDelta delta) { task_environment_.FastForwardBy(delta); } private: content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; std::unique_ptr<PrefetchProxyProxyConfigurator> configurator_; std::unique_ptr<TestCustomProxyConfigClient> config_client_; }; TEST_F(PrefetchProxyProxyConfiguratorTest, FeatureOff) { base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndDisableFeature(features::kIsolatePrerenders); configurator()->UpdateCustomProxyConfig(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(LatestProxyConfig()); } TEST_F(PrefetchProxyProxyConfiguratorTest, ExperimentOverrides) { GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}, {"proxy_header_key", "test-header"}}); configurator()->UpdateCustomProxyConfig(); base::RunLoop().RunUntilIdle(); net::HttpRequestHeaders headers; headers.SetHeader("test-header", "key=" + google_apis::GetAPIKey()); VerifyLatestProxyConfig(proxy_url, headers); } TEST_F(PrefetchProxyProxyConfiguratorTest, Fallback_DoesRandomBackoff_ErrFailed) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(PrefetchProxyProxyHost())); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnFallback(proxy, net::ERR_FAILED); EXPECT_FALSE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectUniqueSample("PrefetchProxy.Proxy.Fallback.NetError", std::abs(net::ERR_FAILED), 1); FastForwardBy(base::TimeDelta::FromSeconds(5 * 60 + 1)); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); } TEST_F(PrefetchProxyProxyConfiguratorTest, FallbackDoesRandomBackoff_ErrOK) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(PrefetchProxyProxyHost())); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnFallback(proxy, net::OK); EXPECT_FALSE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectUniqueSample("PrefetchProxy.Proxy.Fallback.NetError", net::OK, 1); FastForwardBy(base::TimeDelta::FromSeconds(5 * 60 + 1)); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); } TEST_F(PrefetchProxyProxyConfiguratorTest, Fallback_DifferentProxy) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(GURL("http://foo.com"))); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnFallback(proxy, net::OK); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectTotalCount("PrefetchProxy.Proxy.Fallback.NetError", 0); } TEST_F(PrefetchProxyProxyConfiguratorTest, TunnelHeaders_200OK) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(PrefetchProxyProxyHost())); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnTunnelHeadersReceived( proxy, base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK")); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectUniqueSample("PrefetchProxy.Proxy.RespCode", 200, 1); } TEST_F(PrefetchProxyProxyConfiguratorTest, TunnelHeaders_DifferentProxy) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(GURL("http://foo.com"))); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnTunnelHeadersReceived( proxy, base::MakeRefCounted<net::HttpResponseHeaders>("HTTP/1.1 200 OK")); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectTotalCount("PrefetchProxy.Proxy.RespCode", 0); } TEST_F(PrefetchProxyProxyConfiguratorTest, TunnelHeaders_500NoRetryAfter) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(PrefetchProxyProxyHost())); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnTunnelHeadersReceived( proxy, base::MakeRefCounted<net::HttpResponseHeaders>( "HTTP/1.1 500 Internal Server Error")); EXPECT_FALSE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectUniqueSample("PrefetchProxy.Proxy.RespCode", 500, 1); FastForwardBy(base::TimeDelta::FromSeconds(5 * 60 + 1)); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); } TEST_F(PrefetchProxyProxyConfiguratorTest, TunnelHeaders_500WithRetryAfter) { base::HistogramTester histogram_tester; GURL proxy_url("https://proxy.com"); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeatureWithParameters( features::kIsolatePrerenders, {{"proxy_host", proxy_url.spec()}}); net::ProxyServer proxy( net::ProxyServer::GetSchemeFromURI(PrefetchProxyProxyHost().scheme()), net::HostPortPair::FromURL(PrefetchProxyProxyHost())); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); configurator()->OnTunnelHeadersReceived( proxy, base::MakeRefCounted< net::HttpResponseHeaders>(net::HttpUtil::AssembleRawHeaders( "HTTP/1.1 500 Internal Server Error\r\nRetry-After: 120\r\n\r\n"))); EXPECT_FALSE(configurator()->IsPrefetchProxyAvailable()); histogram_tester.ExpectUniqueSample("PrefetchProxy.Proxy.RespCode", 500, 1); FastForwardBy(base::TimeDelta::FromSeconds(119)); EXPECT_FALSE(configurator()->IsPrefetchProxyAvailable()); FastForwardBy(base::TimeDelta::FromSeconds(1)); EXPECT_TRUE(configurator()->IsPrefetchProxyAvailable()); }
4,046
6,992
<filename>core/src/main/java/org/springframework/security/authorization/method/ExpressionAttributeAuthorizationDecision.java /* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization.method; import org.springframework.security.authorization.AuthorizationDecision; /** * Represents an {@link AuthorizationDecision} based on a {@link ExpressionAttribute} * * @author <NAME> * @since 5.6 */ public class ExpressionAttributeAuthorizationDecision extends AuthorizationDecision { private final ExpressionAttribute expressionAttribute; public ExpressionAttributeAuthorizationDecision(boolean granted, ExpressionAttribute expressionAttribute) { super(granted); this.expressionAttribute = expressionAttribute; } public ExpressionAttribute getExpressionAttribute() { return this.expressionAttribute; } @Override public String toString() { return getClass().getSimpleName() + " [" + "granted=" + isGranted() + ", expressionAttribute=" + this.expressionAttribute + ']'; } }
417
335
{ "word": "Rivet", "definitions": [ "A short metal pin or bolt for holding together two plates of metal, its headless end being beaten out or pressed down when in place.", "A device similar to a rivet for holding seams of clothing together." ], "parts-of-speech": "Noun" }
104
1,189
<reponame>gcatanese/opentelemetry-java-tmp /* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.sdk.testing.time; import io.opentelemetry.api.internal.GuardedBy; import io.opentelemetry.sdk.common.Clock; import java.time.Duration; import java.time.Instant; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; /** A mutable {@link Clock} that allows the time to be set for testing. */ @ThreadSafe public final class TestClock implements Clock { @GuardedBy("this") private long currentEpochNanos; private TestClock(long epochNanos) { currentEpochNanos = epochNanos; } /** * Creates a clock initialized to a constant non-zero time. * * @return a clock initialized to a constant non-zero time. */ public static TestClock create() { // Set Time to Tuesday, May 7, 2019 12:00:00 AM GMT-07:00 DST return create(Instant.ofEpochMilli(1_557_212_400_000L)); } /** Creates a clock with the given time. */ public static TestClock create(Instant instant) { return new TestClock(toNanos(instant)); } /** Sets the current time. */ public synchronized void setTime(Instant instant) { currentEpochNanos = toNanos(instant); } /** Advances the time and mutates this instance. */ public synchronized void advance(Duration duration) { advance(duration.toNanos(), TimeUnit.NANOSECONDS); } /** Advances the time and mutates this instance. */ public synchronized void advance(long duration, TimeUnit unit) { currentEpochNanos += unit.toNanos(duration); } @Override public synchronized long now() { return currentEpochNanos; } @Override public synchronized long nanoTime() { return currentEpochNanos; } private static long toNanos(Instant instant) { return TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano(); } }
620
5,169
{ "name": "SwiftCircleProgressBar", "version": "1.0", "summary": "a circle progress bar control written in swift for ios development", "description": "a circle progress bar control written in swift for ios development \nwritten by zoe.liu", "homepage": "https://github.com/xdongliu123/SwiftCircleProgressBar", "license": "MIT", "authors": { "xdongliu123": "<EMAIL>" }, "platforms": { "ios": "11.0" }, "swift_versions": "5.0", "source": { "git": "https://github.com/xdongliu123/SwiftCircleProgressBar.git", "tag": "1.0" }, "source_files": "SwiftCircleProgressBarDemo/CircleProgressBar/*", "frameworks": [ "UIKit", "QuartzCore" ], "swift_version": "5.0" }
280
485
#include "luat_base.h" int luat_socket_ntp_sync(const char* ntpServer); int luat_socket_tsend(const char* hostname, int port, void* buff, int len); int luat_socket_is_ready(void); uint32_t luat_socket_selfip(void);
90
5,342
<reponame>suryatmodulus/lepton /** # $FreeBSD$ # @(#)COPYRIGHT 8.2 (Berkeley) 3/21/94 The compilation of software known as the FreeBSD Ports Collection is distributed under the following terms: Copyright (C) 1994-2016 The FreeBSD Project. 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. THIS SOFTWARE IS PROVIDED BY 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 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. */ #if !defined(_WIN32) && defined(__SSE2__) && !defined(__SSE4_1__) && !defined(MM_MULLO_EPI32_H) #define MM_MULLO_EPI32_H #include <immintrin.h> // See: http://stackoverflow.com/questions/10500766/sse-multiplication-of-4-32-bit-integers // and https://software.intel.com/en-us/forums/intel-c-compiler/topic/288768 static inline __m128i fallback_mm_mullo_epi32(const __m128i &a, const __m128i &b) { __m128i tmp1 = _mm_mul_epu32(a,b); /* mul 2,0*/ __m128i tmp2 = _mm_mul_epu32(_mm_srli_si128(a,4), _mm_srli_si128(b,4)); /* mul 3,1 */ return _mm_unpacklo_epi32( /* shuffle results to [63..0] and pack */ _mm_shuffle_epi32(tmp1, _MM_SHUFFLE (0,0,2,0)), _mm_shuffle_epi32(tmp2, _MM_SHUFFLE (0,0,2,0))); } #define _mm_mullo_epi32 fallback_mm_mullo_epi32 #endif
842
990
''' Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8 Note: The array is only modifiable by the update function. You may assume the number of calls to update and sumRange function is distributed evenly. ''' class Node(object): def __init__(self, val ,start, end): self.sum = val self.right, self.left = None, None self.range= [start, end] class SegementTree(object): def __init__(self, size): self.root = self._build_segment_tree(0, size-1) def _build_segment_tree(self, start, end): if start > end: return None node = Node(0, start, end) if start == end: return node mid = (start+end)/2 node.left, node.right = self._build_segment_tree(start, mid), self._build_segment_tree(mid+1, end) return node def update(self, index, val, root=None): root = root or self.root if index < root.range[0] or index > root.range[1]: return root.sum += val if index == root.range[0] == root.range[1]: return self.update(index, val, root.left) self.update(index, val, root.right) def range_sum(self, start, end, root=None): root = root or self.root if end < root.range[0] or start > root.range[1]: return 0 if start <= root.range[0] and end >= root.range[1]: return root.sum return self.range_sum(start, end, root.left) + self.range_sum(start, end, root.right) class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums self.segment_tree = SegementTree(len(nums)) for index, num in enumerate(nums): self.segment_tree.update(index, num) def update(self, i, val): """ :type i: int :type val: int :rtype: None """ diff = val-self.nums[i] self.segment_tree.update(i, diff) self.nums[i] = val def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ return self.segment_tree.range_sum(i, j) # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # obj.update(i,val) # param_2 = obj.sumRange(i,j)
1,216
1,682
/* Copyright (c) 2014 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.linkedin.restli.common; import com.linkedin.data.template.RecordTemplate; import java.util.Map; import java.util.Set; /** * The properties of the resource which are common to all resource types and apply to all methods of * resource implementation. The implementations of this interface must be immutable. */ public interface ResourceProperties { Set<ResourceMethod> getSupportedMethods(); TypeSpec<?> getKeyType(); TypeSpec<? extends RecordTemplate> getValueType(); ComplexKeySpec<? extends RecordTemplate, ? extends RecordTemplate> getComplexKeyType(); Map<String, CompoundKey.TypeInfo> getKeyParts(); boolean isKeylessResource(); }
334
1,086
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ /* File is modified to include Ring Keywords and Ignore the Case Updated by : <NAME> <<EMAIL>> Date : 2016.09.14 */ #include "highlighter.h" Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { setColors(Qt::darkBlue,Qt::darkMagenta,Qt::red,Qt::darkGreen,Qt::blue); } void Highlighter::highlightBlock(const QString &text) { foreach (const HighlightingRule &rule, highlightingRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); index = expression.indexIn(text, index + length); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) startIndex = commentStartExpression.indexIn(text); while (startIndex >= 0) { int endIndex = commentEndExpression.indexIn(text, startIndex); int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + commentEndExpression.matchedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = commentStartExpression.indexIn(text, startIndex + commentLength); } } void Highlighter::setColors(QColor c1,QColor c2,QColor c3,QColor c4,QColor c5) { HighlightingRule rule; highlightingRules.remove(0,highlightingRules.count()); keywordFormat.setForeground(c1); if (this->nKeywordsBold) keywordFormat.setFontWeight(QFont::Bold); QStringList keywordPatterns; keywordPatterns << "\\bagain\\b" << "\\band\\b" << "\\bbut\\b" << "\\bbye\\b" << "\\bcall\\b" << "\\bcase\\b" << "\\bcatch\\b" << "\\bclass\\b" << "\\bdef\\b" << "\\bdo\\b" << "\\bdone\\b" << "\\belse\\b" << "\\belseif\\b" << "\\bend\\b" << "\\bexit\\b" << "\\bfor\\b" << "\\bfrom\\b" << "\\bfunc\\b" << "\\bget\\b" << "\\bgive\\b" << "\\bif\\b" << "\\bimport\\b" << "\\bin\\b" << "\\bload\\b" << "\\bloop\\b" << "\\bnew\\b" << "\\bnext\\b" << "\\bnot\\b" << "\\boff\\b" << "\\bok\\b" << "\\bon\\b" << "\\bor\\b" << "\\bother\\b" << "\\bpackage\\b" << "\\bprivate\\b" << "\\bput\\b" << "\\breturn\\b" << "\\bsee\\b" << "\\bstep\\b" << "\\bswitch\\b" << "\\bto\\b" << "\\btry\\b" << "\\bendfunc\\b" << "\\bendclass\\b" << "\\bendpackage\\b" << "\\bwhile\\b" << "\\bchangeringkeyword\\b" << "\\bchangeringoperator\\b" << "\\bloadsyntax\\b"; foreach (const QString &pattern, keywordPatterns) { rule.pattern = QRegExp(pattern,Qt::CaseInsensitive); rule.format = keywordFormat; highlightingRules.append(rule); } if (this->nKeywordsBold) classFormat.setFontWeight(QFont::Bold); classFormat.setForeground(c2); rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b"); rule.format = classFormat; highlightingRules.append(rule); functionFormat.setFontItalic(true); functionFormat.setForeground(c5); rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()"); rule.format = functionFormat; highlightingRules.append(rule); singleLineCommentFormat.setForeground(c3); rule.pattern = QRegExp("//[^\n]*"); rule.format = singleLineCommentFormat; highlightingRules.append(rule); rule.pattern = QRegExp("^#+[^\n]*"); highlightingRules.append(rule); rule.pattern = QRegExp("#+( |-|=)[^\n]*"); highlightingRules.append(rule); multiLineCommentFormat.setForeground(c3); quotationFormat.setForeground(c4); rule.pattern = QRegExp("\"(?:(?!\\/\\/).)+\""); rule.pattern.setMinimal(true); rule.format = quotationFormat; highlightingRules.append(rule); quotationFormat2.setForeground(c4); rule.pattern = QRegExp("\'(?:(?!\\/\\/).)+\'"); rule.pattern.setMinimal(true); rule.format = quotationFormat2; highlightingRules.append(rule); quotationFormat3.setForeground(c4); rule.pattern = QRegExp("`(?:(?!\\/\\/).)+`"); rule.pattern.setMinimal(true); rule.format = quotationFormat3; highlightingRules.append(rule); commentStartExpression = QRegExp("^\\s*/\\*"); commentEndExpression = QRegExp("\\*/"); } void Highlighter::setKeywordsBold(int nStatus) { this->nKeywordsBold = nStatus; }
2,596
348
{"nom":"Egliseneuve-près-Billom","circ":"5ème circonscription","dpt":"Puy-de-Dôme","inscrits":732,"abs":340,"votants":392,"blancs":7,"nuls":7,"exp":378,"res":[{"nuance":"COM","nom":"M. <NAME>","voix":262},{"nuance":"REM","nom":"<NAME>","voix":116}]}
106
1,030
package com.catchingnow.tinyclipboardmanager; import android.content.Intent; import android.os.Build; import android.preference.PreferenceActivity; import android.support.v4.content.LocalBroadcastManager; import android.view.KeyEvent; /** * Created by heruoxin on 15/2/28. */ public class MyPreferenceActivity extends PreferenceActivity { //Fix LG support V7 bug: //https://code.google.com/p/android/issues/detail?id=78154 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && "LGE".equalsIgnoreCase(Build.BRAND)) { return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && "LGE".equalsIgnoreCase(Build.BRAND)) { openOptionsMenu(); return true; } return super.onKeyUp(keyCode, event); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(MyActionBarActivity.ACTIVITY_CLOSED)); super.onPause(); } @Override protected void onResume() { LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(MyActionBarActivity.ACTIVITY_OPENED)); super.onResume(); } }
523
2,757
<filename>2020/quals/pwn-app-ads/app/ads-impl/src/main/java/com/ads/sdk/impl/webview/AdWebViewClient.java // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.ads.sdk.impl.webview; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.provider.CalendarContract; import android.util.Log; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.ads.sdk.common.Logger; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import static com.ads.sdk.common.dynamic.AidlUtils.runRemote; public class AdWebViewClient extends WebViewClient { private static final Map<String, JsMessageHandler> HANDLERS = new HashMap<>(); static { HANDLERS.put("log", (view, request) -> { Logger.i("JS: " + request.getUrl().getQueryParameter("msg")); return true; }); HANDLERS.put("refresh", (view, request) -> runRemote(() -> { view.getControl().refresh(request.getUrl().getQueryParameter("url")); return true; }) ); HANDLERS.put("init.mraid", (view, request) -> runRemote(() -> { evalJs(view, "MRAID_CALLBACK('init', '2.0')"); return true; }) ); HANDLERS.put("resize.mraid", (view, request) -> runRemote(() -> { Logger.i("MRAID: RESIZE is not supported"); return true; }) ); HANDLERS.put("create-calendar-event.mraid", (view, request) -> runRemote(() -> { String title = request.getUrl().getQueryParameter("title"); String description = request.getUrl().getQueryParameter("desc"); String location = request.getUrl().getQueryParameter("loc"); long startMillis = Long.parseLong(request.getUrl().getQueryParameter("start")); long endMillis = Long.parseLong(request.getUrl().getQueryParameter("end")); Intent intent = new Intent(Intent.ACTION_INSERT) .setData(CalendarContract.Events.CONTENT_URI) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis) .putExtra(CalendarContract.Events.TITLE, title) .putExtra(CalendarContract.Events.DESCRIPTION, description) .putExtra(CalendarContract.Events.EVENT_LOCATION, location); view.getContext().startActivity(intent); evalJs(view, "MRAID_CALLBACK('create-calendar-event', true)"); return true; }) ); HANDLERS.put("play-video.mraid", (view, request) -> runRemote(() -> { Intent intent = new Intent(Intent.ACTION_VIEW); String videoUri = request.getUrl().getQueryParameter("uri"); intent.setDataAndType(Uri.parse(videoUri), "video/mp4"); view.getContext().startActivity(intent); evalJs(view, "MRAID_CALLBACK('play-video', true)"); return true; }) ); HANDLERS.put("store-picture.mraid", (view, request) -> { new Thread(() -> { Context context = view.getContext(); Uri pictureUri = Uri.parse(request.getUrl().getQueryParameter("url")); File mraidPath = new File(view.getContext().getExternalMediaDirs()[0], "mraid"); String fileName = request.getUrl().getQueryParameter("name"); mraidPath.mkdirs(); File picturePath = new File(mraidPath, fileName); Logger.e("MRAID: storing picture"); try { FileUtils.copyURLToFile(new URL(pictureUri.toString()), picturePath); evalJs(view, "MRAID_CALLBACK('store-picture', true)"); } catch (IOException e) { Logger.e("MRAID: unable to store picture", e); evalJs(view, "MRAID_CALLBACK('store-picture', false)"); } }).start(); return true; }); HANDLERS.put("supports.mraid", (view, request) -> { evalJs(view, "MRAID_CALLBACK('supports', {tel: true, sms: true, calendar: true, storePicture: true, inlineVideo: false}))"); return true; }); } private static Handler MAIN_HANDLER = new Handler(Looper.getMainLooper()); private static void evalJs(AdWebView adWebView, String js) { MAIN_HANDLER.post(() -> adWebView.evaluateJavascript(js, null)); } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (request.getUrl().getScheme().equals("ads")) { JsMessageHandler handler = HANDLERS.get(request.getUrl().getHost()); if (handler != null) { return handler.handleMessage((AdWebView) view, request); } } return super.shouldOverrideUrlLoading(view, request); } }
2,787
617
/** * Copyright 1999-2011 Alibaba Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.cobar.client.router.config; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; import org.springframework.util.ObjectUtils; import com.alibaba.cobar.client.router.CobarClientInternalRouter; import com.alibaba.cobar.client.router.rules.IRoutingRule; import com.alibaba.cobar.client.router.support.IBatisRoutingFact; public abstract class AbstractCobarInternalRouterConfigurationFactoryBean implements FactoryBean, InitializingBean { private CobarClientInternalRouter router; private boolean enableCache; private int cacheSize; private Resource configLocation; private Resource[] configLocations; private Map<String, Object> functionsMap = new HashMap<String, Object>(); public Object getObject() throws Exception { return this.router; } @SuppressWarnings("unchecked") public Class getObjectType() { return CobarClientInternalRouter.class; } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { if (enableCache) { if (cacheSize <= 0) { setCacheSize(10000); } } this.router = new CobarClientInternalRouter(enableCache, cacheSize); final Set<IRoutingRule<IBatisRoutingFact, List<String>>> sqlActionShardingRules = new HashSet<IRoutingRule<IBatisRoutingFact, List<String>>>(); final Set<IRoutingRule<IBatisRoutingFact, List<String>>> sqlActionRules = new HashSet<IRoutingRule<IBatisRoutingFact, List<String>>>(); final Set<IRoutingRule<IBatisRoutingFact, List<String>>> namespaceShardingRules = new HashSet<IRoutingRule<IBatisRoutingFact, List<String>>>(); final Set<IRoutingRule<IBatisRoutingFact, List<String>>> namespaceRules = new HashSet<IRoutingRule<IBatisRoutingFact, List<String>>>(); if (getConfigLocation() != null) { assembleRulesForRouter(this.router, getConfigLocation(), sqlActionShardingRules, sqlActionRules, namespaceShardingRules, namespaceRules); } if (!ObjectUtils.isEmpty(getConfigLocations())) { for (Resource res : getConfigLocations()) { assembleRulesForRouter(this.router, res, sqlActionShardingRules, sqlActionRules, namespaceShardingRules, namespaceRules); } } List<Set<IRoutingRule<IBatisRoutingFact, List<String>>>> ruleSequences = new ArrayList<Set<IRoutingRule<IBatisRoutingFact, List<String>>>>() { private static final long serialVersionUID = 1493353938640646578L; { add(sqlActionShardingRules); add(sqlActionRules); add(namespaceShardingRules); add(namespaceRules); } }; router.setRuleSequences(ruleSequences); } /** * Subclass just needs to read in rule configurations and assemble the * router with the rules read from configurations. * * @param router * @param namespaceRules * @param namespaceShardingRules * @param sqlActionRules * @param sqlActionShardingRules */ protected abstract void assembleRulesForRouter( CobarClientInternalRouter router, Resource configLocation, Set<IRoutingRule<IBatisRoutingFact, List<String>>> sqlActionShardingRules, Set<IRoutingRule<IBatisRoutingFact, List<String>>> sqlActionRules, Set<IRoutingRule<IBatisRoutingFact, List<String>>> namespaceShardingRules, Set<IRoutingRule<IBatisRoutingFact, List<String>>> namespaceRules) throws IOException; public void setConfigLocation(Resource configLocation) { this.configLocation = configLocation; } public Resource getConfigLocation() { return configLocation; } public void setConfigLocations(Resource[] configLocations) { this.configLocations = configLocations; } public Resource[] getConfigLocations() { return configLocations; } public void setEnableCache(boolean enableCache) { this.enableCache = enableCache; } public boolean isEnableCache() { return enableCache; } public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } public int getCacheSize() { return cacheSize; } public void setFunctionsMap(Map<String, Object> functionMaps) { if (functionMaps == null) { return; } this.functionsMap = functionMaps; } public Map<String, Object> getFunctionsMap() { return functionsMap; } }
2,342
794
package github.tornaco.android.nitro.framework.host.manager.data.source.local; import android.content.Context; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; import github.tornaco.android.nitro.framework.host.manager.data.converter.ActivityInfoConverter; import github.tornaco.android.nitro.framework.host.manager.data.converter.ApplicationInfoConverter; import github.tornaco.android.nitro.framework.host.manager.data.converter.IntentFilterConverter; import github.tornaco.android.nitro.framework.host.manager.data.model.ActivityIntentFilter; import github.tornaco.android.nitro.framework.host.manager.data.model.InstalledPlugin; import github.tornaco.android.nitro.framework.host.manager.data.model.PluginActivityInfo; import github.tornaco.android.nitro.framework.host.manager.data.model.PluginApplicationInfo; import util.Singleton2; @Database(entities = { InstalledPlugin.class, PluginApplicationInfo.class, PluginActivityInfo.class, ActivityIntentFilter.class}, version = 3, exportSchema = false) @TypeConverters({ActivityInfoConverter.class, ApplicationInfoConverter.class, IntentFilterConverter.class}) public abstract class InstalledPluginDatabase extends RoomDatabase { private static final Singleton2<Context, InstalledPluginDatabase> SINGLETON = new Singleton2<Context, InstalledPluginDatabase>() { @Override protected InstalledPluginDatabase create(Context context) { return Room .databaseBuilder(context, InstalledPluginDatabase.class, "plugins.db") // Add stable and withHooks .addMigrations(new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `installed_plugins` ADD COLUMN `stable` INTEGER NOT NULL DEFAULT 0"); database.execSQL("ALTER TABLE `installed_plugins` ADD COLUMN `withHooks` INTEGER NOT NULL DEFAULT 1"); } }) .addMigrations(new Migration(2, 3) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `installed_plugins` ADD COLUMN `statusCallableClass` TEXT DEFAULT ''"); } }) .allowMainThreadQueries() .build(); } }; public static InstalledPluginDatabase getInstance(Context context) { return SINGLETON.get(context); } public abstract InstalledPluginDao installedPluginDao(); public abstract PluginActivityDao pluginActivityDao(); public abstract PluginAppDao pluginAppDao(); public abstract ActivityIntentFilterDao intentFilterDao(); }
1,258
3,084
// // Copyright (C) Microsoft Corporation 2005 // IHV UI Extension sample // #include "precomp.h" #include "ihvsample_i.c" extern HINSTANCE g_hInst; LPWSTR g_IHVAuthFriendlyName[] = { L"IHVAuth V1", L"IHVAuth V2", L"IHVAuth V3" }; LPWSTR g_IHVCipherFriendlyName[] = { L"None", L"IHVCipher 1", L"IHVCipher 2", L"IHVCipher 3" }; IHV_AUTH_CIPHER_CAPABILITY g_IHVOneXExtCapability = { 3, { { IHVAuthV1, 1, {IHVCipher1} }, { IHVAuthV2, 3, {None, IHVCipher1, IHVCipher2} }, { IHVAuthV3, 2, {IHVCipher2, IHVCipher3} } } }; static const WCHAR c_szIhvUIRequest[] = L"_UI_Request"; static const WCHAR c_szIhvUIResponse[] = L"_UI_Response"; template<typename T> T* GetThis(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { static const WCHAR c_szThisPointer[]= L"_Win32_this_"; UNREFERENCED_PARAMETER(wParam); T* pThis = NULL; if (uMsg == WM_INITDIALOG) { if (sizeof(PROPSHEETPAGE) == ((LPPROPSHEETPAGE)lParam)->dwSize) { // This corresponds to MSDN pThis = (T *)((LPPROPSHEETPAGE)lParam)->lParam; } else { // TODO: Need to determine when this abnormality happens... pThis = (T *)lParam; } SetProp(hwnd, c_szThisPointer, (HANDLE)pThis); } else if (uMsg == WM_DESTROY) { RemoveProp(hwnd, c_szThisPointer); } else { pThis = (T *)GetProp(hwnd, c_szThisPointer); } return pThis; } CDot11SampleExtUI::CDot11SampleExtUI(): m_crefCount(0) { InterlockedIncrement(&g_objRefCount); m_pUnkSite = NULL; m_hFirstPagePsp = NULL; m_hLastPagePsp = NULL; m_pUIRequest = NULL; } CDot11SampleExtUI::~CDot11SampleExtUI() { InterlockedDecrement(&g_objRefCount); if( m_pUIRequest) { delete m_pUIRequest; } if( m_pUnkSite) { m_pUnkSite ->Release(); m_pUnkSite = NULL; } } // Used to get the IHV friendly name STDMETHODIMP CDot11SampleExtUI::GetDot11ExtUIFriendlyName( BSTR* bstrFriendlyName) { HRESULT hr = E_INVALIDARG; if (NULL != bstrFriendlyName) { *bstrFriendlyName = SysAllocString(IHV_SAMPLE_IHV_NAME); hr = S_OK; } return hr; } // Returns the requested property type STDMETHODIMP CDot11SampleExtUI::GetDot11ExtUIProperties( DOT11_EXT_UI_PROPERTY_TYPE ExtType, ULONG *pcExtensions, IDot11ExtUIProperty **ppDot11ExtUIProperty ) { HRESULT hr = S_OK; if (!pcExtensions || !ppDot11ExtUIProperty) { hr = E_INVALIDARG; goto error; } // Initialize the out parameters *pcExtensions = 0; *ppDot11ExtUIProperty = NULL; switch(ExtType) { case DOT11_EXT_UI_CONNECTION: hr = CreateConnectionProperties(pcExtensions, ppDot11ExtUIProperty); break; case DOT11_EXT_UI_SECURITY: hr = CreateSecurityProperties(pcExtensions, ppDot11ExtUIProperty); break; case DOT11_EXT_UI_KEYEXTENSION: hr = CreateKeyProperties(pcExtensions, ppDot11ExtUIProperty); break; default: hr = E_NOTIMPL; break; } error: return hr; } #define IHV_BALLOON_TEXT L"Please enter key information" STDMETHODIMP CDot11SampleExtUI::GetDot11ExtUIBalloonText( BSTR pIHVUIRequest, // the UI request structure from IHV BSTR* pwszBalloonText // the balloon text to be displayed ) { HRESULT hr = E_INVALIDARG; PDOT11EXT_IHV_UI_REQUEST pIhvUiRequest = (PDOT11EXT_IHV_UI_REQUEST) pIHVUIRequest; if (NULL != pwszBalloonText) { // Ihv could choose to parse the UI request data here ... UNREFERENCED_PARAMETER( pIhvUiRequest ); *pwszBalloonText = SysAllocString( IHV_BALLOON_TEXT ); hr = S_OK; } return hr; } HRESULT CDot11SampleExtUI::CreateConnectionProperties( ULONG *pcExtensions, IDot11ExtUIProperty **ppDot11ExtUIProperty ) { HRESULT hr = ERROR_SUCCESS; BSTR strName = NULL; ULONG uCount = 0; IDot11SampleExtUIConProperty **pprgProps = NULL; uCount = PROP_COUNT_CONNECTION; pprgProps = (IDot11SampleExtUIConProperty**) CoTaskMemAlloc(sizeof(IDot11SampleExtUIConProperty*) * uCount); if (!pprgProps) { hr = E_UNEXPECTED; goto error; } // Since we just have one property of each, we'll // create one interface first and initialize it separately IDot11SampleExtUIConProperty *pTempIProp = NULL; hr = CoCreateInstance( GUID_SAMPLE_IHVUI_CLSID, NULL, CLSCTX_INPROC, IID_IDot11SampleExtUIConProperty, (PVOID*)&pTempIProp ); if (FAILED(hr)) { goto error; } // this will probably never be displayed strName = SysAllocString(L"IHV Connection Settings"); hr = pTempIProp->Initialize(strName); pprgProps[0] = pTempIProp; if (SUCCEEDED(hr)) { *pcExtensions = uCount; *ppDot11ExtUIProperty = (IDot11ExtUIProperty*)pprgProps; // Set the current pointer to NULL so it doesn't get freed at the bottom pprgProps = NULL; } error: if (FAILED(hr) && pprgProps) { CoTaskMemFree(pprgProps); pprgProps = NULL; } SysFreeString(strName); return hr; } HRESULT CDot11SampleExtUI::CreateSecurityProperties( ULONG *pcExtensions, IDot11ExtUIProperty **ppDot11ExtUIProperty ) { HRESULT hr = ERROR_SUCCESS; BSTR strName = NULL; ULONG uCount = 0; DWORD i = 0; WCHAR wbuf[128]; IDot11SampleExtUISecProperty **pprgProps = NULL; uCount = PROP_COUNT_SECURITY; pprgProps = (IDot11SampleExtUISecProperty**) CoTaskMemAlloc(sizeof(IDot11SampleExtUISecProperty*) * uCount); if (!pprgProps) { hr = E_UNEXPECTED; goto error; } // Since we just have one property of each, we'll // create one interface first and initialize it separately IDot11SampleExtUISecProperty *pTempIProp = NULL; for (i = 0; i < uCount; ++i) { ZeroMemory( wbuf, 128 ); pTempIProp = NULL; SysFreeString(strName); strName = NULL; hr = CoCreateInstance( GUID_SAMPLE_IHVUI_CLSID, NULL, CLSCTX_INPROC, IID_IDot11SampleExtUISecProperty, (PVOID*)&pTempIProp ); if (FAILED(hr)) { continue; } StringCchPrintf( wbuf, 128, wstrSecurityTypes[i] ); strName = SysAllocString(wbuf); hr = pTempIProp->Initialize(strName, i); pprgProps[i] = pTempIProp; } if (SUCCEEDED(hr)) { *pcExtensions = uCount; *ppDot11ExtUIProperty = (IDot11ExtUIProperty*)pprgProps; // Set the current pointer to NULL so it doesn't get freed at the bottom pprgProps = NULL; } error: if (FAILED(hr) && pprgProps) { CoTaskMemFree(pprgProps); pprgProps = NULL; } SysFreeString(strName); return hr; } HRESULT CDot11SampleExtUI::CreateKeyProperties( ULONG *pcExtensions, IDot11ExtUIProperty **ppDot11ExtUIProperty ) { HRESULT hr = ERROR_SUCCESS; BSTR strName = NULL; ULONG uCount = 0; DWORD i = 0; WCHAR wbuf[128]; IDot11SampleExtUIKeyProperty **pprgProps = NULL; uCount = g_IHVOneXExtCapability.dwAuthCount; pprgProps = (IDot11SampleExtUIKeyProperty**) CoTaskMemAlloc(sizeof(IDot11SampleExtUIKeyProperty*) * uCount); if (!pprgProps) { hr = E_UNEXPECTED; goto error; } // Since we just have one property of each, we'll // create one interface first and initialize it separately IDot11SampleExtUIKeyProperty *pTempIProp = NULL; for (i = 0; i < uCount; ++i) { ZeroMemory( wbuf, 128 ); pTempIProp = NULL; SysFreeString(strName); strName = NULL; hr = CoCreateInstance( GUID_SAMPLE_IHVUI_CLSID, NULL, CLSCTX_INPROC, IID_IDot11SampleExtUIKeyProperty, (PVOID*)&pTempIProp ); if (FAILED(hr)) { continue; } StringCchPrintf( wbuf, 128, g_IHVAuthFriendlyName[g_IHVOneXExtCapability.IhvAuthCiphers[i].IHVAuth] ); strName = SysAllocString(wbuf); hr = pTempIProp->Initialize((BYTE *) &(g_IHVOneXExtCapability.IhvAuthCiphers[i])); pprgProps[i] = pTempIProp; } if (SUCCEEDED(hr)) { *pcExtensions = uCount; *ppDot11ExtUIProperty = (IDot11ExtUIProperty*)pprgProps; // Set the current pointer to NULL so it doesn't get freed at the bottom pprgProps = NULL; } error: if (FAILED(hr) && pprgProps) { CoTaskMemFree(pprgProps); pprgProps = NULL; } SysFreeString(strName); return hr; } HRESULT CDot11SampleExtUI::FinalConstruct() { m_pUnkSite = NULL; m_hFirstPagePsp = NULL; m_hLastPagePsp = NULL; m_pUIRequest = NULL; return S_OK; } VOID CDot11SampleExtUI::FinalRelease() { if( m_pUnkSite) { m_pUnkSite ->Release(); m_pUnkSite = NULL; } if( m_pUIRequest) { delete m_pUIRequest; m_pUIRequest = NULL; } } // IObjectWithSite STDMETHODIMP CDot11SampleExtUI::SetSite ( IUnknown* pUnkSite ) { if( m_pUnkSite) m_pUnkSite ->Release(); m_pUnkSite = pUnkSite; if( m_pUnkSite) m_pUnkSite ->AddRef(); return S_OK; } STDMETHODIMP CDot11SampleExtUI::GetSite ( REFIID riid, void** ppvSite ) { *ppvSite = NULL; if( m_pUnkSite == NULL) return E_FAIL; return m_pUnkSite ->QueryInterface(riid, ppvSite); } //IWizardExtension STDMETHODIMP CDot11SampleExtUI::AddPages ( HPROPSHEETPAGE* aPages, UINT cPages, UINT *pnPagesAdded ) { IPropertyBag *pIPropertyBag = NULL; UNREFERENCED_PARAMETER(cPages); HRESULT hr = m_pUnkSite->QueryInterface(IID_IPropertyBag, (VOID **)&pIPropertyBag); if (SUCCEEDED(hr)) { VARIANT v; VariantInit(&v); WCHAR ihvKeyName[IHV_KEY_LENGTH]; GetClsidPropertyName ( & GUID_SAMPLE_IHVUI_CLSID, (LPWSTR) c_szIhvUIRequest, ihvKeyName, IHV_KEY_LENGTH ); hr = pIPropertyBag->Read( ihvKeyName, &v, NULL); if (SUCCEEDED(hr) && (VT_BSTR == V_VT(&v))) { if( m_pUIRequest == NULL) { m_pUIRequest = new(std::nothrow) IHV_UI_REQUEST; if (m_pUIRequest == NULL) { VariantClear(&v); pIPropertyBag->Release(); return E_OUTOFMEMORY; } } memcpy(m_pUIRequest, v.bstrVal, sizeof(IHV_UI_REQUEST)); } VariantClear(&v); pIPropertyBag->Release(); } //////////////// *pnPagesAdded = 0; PROPSHEETPAGE psp = {0}; psp.dwSize = sizeof( psp); psp.hInstance = g_hInst; psp.dwFlags = PSP_DEFAULT | PSP_USETITLE | PSP_USEHEADERTITLE; psp.lParam = (LPARAM) this; psp.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG_SHOWHELP); psp.pfnDlgProc = (DLGPROC) CDot11SampleExtUI::HelpDlgProc; psp.pszHeaderTitle = MAKEINTRESOURCE( IDS_TITLE_SHOWHELP); m_hFirstPagePsp = CreatePropertySheetPage(& psp); psp.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG_GETKEY); psp.pfnDlgProc = (DLGPROC) CDot11SampleExtUI::GetKeyDlgProc; psp.pszHeaderTitle = MAKEINTRESOURCE( IDS_TITLE_GETKEY); HPROPSHEETPAGE hPsp= CreatePropertySheetPage(& psp); psp.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG_LASTPAGE); psp.pfnDlgProc = (DLGPROC) CDot11SampleExtUI::LastPageDlgProc; psp.pszHeaderTitle = MAKEINTRESOURCE( IDS_TITLE_LASTPAGE); m_hLastPagePsp = CreatePropertySheetPage(& psp); if( m_hFirstPagePsp && hPsp && m_hLastPagePsp) { aPages[0] = m_hFirstPagePsp; aPages[1] = hPsp; aPages[2] = m_hLastPagePsp; *pnPagesAdded = 3; return S_OK; } else { if(m_hFirstPagePsp) { DestroyPropertySheetPage(m_hFirstPagePsp); } if(hPsp) { DestroyPropertySheetPage(hPsp); } if(m_hLastPagePsp) { DestroyPropertySheetPage(m_hLastPagePsp); } m_hFirstPagePsp = hPsp = m_hLastPagePsp = NULL; return E_FAIL; } } STDMETHODIMP CDot11SampleExtUI::GetFirstPage ( HPROPSHEETPAGE *phpage ) { *phpage = m_hFirstPagePsp; return S_OK; } STDMETHODIMP CDot11SampleExtUI::GetLastPage (HPROPSHEETPAGE *phpage) { * phpage = m_hLastPagePsp; return S_OK; } BOOL CALLBACK CDot11SampleExtUI::HelpDlgProc ( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { CDot11SampleExtUI* pthis = NULL; switch (uMsg) { case WM_INITDIALOG: { pthis = GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); if(pthis && pthis->m_pUIRequest) { // // Convert the ANSI string into a WCHAR string and display it // int iBufferSize = MultiByteToWideChar(CP_ACP, 0, pthis->m_pUIRequest->title, -1, NULL, 0); if (iBufferSize > 0) { WCHAR *pwszBuffer = new WCHAR[iBufferSize]; if (NULL != pwszBuffer) { pwszBuffer[0] = 0; (VOID)MultiByteToWideChar(CP_ACP, 0, pthis->m_pUIRequest->title, -1, pwszBuffer, iBufferSize); SetDlgItemText(hwndDlg, IDC_EDIT_HELPER, pwszBuffer); delete[] pwszBuffer; } } } } return TRUE; case WM_DESTROY: { // Don't release our properties here, wait // rather for Abort or Commit event notifications. // Then we will have the same values when resurrected. } return TRUE; case WM_NOTIFY: { LPNMHDR pnmh = (LPNMHDR) lParam; switch (pnmh->code) { case PSN_SETACTIVE : PropSheet_SetWizButtons(GetParent(hwndDlg), PSWIZB_NEXT); return TRUE; case PSN_QUERYCANCEL: { IWizardSite *pIWizardSite = NULL; HRESULT hr = S_OK; pthis = GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); if(pthis != NULL) { hr = pthis->m_pUnkSite->QueryInterface(IID_IWizardSite, (VOID **)&pIWizardSite); if (SUCCEEDED(hr)) { HPROPSHEETPAGE hpage = NULL; hr = pIWizardSite->GetCancelledPage(&hpage); if (SUCCEEDED(hr)) { PropSheet_SetCurSel(GetParent(hwndDlg), hpage, 0); } pIWizardSite->Release(); } } } return TRUE; } } return FALSE; } return FALSE; } BOOL CALLBACK CDot11SampleExtUI::GetKeyDlgProc ( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { CDot11SampleExtUI* pthis = NULL; switch (uMsg) { case WM_INITDIALOG: { (VOID)GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); } return TRUE; case WM_DESTROY: { // Don't release our properties here, wait // rather for Abort or Commit event notifications. // Then we will have the same values when resurrected. } return TRUE; case WM_NOTIFY: { LPNMHDR pnmh = (LPNMHDR) lParam; switch (pnmh->code) { case PSN_SETACTIVE : PropSheet_SetWizButtons(GetParent(hwndDlg), PSWIZB_BACK | PSWIZB_NEXT); return TRUE; case PSN_WIZNEXT : { WCHAR szBuffer[50 + 1] = {0}; HRESULT hr = S_OK; IPropertyBag *pIPropertyBag = NULL; GetDlgItemText(hwndDlg, IDC_EDIT_KEY, szBuffer, 50); pthis = GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); if(pthis) { hr = pthis->m_pUnkSite->QueryInterface(IID_IPropertyBag, (VOID **)&pIPropertyBag); if (SUCCEEDED(hr)) { VARIANT v; VariantInit(&v); WCHAR ihvKeyName[IHV_KEY_LENGTH] = {0}; pthis->GetClsidPropertyName( &GUID_SAMPLE_IHVUI_CLSID, (LPWSTR) c_szIhvUIResponse, ihvKeyName, IHV_KEY_LENGTH ); // Make sure we remove the previous property if any hr = pIPropertyBag->Read(ihvKeyName, &v, NULL); VariantClear(&v); V_VT(&v) = VT_BSTR; v.bstrVal = SysAllocStringByteLen((LPCSTR)szBuffer, IHV_KEY_LENGTH); // Write the updated property if any hr = pIPropertyBag->Write(ihvKeyName, &v); pIPropertyBag->Release(); // // hr is not used below // hr; } } } return TRUE; case PSN_QUERYCANCEL: { IWizardSite *pIWizardSite = NULL; HRESULT hr = S_OK; pthis = GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); if(pthis) { hr = pthis->m_pUnkSite->QueryInterface(IID_IWizardSite,(VOID **)&pIWizardSite); if (SUCCEEDED(hr)) { HPROPSHEETPAGE hpage = NULL; hr = pIWizardSite->GetCancelledPage(&hpage); if (SUCCEEDED(hr)) { PropSheet_SetCurSel(GetParent(hwndDlg), hpage, 0); } pIWizardSite->Release(); } } } return TRUE; } } return FALSE; } return FALSE; } BOOL CALLBACK CDot11SampleExtUI::LastPageDlgProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { CDot11SampleExtUI* pthis = NULL; switch (uMsg) { case WM_INITDIALOG: { (VOID)GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); } return TRUE; case WM_DESTROY: { (VOID)GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); } return TRUE; case WM_NOTIFY: { LPNMHDR pnmh = (LPNMHDR) lParam; switch (pnmh->code) { case PSN_SETACTIVE : PropSheet_SetWizButtons(GetParent(hwndDlg), PSWIZB_BACK | PSWIZB_NEXT); return TRUE; case PSN_WIZNEXT : { IWizardSite *pIWizardSite = NULL; HRESULT hr = S_OK; pthis = GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); if(pthis) { hr = pthis->m_pUnkSite->QueryInterface(IID_IWizardSite,(VOID **)&pIWizardSite); if (SUCCEEDED(hr)) { HPROPSHEETPAGE hpage = NULL; hr = pIWizardSite->GetNextPage(&hpage); if (SUCCEEDED(hr)) { PropSheet_SetCurSel(GetParent(hwndDlg), hpage, 0); } pIWizardSite->Release(); } } SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LPARAM)-1); } return TRUE; case PSN_QUERYCANCEL: { IWizardSite *pIWizardSite = NULL; HRESULT hr = S_OK; pthis = GetThis<CDot11SampleExtUI>(hwndDlg, uMsg, wParam, lParam); if(pthis) { hr = pthis->m_pUnkSite->QueryInterface(IID_IWizardSite,(VOID **)&pIWizardSite); if (SUCCEEDED(hr)) { HPROPSHEETPAGE hpage = NULL; hr = pIWizardSite->GetCancelledPage(&hpage); if (SUCCEEDED(hr)) { PropSheet_SetCurSel(GetParent(hwndDlg), hpage, 0); } pIWizardSite->Release(); } } } return TRUE; } } return FALSE; } return FALSE; } HRESULT CDot11SampleExtUI::GetClsidPropertyName ( _In_ const CLSID* pCLSID, _In_opt_ PCWSTR pwszPropertyName, _Out_writes_(maxResultLen) PWSTR pwszResultStr, _In_ UINT maxResultLen) { #define MIN_BUFFER_SIZE 50 wchar_t *pwszCLSID = NULL; wchar_t *pwszKeyName = NULL; HRESULT hRetCode = S_OK; size_t iCharCount = 0; // Sanity //======= if( pCLSID == NULL || pwszResultStr == NULL || maxResultLen < MIN_BUFFER_SIZE ) { return E_INVALIDARG; } // Convert CLSID to string //======================== hRetCode = StringFromCLSID(*pCLSID, &pwszCLSID); if(FAILED(hRetCode)) { goto Done; } // Allocate buffer for entire CLSID\PropertyName string //===================================================== iCharCount = wcslen(pwszCLSID) + 1; if(pwszPropertyName) { iCharCount += wcslen(pwszPropertyName); } pwszKeyName = new(std::nothrow) wchar_t[iCharCount]; if(pwszKeyName == NULL) { hRetCode = E_OUTOFMEMORY; goto Done; } swprintf_s(pwszKeyName, iCharCount, L"%s%s", pwszCLSID, pwszPropertyName ? pwszPropertyName : L""); // Copy as much as we can to the target buffer //============================================ wcsncpy_s(pwszResultStr, maxResultLen, pwszKeyName, _TRUNCATE); Done: if(pwszKeyName != NULL) { delete [] pwszKeyName; } if(pwszCLSID != NULL) { CoTaskMemFree(pwszCLSID); } return hRetCode; }
15,308
428
<reponame>cping/LGame package org.test.towerdefense; import loon.action.sprite.painting.IGameComponent; import loon.events.SysInput; import loon.geom.Vector2f; import loon.utils.timer.GameTime; public class MonsterInfoScreen extends MenuScreen { private java.util.ArrayList<AnimatedSprite> animatedSprites; private MainGame game; private boolean isFirstExit; private MonsterInfoScreenSpriteWithText monsterInfoScreenSpriteWithText; public MonsterInfoScreen(MainGame game, ScreenType prevScreen) { super("", game, prevScreen); this.isFirstExit = true; this.game = game; super.setScreenType(ScreenType.MonsterInfoScreen); super.setTransitionOnTime(0f); super.setTransitionOffTime(0.5f); MenuEntry item = new MenuEntry(""); item.setuseButtonBackground(false); item.setPosition(new Vector2f(110f, 422f)); item.setnoButtonBackgroundSize(new Vector2f(120f, 38f)); item.Selected = new GameEvent() { @Override public void invoke(MenuEntry comp) { StartInstructionsMenuEntrySelected(); } }; super.getMenuEntries().add(item); this.monsterInfoScreenSpriteWithText = new MonsterInfoScreenSpriteWithText( game); } private void Exit() { if (this.monsterInfoScreenSpriteWithText != null) { this.game.Components().remove(this.monsterInfoScreenSpriteWithText); } } @Override public void HandleInput(GameTime gameTime, SysInput input) { super.HandleInput(gameTime, input); } @Override public void LoadContent() { this.animatedSprites = AnimatedSpriteMonster .GetAllAnimatedSpriteMonsters(this.game); for (AnimatedSprite sprite : this.animatedSprites) { sprite.setOnlyAnimateIfGameStateStarted(false); sprite.setObeyGameOpacity(false); super.getScreenManager().getGame().Components().add(sprite); } } @Override protected void OnCancel() { this.Exit(); super.getScreenManager().ExitAllScreens(); super.OnCancel(); } private void StartInstructionsMenuEntrySelected() { this.Exit(); super.getScreenManager().ExitAllScreens(); super.getScreenManager().AddScreen( new InstructionScreen(this.game, ScreenType.MonsterInfoScreen)); } @Override public void Update(GameTime gameTime, boolean otherScreenHasFocus, boolean coveredByOtherScreen) { if (super.getIsExiting() && this.isFirstExit) { for (IGameComponent component : this.animatedSprites) { super.getScreenManager().getGame().Components() .remove(component); } this.isFirstExit = false; } super.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); } }
878
348
<filename>docs/data/leg-t2/080/08004259.json<gh_stars>100-1000 {"nom":"Dromesnil","circ":"4ème circonscription","dpt":"Somme","inscrits":87,"abs":28,"votants":59,"blancs":8,"nuls":1,"exp":50,"res":[{"nuance":"REM","nom":"<NAME>","voix":29},{"nuance":"FN","nom":"<NAME>","voix":21}]}
118
868
package com.sedmelluq.discord.lavaplayer.track.playback; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A provider for audio frames */ public interface AudioFrameProvider { /** * @return Provided frame, or null if none available */ AudioFrame provide(); /** * @param timeout Specifies the maximum time to wait for data. Pass 0 for non-blocking mode. * @param unit Specifies the time unit of the maximum wait time. * @return Provided frame. In case wait time is above zero, null indicates that no data is not available at the * current moment, otherwise null means the end of the track. * @throws TimeoutException When wait time is above zero, but no track info is found in that time. * @throws InterruptedException When interrupted externally (or for seek/stop). */ AudioFrame provide(long timeout, TimeUnit unit) throws TimeoutException, InterruptedException; /** * @param targetFrame Frame to update with the details and data of the provided frame. * @return <code>true</code> if a frame was provided. */ boolean provide(MutableAudioFrame targetFrame); /** * @param targetFrame Frame to update with the details and data of the provided frame. * @param timeout Timeout. * @param unit Time unit for the timeout value. * @return <code>true</code> if a frame was provided. * @throws TimeoutException If no frame became available within the timeout. * @throws InterruptedException When interrupted externally (or for seek/stop). */ boolean provide(MutableAudioFrame targetFrame, long timeout, TimeUnit unit) throws TimeoutException, InterruptedException; }
468
305
//===-- ActivityStore.h -----------------------------------------*- C++ -*-===// // // 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 // //===----------------------------------------------------------------------===// #ifndef LLDB_TOOLS_DEBUGSERVER_SOURCE_MACOSX_DARWINLOG_ACTIVITYSTORE_H #define LLDB_TOOLS_DEBUGSERVER_SOURCE_MACOSX_DARWINLOG_ACTIVITYSTORE_H #include <string> #include "ActivityStreamSPI.h" class ActivityStore { public: virtual ~ActivityStore(); virtual const char *GetActivityForID(os_activity_id_t activity_id) const = 0; virtual std::string GetActivityChainForID(os_activity_id_t activity_id) const = 0; protected: ActivityStore(); }; #endif // LLDB_TOOLS_DEBUGSERVER_SOURCE_MACOSX_DARWINLOG_ACTIVITYSTORE_H
295
12,824
<reponame>tanishiking/dotty<gh_stars>1000+ public class J { @Override public void foo() { } public void bar() { foo(); } }
46
922
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Code to assist in the compression of structured-pruned models """ from typing import Dict, List, Set, Union import onnx from sparseml.onnx.utils import ONNXGraph, get_node_attributes __all__ = ["get_param_structured_pruning_group_dependencies"] _PRUNABLE_OP_TYPES = ["Conv", "Gemm", "MatMul"] _OUTPUT_CHANNEL_OP_TYPES = _PRUNABLE_OP_TYPES + ["BatchNormalization"] def get_param_structured_pruning_group_dependencies( model: Union[onnx.ModelProto, str], structure_type: str = "filter", ) -> Dict[str, List[str]]: """ :param model: model to generate pruning groups and dependencies for :param structure_type: valid options are 'filter' and 'channel'. Generates dependency map for corresponding pruning scheme. Default is 'filter' :return: dictionary of parameter names that should be grouped during structured pruning to a list of parameter names whose parameters should be updated accordingly to the param group pruning results. prunable parameter names will be represented as a comma separated string """ if structure_type not in ["filter", "channel"]: raise ValueError( f"invalid structure_type {structure_type}. not in ['filter', 'channel']" ) if isinstance(model, str): model = onnx.load(model) graph = ONNXGraph(model) param_name_to_dependents = {} # Dict[str, Set[str]] for node in model.graph.node: if node.op_type not in _PRUNABLE_OP_TYPES or ( graph.get_init_by_name(node.input[1]) is None ): # main param not found or not prunable continue param_name_to_dependents[node.input[1]] = _get_node_dependency_names( graph, node, structure_type ) # merge disjoint sets of dependencies (could improve with union-find) prunable_param_group_to_dep_params = [] # List[Tuple[List, Set]] for prunable_param_name, dep_params in param_name_to_dependents.items(): intersected_group_idxs = { idx for idx, (_, group_dep_params) in enumerate( prunable_param_group_to_dep_params ) if not dep_params.isdisjoint(group_dep_params) } new_group_val = ([prunable_param_name], dep_params) if not intersected_group_idxs: prunable_param_group_to_dep_params.append(new_group_val) else: non_intersected_vals = [] for idx, (prunable_param_group, group_dep_params) in enumerate( prunable_param_group_to_dep_params ): if idx not in intersected_group_idxs: non_intersected_vals.append( (prunable_param_group, group_dep_params) ) else: new_group_val = ( new_group_val[0] + prunable_param_group, new_group_val[1].union(group_dep_params), ) prunable_param_group_to_dep_params = non_intersected_vals + [new_group_val] return { ",".join(prunable_param_group): list(dependent_params) for prunable_param_group, dependent_params in prunable_param_group_to_dep_params } def _get_next_layer_deps( graph: ONNXGraph, node: onnx.NodeProto, structure_type: str ) -> List[onnx.NodeProto]: return ( [ parent_node for parent_node in graph.get_node_parents(node) if isinstance(parent_node, onnx.NodeProto) ] if structure_type == "channel" else graph.get_node_children(node) ) def _get_node_output_ids(nodes: List[onnx.NodeProto]) -> Set[str]: if isinstance(nodes, onnx.NodeProto): nodes = [nodes] ids = set() for node in nodes: ids.update(set(node.output)) return ids def _get_node_dependency_names( graph: ONNXGraph, node: onnx.NodeProto, structure_type: str ) -> Set[str]: # returns a list of parameters whose should be pruned to match # the target dimensions of this node unchecked_nodes = _get_next_layer_deps(graph, node, structure_type) seen_output_ids = _get_node_output_ids(unchecked_nodes) dependent_params = set() if structure_type == "filter" and len(node.input) > 2: # node bias depends on num filters dependent_params.add(node.input[2]) while unchecked_nodes: current_node = unchecked_nodes.pop(0) if not isinstance(current_node, onnx.NodeProto): continue if current_node.op_type in _OUTPUT_CHANNEL_OP_TYPES: prunable = current_node.op_type in _PRUNABLE_OP_TYPES params = ( list(current_node.input[1:]) # skip layer input tensor if not (prunable and structure_type != "filter") else [current_node.input[1]] # bias not dependent on prev filter ) for param in params: if graph.get_init_by_name(param) is not None: dependent_params.add(param) if prunable and not _is_group_conv(current_node): # continue on other branches, do not go past prunable nodes continue dep_nodes = _get_next_layer_deps(graph, current_node, structure_type) for dep_node in dep_nodes: dep_node_ids = _get_node_output_ids(dep_node) if dep_node_ids.isdisjoint(seen_output_ids): unchecked_nodes.append(dep_node) seen_output_ids.update(dep_node_ids) return dependent_params def _is_group_conv(node: onnx.NodeProto) -> bool: if not node.op_type == "Conv": return False attrs = get_node_attributes(node) groups = attrs.get("group", 1) try: return int(groups) != 1 except Exception: return False
2,810
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-qj5f-6rc3-vgfv", "modified": "2022-03-30T00:01:02Z", "published": "2022-03-24T00:00:19Z", "aliases": [ "CVE-2021-27471" ], "details": "The parsing mechanism that processes certain file types does not provide input sanitization for file paths. This may allow an attacker to craft malicious files that, when opened by Rockwell Automation Connected Components Workbench v12.00.00 and prior, can traverse the file system. If successfully exploited, an attacker could overwrite existing files and create additional files with the same permissions of the Connected Components Workbench software. User interaction is required for this exploit to be successful.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-27471" }, { "type": "WEB", "url": "https://rockwellautomation.custhelp.com/app/answers/answer_view/a_id/1131435" }, { "type": "WEB", "url": "https://www.cisa.gov/uscert/ics/advisories/icsa-21-133-01" } ], "database_specific": { "cwe_ids": [ "CWE-22" ], "severity": "HIGH", "github_reviewed": false } }
561
1,269
<gh_stars>1000+ package class_bytecode; import java.io.Serializable; @Deprecated public class Client implements Serializable { @Deprecated private String username; @Deprecated public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public static void main(String[] args) { Client client = new Client(); client.setUsername("Chiclaim"); System.out.println(client.getUsername()); } }
193
772
<gh_stars>100-1000 { "startButton": "crwdns110214:0crwdne110214:0", "filterOrgNames": "crwdns92060:0crwdne92060:0", "filterOrgNamesAll": "crwdns92061:0crwdne92061:0", "filterSortBy": "crwdns95803:0crwdne95803:0", "filterSortByDisplayWeight": "crwdns95804:0crwdne95804:0", "filterSortByPopularityRank": "crwdns95805:0crwdne95805:0", "filterGrades": "crwdns69336:0crwdne69336:0", "filterGradesAll": "crwdns96012:0crwdne96012:0", "filterGradesPre": "crwdns69337:0crwdne69337:0", "filterGrades25": "crwdns69338:0crwdne69338:0", "filterGrades68": "crwdns69339:0crwdne69339:0", "filterGrades9": "crwdns69340:0crwdne69340:0", "filterStudentExperience": "crwdns69344:0crwdne69344:0", "filterStudentExperienceBeginner": "crwdns69345:0crwdne69345:0", "filterStudentExperienceComfortable": "crwdns69346:0crwdne69346:0", "filterStudentExperienceExperienced": "crwdns96014:0crwdne96014:0", "filterPlatform": "crwdns69347:0crwdne69347:0", "filterPlatformComputers": "crwdns69348:0crwdne69348:0", "filterPlatformAndroid": "crwdns69349:0crwdne69349:0", "filterPlatformIos": "crwdns69350:0crwdne69350:0", "filterPlatformNoInternet": "crwdns69351:0crwdne69351:0", "filterPlatformNoComputers": "crwdns69352:0crwdne69352:0", "filterPlatformScreenReader": "crwdns2471098:0crwdne2471098:0", "filterTopics": "crwdns69353:0crwdne69353:0", "filterTopicsScience": "crwdns69354:0crwdne69354:0", "filterTopicsMath": "crwdns69355:0crwdne69355:0", "filterTopicsHistory": "crwdns69356:0crwdne69356:0", "filterTopicsLa": "crwdns69357:0crwdne69357:0", "filterTopicsArt": "crwdns69358:0crwdne69358:0", "filterTopicsCsOnly": "crwdns69359:0crwdne69359:0", "filterActivityType": "crwdns69360:0crwdne69360:0", "filterActivityTypeOnlineTutorial": "crwdns69361:0crwdne69361:0", "filterActivityTypeLessonPlan": "crwdns69362:0crwdne69362:0", "filterLength": "crwdns69363:0crwdne69363:0", "filterLength1Hour": "crwdns69364:0crwdne69364:0", "filterLength1HourFollow": "crwdns69365:0crwdne69365:0", "filterLengthFewHours": "crwdns69366:0crwdne69366:0", "filterProgrammingLanguage": "crwdns69367:0crwdne69367:0", "filterProgrammingLanguageBlocks": "crwdns69368:0crwdne69368:0", "filterProgrammingLanguageTyping": "crwdns69369:0crwdne69369:0", "filterProgrammingLanguageOther": "crwdns69370:0crwdne69370:0", "filterActivityTypeRobotics": "crwdns69371:0crwdne69371:0", "backButtonBack": "crwdns69372:0crwdne69372:0", "filterHeaderShowFilters": "crwdns69374:0crwdne69374:0", "filterHeaderHideFilters": "crwdns69375:0crwdne69375:0", "filterHeaderTutorialCountSingle": "crwdns69376:0crwdne69376:0", "filterHeaderTutorialCountPlural": "crwdns69377:0{tutorial_count}crwdne69377:0", "roboticsButtonText": "crwdns69381:0crwdne69381:0", "roboticsText": "crwdns69382:0crwdne69382:0", "tutorialSetNoTutorials": "crwdns69383:0crwdne69383:0", "tutorialDetailsMoreResources": "crwdns2059830:0crwdne2059830:0", "tutorialDetailsTeacherNotes": "crwdns69384:0crwdne69384:0", "tutorialDetailsShortLink": "crwdns69385:0crwdne69385:0", "tutorialDetailInternationalLanguages": "crwdns69386:0crwdne69386:0", "tutorialDetailStandards": "crwdns69387:0crwdne69387:0", "tutorialDetailDisabled": "crwdns69388:0crwdne69388:0", "headingTutorialsYourLanguage": "crwdns69389:0crwdne69389:0", "showAllTutorialsButton": "crwdns69390:0crwdne69390:0", "hideAllTutorialsButton": "crwdns69391:0crwdne69391:0", "noTutorialsYourLanguage": "crwdns69392:0crwdne69392:0", "bottomGuidelinesLink": "crwdns69393:0crwdne69393:0", "bottomSpecialNeedsLink": "crwdns69394:0crwdne69394:0" }
1,539
12,278
<reponame>rajeev02101987/arangodb /*============================================================================= Copyright (c) 2017 <NAME> sequence.cpp Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ /*============================================================================= Copyright (c) 2016 <NAME> print.cpp Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #include "example.h" #include <tuple> using namespace boost::hof; // Transform each element of a tuple by calling f BOOST_HOF_STATIC_LAMBDA_FUNCTION(tuple_transform) = [](auto&& sequence, auto f) { return unpack(proj(f, construct<std::tuple>()))(std::forward<decltype(sequence)>(sequence)); }; // Call f on each element of tuple BOOST_HOF_STATIC_LAMBDA_FUNCTION(tuple_for_each) = [](auto&& sequence, auto f) { return unpack(proj(f))(std::forward<decltype(sequence)>(sequence)); }; // Fold over tuple using a f as the binary operator BOOST_HOF_STATIC_LAMBDA_FUNCTION(tuple_fold) = [](auto&& sequence, auto f) { return unpack(fold(f))(std::forward<decltype(sequence)>(sequence)); }; // Concat multiple tuples BOOST_HOF_STATIC_FUNCTION(tuple_cat) = unpack(construct<std::tuple>()); // Join a tuple of tuples into just a tuple BOOST_HOF_STATIC_FUNCTION(tuple_join) = unpack(tuple_cat); // Filter elements in a tuple using a predicate BOOST_HOF_STATIC_LAMBDA_FUNCTION(tuple_filter) = [](auto&& sequence, auto predicate) { return compose(tuple_join, tuple_transform)( std::forward<decltype(sequence)>(sequence), [&](auto&& x) { return first_of( if_(predicate(std::forward<decltype(x)>(x)))(pack), always(pack()) )(std::forward<decltype(x)>(x)); } ); }; // Zip two tuples together BOOST_HOF_STATIC_LAMBDA_FUNCTION(tuple_zip_with) = [](auto&& sequence1, auto&& sequence2, auto f) { auto&& functions = tuple_transform( std::forward<decltype(sequence1)>(sequence1), [&](auto&& x) { return [&](auto&& y) { return f(std::forward<decltype(x)>(x), std::forward<decltype(y)>(y)); }; } ); auto combined = unpack(capture(construct<std::tuple>())(combine))(functions); return unpack(combined)(std::forward<decltype(sequence2)>(sequence2)); }; // Dot product of a tuple BOOST_HOF_STATIC_LAMBDA_FUNCTION(tuple_dot) = [](auto&& a, auto&& b) { auto product = tuple_zip_with(a, b, [](auto x, auto y) { return x*y; }); return tuple_fold(product, [](auto x, auto y) { return x+y; }); }; void run_each() { auto t = std::make_tuple(1, 2); tuple_for_each(t, [](int i) { std::cout << i << std::endl; }); } void run_transform() { auto t = std::make_tuple(1, 2); auto r = tuple_transform(t, [](int i) { return i*i; }); assert(r == std::make_tuple(1, 4)); (void)r; } void run_filter() { auto t = std::make_tuple(1, 2, 'x', 3); auto r = tuple_filter(t, [](auto x) { return std::is_same<int, decltype(x)>(); }); assert(r == std::make_tuple(1, 2, 3)); (void)r; } void run_zip() { auto t1 = std::make_tuple(1, 2); auto t2 = std::make_tuple(3, 4); auto p = tuple_zip_with(t1, t2, [](auto x, auto y) { return x*y; }); int r = tuple_fold(p, [](auto x, auto y) { return x+y; }); assert(r == (1*3 + 4*2)); (void)r; } void run_dot() { auto t1 = std::make_tuple(1, 2); auto t2 = std::make_tuple(3, 4); int r = tuple_dot(t1, t2); assert(r == (1*3 + 4*2)); (void)r; } int main() { run_transform(); run_filter(); run_zip(); }
1,623
2,996
<reponame>Elyahu41/Terasology // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.rendering.dag; /** * TODO: Add javadocs */ public interface RenderPipelineTask { void process(); }
88
2,151
<reponame>hustwei/libwebm // Copyright (c) 2016 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include "src/ebml_parser.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "test_utils/element_parser_test.h" #include "webm/id.h" using webm::Ebml; using webm::EbmlParser; using webm::ElementParserTest; using webm::Id; namespace { class EbmlParserTest : public ElementParserTest<EbmlParser, Id::kEbml> {}; TEST_F(EbmlParserTest, DefaultParse) { EXPECT_CALL(callback_, OnEbml(metadata_, Ebml{})).Times(1); ParseAndVerify(); } TEST_F(EbmlParserTest, DefaultValues) { SetReaderData({ 0x42, 0x86, // ID = 0x4286 (EBMLVersion). 0x80, // Size = 0. 0x42, 0xF7, // ID = 0x42F7 (EBMLReadVersion). 0x80, // Size = 0. 0x42, 0xF2, // ID = 0x42F2 (EBMLMaxIDLength). 0x40, 0x00, // Size = 0. 0x42, 0xF3, // ID = 0x42F3 (EBMLMaxSizeLength). 0x80, // Size = 0. 0xEC, // ID = 0xEC (Void). 0x40, 0x00, // Size = 0. 0x42, 0x82, // ID = 0x4282 (DocType). 0x40, 0x00, // Size = 0. 0x42, 0x87, // ID = 0x4287 (DocTypeVersion). 0x80, // Size = 0. 0x42, 0x85, // ID = 0x4285 (DocTypeReadVersion). 0x80, // Size = 0. 0xEC, // ID = 0xEC (Void). 0x82, // Size = 2. 0x01, 0x02, // Body. }); Ebml ebml; ebml.ebml_version.Set(1, true); ebml.ebml_read_version.Set(1, true); ebml.ebml_max_id_length.Set(4, true); ebml.ebml_max_size_length.Set(8, true); ebml.doc_type.Set("matroska", true); ebml.doc_type_version.Set(1, true); ebml.doc_type_read_version.Set(1, true); EXPECT_CALL(callback_, OnEbml(metadata_, ebml)).Times(1); ParseAndVerify(); } TEST_F(EbmlParserTest, CustomValues) { SetReaderData({ 0x42, 0x86, // ID = 0x4286 (EBMLVersion). 0x81, // Size = 1. 0x02, // Body (value = 2). 0x42, 0xF7, // ID = 0x42F7 (EBMLReadVersion). 0x81, // Size = 1. 0x04, // Body (value = 4). 0x42, 0xF2, // ID = 0x42F2 (EBMLMaxIDLength). 0x40, 0x02, // Size = 2. 0x00, 0x02, // Body (value = 2). 0x42, 0xF3, // ID = 0x42F3 (EBMLMaxSizeLength). 0x81, // Size = 1. 0x04, // Body (value = 4). 0xEC, // ID = 0xEC (Void). 0x40, 0x00, // Size = 0. 0x42, 0x82, // ID = 0x4282 (DocType). 0x40, 0x02, // Size = 2. 0x48, 0x69, // Body (value = "Hi"). 0x42, 0x87, // ID = 0x4287 (DocTypeVersion). 0x81, // Size = 1. 0xFF, // Body (value = 255). 0x42, 0x85, // ID = 0x4285 (DocTypeReadVersion). 0x81, // Size = 1. 0x02, // Body (value = 2). 0xEC, // ID = 0xEC (Void). 0x82, // Size = 2. 0x01, 0x02, // Body. }); Ebml ebml; ebml.ebml_version.Set(2, true); ebml.ebml_read_version.Set(4, true); ebml.ebml_max_id_length.Set(2, true); ebml.ebml_max_size_length.Set(4, true); ebml.doc_type.Set("Hi", true); ebml.doc_type_version.Set(255, true); ebml.doc_type_read_version.Set(2, true); EXPECT_CALL(callback_, OnEbml(metadata_, ebml)).Times(1); ParseAndVerify(); } } // namespace
1,662
1,473
/* * Copyright 2019 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.plugin.rabbitmq.client; import com.navercorp.pinpoint.bootstrap.instrument.InstrumentClass; import com.navercorp.pinpoint.bootstrap.instrument.InstrumentException; import com.navercorp.pinpoint.bootstrap.instrument.InstrumentMethod; import com.navercorp.pinpoint.bootstrap.instrument.MethodFilter; import com.navercorp.pinpoint.bootstrap.instrument.MethodFilters; import com.navercorp.pinpoint.plugin.rabbitmq.client.interceptor.ConsumerHandleDeliveryInterceptor; import java.lang.reflect.Modifier; /** * @author <NAME>(emeroad) */ public final class RabbitMQUtils { private RabbitMQUtils() { } public static boolean addConsumerHandleDeliveryInterceptor(InstrumentClass target) throws InstrumentException { if (target == null) { return false; } final InstrumentMethod handleDelivery = target.getDeclaredMethod("handleDelivery", "java.lang.String", "com.rabbitmq.client.Envelope", "com.rabbitmq.client.AMQP$BasicProperties", "byte[]"); if (handleDelivery == null) { return false; } handleDelivery.addScopedInterceptor(ConsumerHandleDeliveryInterceptor.class, RabbitMQClientConstants.RABBITMQ_CONSUMER_SCOPE); return true; } public static MethodFilter getPublicApiFilter() { // RabbitTemplate // public APIs final MethodFilter publicApiFilter = MethodFilters.chain( MethodFilters.name("execute", "convertAndSend", "convertSendAndReceive", "convertSendAndReceiveAsType", "correlationConvertAndSend", "doSend", "send", "sendAndReceive", "receive", "receiveAndConvert", "receiveAndReply"), MethodFilters.modifier(Modifier.PUBLIC)); return publicApiFilter; } }
839
993
/** * Copyright 2015 Netflix, Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.servo.publish.atlas; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.netflix.servo.Metric; import com.netflix.servo.monitor.MonitorConfig; import com.netflix.servo.tag.BasicTag; import com.netflix.servo.tag.BasicTagList; import com.netflix.servo.tag.Tag; import org.testng.annotations.Test; import java.io.IOException; import java.io.StringWriter; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; public class ValidCharactersTest { @Test public void testValidStrIsUnchanged() throws Exception { String valid = "abc09.-_"; assertEquals(ValidCharacters.toValidCharset(valid), valid); } @Test public void testInvalidStrIsFixed() throws Exception { String str = "Aabc09.-~^_ abc"; assertEquals(ValidCharacters.toValidCharset(str), "Aabc09.-____abc"); String boundaries = "\u0000\u0128\uffff"; assertEquals(ValidCharacters.toValidCharset(boundaries), "___"); } @Test public void testValidStr() throws Exception { String valid = "AZabc09.-_"; assertFalse(ValidCharacters.hasInvalidCharacters(valid)); } @Test public void testInvalidStr() throws Exception { String caret = "abc09.-_^abc"; assertTrue(ValidCharacters.hasInvalidCharacters(caret)); String tilde = "abc09.-_~abc"; assertTrue(ValidCharacters.hasInvalidCharacters(tilde)); String str = "abc09.-_ abc"; assertTrue(ValidCharacters.hasInvalidCharacters(str)); String boundaries = "\u0000\u0128\uffff"; assertTrue(ValidCharacters.hasInvalidCharacters(boundaries)); } @Test public void testValidValue() throws Exception { MonitorConfig cfg = MonitorConfig.builder("foo^bar") .withTag("nf.asg", "foo~1") .withTag("nf.cluster", "foo^1.0") .withTag("key^1.0", "val~1.0") .build(); Metric metric = new Metric(cfg, 0, 0.0); Metric fixed = ValidCharacters.toValidValue(metric); Metric expected = new Metric("foo_bar", BasicTagList.of("nf.asg", "foo~1", "nf.cluster", "foo^1.0", "key_1.0", "val_1.0"), 0, 0.0); assertEquals(fixed, expected); } private static JsonFactory factory = new JsonFactory(); static { factory.enable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); } private static String toJson(Tag tag) throws IOException { StringWriter writer = new StringWriter(); JsonGenerator generator = factory.createGenerator(writer); generator.writeStartObject(); ValidCharacters.tagToJson(generator, tag); generator.writeEndObject(); generator.close(); return writer.toString(); } @Test public void testTagToJson() throws Exception { Tag valid = new BasicTag("key", "value"); assertEquals(toJson(valid), "{\"key\":\"value\"}"); Tag invalidKey = new BasicTag("key~^a", "value"); assertEquals(toJson(invalidKey), "{\"key__a\":\"value\"}"); Tag invalidValue = new BasicTag("key", "value~^ 1"); assertEquals(toJson(invalidValue), "{\"key\":\"value___1\"}"); Tag relaxedValue = new BasicTag("nf.asg", "value~^ 1"); assertEquals(toJson(relaxedValue), "{\"nf.asg\":\"value~^_1\"}"); } }
1,326
526
from django.db import models from coderedcms.widgets import ColorPickerWidget from django.forms.widgets import Textarea class ColorField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 255 super().__init__(*args, **kwargs) def formfield(self, **kwargs): kwargs['widget'] = ColorPickerWidget return super().formfield(**kwargs) class MonospaceField(models.TextField): def formfield(self, **kwargs): kwargs["widget"] = Textarea(attrs={ "rows": 12, "class": "monospace", "spellcheck": "false", }) return super().formfield(**kwargs)
281
310
{ "name": "Kingdom Rush (iOS)", "description": "A fantasy action game.", "url": "https://itunes.apple.com/us/app/kingdom-rush/id489265199" }
55
1,338
<reponame>Kirishikesan/haiku #ifndef _MIDI_DEFS_H #define _MIDI_DEFS_H #include <OS.h> #include <Errors.h> //------------------------------------------------------------------------------ /* System time converted to int milliseconds */ #define B_NOW ((uint32)(system_time()/1000)) //------------------------------------------------------------------------------ /* Synthesizer things */ #define B_SYNTH_DIRECTORY B_SYSTEM_DATA_DIRECTORY /* Deprecated */ #define B_BIG_SYNTH_FILE "synth/big_synth.sy" #define B_LITTLE_SYNTH_FILE "synth/little_synth.sy" typedef enum synth_mode { B_NO_SYNTH, B_BIG_SYNTH, B_LITTLE_SYNTH, B_DEFAULT_SYNTH, B_SAMPLES_ONLY } synth_mode; //------------------------------------------------------------------------------ /* Need to move these into Errors.h */ enum { B_BAD_INSTRUMENT = B_MIDI_ERROR_BASE + 0x100, B_BAD_MIDI_DATA, B_ALREADY_PAUSED, B_ALREADY_RESUMED, B_NO_SONG_PLAYING, B_TOO_MANY_SONGS_PLAYING }; //------------------------------------------------------------------------------ #ifndef uchar typedef unsigned char uchar; #endif #ifndef _MIDI_CONSTANTS_ #define _MIDI_CONSTANTS_ /* Channel Message Masks*/ const uchar B_NOTE_OFF = 0x80; const uchar B_NOTE_ON = 0x90; const uchar B_KEY_PRESSURE = 0xa0; const uchar B_CONTROL_CHANGE = 0xb0; const uchar B_PROGRAM_CHANGE = 0xc0; const uchar B_CHANNEL_PRESSURE = 0xd0; const uchar B_PITCH_BEND = 0xe0; /* System Messages*/ const uchar B_SYS_EX_START = 0xf0; const uchar B_MIDI_TIME_CODE = 0xf1; const uchar B_SONG_POSITION = 0xf2; const uchar B_SONG_SELECT = 0xf3; const uchar B_CABLE_MESSAGE = 0xf5; const uchar B_TUNE_REQUEST = 0xf6; const uchar B_SYS_EX_END = 0xf7; const uchar B_TIMING_CLOCK = 0xf8; const uchar B_START = 0xfa; const uchar B_CONTINUE = 0xfb; const uchar B_STOP = 0xfc; const uchar B_ACTIVE_SENSING = 0xfe; const uchar B_SYSTEM_RESET = 0xff; /* Controller Numbers*/ const uchar B_MODULATION = 0x01; const uchar B_BREATH_CONTROLLER = 0x02; const uchar B_FOOT_CONTROLLER = 0x04; const uchar B_PORTAMENTO_TIME = 0x05; const uchar B_DATA_ENTRY = 0x06; const uchar B_MAIN_VOLUME = 0x07; const uchar B_MIDI_BALANCE = 0x08; /* used to be B_BALANCE */ const uchar B_PAN = 0x0a; const uchar B_EXPRESSION_CTRL = 0x0b; const uchar B_GENERAL_CTRL_1 = 0x10; const uchar B_GENERAL_CTRL_2 = 0x11; const uchar B_GENERAL_CTRL_3 = 0x12; const uchar B_GENERAL_CTRL_4 = 0x13; const uchar B_SUSTAIN_PEDAL = 0x40; const uchar B_PORTAMENTO = 0x41; const uchar B_SOSTENUTO = 0x42; const uchar B_SOFT_PEDAL = 0x43; const uchar B_HOLD_2 = 0x45; const uchar B_GENERAL_CTRL_5 = 0x50; const uchar B_GENERAL_CTRL_6 = 0x51; const uchar B_GENERAL_CTRL_7 = 0x52; const uchar B_GENERAL_CTRL_8 = 0x53; const uchar B_EFFECTS_DEPTH = 0x5b; const uchar B_TREMOLO_DEPTH = 0x5c; const uchar B_CHORUS_DEPTH = 0x5d; const uchar B_CELESTE_DEPTH = 0x5e; const uchar B_PHASER_DEPTH = 0x5f; const uchar B_DATA_INCREMENT = 0x60; const uchar B_DATA_DECREMENT = 0x61; const uchar B_RESET_ALL_CONTROLLERS = 0x79; const uchar B_LOCAL_CONTROL = 0x7a; const uchar B_ALL_NOTES_OFF = 0x7b; const uchar B_OMNI_MODE_OFF = 0x7c; const uchar B_OMNI_MODE_ON = 0x7d; const uchar B_MONO_MODE_ON = 0x7e; const uchar B_POLY_MODE_ON = 0x7f; const uchar B_TEMPO_CHANGE = 0x51; #endif // _MIDI_CONSTANTS_ //------------------------------------------------------------------------------ typedef enum midi_axe { /* Pianos */ B_ACOUSTIC_GRAND=0, B_BRIGHT_GRAND, B_ELECTRIC_GRAND, B_HONKY_TONK, B_ELECTRIC_PIANO_1, B_ELECTRIC_PIANO_2, B_HARPSICHORD, B_CLAVICHORD, /* Tuned Idiophones */ B_CELESTA, B_GLOCKENSPIEL, B_MUSIC_BOX, B_VIBRAPHONE, B_MARIMBA, B_XYLOPHONE, B_TUBULAR_BELLS, B_DULCIMER, /* Organs */ B_DRAWBAR_ORGAN, B_PERCUSSIVE_ORGAN, B_ROCK_ORGAN, B_CHURCH_ORGAN, B_REED_ORGAN, B_ACCORDION, B_HARMONICA, B_TANGO_ACCORDION, /* Guitars */ B_ACOUSTIC_GUITAR_NYLON, B_ACOUSTIC_GUITAR_STEEL, B_ELECTRIC_GUITAR_JAZZ, B_ELECTRIC_GUITAR_CLEAN, B_ELECTRIC_GUITAR_MUTED, B_OVERDRIVEN_GUITAR, B_DISTORTION_GUITAR, B_GUITAR_HARMONICS, /* Basses */ B_ACOUSTIC_BASS, B_ELECTRIC_BASS_FINGER, B_ELECTRIC_BASS_PICK, B_FRETLESS_BASS, B_SLAP_BASS_1, B_SLAP_BASS_2, B_SYNTH_BASS_1, B_SYNTH_BASS_2, /* Strings */ B_VIOLIN, B_VIOLA, B_CELLO, B_CONTRABASS, B_TREMOLO_STRINGS, B_PIZZICATO_STRINGS, B_ORCHESTRAL_STRINGS, B_TIMPANI, /* Ensemble strings and voices */ B_STRING_ENSEMBLE_1, B_STRING_ENSEMBLE_2, B_SYNTH_STRINGS_1, B_SYNTH_STRINGS_2, B_VOICE_AAH, B_VOICE_OOH, B_SYNTH_VOICE, B_ORCHESTRA_HIT, /* Brass */ B_TRUMPET, B_TROMBONE, B_TUBA, B_MUTED_TRUMPET, B_FRENCH_HORN, B_BRASS_SECTION, B_SYNTH_BRASS_1, B_SYNTH_BRASS_2, /* Reeds */ B_SOPRANO_SAX, B_ALTO_SAX, B_TENOR_SAX, B_BARITONE_SAX, B_OBOE, B_ENGLISH_HORN, B_BASSOON, B_CLARINET, /* Pipes */ B_PICCOLO, B_FLUTE, B_RECORDER, B_PAN_FLUTE, B_BLOWN_BOTTLE, B_SHAKUHACHI, B_WHISTLE, B_OCARINA, /* Synth Leads*/ B_LEAD_1, B_SQUARE_WAVE = B_LEAD_1, B_LEAD_2, B_SAWTOOTH_WAVE = B_LEAD_2, B_LEAD_3, B_CALLIOPE = B_LEAD_3, B_LEAD_4, B_CHIFF = B_LEAD_4, B_LEAD_5, B_CHARANG = B_LEAD_5, B_LEAD_6, B_VOICE = B_LEAD_6, B_LEAD_7, B_FIFTHS = B_LEAD_7, B_LEAD_8, B_BASS_LEAD = B_LEAD_8, /* Synth Pads */ B_PAD_1, B_NEW_AGE = B_PAD_1, B_PAD_2, B_WARM = B_PAD_2, B_PAD_3, B_POLYSYNTH = B_PAD_3, B_PAD_4, B_CHOIR = B_PAD_4, B_PAD_5, B_BOWED = B_PAD_5, B_PAD_6, B_METALLIC = B_PAD_6, B_PAD_7, B_HALO = B_PAD_7, B_PAD_8, B_SWEEP = B_PAD_8, /* Effects */ B_FX_1, B_FX_2, B_FX_3, B_FX_4, B_FX_5, B_FX_6, B_FX_7, B_FX_8, /* Ethnic */ B_SITAR, B_BANJO, B_SHAMISEN, B_KOTO, B_KALIMBA, B_BAGPIPE, B_FIDDLE, B_SHANAI, /* Percussion */ B_TINKLE_BELL, B_AGOGO, B_STEEL_DRUMS, B_WOODBLOCK, B_TAIKO_DRUMS, B_MELODIC_TOM, B_SYNTH_DRUM, B_REVERSE_CYMBAL, /* Sound Effects */ B_FRET_NOISE, B_BREATH_NOISE, B_SEASHORE, B_BIRD_TWEET, B_TELEPHONE, B_HELICOPTER, B_APPLAUSE, B_GUNSHOT } midi_axe; #endif // _MIDI_DEFS_H
3,543
940
<filename>jbake-core/src/main/java/org/jbake/parser/ErrorEngine.java package org.jbake.parser; import org.jbake.model.DocumentModel; import java.util.Date; /** * An internal rendering engine used to notify the user that the markup format he used requires an engine that couldn't * be loaded. * * @author <NAME> */ public class ErrorEngine extends MarkupEngine { private final String engineName; public ErrorEngine() { this("unknown"); } public ErrorEngine(final String name) { engineName = name; } @Override public void processHeader(final ParserContext context) { DocumentModel documentModel = context.getDocumentModel(); documentModel.setType("post"); documentModel.setStatus("published"); documentModel.setTitle("Rendering engine missing"); documentModel.setDate(new Date()); documentModel.setTags(new String[0]); } @Override public void processBody(final ParserContext context) { context.setBody("The markup engine [" + engineName + "] for [" + context.getFile() + "] couldn't be loaded"); } }
382
575
<filename>chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/suggestions/VoiceSuggestionProviderTest.java // Copyright 2015 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. package org.chromium.chrome.browser.omnibox.suggestions; import android.text.TextUtils; import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.UiThreadTest; import org.chromium.base.test.util.Feature; import org.chromium.chrome.browser.omnibox.OmniboxSuggestionType; import org.chromium.chrome.browser.omnibox.voice.VoiceRecognitionHandler.VoiceResult; import org.chromium.chrome.test.ChromeBrowserTestRule; import org.chromium.components.omnibox.AutocompleteMatch; import org.chromium.components.omnibox.AutocompleteMatchBuilder; import java.util.ArrayList; import java.util.List; /** * Test the {@link VoiceSuggestionProvider} class through simulating omnibox results and voice * recognition results. */ @RunWith(BaseJUnit4ClassRunner.class) public class VoiceSuggestionProviderTest { @Rule public final ChromeBrowserTestRule mChromeBrowserTestRule = new ChromeBrowserTestRule(); private static List<AutocompleteMatch> createDummySuggestions(String... texts) { List<AutocompleteMatch> suggestions = new ArrayList<AutocompleteMatch>(texts.length); for (int i = 0; i < texts.length; ++i) { suggestions.add( AutocompleteMatchBuilder.searchWithType(OmniboxSuggestionType.SEARCH_SUGGEST) .setDisplayText(texts[i]) .build()); } return suggestions; } private static List<VoiceResult> createVoiceResults(String[] texts, float[] confidences) { List<VoiceResult> results = new ArrayList<>(); for (int i = 0; i < texts.length; i++) { results.add(new VoiceResult(texts[i], confidences[i])); } return results; } private static boolean assertSuggestionMatchesVoiceResult(AutocompleteMatch a, VoiceResult b) { return a.getType() == OmniboxSuggestionType.VOICE_SUGGEST && TextUtils.equals(a.getDisplayText(), b.getMatch()); } private void assertArrayStartsWith(List<AutocompleteMatch> a, List<AutocompleteMatch> b) { Assert.assertTrue((a != null && b != null) || (a == null && b == null)); if (a == null || b == null) return; Assert.assertTrue(a.size() >= b.size()); for (int i = 0; i < b.size(); ++i) { Assert.assertEquals( "The AutocompleteMatch entries are not the same.", a.get(i), b.get(i)); } } private void assertArrayEndsWith( List<AutocompleteMatch> a, List<VoiceResult> b, int expectedResultCount) { Assert.assertTrue((a != null && b != null) || (a == null && b == null)); if (a == null || b == null) return; expectedResultCount = Math.min(expectedResultCount, b.size()); Assert.assertTrue(a.size() >= expectedResultCount); for (int i = 0; i < expectedResultCount; ++i) { Assert.assertTrue("The AutocompleteMatch entry does not match the VoiceResult", assertSuggestionMatchesVoiceResult( a.get(a.size() - expectedResultCount + i), b.get(i))); } } private boolean isVoiceResultInSuggestions( List<AutocompleteMatch> suggestions, VoiceResult result) { for (AutocompleteMatch suggestion : suggestions) { if (assertSuggestionMatchesVoiceResult(suggestion, result)) return true; } return false; } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testNoSuggestions() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); List<AutocompleteMatch> suggestions = createDummySuggestions("a", "b", "c"); List<AutocompleteMatch> updatedSuggestions = provider.addVoiceSuggestions(suggestions, 10); Assert.assertArrayEquals(suggestions.toArray(), updatedSuggestions.toArray()); } @Test @SmallTest @UiThreadTest public void testClearVoiceResults() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 0.99f, 0.98f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); Assert.assertNotNull(provider.getResults()); Assert.assertEquals( "Invalid number of results", texts.length, provider.getResults().size()); provider.clearVoiceSearchResults(); Assert.assertEquals(0, provider.getResults().size()); } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testAddToEmtpyResultsCase() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 1.0f, 1.0f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = provider.addVoiceSuggestions(null, texts.length); assertArrayEndsWith(suggestions, provider.getResults(), texts.length); } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testAddToEmptyOverflowCase() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 1.0f, 1.0f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = provider.addVoiceSuggestions(null, 2); assertArrayEndsWith(suggestions, provider.getResults(), 2); } @Test @SmallTest @UiThreadTest public void testAddToResultsCase() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 1.0f, 1.0f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = createDummySuggestions("oa", "ob", "oc"); List<AutocompleteMatch> updatedSuggestions = provider.addVoiceSuggestions(suggestions, texts.length); assertArrayStartsWith(updatedSuggestions, suggestions); assertArrayEndsWith(updatedSuggestions, provider.getResults(), texts.length); } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testAddToResultsOverflowCase() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 1.0f, 1.0f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = createDummySuggestions("oa", "ob", "oc"); List<AutocompleteMatch> updatedSuggestions = provider.addVoiceSuggestions(suggestions, 2); assertArrayStartsWith(updatedSuggestions, suggestions); assertArrayEndsWith(updatedSuggestions, provider.getResults(), 2); } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testAddDuplicateToResultsCase() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.0f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 1.0f, 1.0f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = createDummySuggestions("oa", "b", "oc"); List<AutocompleteMatch> updatedSuggestions = provider.addVoiceSuggestions(suggestions, texts.length); Assert.assertEquals(provider.getResults().get(0).getMatch(), texts[0]); Assert.assertTrue("Result 'a' was not found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(0))); Assert.assertEquals(provider.getResults().get(1).getMatch(), texts[1]); Assert.assertFalse("Result 'b' was found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(1))); Assert.assertEquals(provider.getResults().get(2).getMatch(), texts[2]); Assert.assertTrue("Result 'c' was not found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(2))); } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testConfidenceThresholdHideLowConfidence() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.5f, 1.1f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {1.0f, 0.6f, 0.3f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = createDummySuggestions("oa", "ob", "oc"); List<AutocompleteMatch> updatedSuggestions = provider.addVoiceSuggestions(suggestions, texts.length); Assert.assertEquals(provider.getResults().get(0).getMatch(), texts[0]); Assert.assertTrue("Result 'a' was not found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(0))); Assert.assertEquals(provider.getResults().get(1).getMatch(), texts[1]); Assert.assertTrue("Result 'b' was not found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(1))); Assert.assertEquals(provider.getResults().get(2).getMatch(), texts[2]); Assert.assertFalse("Result 'c' was found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(2))); } @Test @SmallTest @UiThreadTest @Feature({"Omnibox"}) public void testConfidenceThresholdHideAlts() { VoiceSuggestionProvider provider = new VoiceSuggestionProvider(0.5f, 0.5f); String[] texts = new String[] {"a", "b", "c"}; float[] confidences = new float[] {0.8f, 1.0f, 1.0f}; provider.setVoiceResults(createVoiceResults(texts, confidences)); List<AutocompleteMatch> suggestions = createDummySuggestions("oa", "ob", "oc"); List<AutocompleteMatch> updatedSuggestions = provider.addVoiceSuggestions(suggestions, texts.length); Assert.assertEquals(provider.getResults().get(0).getMatch(), texts[0]); Assert.assertTrue("Result 'a' was not found (First entry. Must be shown).", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(0))); Assert.assertEquals(provider.getResults().get(1).getMatch(), texts[1]); Assert.assertFalse("Result 'b' was found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(1))); Assert.assertEquals(provider.getResults().get(2).getMatch(), texts[2]); Assert.assertFalse("Result 'c' was found.", isVoiceResultInSuggestions(updatedSuggestions, provider.getResults().get(2))); } }
4,496
21,684
<filename>src/repli_timestamp.cc // Copyright 2010-2014 RethinkDB, all rights reserved. #include <inttypes.h> #include <algorithm> #include "containers/archive/archive.hpp" #include "containers/archive/versioned.hpp" #include "containers/printf_buffer.hpp" #include "repli_timestamp.hpp" #include "utils.hpp" template <cluster_version_t W> void serialize(write_message_t *wm, const repli_timestamp_t &tstamp) { serialize<W>(wm, tstamp.longtime); } INSTANTIATE_SERIALIZE_FOR_CLUSTER_AND_DISK(repli_timestamp_t); template <cluster_version_t W> MUST_USE archive_result_t deserialize(read_stream_t *s, repli_timestamp_t *tstamp) { return deserialize<W>(s, &tstamp->longtime); } INSTANTIATE_DESERIALIZE_SINCE_v1_13(repli_timestamp_t); const repli_timestamp_t repli_timestamp_t::invalid = { UINT64_MAX }; const repli_timestamp_t repli_timestamp_t::distant_past = { 0 }; repli_timestamp_t superceding_recency(repli_timestamp_t x, repli_timestamp_t y) { repli_timestamp_t ret; // This uses the fact that invalid is UINT64_MAX. ret.longtime = std::max<uint64_t>(x.longtime + 1, y.longtime + 1) - 1; return ret; } void debug_print(printf_buffer_t *buf, repli_timestamp_t tstamp) { buf->appendf("%" PRIu64, tstamp.longtime); }
513
3,680
// // Copyright 2021 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/tf/pyInvoke.h" #include "pxr/base/tf/diagnostic.h" #include "pxr/base/tf/errorMark.h" #include "pxr/base/tf/py3Compat.h" #include "pxr/base/tf/pyInterpreter.h" #include "pxr/base/tf/stringUtils.h" #include <boost/python.hpp> #include <vector> PXR_NAMESPACE_OPEN_SCOPE // Convert nullptr to None. boost::python::object Tf_ArgToPy(const std::nullptr_t &value) { return boost::python::object(); } void Tf_BuildPyInvokeKwArgs( boost::python::dict *kwArgsOut) { // Variadic template recursion base case: all args already processed, do // nothing. } void Tf_BuildPyInvokeArgs( boost::python::list *posArgsOut, boost::python::dict *kwArgsOut) { // Variadic template recursion base case: all args already processed, do // nothing. } bool Tf_PyInvokeImpl( const std::string &moduleName, const std::string &callableExpr, const boost::python::list &posArgs, const boost::python::dict &kwArgs, boost::python::object *resultObjOut) { static const char* const listVarName = "_Tf_invokeList_"; static const char* const dictVarName = "_Tf_invokeDict_"; static const char* const resultVarName = "_Tf_invokeResult_"; // Build globals dict, containing builtins and args. // No need for TfScriptModuleLoader; our python code performs import. boost::python::dict globals; boost::python::handle<> modHandle( PyImport_ImportModule(TfPyBuiltinModuleName)); globals["__builtins__"] = boost::python::object(modHandle); globals[listVarName] = posArgs; globals[dictVarName] = kwArgs; // Build python code for interpreter. // Import, look up callable, perform call, store result. const std::string pyStr = TfStringPrintf( "import %s\n" "%s = %s.%s(*%s, **%s)\n", moduleName.c_str(), resultVarName, moduleName.c_str(), callableExpr.c_str(), listVarName, dictVarName); TfErrorMark errorMark; // Execute code. TfPyRunString(pyStr, Py_file_input, globals); // Bail if python code raised any TfErrors. if (!errorMark.IsClean()) return false; // Look up result. If we got this far, it should be there. if (!TF_VERIFY(globals.has_key(resultVarName))) return false; *resultObjOut = globals.get(resultVarName); return true; } PXR_NAMESPACE_CLOSE_SCOPE
1,227
559
/** * Copyright (c) 2014 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package burp; import burp.msl.WiretapException; import java.awt.*; /** * User: skommidi * Date: 9/25/14 */ public class MSLTab implements IMessageEditorTab { public MSLTab(IMessageEditorController controller, boolean editable, IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers) { this.editable = editable; this.callbacks = callbacks; this.helpers = helpers; // create an instance of Burp's text editor txtInput = callbacks.createTextEditor(); txtInput.setEditable(editable); this.mslHttpListener = new MSLHttpListener(this.callbacks, this.helpers); } @Override public String getTabCaption() { return "MSL Parse"; } @Override public Component getUiComponent() { return txtInput.getComponent(); } @Override public boolean isEnabled(byte[] content, boolean isRequest) { return true; } @Override public void setMessage(byte[] content, boolean isRequest) { if(content == null) { // clear our display txtInput.setText(null); txtInput.setEditable(false); } else { // TODO: fix setText String data = null; String body = mslHttpListener.getBody(content); try { data = mslHttpListener.processMslMessage(body); } catch (WiretapException e) { throw new RuntimeException(e.getMessage(), e); } txtInput.setText(data.getBytes()); txtInput.setEditable(editable); } // remember the displayed content currentMessage = content; } @Override public byte[] getMessage() { // determine whether the user modified the deserialized data if (txtInput.isTextModified()) { // reserialize the data // TODO: fix the reserialization part return currentMessage; } else return currentMessage; } @Override public boolean isModified() { return txtInput.isTextModified(); } @Override public byte[] getSelectedData() { return txtInput.getSelectedText(); } private final IBurpExtenderCallbacks callbacks; private final IExtensionHelpers helpers; private final boolean editable; private final MSLHttpListener mslHttpListener; private ITextEditor txtInput; private byte[] currentMessage; }
1,179
542
<reponame>js20166098/sxfStandard /* * Copyright ©2018 vbill.cn. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package cn.vbill.middleware.porter.common.task.dic; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.HashMap; import java.util.LinkedHashMap; /** * 任务状态 * * @author: zhangkewei[<EMAIL>] * @date: 2018年02月24日 10:32 * @version: V1.0 * @review: zhangkewei[<EMAIL>]/2018年02月24日 10:32 */ @AllArgsConstructor @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum TaskStatusType { /** * 新建 */ NEW("NEW", "新建"), /** * 已停止 */ STOPPED("STOPPED", "已停止"), /** * 工作中 */ WORKING("WORKING", "工作中"), /** * 已删除 */ DELETED("DELETED", "已删除"); /** * LINKMAP */ public static final HashMap<String, Object> LINKMAP = new LinkedHashMap<>(); static { LINKMAP.put(NEW.code, NEW.name); LINKMAP.put(WORKING.code, WORKING.name); LINKMAP.put(STOPPED.code, STOPPED.name); } @Getter private final String code; @Getter private final String name; @JsonIgnore public boolean isStopped() { return this == STOPPED; } @JsonIgnore public boolean isWorking() { return this == WORKING; } @JsonIgnore public boolean isDeleted() { return this == DELETED; } }
947
1,337
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.desktop.gui; import com.haulmont.cuba.core.global.AppBeans; import com.haulmont.cuba.core.global.Configuration; import com.haulmont.cuba.desktop.App; import com.haulmont.cuba.desktop.Connection; import com.haulmont.cuba.desktop.DesktopConfig; import com.haulmont.cuba.security.app.UserSessionService; import com.haulmont.cuba.security.global.NoUserSessionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.annotation.Nullable; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ExecutionException; @Component(SessionMessagesNotifier.NAME) public class SessionMessagesNotifier { public final static String NAME = "cuba_SessionMessagesNotifier"; private final static Logger log = LoggerFactory.getLogger(SessionMessagesNotifier.class); protected Timer timer; protected SwingWorker<String, Void> asyncMessageLoader; public void activate() { if (timer != null) { return; } Configuration configuration = AppBeans.get(Configuration.NAME); int timeout = configuration.getConfig(DesktopConfig.class).getSessionMessagesIntervalSec(); if (timeout > 0) { timer = new Timer(timeout * 1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { syncMessages(); } }); timer.start(); } } public void deactivate() { if (timer != null) { timer.stop(); if (asyncMessageLoader != null) { asyncMessageLoader.cancel(true); asyncMessageLoader = null; } timer = null; } } protected void syncMessages() { Connection connection = App.getInstance().getConnection(); if (connection.isConnected()) { log.trace("Check session messages"); asyncMessageLoader = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { try { UserSessionService uss = AppBeans.get(UserSessionService.NAME); return uss.getMessages(); } catch (NoUserSessionException e) { log.warn("Unable to get messages for session, user session not found"); } catch (Exception e) { log.warn("Session messages exception: " + e.toString()); } return null; } @Override protected void done() { try { if (!isCancelled()) { processServerMessage(get()); } } catch (InterruptedException | ExecutionException ignored) { // do nothing } finally { asyncMessageLoader = null; } } }; asyncMessageLoader.execute(); } } protected void processServerMessage(@Nullable String message) { if (message != null) { log.debug("Received session message"); Connection connection = App.getInstance().getConnection(); if (connection.isConnected() && timer != null && timer.isRunning()) { SessionMessageWindow dialog = new SessionMessageWindow(App.getInstance().getMainFrame()); dialog.setMessage(message); dialog.setVisible(true); } } } }
1,899
1,056
<reponame>ses1112/adito-nb-modules /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.core.windows.design; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.openide.util.NbBundle; import org.openide.windows.Mode; import org.openide.windows.TopComponent; import org.netbeans.api.settings.ConvertAsProperties; import org.netbeans.core.windows.ModeImpl; import org.openide.windows.WindowManager; @ConvertAsProperties( dtd = "-//org.netbeans.core.windows.model//DesignViewComponent//EN", autostore = false ) @TopComponent.Description(preferredID = "DesignViewComponentTopComponent", iconBase = "org/netbeans/core/windows/model/DesignView.png", persistenceType = TopComponent.PERSISTENCE_ONLY_OPENED ) final class DesignViewComponent extends TopComponent implements DocumentListener { DesignViewComponent() { initComponents(); setName(NbBundle.getMessage(DesignViewComponent.class, "CTL_DesignViewComponentTopComponent")); setToolTipText(NbBundle.getMessage(DesignViewComponent.class, "HINT_DesignViewComponentTopComponent")); putClientProperty("TopComponentAllowDockAnywhere", true); refresh(); modeName.getDocument().addDocumentListener(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { modeName = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); modeName.setText(org.openide.util.NbBundle.getMessage(DesignViewComponent.class, "DesignViewComponent.modeName.text", new Object[] {})); // NOI18N modeName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { modeNameActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 500, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 88, Short.MAX_VALUE) ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 500, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 63, Short.MAX_VALUE) ); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(DesignViewComponent.class, "DesignViewComponent.jLabel1.text", new Object[] {})); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(modeName, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(modeName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void refresh() { Mode mode = WindowManager.getDefault().findMode(this); if (mode != null) { if (!modeName.getText().equals(mode.getName())) { modeName.setText(mode.getName()); } setName(mode.getName()); } } private void modeNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modeNameActionPerformed Mode mode = WindowManager.getDefault().findMode(this); if (mode instanceof ModeImpl) { ModeImpl mi = (ModeImpl)mode; mi.setModeName(modeName.getText()); } for (TopComponent tc : mode.getTopComponents()) { if (tc instanceof DesignViewComponent) { DesignViewComponent dvc = (DesignViewComponent)tc; dvc.refresh(); } } }//GEN-LAST:event_modeNameActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField modeName; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { refresh(); } @Override protected void componentActivated() { refresh(); } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } @Override public void insertUpdate(DocumentEvent e) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { modeNameActionPerformed(null); } }); } @Override public void removeUpdate(DocumentEvent e) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { modeNameActionPerformed(null); } }); } @Override public void changedUpdate(DocumentEvent e) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { modeNameActionPerformed(null); } }); } }
3,527
1,863
// // 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 NVIDIA CORPORATION 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 ``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. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef __NVPHYSXTODRV_H__ #define __NVPHYSXTODRV_H__ // The puprose of this interface is to provide graphics drivers with information // about PhysX state to draw PhysX visual indicator // We share information between modules using a memory section object. PhysX creates // such object, graphics drivers try to open it. The name of the object has // fixed part (NvPhysXToDrv_SectionName) followed by the process id. This allows // each process to have its own communication channel. namespace physx { #define NvPhysXToDrv_SectionName "PH71828182845_" // Vista apps cannot create stuff in Global\\ namespace when NOT elevated, so use local scope #define NvPhysXToDrv_Build_SectionName(PID, buf) sprintf(buf, NvPhysXToDrv_SectionName "%x", static_cast<unsigned int>(PID)) #define NvPhysXToDrv_Build_SectionNameXP(PID, buf) sprintf(buf, "Global\\" NvPhysXToDrv_SectionName "%x", static_cast<unsigned int>(PID)) typedef struct NvPhysXToDrv_Header_ { int signature; // header interface signature int version; // version of the interface int size; // size of the structure int reserved; // reserved, must be zero } NvPhysXToDrv_Header; // this structure describes layout of data in the shared memory section typedef struct NvPhysXToDrv_Data_V1_ { NvPhysXToDrv_Header header; // keep this member first in all versions of the interface. int bCpuPhysicsPresent; // nonzero if cpu physics is initialized int bGpuPhysicsPresent; // nonzero if gpu physics is initialized } NvPhysXToDrv_Data_V1; // some random magic number as our interface signature #define NvPhysXToDrv_Header_Signature 0xA7AB // use the macro to setup the header to the latest version of the interface // update the macro when a new verson of the interface is added #define NvPhysXToDrv_Header_Init(header) \ { \ header.signature = NvPhysXToDrv_Header_Signature; \ header.version = 1; \ header.size = sizeof(NvPhysXToDrv_Data_V1); \ header.reserved = 0; \ } // validate the header against all known interface versions // add validation checks when new interfaces are added #define NvPhysXToDrv_Header_Validate(header, curVersion) \ ( \ (header.signature == NvPhysXToDrv_Header_Signature) && \ (header.version == curVersion) && \ (curVersion == 1) && \ (header.size == sizeof(NvPhysXToDrv_Data_V1)) \ ) } #endif // __NVPHYSXTODRV_H__
1,541
554
package github.tornaco.xposedmoduletest.util; import com.andrognito.patternlockview.PatternLockView; import com.andrognito.patternlockview.listener.PatternLockViewListener; import java.util.List; /** * Created by guohao4 on 2017/11/15. * Email: <EMAIL> */ public class PatternLockViewListenerAdapter implements PatternLockViewListener { @Override public void onStarted() { } @Override public void onProgress(List<PatternLockView.Dot> progressPattern) { } @Override public void onComplete(List<PatternLockView.Dot> pattern) { } @Override public void onCleared() { } }
257
486
{ "balanceHeld": { "description": "Balance of the account held for transferring to other users (in cents) and then a bunch more text after that", "type": "integer" } }
56
2,151
<gh_stars>1000+ # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import datetime import mock import os import tempfile import unittest2 from expects import be_false, be_none, be_true, expect, equal, raise_error from google.api.control import caches, check_request, client, messages, report_request class TestSimpleLoader(unittest2.TestCase): SERVICE_NAME = 'simpler-loader' @mock.patch("google.api.control.client.ReportOptions", autospec=True) @mock.patch("google.api.control.client.CheckOptions", autospec=True) def test_should_create_client_ok(self, check_opts, report_opts): # the mocks return fake instances else code using them fails check_opts.return_value = caches.CheckOptions() report_opts.return_value = caches.ReportOptions() # ensure the client is constructed using no args instances of the opts expect(client.Loaders.DEFAULT.load(self.SERVICE_NAME)).not_to(be_none) check_opts.assert_called_once_with() report_opts.assert_called_once_with() _TEST_CONFIG = """{ "checkAggregatorConfig": { "cacheEntries": 10, "responseExpirationMs": 1000, "flushIntervalMs": 2000 }, "reportAggregatorConfig": { "cacheEntries": 10, "flushIntervalMs": 1000 } } """ class TestEnvironmentLoader(unittest2.TestCase): SERVICE_NAME = 'environment-loader' def setUp(self): json_fd = tempfile.NamedTemporaryFile(delete=False) with json_fd as f: f.write(_TEST_CONFIG) self._config_file = json_fd.name os.environ[client.CONFIG_VAR] = self._config_file def tearDown(self): if os.path.exists(self._config_file): os.remove(self._config_file) @mock.patch("google.api.control.client.ReportOptions", autospec=True) @mock.patch("google.api.control.client.CheckOptions", autospec=True) def test_should_create_client_from_environment_ok(self, check_opts, report_opts): check_opts.return_value = caches.CheckOptions() report_opts.return_value = caches.ReportOptions() # ensure the client is constructed using options values from the test JSON expect(client.Loaders.ENVIRONMENT.load(self.SERVICE_NAME)).not_to(be_none) check_opts.assert_called_once_with(expiration=datetime.timedelta(0, 1), flush_interval=datetime.timedelta(0, 2), num_entries=10) report_opts.assert_called_once_with(flush_interval=datetime.timedelta(0, 1), num_entries=10) @mock.patch("google.api.control.client.ReportOptions", autospec=True) @mock.patch("google.api.control.client.CheckOptions", autospec=True) def test_should_use_defaults_if_file_is_missing(self, check_opts, report_opts): os.remove(self._config_file) self._assert_called_with_no_args_options(check_opts, report_opts) @mock.patch("google.api.control.client.ReportOptions", autospec=True) @mock.patch("google.api.control.client.CheckOptions", autospec=True) def test_should_use_defaults_if_file_is_missing(self, check_opts, report_opts): del os.environ[client.CONFIG_VAR] self._assert_called_with_no_args_options(check_opts, report_opts) @mock.patch("google.api.control.client.ReportOptions") @mock.patch("google.api.control.client.CheckOptions") def test_should_use_defaults_if_json_is_bad(self, check_opts, report_opts): with open(self._config_file, 'w') as f: f.write(_TEST_CONFIG + '\n{ this will not parse as json}') self._assert_called_with_no_args_options(check_opts, report_opts) def _assert_called_with_no_args_options(self, check_opts, report_opts): # the mocks return fake instances else code using them fails check_opts.return_value = caches.CheckOptions() report_opts.return_value = caches.ReportOptions() # ensure the client is constructed using no args instances of the opts expect(client.Loaders.ENVIRONMENT.load(self.SERVICE_NAME)).not_to(be_none) check_opts.assert_called_once_with() report_opts.assert_called_once_with() def _make_dummy_report_request(project_id, service_name): rules = report_request.ReportingRules() info = report_request.Info( consumer_project_id=project_id, operation_id='an_op_id', operation_name='an_op_name', method='GET', referer='a_referer', service_name=service_name) return info.as_report_request(rules) def _make_dummy_check_request(project_id, service_name): info = check_request.Info( consumer_project_id=project_id, operation_id='an_op_id', operation_name='an_op_name', referer='a_referer', service_name=service_name) return info.as_check_request() class TestClientStartAndStop(unittest2.TestCase): SERVICE_NAME = 'start-and-stop' PROJECT_ID = SERVICE_NAME + '.project' def setUp(self): self._mock_transport = mock.MagicMock() self._subject = client.Loaders.DEFAULT.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_create_a_thread_when_started(self, thread_class): self._subject.start() expect(thread_class.called).to(be_true) expect(len(thread_class.call_args_list)).to(equal(1)) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_only_create_thread_on_first_start(self, thread_class): self._subject.start() self._subject.start() expect(len(thread_class.call_args_list)).to(equal(1)) def test_should_noop_stop_if_not_started(self): # stop the subject, the transport should not see a request self._subject.stop() expect(self._mock_transport.called).to(be_false) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_clear_requests_on_stop(self, dummy_thread_class): # stop the subject, the transport did not see a request self._subject.start() self._subject.report( _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME)) self._subject.stop() expect(self._mock_transport.services.report.called).to(be_true) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_ignore_stop_if_already_stopped(self, dummy_thread_class): # stop the subject, the transport did not see a request self._subject.start() self._subject.report( _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME)) self._subject.stop() self._mock_transport.reset_mock() self._subject.stop() expect(self._mock_transport.services.report.called).to(be_false) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_ignore_bad_transport_when_not_cached(self, dummy_thread_class): self._subject.start() self._subject.report( _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME)) self._mock_transport.services.report.side_effect = lambda: 1/0 self._subject.stop() expect(self._mock_transport.services.report.called).to(be_true) class TestClientCheck(unittest2.TestCase): SERVICE_NAME = 'check' PROJECT_ID = SERVICE_NAME + '.project' def setUp(self): self._mock_transport = mock.MagicMock() self._subject = client.Loaders.DEFAULT.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport) def test_should_raise_on_check_without_start(self): dummy_request = _make_dummy_check_request(self.PROJECT_ID, self.SERVICE_NAME) expect(lambda: self._subject.check(dummy_request)).to( raise_error(AssertionError)) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_send_the_request_if_not_cached(self, dummy_thread_class): self._subject.start() dummy_request = _make_dummy_check_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.check(dummy_request) expect(self._mock_transport.services.check.called).to(be_true) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_not_send_the_request_if_cached(self, dummy_thread_class): t = self._mock_transport self._subject.start() dummy_request = _make_dummy_check_request(self.PROJECT_ID, self.SERVICE_NAME) dummy_response = messages.CheckResponse( operationId=dummy_request.checkRequest.operation.operationId) t.services.check.return_value = dummy_response expect(self._subject.check(dummy_request)).to(equal(dummy_response)) t.reset_mock() expect(self._subject.check(dummy_request)).to(equal(dummy_response)) expect(t.services.check.called).to(be_false) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_return_null_if_transport_fails(self, dummy_thread_class): self._subject.start() dummy_request = _make_dummy_check_request(self.PROJECT_ID, self.SERVICE_NAME) self._mock_transport.services.check.side_effect = lambda: 1/0 expect(self._subject.check(dummy_request)).to(be_none) class TestClientReport(unittest2.TestCase): SERVICE_NAME = 'report' PROJECT_ID = SERVICE_NAME + '.project' def setUp(self): self._mock_transport = mock.MagicMock() self._subject = client.Loaders.DEFAULT.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport) def test_should_raise_on_report_without_start(self): dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) expect(lambda: self._subject.report(dummy_request)).to( raise_error(AssertionError)) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_not_send_the_request_if_cached(self, dummy_thread_class): t = self._mock_transport self._subject.start() dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.report(dummy_request) expect(t.services.report.called).to(be_false) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_send_a_request_if_not_cached(self, dummy_thread_class): self._subject = client.Loaders.NO_CACHE.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport) t = self._mock_transport self._subject.start() dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.report(dummy_request) expect(t.services.report.called).to(be_true) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_ignore_bad_transport_when_not_cached(self, dummy_thread_class): self._subject = client.Loaders.NO_CACHE.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport) self._mock_transport.services.report.side_effect = lambda: 1/0 self._subject.start() dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.report(dummy_request) expect(self._mock_transport.services.report.called).to(be_true) class TestNoSchedulerThread(unittest2.TestCase): SERVICE_NAME = 'no-scheduler-thread' PROJECT_ID = SERVICE_NAME + '.project' def setUp(self): self._timer = _DateTimeTimer() self._mock_transport = mock.MagicMock() self._subject = client.Loaders.DEFAULT.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport, timer=self._timer) self._no_cache_subject = client.Loaders.NO_CACHE.load( self.SERVICE_NAME, create_transport=lambda: self._mock_transport, timer=self._timer) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) @mock.patch("google.api.control.client.sched", spec=True) def test_should_initialize_scheduler(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 for s in (self._subject, self._no_cache_subject): s.start() expect(sched.scheduler.called).to(be_true) sched.reset_mock() @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) @mock.patch("google.api.control.client.sched", spec=True) def test_should_not_enter_scheduler_when_there_is_no_cache(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 self._no_cache_subject.start() expect(sched.scheduler.called).to(be_true) scheduler = sched.scheduler.return_value expect(scheduler.enter.called).to(be_false) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) @mock.patch("google.api.control.client.sched", spec=True) def test_should_enter_scheduler_when_there_is_a_cache(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 self._subject.start() expect(sched.scheduler.called).to(be_true) scheduler = sched.scheduler.return_value expect(scheduler.enter.called).to(be_true) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) @mock.patch("google.api.control.client.sched", spec=True) def test_should_not_enter_scheduler_for_cached_checks(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 self._subject.start() # confirm scheduler is created and initialized expect(sched.scheduler.called).to(be_true) scheduler = sched.scheduler.return_value expect(scheduler.enter.called).to(be_true) scheduler.reset_mock() # call check once, to a cache response dummy_request = _make_dummy_check_request(self.PROJECT_ID, self.SERVICE_NAME) dummy_response = messages.CheckResponse( operationId=dummy_request.checkRequest.operation.operationId) t = self._mock_transport t.services.check.return_value = dummy_response expect(self._subject.check(dummy_request)).to(equal(dummy_response)) t.reset_mock() # call check again - response is cached... expect(self._subject.check(dummy_request)).to(equal(dummy_response)) expect(self._mock_transport.services.check.called).to(be_false) # ... the scheduler is not run expect(scheduler.run.called).to(be_false) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) @mock.patch("google.api.control.client.sched", spec=True) def test_should_enter_scheduler_for_aggregated_reports(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 self._subject.start() # confirm scheduler is created and initialized expect(sched.scheduler.called).to(be_true) scheduler = sched.scheduler.return_value expect(scheduler.enter.called).to(be_true) scheduler.reset_mock() # call report once; transport is not called, but the scheduler is run dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.report(dummy_request) expect(self._mock_transport.services.report.called).to(be_false) expect(scheduler.run.called).to(be_true) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) def test_should_flush_report_cache_in_scheduler(self, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 self._subject.start() # call report once; transport is not called dummy_request = _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME) self._subject.report(dummy_request) # cached a report expect(self._mock_transport.services.report.called).to(be_false) # pass time, at least the flush interval, after which the report # cache to flush self._timer.tick() self._timer.tick() self._subject.report(dummy_request) expect(self._mock_transport.services.report.called).to(be_true) @mock.patch("google.api.control.client._THREAD_CLASS", spec=True) @mock.patch("google.api.control.client.sched", spec=True) def test_should_not_run_scheduler_when_stopping(self, sched, thread_class): thread_class.return_value.start.side_effect = lambda: 1/0 self._subject.start() # confirm scheduler is created and initialized expect(sched.scheduler.called).to(be_true) scheduler = sched.scheduler.return_value expect(scheduler.enter.called).to(be_true) # stop the subject. transport is called, but the scheduler is not run self._subject.report( _make_dummy_report_request(self.PROJECT_ID, self.SERVICE_NAME)) scheduler.reset_mock() self._subject.stop() expect(self._mock_transport.services.report.called).to(be_true) expect(scheduler.run.called).to(be_false) class _DateTimeTimer(object): def __init__(self, auto=False): self.auto = auto self.time = datetime.datetime.utcfromtimestamp(0) def __call__(self): if self.auto: self.tick() return self.time def tick(self): self.time += datetime.timedelta(seconds=1)
8,111
418
/* copyright 2013 <NAME> and contributors (see LICENSE for licensing information) */ #ifndef DUNST_DUNST_H #define DUNST_DUNST_H #include <glib.h> #include <stdbool.h> #include <stdio.h> #include "notification.h" #define ColLast 3 #define ColFrame 2 #define ColFG 1 #define ColBG 0 extern GSList *rules; extern const char *colors[3][3]; void wake_up(void); int dunst_main(int argc, char *argv[]); void usage(int exit_status); void print_version(void); char *extract_urls(const char *str); void context_menu(void); void pause_signal_handler(int sig); #endif /* vim: set tabstop=8 shiftwidth=8 expandtab textwidth=0: */
235
1,604
package org.bouncycastle.crypto.engines; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.StreamCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Memoable; /** * Zuc128Engine implementation. * Based on https://www.gsma.com/aboutus/wp-content/uploads/2014/12/eea3eia3zucv16.pdf */ public class Zuc128CoreEngine implements StreamCipher, Memoable { /* the s-boxes */ private static final byte[] S0 = new byte[]{ (byte)0x3e, (byte)0x72, (byte)0x5b, (byte)0x47, (byte)0xca, (byte)0xe0, (byte)0x00, (byte)0x33, (byte)0x04, (byte)0xd1, (byte)0x54, (byte)0x98, (byte)0x09, (byte)0xb9, (byte)0x6d, (byte)0xcb, (byte)0x7b, (byte)0x1b, (byte)0xf9, (byte)0x32, (byte)0xaf, (byte)0x9d, (byte)0x6a, (byte)0xa5, (byte)0xb8, (byte)0x2d, (byte)0xfc, (byte)0x1d, (byte)0x08, (byte)0x53, (byte)0x03, (byte)0x90, (byte)0x4d, (byte)0x4e, (byte)0x84, (byte)0x99, (byte)0xe4, (byte)0xce, (byte)0xd9, (byte)0x91, (byte)0xdd, (byte)0xb6, (byte)0x85, (byte)0x48, (byte)0x8b, (byte)0x29, (byte)0x6e, (byte)0xac, (byte)0xcd, (byte)0xc1, (byte)0xf8, (byte)0x1e, (byte)0x73, (byte)0x43, (byte)0x69, (byte)0xc6, (byte)0xb5, (byte)0xbd, (byte)0xfd, (byte)0x39, (byte)0x63, (byte)0x20, (byte)0xd4, (byte)0x38, (byte)0x76, (byte)0x7d, (byte)0xb2, (byte)0xa7, (byte)0xcf, (byte)0xed, (byte)0x57, (byte)0xc5, (byte)0xf3, (byte)0x2c, (byte)0xbb, (byte)0x14, (byte)0x21, (byte)0x06, (byte)0x55, (byte)0x9b, (byte)0xe3, (byte)0xef, (byte)0x5e, (byte)0x31, (byte)0x4f, (byte)0x7f, (byte)0x5a, (byte)0xa4, (byte)0x0d, (byte)0x82, (byte)0x51, (byte)0x49, (byte)0x5f, (byte)0xba, (byte)0x58, (byte)0x1c, (byte)0x4a, (byte)0x16, (byte)0xd5, (byte)0x17, (byte)0xa8, (byte)0x92, (byte)0x24, (byte)0x1f, (byte)0x8c, (byte)0xff, (byte)0xd8, (byte)0xae, (byte)0x2e, (byte)0x01, (byte)0xd3, (byte)0xad, (byte)0x3b, (byte)0x4b, (byte)0xda, (byte)0x46, (byte)0xeb, (byte)0xc9, (byte)0xde, (byte)0x9a, (byte)0x8f, (byte)0x87, (byte)0xd7, (byte)0x3a, (byte)0x80, (byte)0x6f, (byte)0x2f, (byte)0xc8, (byte)0xb1, (byte)0xb4, (byte)0x37, (byte)0xf7, (byte)0x0a, (byte)0x22, (byte)0x13, (byte)0x28, (byte)0x7c, (byte)0xcc, (byte)0x3c, (byte)0x89, (byte)0xc7, (byte)0xc3, (byte)0x96, (byte)0x56, (byte)0x07, (byte)0xbf, (byte)0x7e, (byte)0xf0, (byte)0x0b, (byte)0x2b, (byte)0x97, (byte)0x52, (byte)0x35, (byte)0x41, (byte)0x79, (byte)0x61, (byte)0xa6, (byte)0x4c, (byte)0x10, (byte)0xfe, (byte)0xbc, (byte)0x26, (byte)0x95, (byte)0x88, (byte)0x8a, (byte)0xb0, (byte)0xa3, (byte)0xfb, (byte)0xc0, (byte)0x18, (byte)0x94, (byte)0xf2, (byte)0xe1, (byte)0xe5, (byte)0xe9, (byte)0x5d, (byte)0xd0, (byte)0xdc, (byte)0x11, (byte)0x66, (byte)0x64, (byte)0x5c, (byte)0xec, (byte)0x59, (byte)0x42, (byte)0x75, (byte)0x12, (byte)0xf5, (byte)0x74, (byte)0x9c, (byte)0xaa, (byte)0x23, (byte)0x0e, (byte)0x86, (byte)0xab, (byte)0xbe, (byte)0x2a, (byte)0x02, (byte)0xe7, (byte)0x67, (byte)0xe6, (byte)0x44, (byte)0xa2, (byte)0x6c, (byte)0xc2, (byte)0x93, (byte)0x9f, (byte)0xf1, (byte)0xf6, (byte)0xfa, (byte)0x36, (byte)0xd2, (byte)0x50, (byte)0x68, (byte)0x9e, (byte)0x62, (byte)0x71, (byte)0x15, (byte)0x3d, (byte)0xd6, (byte)0x40, (byte)0xc4, (byte)0xe2, (byte)0x0f, (byte)0x8e, (byte)0x83, (byte)0x77, (byte)0x6b, (byte)0x25, (byte)0x05, (byte)0x3f, (byte)0x0c, (byte)0x30, (byte)0xea, (byte)0x70, (byte)0xb7, (byte)0xa1, (byte)0xe8, (byte)0xa9, (byte)0x65, (byte)0x8d, (byte)0x27, (byte)0x1a, (byte)0xdb, (byte)0x81, (byte)0xb3, (byte)0xa0, (byte)0xf4, (byte)0x45, (byte)0x7a, (byte)0x19, (byte)0xdf, (byte)0xee, (byte)0x78, (byte)0x34, (byte)0x60 }; private static final byte[] S1 = new byte[]{ (byte)0x55, (byte)0xc2, (byte)0x63, (byte)0x71, (byte)0x3b, (byte)0xc8, (byte)0x47, (byte)0x86, (byte)0x9f, (byte)0x3c, (byte)0xda, (byte)0x5b, (byte)0x29, (byte)0xaa, (byte)0xfd, (byte)0x77, (byte)0x8c, (byte)0xc5, (byte)0x94, (byte)0x0c, (byte)0xa6, (byte)0x1a, (byte)0x13, (byte)0x00, (byte)0xe3, (byte)0xa8, (byte)0x16, (byte)0x72, (byte)0x40, (byte)0xf9, (byte)0xf8, (byte)0x42, (byte)0x44, (byte)0x26, (byte)0x68, (byte)0x96, (byte)0x81, (byte)0xd9, (byte)0x45, (byte)0x3e, (byte)0x10, (byte)0x76, (byte)0xc6, (byte)0xa7, (byte)0x8b, (byte)0x39, (byte)0x43, (byte)0xe1, (byte)0x3a, (byte)0xb5, (byte)0x56, (byte)0x2a, (byte)0xc0, (byte)0x6d, (byte)0xb3, (byte)0x05, (byte)0x22, (byte)0x66, (byte)0xbf, (byte)0xdc, (byte)0x0b, (byte)0xfa, (byte)0x62, (byte)0x48, (byte)0xdd, (byte)0x20, (byte)0x11, (byte)0x06, (byte)0x36, (byte)0xc9, (byte)0xc1, (byte)0xcf, (byte)0xf6, (byte)0x27, (byte)0x52, (byte)0xbb, (byte)0x69, (byte)0xf5, (byte)0xd4, (byte)0x87, (byte)0x7f, (byte)0x84, (byte)0x4c, (byte)0xd2, (byte)0x9c, (byte)0x57, (byte)0xa4, (byte)0xbc, (byte)0x4f, (byte)0x9a, (byte)0xdf, (byte)0xfe, (byte)0xd6, (byte)0x8d, (byte)0x7a, (byte)0xeb, (byte)0x2b, (byte)0x53, (byte)0xd8, (byte)0x5c, (byte)0xa1, (byte)0x14, (byte)0x17, (byte)0xfb, (byte)0x23, (byte)0xd5, (byte)0x7d, (byte)0x30, (byte)0x67, (byte)0x73, (byte)0x08, (byte)0x09, (byte)0xee, (byte)0xb7, (byte)0x70, (byte)0x3f, (byte)0x61, (byte)0xb2, (byte)0x19, (byte)0x8e, (byte)0x4e, (byte)0xe5, (byte)0x4b, (byte)0x93, (byte)0x8f, (byte)0x5d, (byte)0xdb, (byte)0xa9, (byte)0xad, (byte)0xf1, (byte)0xae, (byte)0x2e, (byte)0xcb, (byte)0x0d, (byte)0xfc, (byte)0xf4, (byte)0x2d, (byte)0x46, (byte)0x6e, (byte)0x1d, (byte)0x97, (byte)0xe8, (byte)0xd1, (byte)0xe9, (byte)0x4d, (byte)0x37, (byte)0xa5, (byte)0x75, (byte)0x5e, (byte)0x83, (byte)0x9e, (byte)0xab, (byte)0x82, (byte)0x9d, (byte)0xb9, (byte)0x1c, (byte)0xe0, (byte)0xcd, (byte)0x49, (byte)0x89, (byte)0x01, (byte)0xb6, (byte)0xbd, (byte)0x58, (byte)0x24, (byte)0xa2, (byte)0x5f, (byte)0x38, (byte)0x78, (byte)0x99, (byte)0x15, (byte)0x90, (byte)0x50, (byte)0xb8, (byte)0x95, (byte)0xe4, (byte)0xd0, (byte)0x91, (byte)0xc7, (byte)0xce, (byte)0xed, (byte)0x0f, (byte)0xb4, (byte)0x6f, (byte)0xa0, (byte)0xcc, (byte)0xf0, (byte)0x02, (byte)0x4a, (byte)0x79, (byte)0xc3, (byte)0xde, (byte)0xa3, (byte)0xef, (byte)0xea, (byte)0x51, (byte)0xe6, (byte)0x6b, (byte)0x18, (byte)0xec, (byte)0x1b, (byte)0x2c, (byte)0x80, (byte)0xf7, (byte)0x74, (byte)0xe7, (byte)0xff, (byte)0x21, (byte)0x5a, (byte)0x6a, (byte)0x54, (byte)0x1e, (byte)0x41, (byte)0x31, (byte)0x92, (byte)0x35, (byte)0xc4, (byte)0x33, (byte)0x07, (byte)0x0a, (byte)0xba, (byte)0x7e, (byte)0x0e, (byte)0x34, (byte)0x88, (byte)0xb1, (byte)0x98, (byte)0x7c, (byte)0xf3, (byte)0x3d, (byte)0x60, (byte)0x6c, (byte)0x7b, (byte)0xca, (byte)0xd3, (byte)0x1f, (byte)0x32, (byte)0x65, (byte)0x04, (byte)0x28, (byte)0x64, (byte)0xbe, (byte)0x85, (byte)0x9b, (byte)0x2f, (byte)0x59, (byte)0x8a, (byte)0xd7, (byte)0xb0, (byte)0x25, (byte)0xac, (byte)0xaf, (byte)0x12, (byte)0x03, (byte)0xe2, (byte)0xf2 }; /* the constants D */ private static final short[] EK_d = new short[]{ 0x44D7, 0x26BC, 0x626B, 0x135E, 0x5789, 0x35E2, 0x7135, 0x09AF, 0x4D78, 0x2F13, 0x6BC4, 0x1AF1, 0x5E26, 0x3C4D, 0x789A, 0x47AC }; /** * State. */ private final int[] LFSR = new int[16]; private final int[] F = new int[2]; private final int[] BRC = new int[4]; /** * index of next byte in keyStream. */ private int theIndex; /** * Advanced stream. */ private final byte[] keyStream = new byte[4]; // Integer.BYTES /** * The iterations. */ private int theIterations; /** * Reset state. */ private Zuc128CoreEngine theResetState; /** * Constructor. */ protected Zuc128CoreEngine() { } /** * Constructor. * * @param pSource the source engine */ protected Zuc128CoreEngine(final Zuc128CoreEngine pSource) { reset(pSource); } /** * initialise a Snow3G cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @throws IllegalArgumentException if the params argument is inappropriate. */ public void init(final boolean forEncryption, final CipherParameters params) { /* * encryption and decryption is completely symmetrical, so the 'forEncryption' is * irrelevant. (Like 90% of stream ciphers) */ /* Determine parameters */ CipherParameters myParams = params; byte[] newKey = null; byte[] newIV = null; if ((myParams instanceof ParametersWithIV)) { final ParametersWithIV ivParams = (ParametersWithIV)myParams; newIV = ivParams.getIV(); myParams = ivParams.getParameters(); } if (myParams instanceof KeyParameter) { final KeyParameter keyParam = (KeyParameter)myParams; newKey = keyParam.getKey(); } /* Initialise engine and mark as initialised */ theIndex = 0; theIterations = 0; setKeyAndIV(newKey, newIV); /* Save reset state */ theResetState = (Zuc128CoreEngine)copy(); } /** * Obtain Max iterations. * * @return the maximum iterations */ protected int getMaxIterations() { return 2047; } /** * Obtain Algorithm Name. * * @return the name */ public String getAlgorithmName() { return "Zuc-128"; } /** * Process bytes. * * @param in the input buffer * @param inOff the starting offset in the input buffer * @param len the length of data in the input buffer * @param out the output buffer * @param outOff the starting offset in the output buffer * @return the number of bytes returned in the output buffer */ public int processBytes(final byte[] in, final int inOff, final int len, final byte[] out, final int outOff) { /* Check for errors */ if (theResetState == null) { throw new IllegalStateException(getAlgorithmName() + " not initialised"); } if ((inOff + len) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + len) > out.length) { throw new OutputLengthException("output buffer too short"); } /* Loop through the input bytes */ for (int i = 0; i < len; i++) { out[i + outOff] = returnByte(in[i + inOff]); } return len; } /** * Reset the engine. */ public void reset() { if (theResetState != null) { reset(theResetState); } } /** * Process single byte. * * @param in the input byte * @return the output byte */ public byte returnByte(final byte in) { /* Make the keyStream if required */ if (theIndex == 0) { makeKeyStream(); } /* Map the next byte and adjust index */ final byte out = (byte)(keyStream[theIndex] ^ in); theIndex = (theIndex + 1) % 4; // Integer.BYTES /* Return the mapped character */ return out; } /** * Encode a 32-bit value into a buffer (little-endian). * * @param val the value to encode * @param buf the output buffer * @param off the output offset */ public static void encode32be(int val, byte[] buf, int off) { buf[off] = (byte)(val >> 24); buf[off + 1] = (byte)(val >> 16); buf[off + 2] = (byte)(val >> 8); buf[off + 3] = (byte)val; } /* ����������������������- */ /** * Modular add c = a + b mod (2^31 � 1). * * @param a value A * @param b value B * @return the result */ private int AddM(final int a, final int b) { final int c = a + b; return (c & 0x7FFFFFFF) + (c >>> 31); } /** * Multiply by power of two. * * @param x input value * @param k the power of two * @return the result */ private static int MulByPow2(final int x, final int k) { return ((((x) << k) | ((x) >>> (31 - k))) & 0x7FFFFFFF); } /** * LFSR with initialisation mode. * * @param u */ private void LFSRWithInitialisationMode(final int u) { int f = LFSR[0]; int v = MulByPow2(LFSR[0], 8); f = AddM(f, v); v = MulByPow2(LFSR[4], 20); f = AddM(f, v); v = MulByPow2(LFSR[10], 21); f = AddM(f, v); v = MulByPow2(LFSR[13], 17); f = AddM(f, v); v = MulByPow2(LFSR[15], 15); f = AddM(f, v); f = AddM(f, u); /* update the state */ LFSR[0] = LFSR[1]; LFSR[1] = LFSR[2]; LFSR[2] = LFSR[3]; LFSR[3] = LFSR[4]; LFSR[4] = LFSR[5]; LFSR[5] = LFSR[6]; LFSR[6] = LFSR[7]; LFSR[7] = LFSR[8]; LFSR[8] = LFSR[9]; LFSR[9] = LFSR[10]; LFSR[10] = LFSR[11]; LFSR[11] = LFSR[12]; LFSR[12] = LFSR[13]; LFSR[13] = LFSR[14]; LFSR[14] = LFSR[15]; LFSR[15] = f; } /** * LFSR with work mode. */ private void LFSRWithWorkMode() { int f, v; f = LFSR[0]; v = MulByPow2(LFSR[0], 8); f = AddM(f, v); v = MulByPow2(LFSR[4], 20); f = AddM(f, v); v = MulByPow2(LFSR[10], 21); f = AddM(f, v); v = MulByPow2(LFSR[13], 17); f = AddM(f, v); v = MulByPow2(LFSR[15], 15); f = AddM(f, v); /* update the state */ LFSR[0] = LFSR[1]; LFSR[1] = LFSR[2]; LFSR[2] = LFSR[3]; LFSR[3] = LFSR[4]; LFSR[4] = LFSR[5]; LFSR[5] = LFSR[6]; LFSR[6] = LFSR[7]; LFSR[7] = LFSR[8]; LFSR[8] = LFSR[9]; LFSR[9] = LFSR[10]; LFSR[10] = LFSR[11]; LFSR[11] = LFSR[12]; LFSR[12] = LFSR[13]; LFSR[13] = LFSR[14]; LFSR[14] = LFSR[15]; LFSR[15] = f; } /** * BitReorganization. */ private void BitReorganization() { BRC[0] = ((LFSR[15] & 0x7FFF8000) << 1) | (LFSR[14] & 0xFFFF); BRC[1] = ((LFSR[11] & 0xFFFF) << 16) | (LFSR[9] >>> 15); BRC[2] = ((LFSR[7] & 0xFFFF) << 16) | (LFSR[5] >>> 15); BRC[3] = ((LFSR[2] & 0xFFFF) << 16) | (LFSR[0] >>> 15); } /** * Rotate integer. * * @param a the integer * @param k the shift * @return the result */ static int ROT(int a, int k) { return (((a) << k) | ((a) >>> (32 - k))); } /** * L1. * * @param X the input integer. * @return the result */ private static int L1(final int X) { return (X ^ ROT(X, 2) ^ ROT(X, 10) ^ ROT(X, 18) ^ ROT(X, 24)); } /** * L2. * * @param X the input integer. * @return the result */ private static int L2(final int X) { return (X ^ ROT(X, 8) ^ ROT(X, 14) ^ ROT(X, 22) ^ ROT(X, 30)); } /** * Build a 32-bit integer from constituent parts. * * @param a part A * @param b part B * @param c part C * @param d part D * @return the built integer */ private static int MAKEU32(final byte a, final byte b, final byte c, final byte d) { return (((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF))); } /** * F. */ int F() { int W, W1, W2, u, v; W = (BRC[0] ^ F[0]) + F[1]; W1 = F[0] + BRC[1]; W2 = F[1] ^ BRC[2]; u = L1((W1 << 16) | (W2 >>> 16)); v = L2((W2 << 16) | (W1 >>> 16)); F[0] = MAKEU32(S0[u >>> 24], S1[(u >>> 16) & 0xFF], S0[(u >>> 8) & 0xFF], S1[u & 0xFF]); F[1] = MAKEU32(S0[v >>> 24], S1[(v >>> 16) & 0xFF], S0[(v >>> 8) & 0xFF], S1[v & 0xFF]); return W; } /** * Build a 31-bit integer from constituent parts. * * @param a part A * @param b part B * @param c part C * @return the built integer */ private static int MAKEU31(final byte a, final short b, final byte c) { return (((a & 0xFF) << 23) | ((b & 0xFFFF) << 8) | (c & 0xFF)); } /** * Process key and IV into LFSR. * * @param pLFSR the LFSR * @param k the key * @param iv the iv */ protected void setKeyAndIV(final int[] pLFSR, final byte[] k, final byte[] iv) { /* Check lengths */ if (k == null || k.length != 16) { throw new IllegalArgumentException("A key of 16 bytes is needed"); } if (iv == null || iv.length != 16) { throw new IllegalArgumentException("An IV of 16 bytes is needed"); } /* expand key */ LFSR[0] = MAKEU31(k[0], EK_d[0], iv[0]); LFSR[1] = MAKEU31(k[1], EK_d[1], iv[1]); LFSR[2] = MAKEU31(k[2], EK_d[2], iv[2]); LFSR[3] = MAKEU31(k[3], EK_d[3], iv[3]); LFSR[4] = MAKEU31(k[4], EK_d[4], iv[4]); LFSR[5] = MAKEU31(k[5], EK_d[5], iv[5]); LFSR[6] = MAKEU31(k[6], EK_d[6], iv[6]); LFSR[7] = MAKEU31(k[7], EK_d[7], iv[7]); LFSR[8] = MAKEU31(k[8], EK_d[8], iv[8]); LFSR[9] = MAKEU31(k[9], EK_d[9], iv[9]); LFSR[10] = MAKEU31(k[10], EK_d[10], iv[10]); LFSR[11] = MAKEU31(k[11], EK_d[11], iv[11]); LFSR[12] = MAKEU31(k[12], EK_d[12], iv[12]); LFSR[13] = MAKEU31(k[13], EK_d[13], iv[13]); LFSR[14] = MAKEU31(k[14], EK_d[14], iv[14]); LFSR[15] = MAKEU31(k[15], EK_d[15], iv[15]); } /** * Process key and IV. * * @param k the key * @param iv the IV */ private void setKeyAndIV(final byte[] k, final byte[] iv) { /* Initialise LFSR */ setKeyAndIV(LFSR, k, iv); /* set F_R1 and F_R2 to zero */ F[0] = 0; F[1] = 0; int nCount = 32; while (nCount > 0) { BitReorganization(); final int w = F(); LFSRWithInitialisationMode(w >>> 1); nCount--; } BitReorganization(); F(); /* discard the output of F */ LFSRWithWorkMode(); } /** * Create the next byte keyStream. */ private void makeKeyStream() { encode32be(makeKeyStreamWord(), keyStream, 0); } /** * Create the next keyStream word. * * @return the next word */ protected int makeKeyStreamWord() { if (theIterations++ >= getMaxIterations()) { throw new IllegalStateException("Too much data processed by singleKey/IV"); } BitReorganization(); final int result = F() ^ BRC[3]; LFSRWithWorkMode(); return result; } /** * Create a copy of the engine. * * @return the copy */ public Memoable copy() { return new Zuc128CoreEngine(this); } /** * Reset from saved engine state. * * @param pState the state to restore */ public void reset(final Memoable pState) { final Zuc128CoreEngine e = (Zuc128CoreEngine)pState; System.arraycopy(e.LFSR, 0, LFSR, 0, LFSR.length); System.arraycopy(e.F, 0, F, 0, F.length); System.arraycopy(e.BRC, 0, BRC, 0, BRC.length); System.arraycopy(e.keyStream, 0, keyStream, 0, keyStream.length); theIndex = e.theIndex; theIterations = e.theIterations; theResetState = e; } }
11,241
1,483
<gh_stars>1000+ /* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package org.lealone.test.runmode; import org.junit.Test; public class ClientServerToReplicationTest extends RunModeTest { public ClientServerToReplicationTest() { setHost("127.0.0.1"); } @Test public void run() throws Exception { String dbName = ClientServerToReplicationTest.class.getSimpleName(); sql = "CREATE DATABASE IF NOT EXISTS " + dbName + " RUN MODE client_server"; sql += " PARAMETERS (node_assignment_strategy: 'RandomNodeAssignmentStrategy')"; executeUpdate(sql); Thread t = new Thread(() -> { new CrudTest(dbName).runTest(); }); t.start(); t.join(); sql = "ALTER DATABASE " + dbName + " RUN MODE replication"; sql += " PARAMETERS (replication_strategy: 'SimpleStrategy', replication_factor: 2,"; sql += " node_assignment_strategy: 'RandomNodeAssignmentStrategy')"; executeUpdate(sql); } }
420
348
/** * Copyright 2017 Netflix, Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.raigad.aws; import com.amazonaws.services.autoscaling.AmazonAutoScaling; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.model.*; import com.amazonaws.services.autoscaling.model.Instance; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.*; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.netflix.raigad.configuration.IConfiguration; import com.netflix.raigad.identity.IMembership; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Class to query amazon ASG for its members to provide - Number of valid nodes * in the ASG - Number of zones - Methods for adding ACLs for the nodes */ public class AWSMembership implements IMembership { private static final Logger logger = LoggerFactory.getLogger(AWSMembership.class); private final IConfiguration config; private final ICredential provider; @Inject public AWSMembership(IConfiguration config, ICredential provider) { this.config = config; this.provider = provider; } @Override public Map<String, List<String>> getRacMembership(Collection<String> autoScalingGroupNames) { if (CollectionUtils.isEmpty(autoScalingGroupNames)) { return Collections.emptyMap(); } AmazonAutoScaling client = null; try { client = getAutoScalingClient(); DescribeAutoScalingGroupsRequest describeAutoScalingGroupsRequest = new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(autoScalingGroupNames); DescribeAutoScalingGroupsResult describeAutoScalingGroupsResult = client.describeAutoScalingGroups(describeAutoScalingGroupsRequest); Map<String, List<String>> asgs = new HashMap<>(); for (AutoScalingGroup autoScalingGroup : describeAutoScalingGroupsResult.getAutoScalingGroups()) { List<String> asgInstanceIds = Lists.newArrayList(); for (Instance asgInstance : autoScalingGroup.getInstances()) { if (!(asgInstance.getLifecycleState().equalsIgnoreCase("terminating") || asgInstance.getLifecycleState().equalsIgnoreCase("shutting-down") || asgInstance.getLifecycleState().equalsIgnoreCase("terminated"))) { asgInstanceIds.add(asgInstance.getInstanceId()); } } asgs.put(autoScalingGroup.getAutoScalingGroupName(), asgInstanceIds); logger.info("AWS returned the following instance ID's for {} ASG: {}", autoScalingGroup.getAutoScalingGroupName(), StringUtils.join(asgInstanceIds, ",")); } return asgs; } finally { if (client != null) { client.shutdown(); } } } /** * Actual membership AWS source of truth... */ @Override public int getRacMembershipSize() { AmazonAutoScaling client = null; try { client = getAutoScalingClient(); DescribeAutoScalingGroupsRequest asgReq = new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(config.getASGName()); DescribeAutoScalingGroupsResult res = client.describeAutoScalingGroups(asgReq); int size = 0; for (AutoScalingGroup asg : res.getAutoScalingGroups()) { size += asg.getMaxSize(); } logger.info(String.format("Query on ASG returning %d instances", size)); return size; } finally { if (client != null) { client.shutdown(); } } } @Override public int getRacCount() { return config.getRacs().size(); } /** * Adds a list of IP's to the SG */ public void addACL(Collection<String> listIPs, int from, int to) { AmazonEC2 client = null; try { client = getEc2Client(); List<IpPermission> ipPermissions = new ArrayList<IpPermission>(); ipPermissions.add(new IpPermission().withFromPort(from).withIpProtocol("tcp").withIpRanges(listIPs).withToPort(to)); if (config.isDeployedInVPC()) { if (config.getACLGroupIdForVPC().isEmpty()) { throw new RuntimeException("ACLGroupIdForVPC cannot be empty, check if SetVPCSecurityGroupID had any errors"); } client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest() .withGroupId(config.getACLGroupIdForVPC()) .withIpPermissions(ipPermissions)); } else { client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest(config.getACLGroupName(), ipPermissions)); } logger.info("Added " + StringUtils.join(listIPs, ",") + " to ACL"); } finally { if (client != null) { client.shutdown(); } } } /** * Removes a list of IP's from the SG */ public void removeACL(Collection<String> listIPs, int from, int to) { AmazonEC2 client = null; try { client = getEc2Client(); List<IpPermission> ipPermissions = new ArrayList<IpPermission>(); ipPermissions.add(new IpPermission().withFromPort(from).withIpProtocol("tcp").withIpRanges(listIPs).withToPort(to)); if (config.isDeployedInVPC()) { if (config.getACLGroupIdForVPC().isEmpty()) { throw new RuntimeException("ACLGroupIdForVPC cannot be empty, check if SetVPCSecurityGroupID had any errors"); } client.revokeSecurityGroupIngress( new RevokeSecurityGroupIngressRequest() .withGroupId(config.getACLGroupIdForVPC()) .withIpPermissions(ipPermissions)); } else { client.revokeSecurityGroupIngress( new RevokeSecurityGroupIngressRequest(config.getACLGroupName(), ipPermissions)); } logger.info("Removed " + StringUtils.join(listIPs, ",") + " from ACL"); } finally { if (client != null) { client.shutdown(); } } } /** * List SG ACL's */ public List<String> listACL(int from, int to) { AmazonEC2 client = null; try { client = getEc2Client(); List<String> ipPermissions = new ArrayList<String>(); DescribeSecurityGroupsResult result; if (config.isDeployedInVPC()) { if (config.getACLGroupIdForVPC().isEmpty()) { throw new RuntimeException("ACLGroupIdForVPC cannot be empty, check if SetVPCSecurityGroupID had any errors"); } DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest().withGroupIds(config.getACLGroupIdForVPC()); result = client.describeSecurityGroups(describeSecurityGroupsRequest); } else { DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest().withGroupNames(Arrays.asList(config.getACLGroupName())); result = client.describeSecurityGroups(describeSecurityGroupsRequest); } for (SecurityGroup group : result.getSecurityGroups()) { for (IpPermission perm : group.getIpPermissions()) { if (perm.getFromPort() == from && perm.getToPort() == to) { ipPermissions.addAll(perm.getIpRanges()); } } } return ipPermissions; } finally { if (client != null) { client.shutdown(); } } } public Map<String, List<Integer>> getACLPortMap(String acl) { AmazonEC2 client = null; Map<String, List<Integer>> aclPortMap = new HashMap<String, List<Integer>>(); try { client = getEc2Client(); DescribeSecurityGroupsResult result; if (config.isDeployedInVPC()) { if (config.getACLGroupIdForVPC().isEmpty()) { throw new RuntimeException("ACLGroupIdForVPC cannot be empty, check if SetVPCSecurityGroupID had any errors"); } DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest().withGroupIds(config.getACLGroupIdForVPC()); result = client.describeSecurityGroups(describeSecurityGroupsRequest); } else { DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest().withGroupNames(Arrays.asList(config.getACLGroupName())); result = client.describeSecurityGroups(describeSecurityGroupsRequest); } for (SecurityGroup group : result.getSecurityGroups()) { for (IpPermission perm : group.getIpPermissions()) { for (String ipRange : perm.getIpRanges()) { // If given ACL matches from the list of IP ranges then look for "from" and "to" ports if (acl.equalsIgnoreCase(ipRange)) { List<Integer> fromToList = new ArrayList<Integer>(); fromToList.add(perm.getFromPort()); fromToList.add(perm.getToPort()); logger.info("ACL: {}, from: {}, to: {}", acl, perm.getFromPort(), perm.getToPort()); aclPortMap.put(acl, fromToList); } } } } return aclPortMap; } finally { if (client != null) { client.shutdown(); } } } @Override public void expandRacMembership(int count) { AmazonAutoScaling client = null; try { client = getAutoScalingClient(); DescribeAutoScalingGroupsRequest asgReq = new DescribeAutoScalingGroupsRequest().withAutoScalingGroupNames(config.getASGName()); DescribeAutoScalingGroupsResult res = client.describeAutoScalingGroups(asgReq); AutoScalingGroup asg = res.getAutoScalingGroups().get(0); UpdateAutoScalingGroupRequest ureq = new UpdateAutoScalingGroupRequest(); ureq.setAutoScalingGroupName(asg.getAutoScalingGroupName()); ureq.setMinSize(asg.getMinSize() + 1); ureq.setMaxSize(asg.getMinSize() + 1); ureq.setDesiredCapacity(asg.getMinSize() + 1); client.updateAutoScalingGroup(ureq); } finally { if (client != null) { client.shutdown(); } } } protected AmazonAutoScaling getAutoScalingClient() { AmazonAutoScaling client = new AmazonAutoScalingClient(provider.getAwsCredentialProvider()); client.setEndpoint("autoscaling." + config.getDC() + ".amazonaws.com"); return client; } protected AmazonEC2 getEc2Client() { AmazonEC2 client = new AmazonEC2Client(provider.getAwsCredentialProvider()); client.setEndpoint("ec2." + config.getDC() + ".amazonaws.com"); return client; } }
5,678
335
{ "word": "Morbid", "definitions": [ "Characterized by an abnormal and unhealthy interest in disturbing and unpleasant subjects, especially death and disease." ], "parts-of-speech": "Adjective" }
72
669
<reponame>sarvex/tensorflow-runtime // Copyright 2020 The TensorFlow Runtime Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tfrt/support/ranges_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "tfrt/support/ref_count.h" namespace tfrt { namespace { struct IntValue : ReferenceCounted<IntValue> { explicit IntValue(int v) : v{v} {} int v; }; TEST(RangesUtilTest, CopyRefToVector) { auto int_refs = {MakeRef<IntValue>(1), MakeRef<IntValue>(2)}; EXPECT_TRUE(llvm::equal(int_refs, CopyRefToSmallVector<3>(int_refs))); EXPECT_TRUE(llvm::equal(int_refs, CopyRefToVector(int_refs))); } } // namespace } // namespace tfrt
396
482
package io.nutz.demo.feign.module; import java.util.List; import org.nutz.boot.starter.feign.annotation.FeignInject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.adaptor.JsonAdaptor; import org.nutz.mvc.annotation.AdaptBy; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.DELETE; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.POST; import org.nutz.mvc.annotation.Param; import io.nutz.demo.feign.bean.User; import io.nutz.demo.feign.service.UserService; @IocBean @At("/user") @Ok("json:full") @AdaptBy(type=JsonAdaptor.class) public class UserModule { private static final Log log = Logs.get(); @FeignInject protected UserService userService; @At public List<User> list() { return userService.list(); } @At public User fetch(@Param("id")int id) { return userService.fetch(id); } @POST public User add(@Param("name")String name, @Param("age")int age) { return userService.add(name, age); } @DELETE public void delete(@Param("id")int id) { userService.delete(id); } /** * 这是演示api调用的入口,会顺序调用一堆请求,请关注日志 */ @Ok("raw") @At public String apitest() { List<User> users = userService.list(); log.info("users=" + Json.toJson(users)); User haoqoo = userService.add("haoqoo", 19); User wendal = userService.add("wendal", 28); users = userService.list(); log.info("users=" + Json.toJson(users)); userService.delete(haoqoo.getId()); userService.delete(wendal.getId()); users = userService.list(); log.info("users=" + Json.toJson(users)); return "done"; } }
841
2,151
<reponame>zipated/src<gh_stars>1000+ // Copyright 2018 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 "services/video_capture/texture_virtual_device_mojo_adapter.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "media/base/bind_to_current_loop.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "services/video_capture/public/mojom/constants.mojom.h" namespace video_capture { TextureVirtualDeviceMojoAdapter::TextureVirtualDeviceMojoAdapter( std::unique_ptr<service_manager::ServiceContextRef> service_ref) : service_ref_(std::move(service_ref)) {} TextureVirtualDeviceMojoAdapter::~TextureVirtualDeviceMojoAdapter() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::SetReceiverDisconnectedCallback( base::OnceClosure callback) { optional_receiver_disconnected_callback_ = std::move(callback); } void TextureVirtualDeviceMojoAdapter::OnNewMailboxHolderBufferHandle( int32_t buffer_id, media::mojom::MailboxBufferHandleSetPtr mailbox_handles) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Keep track of the buffer handles in order to be able to forward them to // the Receiver when it connects. This includes cases where a new Receiver // connects after a previous one has disconnected. known_buffer_handles_.insert( std::make_pair(buffer_id, mailbox_handles->Clone())); if (!receiver_.is_bound()) return; media::mojom::VideoBufferHandlePtr buffer_handle = media::mojom::VideoBufferHandle::New(); buffer_handle->set_mailbox_handles(std::move(mailbox_handles)); receiver_->OnNewBuffer(buffer_id, std::move(buffer_handle)); } void TextureVirtualDeviceMojoAdapter::OnFrameReadyInBuffer( int32_t buffer_id, mojom::ScopedAccessPermissionPtr access_permission, media::mojom::VideoFrameInfoPtr frame_info) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!receiver_.is_bound()) return; receiver_->OnFrameReadyInBuffer(buffer_id, 0 /* frame_feedback_id */, std::move(access_permission), std::move(frame_info)); } void TextureVirtualDeviceMojoAdapter::OnBufferRetired(int buffer_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); known_buffer_handles_.erase(buffer_id); if (!receiver_.is_bound()) return; receiver_->OnBufferRetired(buffer_id); } void TextureVirtualDeviceMojoAdapter::Start( const media::VideoCaptureParams& requested_settings, mojom::ReceiverPtr receiver) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); receiver.set_connection_error_handler(base::BindOnce( &TextureVirtualDeviceMojoAdapter::OnReceiverConnectionErrorOrClose, base::Unretained(this))); receiver_ = std::move(receiver); receiver_->OnStarted(); // Notify receiver of known buffer handles */ for (auto& entry : known_buffer_handles_) { media::mojom::VideoBufferHandlePtr buffer_handle = media::mojom::VideoBufferHandle::New(); buffer_handle->set_mailbox_handles(entry.second->Clone()); receiver_->OnNewBuffer(entry.first, std::move(buffer_handle)); } } void TextureVirtualDeviceMojoAdapter::OnReceiverReportingUtilization( int32_t frame_feedback_id, double utilization) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::RequestRefreshFrame() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::MaybeSuspend() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::Resume() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::GetPhotoState( GetPhotoStateCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::move(callback).Run(nullptr); } void TextureVirtualDeviceMojoAdapter::SetPhotoOptions( media::mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::TakePhoto(TakePhotoCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } void TextureVirtualDeviceMojoAdapter::Stop() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!receiver_.is_bound()) return; // Unsubscribe from connection error callbacks. receiver_.set_connection_error_handler(base::OnceClosure()); receiver_.reset(); } void TextureVirtualDeviceMojoAdapter::OnReceiverConnectionErrorOrClose() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); Stop(); if (optional_receiver_disconnected_callback_) std::move(optional_receiver_disconnected_callback_).Run(); } } // namespace video_capture
1,732
642
/* * Copyright 2016-2018 www.jeesuite.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeesuite.security; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import com.jeesuite.common.http.HttpMethod; import com.jeesuite.common.util.ResourceUtils; import com.jeesuite.common.util.WebUtils; import com.jeesuite.security.model.UserSession; import com.jeesuite.springweb.CurrentRuntimeContext; import com.jeesuite.springweb.exception.ForbiddenAccessException; import com.jeesuite.springweb.exception.UnauthorizedException; /** * @description <br> * @author <a href="mailto:<EMAIL>">vakin</a> * @date 2018年11月30日 */ public class SecurityDelegatingFilter implements Filter { private static final String DOT = "."; private static final String MSG_401_UNAUTHORIZED = "{\"code\": 401,\"msg\":\"401 Unauthorized\"}"; private static String MSG_403_FORBIDDEN = "{\"code\": 403,\"msg\":\"403 Forbidden\"}"; private static String apiUriSuffix = ResourceUtils.getProperty("api.uri.suffix"); private AuthAdditionHandler additionHandler; public void setAdditionHandler(AuthAdditionHandler additionHandler) { this.additionHandler = additionHandler; } @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; //忽略静态资源 if(request.getRequestURI().contains(DOT) && (apiUriSuffix == null || !request.getRequestURI().endsWith(apiUriSuffix))) { chain.doFilter(req, res); return; } if(request.getMethod().equals(HttpMethod.OPTIONS.name())) { chain.doFilter(req, res); return; } if(additionHandler != null) { additionHandler.beforeAuthorization(request, response); } CurrentRuntimeContext.init(request, response); UserSession userSession = null; try { userSession = SecurityDelegating.doAuthorization(); } catch (UnauthorizedException e) { response.setStatus(HttpStatus.UNAUTHORIZED.value()); if(WebUtils.isAjax(request)){ WebUtils.responseOutJson(response, MSG_401_UNAUTHORIZED); }else{ if(SecurityDelegating.getConfigurerProvider().error401Page() == null){ WebUtils.responseOutHtml(response, "401 Unauthorized"); }else{ String loginPage = WebUtils.getBaseUrl(request) + SecurityDelegating.getConfigurerProvider().error401Page(); response.sendRedirect(loginPage); } } return; }catch (ForbiddenAccessException e) { if(WebUtils.isAjax(request)){ WebUtils.responseOutJson(response, MSG_403_FORBIDDEN); }else{ if(SecurityDelegating.getConfigurerProvider().error403Page() == null){ WebUtils.responseOutHtml(response, "403 Forbidden"); }else{ String loginPage = WebUtils.getBaseUrl(request) + SecurityDelegating.getConfigurerProvider().error403Page(); response.sendRedirect(loginPage); } } return; } // if(additionHandler != null) { additionHandler.afterAuthorization(userSession); } chain.doFilter(req, res); } @Override public void destroy() {} }
1,431
1,394
<gh_stars>1000+ package com.fastaccess.permission.base.callback; import android.support.annotation.NonNull; public interface OnPermissionCallback { void onPermissionGranted(@NonNull String[] permissionName); void onPermissionDeclined(@NonNull String[] permissionName); void onPermissionPreGranted(@NonNull String permissionsName); void onPermissionNeedExplanation(@NonNull String permissionName); void onPermissionReallyDeclined(@NonNull String permissionName); void onNoPermissionNeeded(); }
154
463
package org.hive2hive.core.extras; import java.io.File; import java.security.PublicKey; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.hive2hive.core.api.interfaces.IFileConfiguration; import org.hive2hive.core.exceptions.NoPeerConnectionException; import org.hive2hive.core.exceptions.NoSessionException; import org.hive2hive.core.model.FileIndex; import org.hive2hive.core.model.FolderIndex; import org.hive2hive.core.model.Index; import org.hive2hive.core.network.NetworkManager; import org.hive2hive.core.processes.ProcessFactory; import org.hive2hive.processframework.composites.SyncProcess; import org.hive2hive.processframework.decorators.AsyncComponent; import org.hive2hive.processframework.interfaces.IProcessComponent; /** * Build a recursive process to add / delete multiple files. When for example uploading a folder with * subfolders, etc., this can't happen concurrently since parent folders must already be uploaded. * * @author Nico * */ @Extra public class FileRecursionUtil { private FileRecursionUtil() { // only static methods } public enum FileProcessAction { NEW_FILE, MODIFY_FILE, } /** * Creates an upload process. The order of the files does not depend. * * @param files a list of files to upload * @param action whether the files are for updating or as new files * @param networkManager the network manager with a session * @param fileConfiguration the file configuration * @return the root process (containing multiple async components) that manages the upload correctly * @throws NoSessionException if the user is not logged in * @throws NoPeerConnectionException if the peer has no connection */ public static IProcessComponent<Void> buildUploadProcess(List<File> files, FileProcessAction action, NetworkManager networkManager, IFileConfiguration fileConfiguration) throws NoSessionException, NoPeerConnectionException { // the root process SyncProcess rootProcess = new SyncProcess(); // key idea: Find the children with the same parents and add them to a sequential process. They need // to be sequential because the parent meta file must be adapted. If they would run in parallel, they // would modify the parent meta folder simultaneously. Map<File, SyncProcess> sameParents = new HashMap<File, SyncProcess>(); for (File file : files) { // create the process which uploads or updates the file IProcessComponent<Void> uploadProcess; if (action == FileProcessAction.NEW_FILE) { uploadProcess = ProcessFactory.instance().createAddFileProcess(file, networkManager, fileConfiguration); } else { uploadProcess = ProcessFactory.instance().createUpdateFileProcess(file, networkManager, fileConfiguration); } File parentFile = file.getParentFile(); if (sameParents.containsKey(parentFile)) { // a sibling exists that already created a sequential process SyncProcess process = sameParents.get(parentFile); process.add(uploadProcess); } else { // first file with this parent; create new sequential process SyncProcess process = new SyncProcess(); process.add(uploadProcess); sameParents.put(parentFile, process); } } // the children are now grouped together. Next, we need to link the parent files. for (File parent : sameParents.keySet()) { IProcessComponent<?> asyncChain = new AsyncComponent<>(sameParents.get(parent)); File parentOfParent = parent.getParentFile(); if (sameParents.containsKey(parentOfParent)) { // parent exists, we add this sub-process (sequential) to it. It can be async here SyncProcess process = sameParents.get(parentOfParent); process.add(asyncChain); } else { // parent does not exist --> attach the sub-tree to the root rootProcess.add(asyncChain); } } return rootProcess; } /** * Creates a process chain to delete all files in the list. Note that the list must be in pre-order, else * there will occur errors. * * @param files list of files to delete in preorder * @param networkManager the network manager with a session * @return the (async) root process component * @throws NoSessionException if the user is not logged in * @throws NoPeerConnectionException if the peer has no connection */ public static AsyncComponent<Void> buildDeletionProcess(List<File> files, NetworkManager networkManager) throws NoSessionException, NoPeerConnectionException { // the root process SyncProcess rootProcess = new SyncProcess(); // deletion must happen in reverse tree order. Since this is very complicated when it contains // asynchronous components, we simply delete them all in the same thread (reverse preorder of course) Collections.reverse(files); for (File file : files) { IProcessComponent<Void> deletionProcess = ProcessFactory.instance().createDeleteFileProcess(file, networkManager); rootProcess.add(deletionProcess); } return new AsyncComponent<Void>(rootProcess); } /** * This is a workaround to delete files when a {@link FolderIndex} is already existent. Since the node is * already here, the deletion could be speed up because it must not be looked up in the user profile. * * @param files list of files to delete * @param networkManager the network manager with a session * @return the process component the (async) root process component * @throws NoSessionException if the user is not logged in * @throws NoPeerConnectionException if the peer has no connection */ @Deprecated public static IProcessComponent<Future<Void>> buildDeletionProcessFromNodelist(List<Index> files, NetworkManager networkManager) throws NoSessionException, NoPeerConnectionException { List<File> filesToDelete = new ArrayList<File>(); for (Index documentIndex : files) { File file = documentIndex.asFile(networkManager.getSession().getRootFile()); filesToDelete.add(file); } return buildDeletionProcess(filesToDelete, networkManager); } /** * Creates a process with all children processes. * * @param files the files to download (order does not depend) * @param networkManager the connected node (note, it must have a session) * @return the root process component containing all sub-processes (and sub-tasks) * @throws NoSessionException if the user is not logged in * @throws NoPeerConnectionException if the peer has no connection */ public static IProcessComponent<Void> buildDownloadProcess(List<Index> files, NetworkManager networkManager) throws NoPeerConnectionException, NoSessionException { // the root process, where everything runs in parallel (only async children are added) SyncProcess rootProcess = new SyncProcess(); // build a flat map of the folders to download (such that O(1) for each lookup) Map<FolderIndex, SyncProcess> folderMap = new HashMap<FolderIndex, SyncProcess>(); Map<FileIndex, AsyncComponent<Void>> fileMap = new HashMap<FileIndex, AsyncComponent<Void>>(); for (Index file : files) { PublicKey fileKey = file.getFilePublicKey(); IProcessComponent<Void> downloadProcess = ProcessFactory.instance().createDownloadFileProcess(fileKey, networkManager); if (file.isFolder()) { // when a directory, the process may have multiple children, thus we need a sequential process SyncProcess folderProcess = new SyncProcess(); folderProcess.add(downloadProcess); folderMap.put((FolderIndex) file, folderProcess); } else { // when a file, the process can run in parallel with all siblings (done in next step) fileMap.put((FileIndex) file, new AsyncComponent<>(downloadProcess)); } } // find children with same parents and make them run in parallel // idea: iterate through all children and search for parent in other map. If not there, they can be // added to the root process anyway for (FileIndex file : fileMap.keySet()) { AsyncComponent<Void> fileProcess = fileMap.get(file); Index parent = file.getParent(); if (parent == null) { // file is in root, thus we can add it to the root process rootProcess.add(fileProcess); } else if (folderMap.containsKey(parent)) { // the parent exists here SyncProcess parentProcess = folderMap.get(parent); parentProcess.add(fileProcess); } else { // file is not in root and parent is not here, thus we simply add it to the root process rootProcess.add(fileProcess); } } // files and folder are linked. We now link the folders with other folders for (FolderIndex folder : folderMap.keySet()) { SyncProcess folderProcess = folderMap.get(folder); // In addition, we can make this process run asynchronous because it does not affect the siblings AsyncComponent<Void> asyncFolderProcess = new AsyncComponent<>(folderProcess); Index parent = folder.getParent(); if (parent == null) { // file is in root, thus we can add it to the root process. rootProcess.add(asyncFolderProcess); } else if (folderMap.containsKey(parent)) { // this folder has a parent SyncProcess parentProcess = folderMap.get(parent); parentProcess.add(asyncFolderProcess); } else { // folder is not in root and parent folder does not sync here, add it to the root process rootProcess.add(asyncFolderProcess); } } return rootProcess; } /** * Creates a process chain of the given processes in the same order * * @param processes the processes to align to a center * @return the process chain */ public static IProcessComponent<Void> createProcessChain(List<IProcessComponent<Void>> processes) { SyncProcess rootProcess = new SyncProcess(); for (IProcessComponent<Void> processComponent : processes) { rootProcess.add(processComponent); } return rootProcess; } /** * Get a list of all files and subfiles in the root directory. The files are visited and returned in * preorder * * @param root the root file * @return a flat list of all files in preorder */ public static List<File> getPreorderList(File root) { List<File> allFiles = new ArrayList<File>(); listFiles(root, allFiles); return allFiles; } private static void listFiles(File file, List<File> preorderList) { preorderList.add(file); File[] listFiles = file.listFiles(); if (listFiles != null) { for (File child : listFiles) { listFiles(child, preorderList); } } } }
3,128
604
/* * Serposcope - SEO rank checker https://serposcope.serphacker.com/ * * Copyright (c) 2016 SERP Hacker * @author <NAME> <<EMAIL>> * @license https://opensource.org/licenses/MIT MIT License */ package com.serphacker.serposcope; import java.util.Properties; import org.junit.Assume; import org.junit.Before; public abstract class DeepIntegrationTest { @Before public void before() throws Exception { Assume.assumeTrue("true".equals(System.getProperty("deepit"))); } }
175
2,060
<reponame>oliverhu/level-ip #include "syshead.h" #include "tcp.h" #include "tcp_data.h" #include "skbuff.h" #include "sock.h" static int tcp_parse_opts(struct tcp_sock *tsk, struct tcphdr *th) { uint8_t *ptr = th->data; uint8_t optlen = tcp_hlen(th) - 20; struct tcp_opt_mss *opt_mss = NULL; uint8_t sack_seen = 0; uint8_t tsopt_seen = 0; while (optlen > 0 && optlen < 20) { switch (*ptr) { case TCP_OPT_MSS: opt_mss = (struct tcp_opt_mss *)ptr; uint16_t mss = ntohs(opt_mss->mss); if (mss > 536 && mss <= 1460) { tsk->smss = mss; } ptr += sizeof(struct tcp_opt_mss); optlen -= 4; break; case TCP_OPT_NOOP: ptr += 1; optlen--; break; case TCP_OPT_SACK_OK: sack_seen = 1; optlen--; break; case TCP_OPT_TS: tsopt_seen = 1; optlen--; break; default: print_err("Unrecognized TCPOPT\n"); optlen--; break; } } if (!tsopt_seen) { tsk->tsopt = 0; } if (sack_seen && tsk->sackok) { // There's room for 4 sack blocks without TS OPT if (tsk->tsopt) tsk->sacks_allowed = 3; else tsk->sacks_allowed = 4; } else { tsk->sackok = 0; } return 0; } /* * Acks all segments from retransmissionn queue that are "older" * than current unacknowledged sequence */ static int tcp_clean_rto_queue(struct sock *sk, uint32_t una) { struct tcp_sock *tsk = tcp_sk(sk); struct sk_buff *skb; int rc = 0; while ((skb = skb_peek(&sk->write_queue)) != NULL) { if (skb->seq > 0 && skb->end_seq <= una) { /* skb fully acknowledged */ skb_dequeue(&sk->write_queue); skb->refcnt--; free_skb(skb); if (tsk->inflight > 0) { tsk->inflight--; } } else { break; } }; if (skb == NULL || tsk->inflight == 0) { /* No unacknowledged skbs, stop rto timer */ tcp_stop_rto_timer(tsk); } return rc; } static inline int __tcp_drop(struct sock *sk, struct sk_buff *skb) { free_skb(skb); return 0; } static int tcp_verify_segment(struct tcp_sock *tsk, struct tcphdr *th, struct sk_buff *skb) { struct tcb *tcb = &tsk->tcb; if (skb->dlen > 0 && tcb->rcv_wnd == 0) return 0; if (th->seq < tcb->rcv_nxt || th->seq > (tcb->rcv_nxt + tcb->rcv_wnd)) { tcpsock_dbg("Received invalid segment", (&tsk->sk)); return 0; } return 1; } /* TCP RST received */ static void tcp_reset(struct sock *sk) { sk->poll_events = (POLLOUT | POLLWRNORM | POLLERR | POLLHUP); switch (sk->state) { case TCP_SYN_SENT: sk->err = -ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->err = -EPIPE; break; case TCP_CLOSE: return; default: sk->err = -ECONNRESET; break; } tcp_done(sk); } static inline int tcp_discard(struct tcp_sock *tsk, struct sk_buff *skb, struct tcphdr *th) { free_skb(skb); return 0; } static int tcp_listen(struct tcp_sock *tsk, struct sk_buff *skb, struct tcphdr *th) { free_skb(skb); return 0; } static int tcp_synsent(struct tcp_sock *tsk, struct sk_buff *skb, struct tcphdr *th) { struct tcb *tcb = &tsk->tcb; struct sock *sk = &tsk->sk; tcpsock_dbg("state is synsent", sk); if (th->ack) { if (th->ack_seq <= tcb->iss || th->ack_seq > tcb->snd_nxt) { tcpsock_dbg("ACK is unacceptable", sk); if (th->rst) goto discard; goto reset_and_discard; } if (th->ack_seq < tcb->snd_una || th->ack_seq > tcb->snd_nxt) { tcpsock_dbg("ACK is unacceptable", sk); goto reset_and_discard; } } /* ACK is acceptable */ if (th->rst) { tcp_reset(&tsk->sk); goto discard; } /* third check the security and precedence -> ignored */ /* fourth check the SYN bit */ if (!th->syn) { goto discard; } tcb->rcv_nxt = th->seq + 1; tcb->irs = th->seq; if (th->ack) { tcb->snd_una = th->ack_seq; /* Any packets in RTO queue that are acknowledged here should be removed */ tcp_clean_rto_queue(sk, tcb->snd_una); } if (tcb->snd_una > tcb->iss) { tcp_set_state(sk, TCP_ESTABLISHED); tcb->snd_una = tcb->snd_nxt; tsk->backoff = 0; /* RFC 6298: Sender SHOULD set RTO <- 1 second */ tsk->rto = 1000; tcp_send_ack(&tsk->sk); tcp_rearm_user_timeout(&tsk->sk); tcp_parse_opts(tsk, th); sock_connected(sk); } else { tcp_set_state(sk, TCP_SYN_RECEIVED); tcb->snd_una = tcb->iss; tcp_send_synack(&tsk->sk); } discard: tcp_drop(sk, skb); return 0; reset_and_discard: //TODO reset tcp_drop(sk, skb); return 0; } static int tcp_closed(struct tcp_sock *tsk, struct sk_buff *skb, struct tcphdr *th) { /* All data in the incoming segment is discarded. An incoming segment containing a RST is discarded. An incoming segment not containing a RST causes a RST to be sent in response. The acknowledgment and sequence field values are selected to make the reset sequence acceptable to the TCP that sent the offending segment. If the ACK bit is off, sequence number zero is used, <SEQ=0><ACK=SEG.SEQ+SEG.LEN><CTL=RST,ACK> If the ACK bit is on, <SEQ=SEG.ACK><CTL=RST> Return. */ int rc = -1; tcpsock_dbg("state is closed", (&tsk->sk)); if (th->rst) { tcp_discard(tsk, skb, th); rc = 0; goto out; } if (th->ack) { } else { } rc = tcp_send_reset(tsk); free_skb(skb); out: return rc; } /* * Follows RFC793 "Segment Arrives" section closely */ int tcp_input_state(struct sock *sk, struct tcphdr *th, struct sk_buff *skb) { struct tcp_sock *tsk = tcp_sk(sk); struct tcb *tcb = &tsk->tcb; tcpsock_dbg("input state", sk); switch (sk->state) { case TCP_CLOSE: return tcp_closed(tsk, skb, th); case TCP_LISTEN: return tcp_listen(tsk, skb, th); case TCP_SYN_SENT: return tcp_synsent(tsk, skb, th); } /* "Otherwise" section in RFC793 */ /* first check sequence number */ if (!tcp_verify_segment(tsk, th, skb)) { /* RFC793: If an incoming segment is not acceptable, an acknowledgment * should be sent in reply (unless the RST bit is set, if so drop * the segment and return): */ if (!th->rst) { tcp_send_ack(sk); } return_tcp_drop(sk, skb); } /* second check the RST bit */ if (th->rst) { free_skb(skb); tcp_enter_time_wait(sk); tsk->sk.ops->recv_notify(&tsk->sk); return 0; } /* third check security and precedence */ // Not implemented /* fourth check the SYN bit */ if (th->syn) { /* RFC 5961 Section 4.2 */ tcp_send_challenge_ack(sk, skb); return_tcp_drop(sk, skb); } /* fifth check the ACK field */ if (!th->ack) { return_tcp_drop(sk, skb); } // ACK bit is on switch (sk->state) { case TCP_SYN_RECEIVED: if (tcb->snd_una <= th->ack_seq && th->ack_seq < tcb->snd_nxt) { tcp_set_state(sk, TCP_ESTABLISHED); } else { return_tcp_drop(sk, skb); } case TCP_ESTABLISHED: case TCP_FIN_WAIT_1: case TCP_FIN_WAIT_2: case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: if (tcb->snd_una < th->ack_seq && th->ack_seq <= tcb->snd_nxt) { tcb->snd_una = th->ack_seq; /* Any segments on the retransmission queue which are thereby entirely acknowledged are removed. */ tcp_rtt(tsk); tcp_clean_rto_queue(sk, tcb->snd_una); } if (th->ack_seq < tcb->snd_una) { // If the ACK is a duplicate, it can be ignored return_tcp_drop(sk, skb); } if (th->ack_seq > tcb->snd_nxt) { // If the ACK acks something not yet sent, then send an ACK, drop segment // and return // TODO: Dropping the seg here, why would I respond with an ACK? Linux // does not respond either //tcp_send_ack(&tsk->sk); return_tcp_drop(sk, skb); } if (tcb->snd_una < th->ack_seq && th->ack_seq <= tcb->snd_nxt) { // TODO: Send window should be updated } break; } /* If the write queue is empty, it means our FIN was acked */ if (skb_queue_empty(&sk->write_queue)) { switch (sk->state) { case TCP_FIN_WAIT_1: tcp_set_state(sk, TCP_FIN_WAIT_2); case TCP_FIN_WAIT_2: break; case TCP_CLOSING: /* In addition to the processing for the ESTABLISHED state, if * the ACK acknowledges our FIN then enter the TIME-WAIT state, otherwise ignore the segment. */ tcp_set_state(sk, TCP_TIME_WAIT); break; case TCP_LAST_ACK: /* The only thing that can arrive in this state is an acknowledgment of our FIN. * If our FIN is now acknowledged, delete the TCB, enter the CLOSED state, and return. */ free_skb(skb); return tcp_done(sk); case TCP_TIME_WAIT: /* TODO: The only thing that can arrive in this state is a retransmission of the remote FIN. Acknowledge it, and restart the 2 MSL timeout. */ if (tcb->rcv_nxt == th->seq) { tcpsock_dbg("Remote FIN retransmitted?", sk); // tcb->rcv_nxt += 1; tsk->flags |= TCP_FIN; tcp_send_ack(sk); } break; } } /* sixth, check the URG bit */ if (th->urg) { } int expected = skb->seq == tcb->rcv_nxt; /* seventh, process the segment txt */ switch (sk->state) { case TCP_ESTABLISHED: case TCP_FIN_WAIT_1: case TCP_FIN_WAIT_2: if (th->psh || skb->dlen > 0) { tcp_data_queue(tsk, th, skb); } break; case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: case TCP_TIME_WAIT: /* This should not occur, since a FIN has been received from the remote side. Ignore the segment text. */ break; } /* eighth, check the FIN bit */ if (th->fin && expected) { tcpsock_dbg("Received in-sequence FIN", sk); switch (sk->state) { case TCP_CLOSE: case TCP_LISTEN: case TCP_SYN_SENT: // Do not process, since SEG.SEQ cannot be validated goto drop_and_unlock; } tcb->rcv_nxt += 1; tsk->flags |= TCP_FIN; sk->poll_events |= (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND); tcp_send_ack(sk); tsk->sk.ops->recv_notify(&tsk->sk); switch (sk->state) { case TCP_SYN_RECEIVED: case TCP_ESTABLISHED: tcp_set_state(sk, TCP_CLOSE_WAIT); break; case TCP_FIN_WAIT_1: /* If our FIN has been ACKed (perhaps in this segment), then enter TIME-WAIT, start the time-wait timer, turn off the other timers; otherwise enter the CLOSING state. */ if (skb_queue_empty(&sk->write_queue)) { tcp_enter_time_wait(sk); } else { tcp_set_state(sk, TCP_CLOSING); } break; case TCP_FIN_WAIT_2: /* Enter the TIME-WAIT state. Start the time-wait timer, turn off the other timers. */ tcp_enter_time_wait(sk); break; case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: /* Remain in the state */ break; case TCP_TIME_WAIT: /* TODO: Remain in the TIME-WAIT state. Restart the 2 MSL time-wait timeout. */ break; } } /* Congestion control and delacks */ switch (sk->state) { case TCP_ESTABLISHED: case TCP_FIN_WAIT_1: case TCP_FIN_WAIT_2: if (expected) { tcp_stop_delack_timer(tsk); int pending = min(skb_queue_len(&sk->write_queue), 3); /* RFC1122: A TCP SHOULD implement a delayed ACK, but an ACK should not * be excessively delayed; in particular, the delay MUST be less than * 0.5 seconds, and in a stream of full-sized segments there SHOULD * be an ACK for at least every second segment. */ if (tsk->inflight == 0 && pending > 0) { tcp_send_next(sk, pending); tsk->inflight += pending; tcp_rearm_rto_timer(tsk); } else if (th->psh || (skb->dlen > 1000 && ++tsk->delacks > 1)) { tsk->delacks = 0; tcp_send_ack(sk); } else if (skb->dlen > 0) { tsk->delack = timer_add(200, &tcp_send_delack, &tsk->sk); } } } free_skb(skb); unlock: return 0; drop_and_unlock: tcp_drop(sk, skb); goto unlock; } int tcp_receive(struct tcp_sock *tsk, void *buf, int len) { int rlen = 0; int curlen = 0; struct sock *sk = &tsk->sk; struct socket *sock = sk->sock; memset(buf, 0, len); while (rlen < len) { curlen = tcp_data_dequeue(tsk, buf + rlen, len - rlen); rlen += curlen; if (tsk->flags & TCP_PSH) { tsk->flags &= ~TCP_PSH; break; } if (tsk->flags & TCP_FIN || rlen == len) break; if (sock->flags & O_NONBLOCK) { if (rlen == 0) { rlen = -EAGAIN; } break; } else { pthread_mutex_lock(&tsk->sk.recv_wait.lock); socket_release(sock); wait_sleep(&tsk->sk.recv_wait); pthread_mutex_unlock(&tsk->sk.recv_wait.lock); socket_wr_acquire(sock); } } if (rlen >= 0) tcp_rearm_user_timeout(sk); return rlen; }
7,553
575
// Copyright 2017 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 "chrome/browser/resource_coordinator/tab_metrics_logger.h" #include <algorithm> #include <string> #include "base/check_op.h" #include "base/containers/contains.h" #include "base/notreached.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/resource_coordinator/tab_lifecycle_unit_external.h" #include "chrome/browser/resource_coordinator/tab_manager_features.h" #include "chrome/browser/resource_coordinator/tab_metrics_event.pb.h" #include "chrome/browser/resource_coordinator/tab_ranker/mru_features.h" #include "chrome/browser/resource_coordinator/tab_ranker/tab_features.h" #include "chrome/browser/resource_coordinator/tab_ranker/window_features.h" #include "chrome/browser/resource_coordinator/utils.h" #include "chrome/browser/tab_contents/form_interaction_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/recently_audible_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/site_engagement/content/site_engagement_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "net/base/mime_util.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "third_party/blink/public/mojom/frame/sudden_termination_disabler_type.mojom.h" #include "url/gurl.h" using metrics::TabMetricsEvent; using metrics::WindowMetricsEvent; namespace { // Returns the number of discards that happened to |contents|. int GetDiscardCount(content::WebContents* contents) { auto* external = resource_coordinator::TabLifecycleUnitExternal::FromWebContents(contents); DCHECK(external); return external->GetDiscardCount(); } // Populates navigation-related metrics. void PopulatePageTransitionFeatures(ui::PageTransition page_transition, tab_ranker::TabFeatures* tab) { // We only report the following core types. // Note: Redirects unrelated to clicking a link still get the "link" type. if (ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_LINK) || ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_AUTO_BOOKMARK) || ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_FORM_SUBMIT) || ui::PageTransitionCoreTypeIs(page_transition, ui::PAGE_TRANSITION_RELOAD)) { tab->page_transition_core_type = ui::PageTransitionStripQualifier(page_transition); } tab->page_transition_from_address_bar = (page_transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) != 0; tab->page_transition_is_redirect = ui::PageTransitionIsRedirect(page_transition); } // Populates TabFeatures from |page_metrics|. void PopulateTabFeaturesFromPageMetrics( const TabMetricsLogger::PageMetrics& page_metrics, tab_ranker::TabFeatures* tab) { static_assert(sizeof(TabMetricsLogger::PageMetrics) == sizeof(int) * 4 + sizeof(ui::PageTransition), "Make sure all fields in PageMetrics are considered here."); tab->key_event_count = page_metrics.key_event_count; tab->mouse_event_count = page_metrics.mouse_event_count; tab->num_reactivations = page_metrics.num_reactivations; tab->touch_event_count = page_metrics.touch_event_count; PopulatePageTransitionFeatures(page_metrics.page_transition, tab); } // Populates TabFeatures that can be calculated simply from |web_contents|. void PopulateTabFeaturesFromWebContents(content::WebContents* web_contents, tab_ranker::TabFeatures* tab_features) { tab_features->has_before_unload_handler = web_contents->GetMainFrame()->GetSuddenTerminationDisablerState( blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler); tab_features->has_form_entry = FormInteractionTabHelper::FromWebContents(web_contents) ->had_form_interaction(); tab_features->host = web_contents->GetLastCommittedURL().host(); tab_features->navigation_entry_count = web_contents->GetController().GetEntryCount(); if (site_engagement::SiteEngagementService::IsEnabled()) { tab_features->site_engagement_score = TabMetricsLogger::GetSiteEngagementScore(web_contents); } // This checks if the tab was audible within the past two seconds, same as the // audio indicator in the tab strip. tab_features->was_recently_audible = RecentlyAudibleHelper::FromWebContents(web_contents) ->WasRecentlyAudible(); tab_features->discard_count = GetDiscardCount(web_contents); } // Populates TabFeatures that calculated from |browser| including WindowMetrics // and PinState. void PopulateTabFeaturesFromBrowser(const Browser* browser, content::WebContents* web_contents, tab_ranker::TabFeatures* tab_features) { // For pin state. const TabStripModel* tab_strip_model = browser->tab_strip_model(); int index = tab_strip_model->GetIndexOfWebContents(web_contents); DCHECK_NE(index, TabStripModel::kNoTab); tab_features->is_pinned = tab_strip_model->IsTabPinned(index); // For window features. tab_ranker::WindowFeatures window = TabMetricsLogger::CreateWindowFeatures(browser); tab_features->window_is_active = window.is_active; tab_features->window_show_state = window.show_state; tab_features->window_tab_count = window.tab_count; tab_features->window_type = window.type; } } // namespace TabMetricsLogger::TabMetricsLogger() = default; TabMetricsLogger::~TabMetricsLogger() = default; // static int TabMetricsLogger::GetSiteEngagementScore( content::WebContents* web_contents) { if (!site_engagement::SiteEngagementService::IsEnabled()) return -1; site_engagement::SiteEngagementService* service = site_engagement::SiteEngagementService::Get( Profile::FromBrowserContext(web_contents->GetBrowserContext())); DCHECK(service); // Scores range from 0 to 100. Round down to a multiple of 10 to conform to // privacy guidelines. double raw_score = service->GetScore(web_contents->GetVisibleURL()); int rounded_score = static_cast<int>(raw_score / 10) * 10; DCHECK_LE(0, rounded_score); DCHECK_GE(100, rounded_score); return rounded_score; } // static base::Optional<tab_ranker::TabFeatures> TabMetricsLogger::GetTabFeatures( const PageMetrics& page_metrics, content::WebContents* web_contents) { Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (!browser) return base::nullopt; tab_ranker::TabFeatures tab; PopulateTabFeaturesFromWebContents(web_contents, &tab); PopulateTabFeaturesFromBrowser(browser, web_contents, &tab); PopulateTabFeaturesFromPageMetrics(page_metrics, &tab); return tab; } void TabMetricsLogger::LogTabMetrics( ukm::SourceId ukm_source_id, const tab_ranker::TabFeatures& tab_features, content::WebContents* web_contents, int64_t label_id) { if (!ukm_source_id) return; if (web_contents) { // UKM recording is disabled in OTR. if (web_contents->GetBrowserContext()->IsOffTheRecord()) return; // Verify that the browser is not closing. const Browser* browser = chrome::FindBrowserWithWebContents(web_contents); if (base::Contains(BrowserList::GetInstance()->currently_closing_browsers(), browser)) { return; } const TabStripModel* tab_strip_model = browser->tab_strip_model(); if (tab_strip_model->closing_all()) return; } ukm::builders::TabManager_TabMetrics entry(ukm_source_id); PopulateTabFeaturesToUkmEntry(tab_features, &entry); entry.SetLabelId(label_id); entry.SetQueryId(query_id_); entry.Record(ukm::UkmRecorder::Get()); } void TabMetricsLogger::LogForegroundedOrClosedMetrics( ukm::SourceId ukm_source_id, const ForegroundedOrClosedMetrics& metrics) { if (!ukm_source_id) return; ukm::builders::TabManager_Background_ForegroundedOrClosed(ukm_source_id) .SetLabelId(metrics.label_id) .SetIsForegrounded(metrics.is_foregrounded) .SetTimeFromBackgrounded(metrics.time_from_backgrounded) .SetIsDiscarded(metrics.is_discarded) .Record(ukm::UkmRecorder::Get()); } void TabMetricsLogger::LogTabLifetime(ukm::SourceId ukm_source_id, base::TimeDelta time_since_navigation) { if (!ukm_source_id) return; ukm::builders::TabManager_TabLifetime(ukm_source_id) .SetTimeSinceNavigation(time_since_navigation.InMilliseconds()) .Record(ukm::UkmRecorder::Get()); } // static tab_ranker::WindowFeatures TabMetricsLogger::CreateWindowFeatures( const Browser* browser) { DCHECK(browser->window()); WindowMetricsEvent::Type window_type = WindowMetricsEvent::TYPE_UNKNOWN; switch (browser->type()) { case Browser::TYPE_NORMAL: window_type = WindowMetricsEvent::TYPE_TABBED; break; case Browser::TYPE_POPUP: window_type = WindowMetricsEvent::TYPE_POPUP; break; case Browser::TYPE_APP: case Browser::TYPE_APP_POPUP: window_type = WindowMetricsEvent::TYPE_APP; break; case Browser::TYPE_DEVTOOLS: window_type = WindowMetricsEvent::TYPE_APP; break; default: NOTREACHED(); } WindowMetricsEvent::ShowState show_state = WindowMetricsEvent::SHOW_STATE_UNKNOWN; if (browser->window()->IsFullscreen()) show_state = WindowMetricsEvent::SHOW_STATE_FULLSCREEN; else if (browser->window()->IsMinimized()) show_state = WindowMetricsEvent::SHOW_STATE_MINIMIZED; else if (browser->window()->IsMaximized()) show_state = WindowMetricsEvent::SHOW_STATE_MAXIMIZED; else show_state = WindowMetricsEvent::SHOW_STATE_NORMAL; const bool is_active = browser->window()->IsActive(); const int tab_count = browser->tab_strip_model()->count(); return {window_type, show_state, is_active, tab_count}; }
3,881
684
<filename>console/config/settings/local.py<gh_stars>100-1000 """ Local settings - Run in Debug mode - Add Django Debug Toolbar """ from .base import * # noqa # DEBUG # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True # django-debug-toolbar # ------------------------------------------------------------------------------ MIDDLEWARE += [ # noqa "debug_toolbar.middleware.DebugToolbarMiddleware", ] INSTALLED_APPS += [ # noqa "debug_toolbar", ] INTERNAL_IPS = ["127.0.0.1"] # Your local stuff: Below this line define 3rd party library settings # ------------------------------------------------------------------------------
198
313
<filename>test/function/224.c<gh_stars>100-1000 /* TEST_HEADER id = $Id$ summary = MVFF allocate large promise, make it small, repeat language = c link = testlib.o harness = 2.5 parameters = PROMISE=65536 ITERATE=2000 END_HEADER */ #include "mpsavm.h" #include "mpscmvff.h" #include "testlib.h" #define VMSIZE ((size_t) 30*1024*1024) static void test(void *stack_pointer) { mps_arena_t arena; mps_pool_t pool; mps_addr_t q; int p; die(mps_arena_create(&arena, mps_arena_class_vm(), VMSIZE), "create"); die(mps_arena_commit_limit_set(arena, VMSIZE), "commit limit"); die(mps_pool_create_k(&pool, arena, mps_class_mvff(), mps_args_none), "pool create"); for (p=0; p<ITERATE; p++) { die(mps_alloc(&q, pool, PROMISE), "alloc"); q = (char *)q + MPS_PF_ALIGN; mps_free(pool, q, PROMISE - MPS_PF_ALIGN); report("promise", "%i", p); } mps_pool_destroy(pool); mps_arena_destroy(arena); } int main(void) { run_test(test); pass(); return 0; }
420
488
######################################################################## # Imports ######################################################################## import cPickle import errno import os import qm.common import qm.executable import qm.fields import qm.test.base from qm.test.test import Test from qm.test.result import Result import string import sys import types ######################################################################## # Classes ######################################################################## class RoseObjectTestBase(Test): """Check a program's output and exit code. An 'RoseTestBase' runs a program and compares its standard output, standard error, and exit code with expected values. The program may be provided with command-line arguments and/or standard input. The test passes if the standard output, standard error, and exit code are identical to the expected values.""" arguments = [ qm.fields.TextField( name="stdin", title="Standard Input", verbatim="true", multiline="true", description="""The contents of the standard input stream. If this field is left blank, the standard input stream will contain no data.""" ), qm.fields.SetField(qm.fields.TextField( name="environment", title="Environment", description="""Additional environment variables. By default, QMTest runs tests with the same environment that QMTest is running in. If you run tests in parallel, or using a remote machine, the environment variables available will be dependent on the context in which the remote test is executing. You may add variables to the environment. Each entry must be of the form 'VAR=VAL'. The program will be run in an environment where the environment variable 'VAR' has the value 'VAL'. If 'VAR' already had a value in the environment, it will be replaced with 'VAL'. In addition, QMTest automatically adds an environment variable corresponding to each context property. The name of the environment variable is the name of the context property, prefixed with 'QMV_'. For example, if the value of the context property named 'target' is available in the environment variable 'QMV_target'. Any dots in the context key are replaced by a double-underscore; e.g., "CompilerTable.c_path" will become "QMV_CompilerTable__c_path".""" )), qm.fields.IntegerField( name="exit_code", title="Exit Code", description="""The expected exit code. Most programs use a zero exit code to indicate success and a non-zero exit code to indicate failure.""" ), qm.fields.TextField( name="stdout", title="Standard Output", verbatim="true", multiline="true", description="""The expected contents of the standard output stream. If the output written by the program does not match this value, the test will fail.""" ), qm.fields.TextField( name="stderr", title="Standard Error", verbatim="true", multiline="true", description="""The expected contents of the standard error stream. If the output written by the program does not match this value, the test will fail.""" ), qm.fields.IntegerField( name="timeout", title="Timeout", description="""The number of seconds the child program will run. If this field is non-negative, it indicates the number of seconds the child program will be permitted to run. If this field is not present, or negative, the child program will be permitted to run for ever.""", default_value = -1, ), ] def MakeEnvironment(self, context): """Construct the environment for executing the target program.""" # Start with any environment variables that are already present # in the environment. environment = os.environ.copy() # Copy context variables into the environment. for key, value in context.items(): # If the value has unicode type, only transfer # it if it can be cast to str. if isinstance(value, unicode): try: value = str(value) except UnicodeEncodeError: continue if isinstance(value, str): name = "QMV_" + key.replace(".", "__") environment[name] = value # Extract additional environment variable assignments from the # 'Environment' field. for assignment in self.environment: if "=" in assignment: # Break the assignment at the first equals sign. variable, value = string.split(assignment, "=", 1) environment[variable] = value else: raise ValueError, \ qm.error("invalid environment assignment", assignment=assignment) return environment def ValidateOutput(self, stdout, stderr, result, objArg): """Validate the output of the program. Check for the presence of ROSE compiled object file specified in arguments. 'stdout' -- A string containing the data written to the standard output stream. 'stderr' -- A string containing the data written to the standard error stream. 'result' -- A 'Result' object. It may be used to annotate the outcome according to the content of stderr. returns -- A list of strings giving causes of failure.""" causes = [] # parse out the obj argument from source file to object file extension object = objArg.split("/") object = object[len(object) - 1].split(".") object = object[0] + ".o" # build and append the object file to the present working path pwd = os.getcwd() pwd = pwd + "/" pwd = pwd + object if not os.path.exists( pwd ): causes.append( object + " Not Found!" ) result["RoseTest.expected_stdout"] = result.Quote(self.stdout) return causes # old code that worked with a modified translator script; not needed! # search for presence of object file, if not found test failed # if stdout.find(object) == -1: # causes.append(object + " Not Found!") # result["RoseTest.expected_stdout"] = result.Quote(self.stdout) def RunProgram(self, program, arguments, context, result): """Run the 'program'. 'program' -- The path to the program to run. 'arguments' -- A list of the arguments to the program. This list must contain a first argument corresponding to 'argv[0]'. 'context' -- A 'Context' giving run-time parameters to the test. 'result' -- A 'Result' object. The outcome will be 'Result.PASS' when this method is called. The 'result' may be modified by this method to indicate outcomes other than 'Result.PASS' or to add annotations.""" # Construct the environment. environment = self.MakeEnvironment(context) # Create the executable. if self.timeout >= 0: timeout = self.timeout else: # If no timeout was specified, we sill run this process in a # separate process group and kill the entire process group # when the child is done executing. That means that # orphaned child processes created by the test will be # cleaned up. timeout = -2 e = qm.executable.Filter(self.stdin, timeout) # Run it. exit_status = e.Run(arguments, environment, path = program) # If the process terminated normally, check the outputs. if sys.platform == "win32" or os.WIFEXITED(exit_status): # There are no causes of failure yet. causes = [] # The target program terminated normally. Extract the # exit code, if this test checks it. if self.exit_code is None: exit_code = None elif sys.platform == "win32": exit_code = exit_status else: exit_code = os.WEXITSTATUS(exit_status) # Get the output generated by the program. stdout = e.stdout stderr = e.stderr # Record the results. result["RoseTest.exit_code"] = str(exit_code) result["RoseTest.stdout"] = result.Quote(stdout) result["RoseTest.stderr"] = result.Quote(stderr) # Check to see if the exit code matches. if exit_code != self.exit_code: causes.append("exit_code") result["RoseTest.expected_exit_code"] = str(self.exit_code) # Validate the output. causes += self.ValidateOutput(stdout, stderr, result, arguments[len(arguments)-1]) # If anything went wrong, the test failed. if causes: result.Fail("Unexpected %s." % string.join(causes, ", ")) elif os.WIFSIGNALED(exit_status): # The target program terminated with a signal. Construe # that as a test failure. signal_number = str(os.WTERMSIG(exit_status)) result.Fail("Program terminated by signal.") result["RoseTest.signal_number"] = signal_number # START MODIFICATION GMY 7/26/2006 # Get the output generated by the program. stdout = e.stdout stderr = e.stderr result["RoseTest.stdout"] = stdout result["RoseTest.stderr"] = stderr # END MODIFICATION GMY 7/26/2006 elif os.WIFSTOPPED(exit_status): # The target program was stopped. Construe that as a # test failure. signal_number = str(os.WSTOPSIG(exit_status)) result.Fail("Program stopped by signal.") result["RoseTest.signal_number"] = signal_number else: # The target program terminated abnormally in some other # manner. (This shouldn't normally happen...) result.Fail("Program did not terminate normally.") class RoseTest(RoseObjectTestBase): """Check a program's output and exit code. An 'RoseTest' runs a program by using the 'exec' system call.""" arguments = [ qm.fields.TextField( name="rose", title="ROSE PATH", not_empty_text=1, description="""The path to the ROSE translator. """ ), qm.fields.SetField(qm.fields.TextField( name="arguments", title="Argument List", description="""The command-line arguments. If this field is left blank, the program is run without any arguments. An implicit 0th argument (the path to the program) is added automatically.""" ))] _allow_arg_names_matching_class_vars = 1 def Run(self, context, result): """Run the test. 'context' -- A 'Context' giving run-time parameters to the test. 'result' -- A 'Result' object. The outcome will be 'Result.PASS' when this method is called. The 'result' may be modified by this method to indicate outcomes other than 'Result.PASS' or to add annotations.""" # Was the program not specified? if string.strip(self.rose) == "": result.Fail("No path to ROSE specified.") return self.RunProgram(self.rose, [ self.rose ] + self.arguments, context, result)
4,953
306
<gh_stars>100-1000 import math import copy import time import torch import torch.nn as nn __all__ = [ 'mix_images', 'mix_labels', 'label_smooth', 'cross_entropy_loss_with_soft_target', 'cross_entropy_with_label_smoothing', 'clean_num_batch_tracked', 'rm_bn_from_net', 'get_net_device', 'count_parameters', 'count_net_flops', 'count_peak_activation_size', 'measure_net_latency', 'get_net_info', 'build_optimizer', 'calc_learning_rate', ] """ Mixup """ def mix_images(images, lam): flipped_images = torch.flip(images, dims=[0]) # flip along the batch dimension return lam * images + (1 - lam) * flipped_images def mix_labels(target, lam, n_classes, label_smoothing=0.1): onehot_target = label_smooth(target, n_classes, label_smoothing) flipped_target = torch.flip(onehot_target, dims=[0]) return lam * onehot_target + (1 - lam) * flipped_target """ Label smooth """ def label_smooth(target, n_classes: int, label_smoothing=0.1): # convert to one-hot batch_size = target.size(0) target = torch.unsqueeze(target, 1) soft_target = torch.zeros((batch_size, n_classes), device=target.device) soft_target.scatter_(1, target, 1) # label smoothing soft_target = soft_target * (1 - label_smoothing) + label_smoothing / n_classes return soft_target def cross_entropy_loss_with_soft_target(pred, soft_target): logsoftmax = nn.LogSoftmax() return torch.mean(torch.sum(- soft_target * logsoftmax(pred), 1)) def cross_entropy_with_label_smoothing(pred, target, label_smoothing=0.1): soft_target = label_smooth(target, pred.size(1), label_smoothing) return cross_entropy_loss_with_soft_target(pred, soft_target) """ BN related """ def clean_num_batch_tracked(net): for m in net.modules(): if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): if m.num_batches_tracked is not None: m.num_batches_tracked.zero_() def rm_bn_from_net(net): for m in net.modules(): if isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d): m.forward = lambda x: x """ Network profiling """ def get_net_device(net): return net.parameters().__next__().device def count_parameters(net): total_params = sum(p.numel() for p in net.parameters() if p.requires_grad) return total_params def count_net_flops(net, data_shape=(1, 3, 224, 224)): from .flops_counter import profile if isinstance(net, nn.DataParallel): net = net.module flop, _ = profile(copy.deepcopy(net), data_shape) return flop def count_peak_activation_size(net, data_shape=(1, 3, 224, 224)): from tinynas.nn.networks import MobileInvertedResidualBlock def record_in_out_size(m, x, y): x = x[0] m.input_size = torch.Tensor([x.numel()]) m.output_size = torch.Tensor([y.numel()]) def add_io_hooks(m_): m_type = type(m_) if m_type in [nn.Conv2d, nn.Linear, MobileInvertedResidualBlock]: m_.register_buffer('input_size', torch.zeros(1)) m_.register_buffer('output_size', torch.zeros(1)) m_.register_forward_hook(record_in_out_size) def count_conv_mem(m): # we assume we only need to store input and output, the weights are partially loaded for computation if m is None: return 0 if hasattr(m, 'conv'): m = m.conv elif hasattr(m, 'linear'): m = m.linear assert isinstance(m, (nn.Conv2d, nn.Linear)) return m.input_size.item() + m.output_size.item() def count_block(m): from tinynas.nn.modules import ZeroLayer assert isinstance(m, MobileInvertedResidualBlock) if m.mobile_inverted_conv is None or isinstance(m.mobile_inverted_conv, ZeroLayer): # just an identical mapping return 0 elif m.shortcut is None or isinstance(m.shortcut, ZeroLayer): # no residual connection, just convs return max([ count_conv_mem(m.mobile_inverted_conv.inverted_bottleneck), count_conv_mem(m.mobile_inverted_conv.depth_conv), count_conv_mem(m.mobile_inverted_conv.point_linear), ]) else: # convs and residual residual_size = m.mobile_inverted_conv.inverted_bottleneck.conv.input_size.item() # consider residual size for later layers return max([ count_conv_mem(m.mobile_inverted_conv.inverted_bottleneck), count_conv_mem(m.mobile_inverted_conv.depth_conv) + residual_size, # TODO: can we omit the residual here? reuse the output? count_conv_mem(m.mobile_inverted_conv.point_linear) # + residual_size, ]) if isinstance(net, nn.DataParallel): net = net.module net = copy.deepcopy(net) from tinynas.nn.networks import ProxylessNASNets assert isinstance(net, ProxylessNASNets) # record the input and output size net.apply(add_io_hooks) with torch.no_grad(): _ = net(torch.randn(*data_shape).to(net.parameters().__next__().device)) mem_list = [ count_conv_mem(net.first_conv), count_conv_mem(net.feature_mix_layer), count_conv_mem(net.classifier) ] + [count_block(blk) for blk in net.blocks] del net return max(mem_list) # pick the peak mem def measure_net_latency(net, l_type='gpu8', fast=True, input_shape=(3, 224, 224), clean=False): if isinstance(net, nn.DataParallel): net = net.module # remove bn from graph rm_bn_from_net(net) # return `ms` if 'gpu' in l_type: l_type, batch_size = l_type[:3], int(l_type[3:]) else: batch_size = 1 data_shape = [batch_size] + list(input_shape) if l_type == 'cpu': if fast: n_warmup = 5 n_sample = 10 else: n_warmup = 50 n_sample = 50 if get_net_device(net) != torch.device('cpu'): if not clean: print('move net to cpu for measuring cpu latency') net = copy.deepcopy(net).cpu() elif l_type == 'gpu': if fast: n_warmup = 5 n_sample = 10 else: n_warmup = 50 n_sample = 50 else: raise NotImplementedError images = torch.zeros(data_shape, device=get_net_device(net)) measured_latency = {'warmup': [], 'sample': []} net.eval() with torch.no_grad(): for i in range(n_warmup): inner_start_time = time.time() net(images) used_time = (time.time() - inner_start_time) * 1e3 # ms measured_latency['warmup'].append(used_time) if not clean: print('Warmup %d: %.3f' % (i, used_time)) outer_start_time = time.time() for i in range(n_sample): net(images) total_time = (time.time() - outer_start_time) * 1e3 # ms measured_latency['sample'].append((total_time, n_sample)) return total_time / n_sample, measured_latency def get_net_info(net, input_shape=(3, 224, 224), measure_latency=None, print_info=True): net_info = {} if isinstance(net, nn.DataParallel): net = net.module # parameters net_info['params'] = count_parameters(net) / 1e6 # flops net_info['flops'] = count_net_flops(net, [1] + list(input_shape)) / 1e6 # latencies latency_types = [] if measure_latency is None else measure_latency.split('#') for l_type in latency_types: latency, measured_latency = measure_net_latency(net, l_type, fast=False, input_shape=input_shape) net_info['%s latency' % l_type] = { 'val': latency, 'hist': measured_latency } if print_info: print(net) print('Total training params: %.2fM' % (net_info['params'])) print('Total FLOPs: %.2fM' % (net_info['flops'])) for l_type in latency_types: print('Estimated %s latency: %.3fms' % (l_type, net_info['%s latency' % l_type]['val'])) return net_info """ optimizer """ def build_optimizer(net_params, opt_type, opt_param, init_lr, weight_decay, no_decay_keys): if no_decay_keys is not None: assert isinstance(net_params, list) and len(net_params) == 2 net_params = [ {'params': net_params[0], 'weight_decay': weight_decay}, {'params': net_params[1], 'weight_decay': 0}, ] else: net_params = [{'params': net_params, 'weight_decay': weight_decay}] if opt_type == 'sgd': opt_param = {} if opt_param is None else opt_param momentum, nesterov = opt_param.get('momentum', 0.9), opt_param.get('nesterov', True) optimizer = torch.optim.SGD(net_params, init_lr, momentum=momentum, nesterov=nesterov) elif opt_type == 'adam': optimizer = torch.optim.Adam(net_params, init_lr) else: raise NotImplementedError return optimizer """ learning rate schedule """ def calc_learning_rate(epoch, init_lr, n_epochs, batch=0, nBatch=None, lr_schedule_type='cosine'): if lr_schedule_type == 'cosine': t_total = n_epochs * nBatch t_cur = epoch * nBatch + batch lr = 0.5 * init_lr * (1 + math.cos(math.pi * t_cur / t_total)) elif lr_schedule_type is None: lr = init_lr else: raise ValueError('do not support: %s' % lr_schedule_type) return lr
4,227
965
class ATL_NO_VTABLE CConnect2 : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CConnect2, &CLSID_Connect2>, public IConnectionPointContainerImpl<CConnect2>, public IPropertyNotifySinkCP<CConnect2>
78
601
<reponame>yangzslife/austin package com.java3y.austin.handler.domain.push.getui; import com.alibaba.fastjson.annotation.JSONField; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Set; /** * 推送消息的param * @author 3y * https://docs.getui.com/getui/server/rest_v2/push/ */ @NoArgsConstructor @AllArgsConstructor @Data @Builder public class SendPushParam { /** * requestId */ @JSONField(name = "request_id") private String requestId; /** * settings */ @JSONField(name = "settings") private SettingsVO settings; /** * audience */ @JSONField(name = "audience") private AudienceVO audience; /** * pushMessage */ @JSONField(name = "push_message") private PushMessageVO pushMessage; /** * SettingsVO */ @NoArgsConstructor @Data public static class SettingsVO { /** * ttl */ @JSONField(name = "ttl") private Integer ttl; } /** * AudienceVO */ @NoArgsConstructor @Data @AllArgsConstructor @Builder public static class AudienceVO { /** * cid */ @JSONField(name = "cid") private Set<String> cid; } /** * PushMessageVO */ @NoArgsConstructor @Data @AllArgsConstructor @Builder public static class PushMessageVO { /** * notification */ @JSONField(name = "notification") private NotificationVO notification; /** * NotificationVO */ @NoArgsConstructor @Data @AllArgsConstructor @Builder public static class NotificationVO { /** * title */ @JSONField(name = "title") private String title; /** * body */ @JSONField(name = "body") private String body; /** * clickType */ @JSONField(name = "click_type") private String clickType; /** * url */ @JSONField(name = "url") private String url; } } }
1,134
464
from __future__ import absolute_import from mplleaflet._display import ( show, display, save_html, fig_to_html, fig_to_geojson, )
64
538
// Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.u2f.gaedemo.storage; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.google.u2f.server.data.SecurityKeyData; import com.google.u2f.server.data.SecurityKeyData.Transports; import com.google.u2f.server.impl.attestation.android.AndroidKeyStoreAttestation; import org.apache.commons.codec.binary.Hex; import java.io.ByteArrayInputStream; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.List; import java.util.Objects; public class TokenStorageData { private long enrollmentTime; private List<Transports> transports; private byte[] keyHandle; private byte[] publicKey; private byte[] attestationCert; private int counter; // used by the storage layer public TokenStorageData() {} public TokenStorageData(SecurityKeyData tokenData) { this.enrollmentTime = tokenData.getEnrollmentTime(); this.keyHandle = tokenData.getKeyHandle(); this.publicKey = tokenData.getPublicKey(); try { this.attestationCert = tokenData.getAttestationCertificate().getEncoded(); } catch (CertificateEncodingException e) { throw new RuntimeException(); } this.transports = tokenData.getTransports(); this.counter = tokenData.getCounter(); } public void updateCounter(int newCounterValue) { counter = newCounterValue; } public SecurityKeyData getSecurityKeyData() { X509Certificate x509cert = parseCertificate(attestationCert); return new SecurityKeyData(enrollmentTime, transports, keyHandle, publicKey, x509cert, counter); } public JsonObject toJson() { X509Certificate x509cert = getSecurityKeyData().getAttestationCertificate(); JsonObject json = new JsonObject(); json.addProperty("enrollment_time", enrollmentTime); json.add("transports", getJsonTransports()); json.addProperty("key_handle", Hex.encodeHexString(keyHandle)); json.addProperty("public_key", Hex.encodeHexString(publicKey)); json.addProperty("issuer", x509cert.getIssuerX500Principal().getName()); try { AndroidKeyStoreAttestation androidKeyStoreAttestation = AndroidKeyStoreAttestation.Parse(x509cert); if (androidKeyStoreAttestation != null) { json.add("android_attestation", androidKeyStoreAttestation.toJson()); } } catch (CertificateParsingException e) { throw new RuntimeException(e); } return json; } /** * Transforms the List of Transports in a JsonArray of Strings. * * @return a JsonArray object containing transport values as strings */ private JsonArray getJsonTransports() { if (transports == null) { return null; } JsonArray jsonTransports = new JsonArray(); for (Transports transport : transports) { jsonTransports.add(new JsonPrimitive(transport.toString())); } return jsonTransports; } @Override public String toString() { return toJson().toString(); } @Override public int hashCode() { return Objects.hash(enrollmentTime, transports, keyHandle, publicKey, attestationCert, counter); } @Override public boolean equals(Object obj) { if (!(obj instanceof TokenStorageData)) return false; TokenStorageData that = (TokenStorageData) obj; return (this.enrollmentTime == that.enrollmentTime) && SecurityKeyData.containSameTransports(this.transports, that.transports) && (this.counter == that.counter) && Arrays.equals(this.keyHandle, that.keyHandle) && Arrays.equals(this.publicKey, that.publicKey) && Arrays.equals(this.attestationCert, that.attestationCert); } private static X509Certificate parseCertificate(byte[] encodedDerCertificate) { try { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate( new ByteArrayInputStream(encodedDerCertificate)); } catch (CertificateException e) { throw new RuntimeException(e); } } }
1,452
368
<gh_stars>100-1000 {"systemKeyword.l":"System Type","systemKeyword.p":"Enter the System Type","systemKeyword.g":"Enter The Text"}
40
6,436
<reponame>gaocegege/openFrameworks<filename>examples/input_output/fileBufferLoadingCSVExample/src/MorseCodePlayer.h /* * MorseCodePlayer.h * * Created by <NAME> on 2/22/12. * */ #include "ofMain.h" struct MorseCodeSymbol { string character; string code; }; class MorseCodePlayer { public: MorseCodePlayer(); void setup(); void update(); void playCode(string morseCode); ofSoundPlayer dotPlayer; ofSoundPlayer dashPlayer; int currentSoundIndex; vector<char> codes; string currentCode; bool isReady; };
193
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <AppKit/NSImageCell.h> @interface IDESourceControlAuthorImageCell : NSImageCell { } - (id)accessibilityHitTest:(struct CGPoint)arg1; - (BOOL)accessibilityIsIgnored; - (void)drawInteriorWithFrame:(struct CGRect)arg1 inView:(id)arg2; - (id)borderColor; @end
152
319
/* * Copyright (c) 2013 Qualcomm Atheros, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) 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 Qualcomm Atheros nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. 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. */ /** * @ingroup adf_os_public * @file adf_os_io.h * This file abstracts I/O operations. */ #ifndef _ADF_OS_IO_H #define _ADF_OS_IO_H #include <adf_os_io_pvt.h> static inline uint8_t ioread8(const volatile uint32_t addr) { return *(const volatile uint8_t *) addr; } static inline uint16_t ioread16(const volatile uint32_t addr) { return *(const volatile uint16_t *) addr; } static inline uint32_t ioread32(const volatile uint32_t addr) { return *(const volatile uint32_t *) addr; } static inline void iowrite8(volatile uint32_t addr, const uint8_t b) { *(volatile uint8_t *) addr = b; } static inline void iowrite16(volatile uint32_t addr, const uint16_t b) { *(volatile uint16_t *) addr = b; } static inline void iowrite32(volatile uint32_t addr, const uint32_t b) { *(volatile uint32_t *) addr = b; } static inline void io8_rmw(volatile uint32_t addr, const uint8_t set, const uint8_t clr) { uint8_t val; val = ioread8(addr); val &= ~clr; val |= set; iowrite8(addr, val); } static inline void io32_rmw(volatile uint32_t addr, const uint32_t set, const uint32_t clr) { uint32_t val; val = ioread32(addr); val &= ~clr; val |= set; iowrite32(addr, val); } /* generic functions */ #define io8_set(addr, s) io8_rmw((addr), (s), 0) #define io8_clr(addr, c) io8_rmw((addr), 0, (c)) #define io32_set(addr, s) io32_rmw((addr), (s), 0) #define io32_clr(addr, c) io32_rmw((addr), 0, (c)) /* mac specific functions */ #define ioread32_mac(addr) ioread32(WLAN_BASE_ADDRESS + (addr)) #define iowrite32_mac(addr, b) iowrite32(WLAN_BASE_ADDRESS + (addr), (b)) /* usb specific functions */ #define ioread8_usb(addr) ioread8(USB_CTRL_BASE_ADDRESS | (addr)^3) #define ioread16_usb(addr) ioread16(USB_CTRL_BASE_ADDRESS | (addr)) #define ioread32_usb(addr) ioread32(USB_CTRL_BASE_ADDRESS | (addr)) #define iowrite8_usb(addr, b) iowrite8(USB_CTRL_BASE_ADDRESS | (addr)^3, (b)) #define iowrite16_usb(addr, b) iowrite16(USB_CTRL_BASE_ADDRESS | (addr), (b)) #define iowrite32_usb(addr, b) iowrite32(USB_CTRL_BASE_ADDRESS | (addr), (b)) #define io8_rmw_usb(addr, s, c) \ io8_rmw(USB_CTRL_BASE_ADDRESS | (addr)^3, (s), (c)) #define io8_set_usb(addr, s) \ io8_rmw(USB_CTRL_BASE_ADDRESS | (addr)^3, (s), 0) #define io8_clr_usb(addr, c) \ io8_rmw(USB_CTRL_BASE_ADDRESS | (addr)^3, 0, (c)) #define io32_rmw_usb(addr, s, c) \ io32_rmw(USB_CTRL_BASE_ADDRESS | (addr), (s), (c)) #define io32_set_usb(addr, s) io32_rmw(USB_CTRL_BASE_ADDRESS | (addr), (s), 0) #define io32_clr_usb(addr, c) io32_rmw(USB_CTRL_BASE_ADDRESS | (addr), 0, (c)) /** * @brief Convert a 16-bit value from network byte order to host byte order */ #define adf_os_ntohs(x) __adf_os_ntohs(x) /** * @brief Convert a 32-bit value from network byte order to host byte order */ #define adf_os_ntohl(x) __adf_os_ntohl(x) /** * @brief Convert a 16-bit value from host byte order to network byte order */ #define adf_os_htons(x) __adf_os_htons(x) /** * @brief Convert a 32-bit value from host byte order to network byte order */ #define adf_os_htonl(x) __adf_os_htonl(x) /** * @brief Convert a 16-bit value from CPU byte order to little-endian byte order */ #define adf_os_cpu_to_le16(x) __adf_os_cpu_to_le16(x) #endif
2,071
2,073
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.h2obindings.ops; import org.apache.mahout.math.Vector; import org.apache.mahout.h2obindings.drm.H2OBCast; import org.apache.mahout.h2obindings.drm.H2ODrm; import water.MRTask; import water.fvec.Frame; import water.fvec.Vec; import water.fvec.Chunk; import water.fvec.NewChunk; /** * Calculate Ax (where x is an in-core Vector) */ public class Ax { /** * Perform Ax operation with a DRM and an in-core Vector to create a new DRM. * * @param drmA DRM representing matrix A. * @param x in-core Mahout Vector. * @return new DRM containing Ax. */ public static H2ODrm exec(H2ODrm drmA, Vector x) { Frame A = drmA.frame; Vec keys = drmA.keys; final H2OBCast<Vector> bx = new H2OBCast<>(x); // Ax is written into nc (single element, not array) with an MRTask on A, // and therefore will be similarly partitioned as A. // // x.size() == A.numCols() == chks.length Frame Ax = new MRTask() { public void map(Chunk chks[], NewChunk nc) { int chunkSize = chks[0].len(); Vector x = bx.value(); for (int r = 0; r < chunkSize; r++) { double v = 0; for (int c = 0; c < chks.length; c++) { v += (chks[c].atd(r) * x.getQuick(c)); } nc.addNum(v); } } }.doAll(1, A).outputFrame(null, null); // Carry forward labels of A blindly into ABt return new H2ODrm(Ax, keys); } }
859
1,346
<reponame>disrupted/Trakttv.bundle<filename>Trakttv.bundle/Contents/Libraries/Shared/plugin/core/ospathfix.py<gh_stars>1000+ import logging import os import sys log = logging.getLogger(__name__) def revert_fix(module, name): original = getattr(module, '_' + name, None) if not original: return setattr(module, name, original) log.debug('Reverted "%s.%s" method', module, name) if sys.platform == 'win32': revert_fix(os, 'listdir') revert_fix(os, 'makedirs') revert_fix(os.path, 'exists')
213
1,488
<reponame>stewartmcgown/react-native-device-info // // ActionViewController.h // example-app-extension // // Created by <NAME> on 10/13/20. // #import <UIKit/UIKit.h> @interface ActionViewController : UIViewController - (void) done; extern ActionViewController * actionViewController; @end
105
3,459
<gh_stars>1000+ // -*- C++ -*- // VisualBoyAdvance - Nintendo Gameboy/GameboyAdvance (TM) emulator. // Copyright (C) 1999-2003 Forgotten // Copyright (C) 2004 Forgotten and the VBA development team // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or(at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. default: case 0x00: // NOP break; case 0x01: // LD BC, NNNN BC.B.B0=gbReadMemory(PC.W++); BC.B.B1=gbReadMemory(PC.W++); break; case 0x02: // LD (BC),A gbWriteMemory(BC.W,AF.B.B1); break; case 0x03: // INC BC BC.W++; break; case 0x04: // INC B BC.B.B1++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[BC.B.B1]| (BC.B.B1&0x0F? 0:H_FLAG); break; case 0x05: // DEC B BC.B.B1--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[BC.B.B1]| ((BC.B.B1&0x0F)==0x0F? H_FLAG:0); break; case 0x06: // LD B, NN BC.B.B1=gbReadMemory(PC.W++); break; case 0x07: // RLCA tempValue=AF.B.B1&0x80? C_FLAG:0; AF.B.B1=(AF.B.B1<<1)|(AF.B.B1>>7); AF.B.B0=tempValue; break; case 0x08: // LD (NNNN), SP tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(tempRegister.W++,SP.B.B0); gbWriteMemory(tempRegister.W,SP.B.B1); break; case 0x09: // ADD HL,BC tempRegister.W=(HL.W+BC.W)&0xFFFF; AF.B.B0= (AF.B.B0 & Z_FLAG)| ((HL.W^BC.W^tempRegister.W)&0x1000? H_FLAG:0)| (((long)HL.W+(long)BC.W)&0x10000? C_FLAG:0); HL.W=tempRegister.W; break; case 0x0a: // LD A,(BC) AF.B.B1=gbReadMemory(BC.W); break; case 0x0b: // DEC BC BC.W--; break; case 0x0c: // INC C BC.B.B0++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[BC.B.B0]| (BC.B.B0&0x0F? 0:H_FLAG); break; case 0x0d: // DEC C BC.B.B0--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[BC.B.B0]| ((BC.B.B0&0x0F)==0x0F? H_FLAG:0); break; case 0x0e: // LD C, NN BC.B.B0=gbReadMemory(PC.W++); break; case 0x0f: // RRCA tempValue=AF.B.B1&0x01; AF.B.B1=(AF.B.B1>>1)|(tempValue? 0x80:0); AF.B.B0=(tempValue<<4); break; case 0x10: // STOP opcode = gbReadMemory(PC.W++); if(gbCgbMode) { if(register_KEY1 & 1) { gbSpeedSwitch(); if(gbSpeed == 0) register_KEY1 = 0x00; else register_KEY1 = 0x80; } } break; case 0x11: // LD DE, NNNN DE.B.B0=gbReadMemory(PC.W++); DE.B.B1=gbReadMemory(PC.W++); break; case 0x12: // LD (DE),A gbWriteMemory(DE.W,AF.B.B1); break; case 0x13: // INC DE DE.W++; break; case 0x14: // INC D DE.B.B1++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[DE.B.B1]| (DE.B.B1&0x0F? 0:H_FLAG); break; case 0x15: // DEC D DE.B.B1--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[DE.B.B1]| ((DE.B.B1&0x0F)==0x0F? H_FLAG:0); break; case 0x16: // LD D,NN DE.B.B1=gbReadMemory(PC.W++); break; case 0x17: // RLA tempValue=AF.B.B1&0x80? C_FLAG:0; AF.B.B1=(AF.B.B1<<1)|((AF.B.B0&C_FLAG)>>4); AF.B.B0=tempValue; break; case 0x18: // JR NN PC.W+=(int8)gbReadMemory(PC.W)+1; break; case 0x19: // ADD HL,DE tempRegister.W=(HL.W+DE.W)&0xFFFF; AF.B.B0= (AF.B.B0 & Z_FLAG)| ((HL.W^DE.W^tempRegister.W)&0x1000? H_FLAG:0)| (((long)HL.W+(long)DE.W)&0x10000? C_FLAG:0); HL.W=tempRegister.W; break; case 0x1a: // LD A,(DE) AF.B.B1=gbReadMemory(DE.W); break; case 0x1b: // DEC DE DE.W--; break; case 0x1c: // INC E DE.B.B0++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[DE.B.B0]| (DE.B.B0&0x0F? 0:H_FLAG); break; case 0x1d: // DEC E DE.B.B0--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[DE.B.B0]| ((DE.B.B0&0x0F)==0x0F? H_FLAG:0); break; case 0x1e: // LD E,NN DE.B.B0=gbReadMemory(PC.W++); break; case 0x1f: // RRA tempValue=AF.B.B1&0x01; AF.B.B1=(AF.B.B1>>1)|(AF.B.B0&C_FLAG? 0x80:0); AF.B.B0=(tempValue<<4); break; case 0x20: // JR NZ,NN if(AF.B.B0&Z_FLAG) PC.W++; else { PC.W+=(int8)gbReadMemory(PC.W)+1; clockTicks++; } break; case 0x21: // LD HL,NNNN HL.B.B0=gbReadMemory(PC.W++); HL.B.B1=gbReadMemory(PC.W++); break; case 0x22: // LDI (HL),A gbWriteMemory(HL.W++,AF.B.B1); break; case 0x23: // INC HL HL.W++; break; case 0x24: // INC H HL.B.B1++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[HL.B.B1]| (HL.B.B1&0x0F? 0:H_FLAG); break; case 0x25: // DEC H HL.B.B1--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[HL.B.B1]| ((HL.B.B1&0x0F)==0x0F? H_FLAG:0); break; case 0x26: // LD H,NN HL.B.B1=gbReadMemory(PC.W++); break; case 0x27: // DAA tempRegister.W=AF.B.B1; tempRegister.W|=(AF.B.B0&(C_FLAG|H_FLAG|N_FLAG))<<4; AF.W=DAATable[tempRegister.W]; break; case 0x28: // JR Z,NN if(AF.B.B0&Z_FLAG) { PC.W+=(int8)gbReadMemory(PC.W)+1; clockTicks++; } else PC.W++; break; case 0x29: // ADD HL,HL tempRegister.W=(HL.W+HL.W)&0xFFFF; AF.B.B0= (AF.B.B0 & Z_FLAG)| ((HL.W^HL.W^tempRegister.W)&0x1000? H_FLAG:0)| (((long)HL.W+(long)HL.W)&0x10000? C_FLAG:0); HL.W=tempRegister.W; break; case 0x2a: // LDI A,(HL) AF.B.B1 = gbReadMemory(HL.W++); break; case 0x2b: // DEC HL HL.W--; break; case 0x2c: // INC L HL.B.B0++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[HL.B.B0]| (HL.B.B0&0x0F? 0:H_FLAG); break; case 0x2d: // DEC L HL.B.B0--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[HL.B.B0]| ((HL.B.B0&0x0F)==0x0F? H_FLAG:0); break; case 0x2e: // LD L,NN HL.B.B0=gbReadMemory(PC.W++); break; case 0x2f: // CPL AF.B.B1 ^= 255; AF.B.B0|=N_FLAG|H_FLAG; break; case 0x30: // JR NC,NN if(AF.B.B0&C_FLAG) PC.W++; else { PC.W+=(int8)gbReadMemory(PC.W)+1; clockTicks++; } break; case 0x31: // LD SP,NNNN SP.B.B0=gbReadMemory(PC.W++); SP.B.B1=gbReadMemory(PC.W++); break; case 0x32: // LDD (HL),A gbWriteMemory(HL.W--,AF.B.B1); break; case 0x33: // INC SP SP.W++; break; case 0x34: // INC (HL) tempValue=gbReadMemory(HL.W)+1; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[tempValue]| (tempValue&0x0F? 0:H_FLAG); gbWriteMemory(HL.W,tempValue); break; case 0x35: // DEC (HL) tempValue=gbReadMemory(HL.W)-1; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[tempValue]| ((tempValue&0x0F)==0x0F? H_FLAG:0);gbWriteMemory(HL.W,tempValue); break; case 0x36: // LD (HL),NN gbWriteMemory(HL.W,gbReadMemory(PC.W++)); break; case 0x37: // SCF AF.B.B0 = (AF.B.B0 & Z_FLAG) | C_FLAG; break; case 0x38: // JR C,NN if(AF.B.B0&C_FLAG) { PC.W+=(int8)gbReadMemory(PC.W)+1; clockTicks ++; } else PC.W++; break; case 0x39: // ADD HL,SP tempRegister.W=(HL.W+SP.W)&0xFFFF; AF.B.B0= (AF.B.B0 & Z_FLAG)| ((HL.W^SP.W^tempRegister.W)&0x1000? H_FLAG:0)| (((long)HL.W+(long)SP.W)&0x10000? C_FLAG:0); HL.W=tempRegister.W; break; case 0x3a: // LDD A,(HL) AF.B.B1 = gbReadMemory(HL.W--); break; case 0x3b: // DEC SP SP.W--; break; case 0x3c: // INC A AF.B.B1++; AF.B.B0= (AF.B.B0 & C_FLAG)|ZeroTable[AF.B.B1]| (AF.B.B1&0x0F? 0:H_FLAG); break; case 0x3d: // DEC A AF.B.B1--; AF.B.B0= N_FLAG|(AF.B.B0 & C_FLAG)|ZeroTable[AF.B.B1]| ((AF.B.B1&0x0F)==0x0F? H_FLAG:0); break; case 0x3e: // LD A,NN AF.B.B1=gbReadMemory(PC.W++); break; case 0x3f: // CCF AF.B.B0^=C_FLAG;AF.B.B0&=~(N_FLAG|H_FLAG); break; case 0x40: // LD B,B BC.B.B1=BC.B.B1; break; case 0x41: // LD B,C BC.B.B1=BC.B.B0; break; case 0x42: // LD B,D BC.B.B1=DE.B.B1; break; case 0x43: // LD B,E BC.B.B1=DE.B.B0; break; case 0x44: // LD B,H BC.B.B1=HL.B.B1; break; case 0x45: // LD B,L BC.B.B1=HL.B.B0; break; case 0x46: // LD B,(HL) BC.B.B1=gbReadMemory(HL.W); break; case 0x47: // LD B,A BC.B.B1=AF.B.B1; break; case 0x48: // LD C,B BC.B.B0=BC.B.B1; break; case 0x49: // LD C,C BC.B.B0=BC.B.B0; break; case 0x4a: // LD C,D BC.B.B0=DE.B.B1; break; case 0x4b: // LD C,E BC.B.B0=DE.B.B0; break; case 0x4c: // LD C,H BC.B.B0=HL.B.B1; break; case 0x4d: // LD C,L BC.B.B0=HL.B.B0; break; case 0x4e: // LD C,(HL) BC.B.B0=gbReadMemory(HL.W); break; case 0x4f: // LD C,A BC.B.B0=AF.B.B1; break; case 0x50: // LD D,B DE.B.B1=BC.B.B1; break; case 0x51: // LD D,C DE.B.B1=BC.B.B0; break; case 0x52: // LD D,D DE.B.B1=DE.B.B1; break; case 0x53: // LD D,E DE.B.B1=DE.B.B0; break; case 0x54: // LD D,H DE.B.B1=HL.B.B1; break; case 0x55: // LD D,L DE.B.B1=HL.B.B0; break; case 0x56: // LD D,(HL) DE.B.B1=gbReadMemory(HL.W); break; case 0x57: // LD D,A DE.B.B1=AF.B.B1; break; case 0x58: // LD E,B DE.B.B0=BC.B.B1; break; case 0x59: // LD E,C DE.B.B0=BC.B.B0; break; case 0x5a: // LD E,D DE.B.B0=DE.B.B1; break; case 0x5b: // LD E,E DE.B.B0=DE.B.B0; break; case 0x5c: // LD E,H DE.B.B0=HL.B.B1; break; case 0x5d: // LD E,L DE.B.B0=HL.B.B0; break; case 0x5e: // LD E,(HL) DE.B.B0=gbReadMemory(HL.W); break; case 0x5f: // LD E,A DE.B.B0=AF.B.B1; break; case 0x60: // LD H,B HL.B.B1=BC.B.B1; break; case 0x61: // LD H,C HL.B.B1=BC.B.B0; break; case 0x62: // LD H,D HL.B.B1=DE.B.B1; break; case 0x63: // LD H,E HL.B.B1=DE.B.B0; break; case 0x64: // LD H,H HL.B.B1=HL.B.B1; break; case 0x65: // LD H,L HL.B.B1=HL.B.B0; break; case 0x66: // LD H,(HL) HL.B.B1=gbReadMemory(HL.W); break; case 0x67: // LD H,A HL.B.B1=AF.B.B1; break; case 0x68: // LD L,B HL.B.B0=BC.B.B1; break; case 0x69: // LD L,C HL.B.B0=BC.B.B0; break; case 0x6a: // LD L,D HL.B.B0=DE.B.B1; break; case 0x6b: // LD L,E HL.B.B0=DE.B.B0; break; case 0x6c: // LD L,H HL.B.B0=HL.B.B1; break; case 0x6d: // LD L,L HL.B.B0=HL.B.B0; break; case 0x6e: // LD L,(HL) HL.B.B0=gbReadMemory(HL.W); break; case 0x6f: // LD L,A HL.B.B0=AF.B.B1; break; case 0x70: // LD (HL),B gbWriteMemory(HL.W,BC.B.B1); break; case 0x71: // LD (HL),C gbWriteMemory(HL.W,BC.B.B0); break; case 0x72: // LD (HL),D gbWriteMemory(HL.W,DE.B.B1); break; case 0x73: // LD (HL),E gbWriteMemory(HL.W,DE.B.B0); break; case 0x74: // LD (HL),H gbWriteMemory(HL.W,HL.B.B1); break; case 0x75: // LD (HL),L gbWriteMemory(HL.W,HL.B.B0); break; case 0x76: // HALT if(IFF) { InHALT = true; } else { InHALT = true; if(!gbCgbMode) RepeatNextByte = true; } break; case 0x77: // LD (HL),A gbWriteMemory(HL.W,AF.B.B1); break; case 0x78: // LD A,B AF.B.B1=BC.B.B1; break; case 0x79: // LD A,C AF.B.B1=BC.B.B0; break; case 0x7a: // LD A,D AF.B.B1=DE.B.B1; break; case 0x7b: // LD A,E AF.B.B1=DE.B.B0; break; case 0x7c: // LD A,H AF.B.B1=HL.B.B1; break; case 0x7d: // LD A,L AF.B.B1=HL.B.B0; break; case 0x7e: // LD A,(HL) AF.B.B1=gbReadMemory(HL.W); break; case 0x7f: // LD A,A AF.B.B1=AF.B.B1; break; case 0x80: // ADD B tempRegister.W=AF.B.B1+BC.B.B1; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B1^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x81: // ADD C tempRegister.W=AF.B.B1+BC.B.B0; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B0^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x82: // ADD D tempRegister.W=AF.B.B1+DE.B.B1; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B1^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x83: // ADD E tempRegister.W=AF.B.B1+DE.B.B0; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B0^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x84: // ADD H tempRegister.W=AF.B.B1+HL.B.B1; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B1^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x85: // ADD L tempRegister.W=AF.B.B1+HL.B.B0; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B0^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x86: // ADD (HL) tempValue=gbReadMemory(HL.W); tempRegister.W=AF.B.B1+tempValue; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x87: // ADD A tempRegister.W=AF.B.B1+AF.B.B1; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^AF.B.B1^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x88: // ADC B: tempRegister.W=AF.B.B1+BC.B.B1+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x89: // ADC C tempRegister.W=AF.B.B1+BC.B.B0+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x8a: // ADC D tempRegister.W=AF.B.B1+DE.B.B1+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x8b: // ADC E tempRegister.W=AF.B.B1+DE.B.B0+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x8c: // ADC H tempRegister.W=AF.B.B1+HL.B.B1+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x8d: // ADC L tempRegister.W=AF.B.B1+HL.B.B0+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x8e: // ADC (HL) tempValue=gbReadMemory(HL.W); tempRegister.W=AF.B.B1+tempValue+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x8f: // ADC A tempRegister.W=AF.B.B1+AF.B.B1+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^AF.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x90: // SUB B tempRegister.W=AF.B.B1-BC.B.B1; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x91: // SUB C tempRegister.W=AF.B.B1-BC.B.B0; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x92: // SUB D tempRegister.W=AF.B.B1-DE.B.B1; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x93: // SUB E tempRegister.W=AF.B.B1-DE.B.B0; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x94: // SUB H tempRegister.W=AF.B.B1-HL.B.B1; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x95: // SUB L tempRegister.W=AF.B.B1-HL.B.B0; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x96: // SUB (HL) tempValue=gbReadMemory(HL.W); tempRegister.W=AF.B.B1-tempValue; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x97: // SUB A AF.B.B1=0; AF.B.B0=N_FLAG|Z_FLAG; break; case 0x98: // SBC B tempRegister.W=AF.B.B1-BC.B.B1-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x99: // SBC C tempRegister.W=AF.B.B1-BC.B.B0-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x9a: // SBC D tempRegister.W=AF.B.B1-DE.B.B1-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x9b: // SBC E tempRegister.W=AF.B.B1-DE.B.B0-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x9c: // SBC H tempRegister.W=AF.B.B1-HL.B.B1-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x9d: // SBC L tempRegister.W=AF.B.B1-HL.B.B0-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x9e: // SBC (HL) tempValue=gbReadMemory(HL.W); tempRegister.W=AF.B.B1-tempValue-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0x9f: // SBC A tempRegister.W=AF.B.B1-AF.B.B1-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^AF.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0xa0: // AND B AF.B.B1&=BC.B.B1; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa1: // AND C AF.B.B1&=BC.B.B0; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa2: // AND_D AF.B.B1&=DE.B.B1; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa3: // AND E AF.B.B1&=DE.B.B0; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa4: // AND H AF.B.B1&=HL.B.B1; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa5: // AND L AF.B.B1&=HL.B.B0; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa6: // AND (HL) tempValue=gbReadMemory(HL.W); AF.B.B1&=tempValue; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa7: // AND A AF.B.B1&=AF.B.B1; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xa8: // XOR B AF.B.B1^=BC.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xa9: // XOR C AF.B.B1^=BC.B.B0; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xaa: // XOR D AF.B.B1^=DE.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xab: // XOR E AF.B.B1^=DE.B.B0; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xac: // XOR H AF.B.B1^=HL.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xad: // XOR L AF.B.B1^=HL.B.B0; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xae: // XOR (HL) tempValue=gbReadMemory(HL.W); AF.B.B1^=tempValue; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xaf: // XOR A AF.B.B1=0; AF.B.B0=Z_FLAG; break; case 0xb0: // OR B AF.B.B1|=BC.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb1: // OR C AF.B.B1|=BC.B.B0; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb2: // OR D AF.B.B1|=DE.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb3: // OR E AF.B.B1|=DE.B.B0; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb4: // OR H AF.B.B1|=HL.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb5: // OR L AF.B.B1|=HL.B.B0; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb6: // OR (HL) tempValue=gbReadMemory(HL.W); AF.B.B1|=tempValue; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb7: // OR A AF.B.B1|=AF.B.B1; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xb8: // CP B: tempRegister.W=AF.B.B1-BC.B.B1; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xb9: // CP C tempRegister.W=AF.B.B1-BC.B.B0; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^BC.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xba: // CP D tempRegister.W=AF.B.B1-DE.B.B1; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xbb: // CP E tempRegister.W=AF.B.B1-DE.B.B0; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^DE.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xbc: // CP H tempRegister.W=AF.B.B1-HL.B.B1; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B1^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xbd: // CP L tempRegister.W=AF.B.B1-HL.B.B0; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^HL.B.B0^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xbe: // CP (HL) tempValue=gbReadMemory(HL.W); tempRegister.W=AF.B.B1-tempValue; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xbf: // CP A AF.B.B0=N_FLAG|Z_FLAG; break; case 0xc0: // RET NZ if(!(AF.B.B0&Z_FLAG)) { PC.B.B0=gbReadMemory(SP.W++); PC.B.B1=gbReadMemory(SP.W++); clockTicks += 3; } break; case 0xc1: // POP BC BC.B.B0=gbReadMemory(SP.W++); BC.B.B1=gbReadMemory(SP.W++); break; case 0xc2: // JP NZ,NNNN if(AF.B.B0&Z_FLAG) PC.W+=2; else { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W); PC.W=tempRegister.W; clockTicks++; } break; case 0xc3: // JP NNNN tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W); PC.W=tempRegister.W; break; case 0xc4: // CALL NZ,NNNN if(AF.B.B0&Z_FLAG) PC.W+=2; else { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=tempRegister.W; clockTicks += 3; } break; case 0xc5: // PUSH BC gbWriteMemory(--SP.W,BC.B.B1); gbWriteMemory(--SP.W,BC.B.B0); break; case 0xc6: // ADD NN tempValue=gbReadMemory(PC.W++); tempRegister.W=AF.B.B1+tempValue; AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10 ? H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0xc7: // RST 00 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0000; break; case 0xc8: // RET Z if(AF.B.B0&Z_FLAG) { PC.B.B0=gbReadMemory(SP.W++); PC.B.B1=gbReadMemory(SP.W++); clockTicks += 3; } break; case 0xc9: // RET PC.B.B0=gbReadMemory(SP.W++); PC.B.B1=gbReadMemory(SP.W++); break; case 0xca: // JP Z,NNNN if(AF.B.B0&Z_FLAG) { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W); PC.W=tempRegister.W; clockTicks++; } else PC.W+=2; break; // CB done outside case 0xcc: // CALL Z,NNNN if(AF.B.B0&Z_FLAG) { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=tempRegister.W; clockTicks += 3; } else PC.W+=2; break; case 0xcd: // CALL NNNN tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=tempRegister.W; break; case 0xce: // ADC NN tempValue=gbReadMemory(PC.W++); tempRegister.W=AF.B.B1+tempValue+(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= (tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0xcf: // RST 08 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0008; break; case 0xd0: // RET NC if(!(AF.B.B0&C_FLAG)) { PC.B.B0=gbReadMemory(SP.W++); PC.B.B1=gbReadMemory(SP.W++); clockTicks += 3; } break; case 0xd1: // POP DE DE.B.B0=gbReadMemory(SP.W++); DE.B.B1=gbReadMemory(SP.W++); break; case 0xd2: // JP NC,NNNN if(AF.B.B0&C_FLAG) PC.W+=2; else { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W); PC.W=tempRegister.W; clockTicks++; } break; // D3 illegal case 0xd4: // CALL NC,NNNN if(AF.B.B0&C_FLAG) PC.W+=2; else { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=tempRegister.W; clockTicks += 3; } break; case 0xd5: // PUSH DE gbWriteMemory(--SP.W,DE.B.B1); gbWriteMemory(--SP.W,DE.B.B0); break; case 0xd6: // SUB NN tempValue=gbReadMemory(PC.W++); tempRegister.W=AF.B.B1-tempValue; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0xd7: // RST 10 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0010; break; case 0xd8: // RET C if(AF.B.B0&C_FLAG) { PC.B.B0=gbReadMemory(SP.W++); PC.B.B1=gbReadMemory(SP.W++); clockTicks += 3; } break; case 0xd9: // RETI PC.B.B0=gbReadMemory(SP.W++); PC.B.B1=gbReadMemory(SP.W++); IFF = true; break; case 0xda: // JP C,NNNN if(AF.B.B0&C_FLAG) { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W); PC.W=tempRegister.W; clockTicks++; } else PC.W+=2; break; // DB illegal case 0xdc: // CALL C,NNNN if(AF.B.B0&C_FLAG) { tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=tempRegister.W; clockTicks += 3; } else PC.W+=2; break; // DD illegal case 0xde: // SBC NN tempValue=gbReadMemory(PC.W++); tempRegister.W=AF.B.B1-tempValue-(AF.B.B0&C_FLAG ? 1 : 0); AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); AF.B.B1=tempRegister.B.B0; break; case 0xdf: // RST 18 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0018; break; case 0xe0: // LD (FF00+NN),A gbWriteMemory(0xff00 + gbReadMemory(PC.W++),AF.B.B1); break; case 0xe1: // POP HL HL.B.B0=gbReadMemory(SP.W++); HL.B.B1=gbReadMemory(SP.W++); break; case 0xe2: // LD (FF00+C),A gbWriteMemory(0xff00 + BC.B.B0,AF.B.B1); break; // E3 illegal // E4 illegal case 0xe5: // PUSH HL gbWriteMemory(--SP.W,HL.B.B1); gbWriteMemory(--SP.W,HL.B.B0); break; case 0xe6: // AND NN tempValue=gbReadMemory(PC.W++); AF.B.B1&=tempValue; AF.B.B0=H_FLAG|ZeroTable[AF.B.B1]; break; case 0xe7: // RST 20 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0020; break; case 0xe8: // ADD SP,NN offset = (int8)gbReadMemory(PC.W++); tempRegister.W = SP.W + offset; AF.B.B0 = ((SP.W^offset^tempRegister.W)&0x100? C_FLAG : 0) | ((SP.W^offset^tempRegister.W)& 0x10? H_FLAG : 0); SP.W = tempRegister.W; break; case 0xe9: // LD PC,HL PC.W=HL.W; break; case 0xea: // LD (NNNN),A tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); gbWriteMemory(tempRegister.W,AF.B.B1); break; // EB illegal // EC illegal // ED illegal case 0xee: // XOR NN tempValue=gbReadMemory(PC.W++); AF.B.B1^=tempValue; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xef: // RST 28 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0028; break; case 0xf0: // LD A,(FF00+NN) AF.B.B1 = gbReadMemory(0xff00+gbReadMemory(PC.W++)); break; case 0xf1: // POP AF AF.B.B0=gbReadMemory(SP.W++)&0xF0; AF.B.B1=gbReadMemory(SP.W++); break; case 0xf2: // LD A,(FF00+C) AF.B.B1 = gbReadMemory(0xff00+BC.B.B0); break; case 0xf3: // DI IFF = false; EI_Delayed = false; break; // F4 illegal case 0xf5: // PUSH AF gbWriteMemory(--SP.W,AF.B.B1); gbWriteMemory(--SP.W,AF.B.B0); break; case 0xf6: // OR NN tempValue=gbReadMemory(PC.W++); AF.B.B1|=tempValue; AF.B.B0=ZeroTable[AF.B.B1]; break; case 0xf7: // RST 30 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0030; break; case 0xf8: // LD HL,SP+NN offset = (int8)gbReadMemory(PC.W++); tempRegister.W = SP.W + offset; AF.B.B0 = ((SP.W^offset^tempRegister.W)&0x100? C_FLAG : 0) | ((SP.W^offset^tempRegister.W)& 0x10? H_FLAG : 0); HL.W = tempRegister.W; break; case 0xf9: // LD SP,HL SP.W=HL.W; break; case 0xfa: // LD A,(NNNN) tempRegister.B.B0=gbReadMemory(PC.W++); tempRegister.B.B1=gbReadMemory(PC.W++); AF.B.B1=gbReadMemory(tempRegister.W); break; case 0xfb: EI_Delayed = true; break; // FC illegal // FD illegal case 0xfe: // CP NN tempValue=gbReadMemory(PC.W++); tempRegister.W=AF.B.B1-tempValue; AF.B.B0= N_FLAG|(tempRegister.B.B1?C_FLAG:0)|ZeroTable[tempRegister.B.B0]| ((AF.B.B1^tempValue^tempRegister.B.B0)&0x10?H_FLAG:0); break; case 0xff: // RST 38 gbWriteMemory(--SP.W,PC.B.B1); gbWriteMemory(--SP.W,PC.B.B0); PC.W=0x0038; break;
18,324
1,754
<gh_stars>1000+ /* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ratpack.jdbctx.internal; import ratpack.exec.Operation; import ratpack.exec.Promise; import ratpack.func.Factory; import ratpack.jdbctx.Transaction; import ratpack.jdbctx.TransactionException; import java.sql.Connection; import java.util.Optional; public class BoundTransaction implements Transaction { private final Factory<? extends Connection> connectionFactory; public BoundTransaction(Factory<? extends Connection> connectionFactory) { this.connectionFactory = connectionFactory; } private Transaction get() { return Transaction.get(connectionFactory); } @Override public Transaction bind() throws TransactionException { get().bind(); return this; } @Override public boolean unbind() { return get().unbind(); } @Override public boolean isActive() { return get().isActive(); } @Override public Optional<Connection> getConnection() { return get().getConnection(); } @Override public Operation begin() { return Operation.flatten(() -> get().begin()); } @Override public Operation rollback() { return Operation.flatten(() -> get().rollback()); } @Override public Operation commit() { return Operation.flatten(() -> get().commit()); } @Override public Transaction autoBind(boolean autoBind) { get().autoBind(autoBind); return this; } @Override public boolean isAutoBind() { return get().isAutoBind(); } @Override public <T> Promise<T> wrap(Promise<T> promise) { return Promise.flatten(() -> get().wrap(promise)); } @Override public Operation wrap(Operation operation) { return Operation.of(() -> get().wrap(operation).then()); } }
670
595
/****************************************************************************** * Copyright (c) 2019 - 2021 Xilinx, Inc. All rights reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ #ifndef XPM_NPDOMAIN_H_ #define XPM_NPDOMAIN_H_ #include "xpm_bisr.h" #include "xpm_powerdomain.h" #include "xpm_regs.h" #ifdef __cplusplus extern "C" { #endif /** * The NOC power domain node class. */ typedef struct XPm_NpDomain { XPm_PowerDomain Domain; /**< Power domain node base class */ } XPm_NpDomain; /*****************************************************************************/ /** * @brief This function unlocks the NPI PCSR registers. * *****************************************************************************/ static inline void XPmNpDomain_UnlockNpiPcsr(u32 BaseAddr) { PmOut32(BaseAddr + NPI_PCSR_LOCK_OFFSET, PCSR_UNLOCK_VAL); } /*****************************************************************************/ /** * @brief This function locks the NPI PCSR registers. * *****************************************************************************/ static inline void XPmNpDomain_LockNpiPcsr(u32 BaseAddr) { PmOut32(BaseAddr + NPI_PCSR_LOCK_OFFSET, PCSR_LOCK_VAL); } /************************** Function Prototypes ******************************/ XStatus XPmNpDomain_Init(XPm_NpDomain *Npd, u32 Id, u32 BaseAddress, XPm_Power *Parent); XStatus XPmNpDomain_MemIcInit(u32 DeviceId, u32 BaseAddr); XStatus XPmNpDomain_IsNpdIdle(const XPm_Node *Node); XStatus XPmNpDomain_ClockGate(const XPm_Node *Node, u8 State); #ifdef __cplusplus } #endif /** @} */ #endif /* XPM_NPDOMAIN_H_ */
519
415
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance # with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and # limitations under the License. import re import pytest from assertpy import assert_that from pcluster.schemas.cluster_schema import ( AwsBatchComputeResourceSchema, AwsBatchQueueSchema, CloudWatchLogsSchema, ClusterSchema, DcvSchema, DirectoryServiceSchema, EbsSettingsSchema, EfsSettingsSchema, FsxLustreSettingsSchema, HeadNodeEphemeralVolumeSchema, HeadNodeNetworkingSchema, HeadNodeRootVolumeSchema, IamSchema, ImageSchema, QueueEphemeralVolumeSchema, QueueNetworkingSchema, QueueRootVolumeSchema, RaidSchema, SharedStorageSchema, SlurmComputeResourceSchema, SlurmQueueSchema, SshSchema, ) @pytest.mark.parametrize( "mount_dir, expected_message", [ ("/t_ 1-2( ):&;<>t?*+|", None), ("", "does not match expected pattern"), ("fake_value", None), ("/test", None), ("/test/test2", None), ("//test", "does not match expected pattern"), ("./test", "does not match expected pattern"), ("\\test", "does not match expected pattern"), (".test", "does not match expected pattern"), ("/test/.test2", "does not match expected pattern"), ("/test/.test2/test3", "does not match expected pattern"), ("/test//test2", "does not match expected pattern"), ("/test\\test2", "does not match expected pattern"), ("NONE", None), # NONE is evaluated as a valid path ], ) def test_mount_dir_validator(mount_dir, expected_message): _validate_and_assert_error(SharedStorageSchema(), {"MountDir": mount_dir}, expected_message) _validate_and_assert_error(HeadNodeEphemeralVolumeSchema(), {"MountDir": mount_dir}, expected_message) _validate_and_assert_error(QueueEphemeralVolumeSchema(), {"MountDir": mount_dir}, expected_message) @pytest.mark.parametrize( "size, expected_message", [ (25, None), ("", "Not a valid integer"), ("NONE", "Not a valid integer"), ("wrong_value", "Not a valid integer"), (19, "must be at least 35"), (36, None), ], ) def test_root_volume_size_validator(size, expected_message): _validate_and_assert_error(HeadNodeRootVolumeSchema(), {"Size": size}, expected_message) _validate_and_assert_error(QueueRootVolumeSchema(), {"Size": size}, expected_message) @pytest.mark.parametrize( "capacity_type, expected_message", [ ("ONDEMAND", None), ("", "Must be one of: ONDEMAND, SPOT"), ("wrong_value", "Must be one of: ONDEMAND, SPOT"), ("NONE", "Must be one of: ONDEMAND, SPOT"), ("SPOT", None), ], ) def test_compute_type_validator(capacity_type, expected_message): _validate_and_assert_error(SlurmQueueSchema(), {"CapacityType": capacity_type}, expected_message) _validate_and_assert_error(AwsBatchQueueSchema(), {"CapacityType": capacity_type}, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"MinCount": -1}, "Must be greater than or equal"), ({"MinCount": 0}, None), ({"MaxCount": 0}, "Must be greater than or equal"), ({"MaxCount": 1}, None), ({"SpotPrice": ""}, "Not a valid number"), ({"SpotPrice": "NONE"}, "Not a valid number"), ({"SpotPrice": "wrong_value"}, "Not a valid number"), ({"SpotPrice": -1.1}, "Must be greater than or equal"), ({"SpotPrice": 0}, None), ({"SpotPrice": 0.09}, None), ({"SpotPrice": 0}, None), ({"SpotPrice": 0.1}, None), ({"SpotPrice": 1}, None), ({"SpotPrice": 100}, None), ({"SpotPrice": 100.0}, None), ({"SpotPrice": 100.1}, None), ({"SpotPrice": 101}, None), ], ) def test_slurm_compute_resource_validator(section_dict, expected_message): _validate_and_assert_error(SlurmComputeResourceSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"MinvCpus": -1}, "Must be greater than or equal"), ({"MinvCpus": 0}, None), ({"DesiredvCpus": -1}, "Must be greater than or equal"), ({"DesiredvCpus": 0}, None), ({"MaxvCpus": 0}, "Must be greater than or equal"), ({"MaxvCpus": 1}, None), ({"SpotBidPercentage": ""}, "Not a valid integer"), ({"SpotBidPercentage": "wrong_value"}, "Not a valid integer"), ({"SpotBidPercentage": 1}, None), ({"SpotBidPercentage": 22}, None), ({"SpotBidPercentage": 101}, "Must be.*less than or equal to 100"), ], ) def test_awsbatch_compute_resource_validator(section_dict, expected_message): _validate_and_assert_error(AwsBatchComputeResourceSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"ComputeResources": []}, "Length must be 1"), ({"ComputeResources": [{"Name": "compute_resource1", "InstanceTypes": ["c5.xlarge"]}]}, None), ( { "ComputeResources": [ {"Name": "compute_resource1", "InstanceTypes": ["c4.xlarge", "c5.xlarge"]}, {"Name": "compute_resource1", "InstanceTypes": ["c4.xlarge"]}, ] }, "Length must be 1", ), ], ) def test_awsbatch_queue_validator(section_dict, expected_message): _validate_and_assert_error(AwsBatchQueueSchema(), section_dict, expected_message) @pytest.mark.parametrize( "custom_ami, expected_message", [ ("", "does not match expected pattern"), ("wrong_value", "does not match expected pattern"), ("ami-12345", "does not match expected pattern"), ("ami-123456789", "does not match expected pattern"), ("NONE", "does not match expected pattern"), ("ami-12345678", None), ("ami-12345678901234567", None), ], ) def test_custom_ami_validator(custom_ami, expected_message): _validate_and_assert_error(ImageSchema(), {"CustomAmi": custom_ami}, expected_message) @pytest.mark.parametrize( "retention_in_days, expected_message", [ # right value (1, None), (14, None), (3653, None), # invalid value (2, "Must be one of"), (3652, "Must be one of"), ("", "Not a valid integer"), ("not_an_int", "Not a valid integer"), ], ) def test_retention_in_days_validator(retention_in_days, expected_message): """Verify that cw_log behaves as expected when parsed in a config file.""" _validate_and_assert_error(CloudWatchLogsSchema(), {"RetentionInDays": retention_in_days}, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"Enabled": True}, None), ({"Enabled": "wrong_value"}, "Not a valid boolean"), ({"Enabled": ""}, "Not a valid boolean"), ({"Enabled": "NONE"}, "Not a valid boolean"), ({"Port": "wrong_value"}, "Not a valid integer"), ({"Port": ""}, "Not a valid integer"), ({"Port": "NONE"}, "Not a valid integer"), ({"Port": "wrong_value"}, "Not a valid integer"), ({"Port": "1"}, None), ({"Port": "20"}, None), ({"invalid_key": "fake_value"}, "Unknown field"), ], ) def test_dcv_validator(section_dict, expected_message): """Verify that dcv behaves as expected when parsed in a config file.""" _validate_and_assert_error(DcvSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"AllowedIps": "wrong_value"}, "does not match expected patter"), ({"AllowedIps": ""}, "does not match expected pattern"), ({"AllowedIps": "wrong_value"}, "does not match expected pattern"), ({"AllowedIps": "172.16.58.3"}, "does not match expected pattern"), ({"AllowedIps": "172.16.58.3/222"}, "does not match expected pattern"), ({"AllowedIps": "NONE"}, "does not match expected pattern"), ({"AllowedIps": "0.0.0.0/0"}, None), ({"AllowedIps": "1.1.1.1/0"}, None), ({"AllowedIps": "1.1.1.1/8"}, None), ({"AllowedIps": "1.1.1.1/15"}, None), ({"AllowedIps": "1.1.1.1/32"}, None), ({"AllowedIps": "1.1.1.1/33"}, "does not match expected pattern"), ({"AllowedIps": "11.11.11.11/32"}, None), ({"AllowedIps": "172.16.58.3/22"}, None), ({"AllowedIps": "255.255.255.255/32"}, None), ({"AllowedIps": "255.255.255.256/32"}, "does not match expected pattern"), ], ) def test_cidr_validator(section_dict, expected_message): """Verify that cidr behaves as expected when parsed in a config file.""" _validate_and_assert_error(DcvSchema(), section_dict, expected_message) _validate_and_assert_error(SshSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"SnapshotId": ""}, "does not match expected pattern"), ({"SnapshotId": "wrong_value"}, "does not match expected pattern"), ({"SnapshotId": "snap-12345"}, "does not match expected pattern"), ({"SnapshotId": "snap-123456789"}, "does not match expected pattern"), ({"SnapshotId": "NONE"}, "does not match expected pattern"), ({"SnapshotId": "snap-12345678"}, None), ({"SnapshotId": "snap-12345678901234567"}, None), ({"VolumeType": ""}, "Must be one of"), ({"VolumeType": "wrong_value"}, "Must be one of"), ({"VolumeType": "st1"}, None), ({"VolumeType": "sc1"}, None), ({"VolumeType": "NONE"}, "Must be one of"), ({"VolumeType": "io1"}, None), ({"VolumeType": "io2"}, None), ({"VolumeType": "standard"}, None), ({"Size": ""}, "Not a valid integer"), ({"Size": "NONE"}, "Not a valid integer"), ({"Size": "wrong_value"}, "Not a valid integer"), ({"Size": 10}, None), ({"Size": 3}, None), ({"Iops": ""}, "Not a valid integer"), ({"Iops": "NONE"}, "Not a valid integer"), ({"Iops": "wrong_value"}, "Not a valid integer"), ({"Iops": 10}, None), ({"Iops": 3}, None), ({"Throughput": ""}, "Not a valid integer"), ({"Throughput": "NONE"}, "Not a valid integer"), ({"Throughput": "wrong_value"}, "Not a valid integer"), ({"Throughput": 200}, None), ({"Encrypted": ""}, "Not a valid boolean"), ({"Encrypted": "NONE"}, "Not a valid boolean"), ({"Encrypted": True}, None), ({"Encrypted": False}, None), ({"KmsKeyId": ""}, None), ({"KmsKeyId": "fake_value"}, None), ({"KmsKeyId": "test"}, None), ({"KmsKeyId": "NONE"}, None), # NONE is evaluated as a valid kms id ({"VolumeId": ""}, "does not match expected pattern"), ({"VolumeId": "wrong_value"}, "does not match expected pattern"), ({"VolumeId": "vol-12345"}, "does not match expected pattern"), ({"VolumeId": "vol-123456789"}, "does not match expected pattern"), ({"VolumeId": "NONE"}, "does not match expected pattern"), ({"VolumeId": "vol-12345678"}, None), ({"VolumeId": "vol-12345678901234567"}, None), ], ) def test_ebs_validator(section_dict, expected_message): """Verify that ebs settings behaves as expected when parsed in a config file.""" _validate_and_assert_error(EbsSettingsSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"FileSystemId": ""}, "does not match expected pattern"), ({"FileSystemId": "wrong_value"}, "does not match expected pattern"), ({"FileSystemId": "fs-12345"}, "does not match expected pattern"), ({"FileSystemId": "fs-123456789"}, "does not match expected pattern"), ({"FileSystemId": "fs-12345678"}, None), ({"FileSystemId": "fs-12345678901234567"}, None), ({"PerformanceMode": ""}, "Must be one of"), ({"PerformanceMode": "maxIO"}, None), ({"PerformanceMode": "wrong_value"}, "Must be one of"), ({"PerformanceMode": "NONE"}, "Must be one of"), ({"KmsKeyId": ""}, None), ({"KmsKeyId": "fake_value"}, None), ({"KmsKeyId": "test"}, None), ({"KmsKeyId": "NONE"}, None), # NONE is evaluated as a valid kms id ({"ProvisionedThroughput": 1}, None), ({"ProvisionedThroughput": 3}, None), ({"ProvisionedThroughput": 1024}, None), ({"ProvisionedThroughput": 102000}, "Must be.*less than or equal to 1024"), ({"ProvisionedThroughput": 0.01}, "Must be greater than or equal to 1"), ({"ProvisionedThroughput": 1025}, "Must be.*less than or equal to 1024"), ({"ProvisionedThroughput": "wrong_value"}, "Not a valid integer"), ({"Encrypted": ""}, "Not a valid boolean"), ({"Encrypted": "NONE"}, "Not a valid boolean"), ({"Encrypted": "true"}, None), ({"Encrypted": False}, None), ({"ThroughputMode": ""}, "Must be one of"), ({"ThroughputMode": "provisioned"}, None), ({"ThroughputMode": "wrong_value"}, "Must be one of"), ({"ThroughputMode": "NONE"}, "Must be one of"), ], ) def test_efs_validator(section_dict, expected_message): """Verify that efs settings expected when parsed in a config file.""" _validate_and_assert_error(EfsSettingsSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ( {"ThroughputMode": "bursting", "ProvisionedThroughput": 1024}, "When specifying provisioned throughput, the throughput mode must be set to provisioned", ), ( {"ThroughputMode": "provisioned"}, "When specifying throughput mode to provisioned, the provisioned throughput option must be specified", ), ({"ThroughputMode": "provisioned", "ProvisionedThroughput": 1024}, None), ], ) def test_efs_throughput_mode_provisioned_throughput_validator(section_dict, expected_message): _validate_and_assert_error(EfsSettingsSchema(), section_dict, expected_message, partial=False) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"FileSystemId": "fs-0123456789abcdef0"}, None), ( {"FileSystemId": "fs-0123456789abcdef0", "StorageCapacity": 3600}, "storage_capacity is ignored when an existing Lustre file system is specified", ), ( { "BackupId": "backup-0ff8da96d57f3b4e3", "DeploymentType": "PERSISTENT_1", }, "When restoring an FSx Lustre file system from backup, 'deployment_type' cannot be specified.", ), ( {"BackupId": "backup-0ff8da96d57f3b4e3", "StorageCapacity": 7200}, "When restoring an FSx Lustre file system from backup, 'storage_capacity' cannot be specified.", ), ( { "BackupId": "backup-0ff8da96d57f3b4e3", "PerUnitStorageThroughput": 100, }, "When restoring an FSx Lustre file system from backup, 'per_unit_storage_throughput' cannot be specified.", ), ( { "BackupId": "backup-0ff8da96d57f3b4e3", "ImportedFileChunkSize": 1024, }, "When restoring an FSx Lustre file system from backup, 'imported_file_chunk_size' cannot be specified.", ), ( { "BackupId": "backup-0ff8da96d57f3b4e3", "KmsKeyId": "somekey", }, "When restoring an FSx Lustre file system from backup, 'kms_key_id' cannot be specified.", ), ({"FileSystemId": ""}, "does not match expected pattern"), ({"FileSystemId": "wrong_value"}, "does not match expected pattern"), ({"FileSystemId": "fs-12345"}, "does not match expected pattern"), ({"FileSystemId": "fs-123456789"}, "does not match expected pattern"), ({"FileSystemId": "fs-12345678"}, "does not match expected pattern"), ({"FileSystemId": "fs-12345678901234567"}, None), ({"StorageCapacity": 3}, None), ({"StorageCapacity": "wrong_value"}, "Not a valid integer"), ({"StorageCapacity": ""}, "Not a valid integer"), ({"StorageCapacity": "NONE"}, "Not a valid integer"), ({"StorageCapacity": 10}, None), ({"KmsKeyId": ""}, None), ({"KmsKeyId": "fake_value"}, None), ({"KmsKeyId": "test"}, None), ({"KmsKeyId": "NONE"}, None), # NONE is evaluated as a valid kms id ({"ImportedFileChunkSize": ""}, "Not a valid integer"), ({"ImportedFileChunkSize": "NONE"}, "Not a valid integer"), ({"ImportedFileChunkSize": "wrong_value"}, "Not a valid integer"), ({"ImportedFileChunkSize": 3}, None), ({"ImportedFileChunkSize": 0}, "has a minimum size of 1 MiB, and max size of 512,000 MiB"), ({"ImportedFileChunkSize": 1}, None), ({"ImportedFileChunkSize": 10}, None), ({"ImportedFileChunkSize": 512000}, None), ({"ImportedFileChunkSize": 512001}, "has a minimum size of 1 MiB, and max size of 512,000 MiB"), # TODO add regex for export path ({"ExportPath": ""}, None), ({"ExportPath": "fake_value"}, None), ({"ExportPath": "http://test"}, None), ({"ExportPath": "s3://test/test2"}, None), ({"ExportPath": "NONE"}, None), # TODO add regex for import path ({"ImportPath": ""}, None), ({"ImportPath": "fake_value"}, None), ({"ImportPath": "http://test"}, None), ({"ImportPath": "s3://test/test2"}, None), ({"ImportPath": "NONE"}, None), # TODO add regex for weekly_maintenance_start_time ({"WeeklyMaintenanceStartTime": ""}, "does not match expected pattern"), ({"WeeklyMaintenanceStartTime": "fake_value"}, "does not match expected pattern"), ({"WeeklyMaintenanceStartTime": "10:00"}, "does not match expected pattern"), ({"WeeklyMaintenanceStartTime": "1:10:00"}, None), ({"WeeklyMaintenanceStartTime": "1:1000"}, "does not match expected pattern"), ({"DeploymentType": "SCRATCH_1"}, None), ({"DeploymentType": "SCRATCH_2"}, None), ({"DeploymentType": "PERSISTENT_1"}, None), ({"DeploymentType": "BLAH"}, "Must be one of"), ({"PerUnitStorageThroughput": 12}, None), ({"PerUnitStorageThroughput": 40}, None), ({"PerUnitStorageThroughput": 50}, None), ({"PerUnitStorageThroughput": 100}, None), ({"PerUnitStorageThroughput": 200}, None), ({"PerUnitStorageThroughput": 101}, "Must be one of"), ({"PerUnitStorageThroughput": 1000}, "Must be one of"), ({"DailyAutomaticBackupStartTime": ""}, "does not match expected pattern"), ({"DailyAutomaticBackupStartTime": "01:00"}, None), ({"DailyAutomaticBackupStartTime": "23:00"}, None), ({"DailyAutomaticBackupStartTime": "25:00"}, "does not match expected pattern"), ({"DailyAutomaticBackupStartTime": "2300"}, "does not match expected pattern"), ({"AutomaticBackupRetentionDays": ""}, "Not a valid integer"), ({"AutomaticBackupRetentionDays": 0}, None), ({"AutomaticBackupRetentionDays": 35}, None), ({"AutomaticBackupRetentionDays": 36}, "Must be.*less than or equal to 35"), ({"CopyTagsToBackups": ""}, "Not a valid boolean"), ({"CopyTagsToBackups": "NONE"}, "Not a valid boolean"), ({"CopyTagsToBackups": True}, None), ({"CopyTagsToBackups": False}, None), ({"BackupId": ""}, "does not match expected pattern"), ({"BackupId": "back-0a1b2c3d4e5f6a7b8"}, "does not match expected pattern"), ({"BackupId": "backup-0A1B2C3d4e5f6a7b8"}, "does not match expected pattern"), ({"BackupId": "backup-0a1b2c3d4e5f6a7b8"}, None), ({"AutoImportPolicy": "NEW"}, None), ({"AutoImportPolicy": "NEW_CHANGED"}, None), ({"StorageType": "SSD"}, None), ({"StorageType": "HDD"}, None), ({"StorageType": "INVALID_VALUE"}, "Must be one of"), ({"DriveCacheType": "READ"}, None), ({"DriveCacheType": "INVALID_VALUE"}, "Must be one of"), ({"DataCompressionType": None}, None), ({"DataCompressionType": "LZ4"}, None), ({"DataCompressionType": "INVALID_VALUE"}, "Must be one of"), ({"invalid_key": "fake_value"}, "Unknown field"), ], ) def test_fsx_validator(section_dict, expected_message): _validate_and_assert_error(FsxLustreSettingsSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"Type": ""}, "Not a valid integer"), ({"Type": "NONE"}, "Not a valid integer"), ({"Type": "wrong_value"}, "Not a valid integer"), ({"Type": 10}, "Must be one of"), ({"Type": 3}, "Must be one of"), ({"Type": 0}, None), ({"Type": 1}, None), ({"NumberOfVolumes": ""}, "Not a valid integer"), ({"NumberOfVolumes": "NONE"}, "Not a valid integer"), ({"NumberOfVolumes": "wrong_value"}, "Not a valid integer"), ({"NumberOfVolumes": 0}, "Must be greater than or equal to 2"), ({"NumberOfVolumes": 1}, "Must be greater than or equal to 2"), ({"NumberOfVolumes": 6}, "Must be.*less than or equal to 5"), ({"NumberOfVolumes": 5}, None), ({"NumberOfVolumes": 2}, None), ], ) def test_raid_validator(section_dict, expected_message): """Verify raid behaves as expected when parsed in a config file.""" _validate_and_assert_error(RaidSchema(), section_dict, expected_message) @pytest.mark.parametrize( "section_dict, expected_message", [ ({"AdditionalSecurityGroups": [""]}, "does not match expected pattern"), ({"AdditionalSecurityGroups": ["wrong_value"]}, "does not match expected pattern"), ({"AdditionalSecurityGroups": ["sg-12345"]}, "does not match expected pattern"), ({"AdditionalSecurityGroups": ["sg-123456789"]}, "does not match expected pattern"), ({"AdditionalSecurityGroups": ["NONE"]}, "does not match expected pattern"), ({"AdditionalSecurityGroups": ["sg-12345678"]}, None), ({"AdditionalSecurityGroups": ["sg-12345678901234567"]}, None), ({"SecurityGroups": [""]}, "does not match expected pattern"), ({"SecurityGroups": ["wrong_value"]}, "does not match expected pattern"), ({"SecurityGroups": ["sg-12345"]}, "does not match expected pattern"), ({"SecurityGroups": ["sg-123456789"]}, "does not match expected pattern"), ({"SecurityGroups": ["NONE"]}, "does not match expected pattern"), ({"SecurityGroups": ["sg-12345678"]}, None), ({"SecurityGroups": ["sg-12345678901234567"]}, None), ], ) def test_base_networking_validator(section_dict, expected_message): """Verify networking behaves as expected when parsed in a config file.""" _validate_and_assert_error(HeadNodeNetworkingSchema(), section_dict, expected_message) _validate_and_assert_error(QueueNetworkingSchema(), section_dict, expected_message) @pytest.mark.parametrize( "subnet_id, expected_message", [ ("", "does not match expected pattern"), ("subnet-12345", "does not match expected pattern"), ("subnet-123456789", "does not match expected pattern"), ("NONE", "does not match expected pattern"), ("subnet-12345678", None), ("subnet-12345678901234567", None), ], ) def test_subnet_id_validator(subnet_id, expected_message): """Verify that subnet ids behaves as expected when parsed in a config file.""" _validate_and_assert_error(HeadNodeNetworkingSchema(), {"SubnetId": subnet_id}, expected_message) _validate_and_assert_error(QueueNetworkingSchema(), {"SubnetIds": [subnet_id]}, expected_message) @pytest.mark.parametrize( "key, expected_message", [ ("key1", None), ("parallelcluster:version", "The tag key prefix 'parallelcluster:' is reserved and cannot be used."), ], ) def test_tags_validator(key, expected_message): _validate_and_assert_error( ClusterSchema(cluster_name="clustername"), {"Tags": [{"Key": key, "Value": "test_value"}]}, expected_message ) def _validate_and_assert_error(schema, section_dict, expected_message, partial=True): if expected_message: messages = schema.validate(section_dict, partial=partial) contain = False for message in list(messages.values()): if isinstance(message, dict): # Special case when validating lists for msg in list(message.values()): if re.search(expected_message, msg[0]): contain = True else: if re.search(expected_message, message[0]): contain = True assert_that(contain).is_true() else: schema.validate(section_dict, partial=partial) @pytest.mark.parametrize( "instance_role, expected_message", [ ("", "does not match expected pattern"), ("arn:aws:iam::aws:role/CustomHeadNodeRole", None), ("CustomHeadNodeRole", "does not match expected pattern"), ("arn:aws:iam::aws:instance-profile/CustomNodeInstanceProfile", "does not match expected pattern"), ], ) def test_instance_role_validator(instance_role, expected_message): """Verify that instance role behaves as expected when parsed in a config file.""" _validate_and_assert_error(IamSchema(), {"InstanceRole": instance_role}, expected_message) @pytest.mark.parametrize( "password_secret_arn, expected_message", [ ("arn:aws:secretsmanager:us-east-1:111111111111:secret:Secret-xxxxxxxx-xxxxx", None), ("wrong_value", "String does not match expected pattern"), ], ) def test_password_secret_arn_validator(password_secret_arn, expected_message): _validate_and_assert_error(DirectoryServiceSchema(), {"PasswordSecretArn": password_secret_arn}, expected_message)
10,905
471
import uuid from django.test import TestCase from corehq.apps.app_manager.tests.app_factory import AppFactory from corehq.apps.reports.analytics.couchaccessors import ( SimpleFormInfo, get_all_form_definitions_grouped_by_app_and_xmlns, get_all_form_details, get_form_details_for_app, get_form_details_for_app_and_module, get_form_details_for_app_and_xmlns, get_form_details_for_xmlns, update_reports_analytics_indexes, ) class SetupSimpleAppMixin(object): @classmethod def class_setup(cls): cls.domain = uuid.uuid4().hex cls.f1_xmlns = 'xmlns1' cls.f2_xmlns = 'xmlns2' app_factory = AppFactory(domain=cls.domain) module1, form1 = app_factory.new_basic_module('m1', '_casetype') module2, form2 = app_factory.new_basic_module('m2', '_casetype2') form1.xmlns = cls.f1_xmlns form2.xmlns = cls.f2_xmlns app_factory.app.save() cls.app = app_factory.app deleted_app_factory = AppFactory(domain=cls.domain) deleted_module1, deleted_form1 = deleted_app_factory.new_basic_module('del-m1', '_casetype3') cls.deleted_xmlns = 'xmlns3' deleted_form1.xmlns = cls.deleted_xmlns deleted_app_factory.app.doc_type = 'Application-Deleted' # make sure the ID comes after the primary app deleted_app_factory.app._id = '{}z'.format(cls.app.id) deleted_app_factory.app.save() cls.deleted_app = deleted_app_factory.app cls.xmlnses = [cls.f1_xmlns, cls.f2_xmlns, cls.deleted_xmlns] update_reports_analytics_indexes() def _assert_form_details_match(self, index, details): expected_app = self.app if index < 2 else self.deleted_app self.assertEqual(expected_app._id, details.app.id) self.assertEqual(index % 2, details.module.id) self.assertEqual(0, details.form.id) self.assertEqual(self.xmlnses[index], details.xmlns) self.assertFalse(details.is_user_registration) class ReportAppAnalyticsTest(SetupSimpleAppMixin, TestCase): @classmethod def setUpClass(cls): super(ReportAppAnalyticsTest, cls).setUpClass() cls.class_setup() def test_get_all_form_definitions_grouped_by_app_and_xmlns_no_data(self): self.assertEqual([], get_all_form_definitions_grouped_by_app_and_xmlns('missing')) def test_get_all_form_definitions_grouped_by_app_and_xmlns(self): self.assertEqual( [SimpleFormInfo(self.app._id, self.f1_xmlns), SimpleFormInfo(self.app._id, self.f2_xmlns), SimpleFormInfo(self.deleted_app._id, self.deleted_xmlns)], get_all_form_definitions_grouped_by_app_and_xmlns(self.domain) ) def test_get_all_form_details_no_data(self): self.assertEqual([], get_all_form_details('missing')) def test_get_all_form_details(self): app_structures = get_all_form_details(self.domain) self.assertEqual(3, len(app_structures)) for i, details in enumerate(app_structures): self._assert_form_details_match(i, details) def test_get_all_form_details_active(self): details = get_all_form_details(self.domain, deleted=False) self.assertEqual(2, len(details)) for i, detail in enumerate(details): self._assert_form_details_match(i, detail) def test_get_all_form_details_deleted(self): details = get_all_form_details(self.domain, deleted=True) self.assertEqual(1, len(details)) self._assert_form_details_match(2, details[0]) def test_get_form_details_for_xmlns_no_data(self): self.assertEqual([], get_form_details_for_xmlns('missing', 'missing')) self.assertEqual([], get_form_details_for_xmlns(self.domain, 'missing')) self.assertEqual([], get_form_details_for_xmlns('missing', self.f1_xmlns)) def test_get_form_details_for_xmlns(self): [details_1] = get_form_details_for_xmlns(self.domain, self.f1_xmlns) [details_2] = get_form_details_for_xmlns(self.domain, self.f2_xmlns) for i, details in enumerate([details_1, details_2]): self._assert_form_details_match(i, details) def test_get_form_details_for_app_no_data(self): self.assertEqual([], get_form_details_for_app('missing', 'missing')) self.assertEqual([], get_form_details_for_app('missing', self.app.id)) self.assertEqual([], get_form_details_for_app(self.domain, 'missing')) def test_get_form_details_for_app(self): details = get_form_details_for_app(self.domain, self.app.id) for i, detail in enumerate(details): self._assert_form_details_match(i, detail) def test_get_form_details_for_app_and_module_no_data(self): self.assertEqual([], get_form_details_for_app_and_module('missing', self.app.id, 0)) self.assertEqual([], get_form_details_for_app_and_module(self.domain, 'missing', 0)) self.assertEqual([], get_form_details_for_app_and_module(self.domain, self.app.id, 3)) def test_get_form_details_for_app_and_module(self): for i in range(2): [details] = get_form_details_for_app_and_module(self.domain, self.app.id, i) self._assert_form_details_match(i, details) def test_get_form_details_for_app_and_xmlns_no_data(self): self.assertEqual([], get_form_details_for_app_and_xmlns('missing', self.app.id, self.f1_xmlns)) self.assertEqual([], get_form_details_for_app_and_xmlns(self.domain, 'missing', self.f1_xmlns)) self.assertEqual([], get_form_details_for_app_and_xmlns(self.domain, self.app.id, 'missing')) self.assertEqual( [], get_form_details_for_app_and_xmlns(self.domain, self.app.id, self.f1_xmlns, deleted=True) ) def test_get_form_details_for_app_and_xmlns(self): for i in range(2): [details] = get_form_details_for_app_and_xmlns(self.domain, self.app.id, self.xmlnses[i]) self._assert_form_details_match(i, details)
2,691
324
<reponame>tormath1/jclouds /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.rackspace.clouddns.v1.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.ws.rs.core.MediaType; import org.jclouds.http.HttpRequest; import org.jclouds.json.Json; import org.jclouds.rackspace.clouddns.v1.binders.UpdateRecordsToJSON.UpdateRecord; import org.jclouds.rackspace.clouddns.v1.domain.Record; import org.jclouds.rest.MapBinder; import com.google.common.collect.ImmutableMap; public class UpdateReverseDNSToJSON implements MapBinder { private final Json jsonBinder; @Inject public UpdateReverseDNSToJSON(Json jsonBinder) { this.jsonBinder = checkNotNull(jsonBinder, "jsonBinder"); } @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { checkArgument(checkNotNull(postParams.get("href"), "href") instanceof URI, "href is only valid for a URI!"); checkArgument(checkNotNull(postParams.get("idsToRecords"), "idsToRecords") instanceof Map, "records is only valid for a Map!"); checkNotNull(postParams.get("serviceName"), "serviceName"); Map<String, Record> idsToRecords = Map.class.cast(postParams.get("idsToRecords")); List<UpdateRecord> updateRecords = UpdateRecordsToJSON.toUpdateRecordList(idsToRecords); URI deviceURI = URI.class.cast(postParams.get("href")); String serviceName = postParams.get("serviceName").toString(); String json = toJSON(updateRecords, deviceURI, serviceName); request.setPayload(json); request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); return (R) request.toBuilder().payload(json).build(); } private String toJSON(Iterable<UpdateRecord> records, URI deviceURI, String serviceName) { return jsonBinder.toJson(ImmutableMap.<String, Object> of( "recordsList", ImmutableMap.of("records", records), "link", ImmutableMap.<String, Object> of( "href", deviceURI, "rel", serviceName))); } @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { throw new UnsupportedOperationException("use map form"); } }
1,114
677
<reponame>InfiniteSynthesis/lynx-native<filename>Android/sdk/src/main/java/com/lynx/ui/anim/TimingFunction.java<gh_stars>100-1000 // Copyright 2017 The Lynx Authors. All rights reserved. package com.lynx.ui.anim; import android.support.v4.view.animation.PathInterpolatorCompat; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.PathInterpolator; public class TimingFunction { public final static String EASING_LINEAR = "linear"; public final static String EASING_EASE = "ease"; public final static String EASING_EASE_IN = "ease-in"; public final static String EASING_EASE_OUT = "ease-out"; public final static String EASING_EASE_IN_OUT = "ease-in-out"; public final static String EASING_CUBIC_BEZIER_PREFIX = "cubic-bezier"; public static Interpolator transform(String easing) { Interpolator interpolator = null; switch (easing) { case EASING_LINEAR: interpolator = new LinearInterpolator(); break; case EASING_EASE_OUT: interpolator = new DecelerateInterpolator(); break; case EASING_EASE_IN: interpolator = new AccelerateInterpolator(); break; case EASING_EASE: case EASING_EASE_IN_OUT: interpolator = new AccelerateDecelerateInterpolator(); break; default: if (easing.startsWith(EASING_CUBIC_BEZIER_PREFIX)) { float[] params = new float[4]; int index = 0; StringBuilder temp = new StringBuilder(); for (int i = EASING_CUBIC_BEZIER_PREFIX.length() + 1; i < easing.length() - 1; i++) { char c = easing.charAt(i); if (Character.isDigit(c) || c == '.' || c == '-' || c == '+') { temp.append(c); } else if (c == ',') { params[index++] = Float.valueOf(temp.toString()); temp = new StringBuilder(); } } params[index] = Float.valueOf(temp.toString()); interpolator = PathInterpolatorCompat.create(params[0], params[1], params[2], params[3]); } else { interpolator = new LinearInterpolator(); } break; } return interpolator; } }
1,303
1,745
//************************************ bs::framework - Copyright 2018 <NAME> **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "Prerequisites/BsTypes.h" #include "String/BsString.h" namespace bs { /** @addtogroup General * @{ */ /** * Identifier for message used with the global messaging system. * * @note * Primary purpose of this class is to avoid expensive string compare, and instead use a unique message identifier for * compare. Generally you want to create one of these using the message name, and then store it for later use. * @note * This class is not thread safe and should only be used on the sim thread. */ class BS_UTILITY_EXPORT MessageId { public: MessageId() = default; MessageId(const String& name); bool operator== (const MessageId& rhs) const { return (mMsgIdentifier == rhs.mMsgIdentifier); } private: friend class MessageHandler; static Map<String, UINT32> UniqueMessageIds; static UINT32 NextMessageId; UINT32 mMsgIdentifier = 0; }; /** Handle to a subscription for a specific message in the global messaging system. */ class BS_UTILITY_EXPORT HMessage { public: HMessage() = default; /** Disconnects the message listener so it will no longer receive events from the messaging system. */ void disconnect(); private: friend class MessageHandler; HMessage(UINT32 id); UINT32 mId = 0; }; /** * Sends a message using the global messaging system. * * @note Sim thread only. */ void BS_UTILITY_EXPORT sendMessage(MessageId message); class MessageHandler; /** @} */ }
522
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Common { class FabricCodeVersion : public Serialization::FabricSerializable { public: static Global<FabricCodeVersion> Invalid; static Global<FabricCodeVersion> Default; static Global<FabricCodeVersion> Baseline; static Global<FabricCodeVersion> MinCompatible; FabricCodeVersion(); FabricCodeVersion(uint majorVersion, uint minorVersion, uint buildVersion, uint hotfixVersion); FabricCodeVersion(FabricCodeVersion const & other); FabricCodeVersion(FabricCodeVersion && other); virtual ~FabricCodeVersion(); __declspec(property(get=get_MajorVersion)) uint MajorVersion; uint get_MajorVersion() const { return majorVersion_; } __declspec(property(get=get_MinorVersion)) uint MinorVersion; uint get_MinorVersion() const { return minorVersion_; } __declspec(property(get=get_BuildVersion)) uint BuildVersion; uint get_BuildVersion() const { return buildVersion_; } __declspec(property(get=get_HotfixVersion)) uint HotfixVersion; uint get_HotfixVersion() const { return hotfixVersion_; } __declspec(property(get=get_IsValid)) bool IsValid; bool get_IsValid() const; bool IsBaseline() const; FabricCodeVersion const & operator = (FabricCodeVersion const & other); FabricCodeVersion const & operator = (FabricCodeVersion && other); int compare(FabricCodeVersion const & other) const; bool operator < (FabricCodeVersion const & other) const; bool operator == (FabricCodeVersion const & other) const; bool operator != (FabricCodeVersion const & other) const; void WriteTo(__in TextWriter&, FormatOptions const &) const; std::wstring ToString() const; static ErrorCode FromString(std::wstring const & fabricCodeVersionString, __out FabricCodeVersion & fabricCodeVersion); static bool TryParse(std::wstring const &, __out FabricCodeVersion &); FABRIC_FIELDS_04(majorVersion_, minorVersion_, buildVersion_, hotfixVersion_); static std::string AddField(TraceEvent & traceEvent, std::string const & name); void FillEventData(TraceEventContext & context) const; private: uint majorVersion_; uint minorVersion_; uint buildVersion_; uint hotfixVersion_; static GlobalWString Delimiter; }; } DEFINE_USER_ARRAY_UTILITY(Common::FabricCodeVersion);
960
384
#include "hook.h" #include <stddef.h> #ifdef __ELF__ #include "elf_hook.h" #include <dlfcn.h> #ifdef __cplusplus extern "C" { #endif void* hook(const char* library_filename, const char* function_name, const void* substitution_address) { void *handle, *address; if (NULL == library_filename) return NULL; handle = dlopen(library_filename, RTLD_LAZY); if (NULL == handle) return NULL; address = LIBRARY_ADDRESS_BY_HANDLE(handle); return elf_hook(library_filename, address, function_name, substitution_address); } #ifdef __cplusplus } #endif #else /* * Only ELF hook is supported now. */ #ifdef __cplusplus extern "C" { #endif void* hook(const char* library_filename, const char* function_name, const void* substitution_address) { return NULL; } #ifdef __cplusplus } #endif #endif
327
768
<gh_stars>100-1000 import matplotlib.pyplot as plt import pandas as pd from .legend_picker import * from .helpers import * def show_peripheral_access(metricsParser, options, twoPlotFigureSize, fontSize): peripherals, peripheralEntries = metricsParser.get_peripheral_entries() data = pd.DataFrame(peripheralEntries, columns=['realTime', 'virtualTime', 'operation', 'address']) fig, (writesAx, readsAx) = plt.subplots(2, 1, figsize=twoPlotFigureSize, constrained_layout=True) writeLines = [] readLines = [] time_column = 'realTime' if options.real_time else 'virtualTime' for key, value in peripherals.items(): tempData = data[data.address >= value[0]] peripheralEntries = tempData[tempData.address <= value[1]] readOperationFilter = peripheralEntries['operation'] == bytes([0]) writeOperationFilter = peripheralEntries['operation'] == bytes([1]) readEntries = peripheralEntries[readOperationFilter] writeEntries = peripheralEntries[writeOperationFilter] if not writeEntries.empty: writeLine, = writesAx.plot(writeEntries[time_column], range(0, len(writeEntries)), label=key) writeLines.append(writeLine) if not readEntries.empty: readLine, = readsAx.plot(readEntries[time_column], range(0, len(readEntries)), label=key) readLines.append(readLine) fig.suptitle('Peripheral access', fontsize=fontSize) writeHandles, writeLabels = writesAx.get_legend_handles_labels() readHandles, readLabels = readsAx.get_legend_handles_labels() writeLegend = fig.legend(writeHandles, writeLabels, loc='upper left') readLegend = fig.legend(readHandles, readLabels, loc='center left') set_legend_picker(fig, writeLines, writeLegend) set_legend_picker(fig, readLines, readLegend) x_label = '{} time in miliseconds'.format('Real' if options.real_time else 'Virtual') writesAx.set_xlabel(x_label) readsAx.set_xlabel(x_label) writesAx.set_ylabel('Write operations') readsAx.set_ylabel('Read operations') save_fig(fig, 'peripherals.png', options)
790
3,976
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'jinyang' from random import Random def codeGenerator(number, codeLength = 8): print '**** Code Generator ****' codeFile = open('codes.txt', 'w') if number <= 0: return 'invalid number of codes' else: chars = 'abcdefghijklmnopgrstuvwxyzABCDEFGHIJKLMNOPGRSTUVWXYZ1234567890' random = Random() for j in range(1, number+1): str = '' for i in range(1, codeLength+1): index = random.randint(1, len(chars)) str = str + chars[index-1] codeFile.write(str+'\n') print codeGenerator(200)
311
8,027
<filename>src/com/facebook/buck/core/graph/transformation/model/ComposedComputationIdentifier.java /* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.core.graph.transformation.model; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.Interner; import com.google.common.collect.Interners; /** * A {@link ComputationIdentifier} for a composed {@link * com.facebook.buck.core.graph.transformation.GraphComputation} * * <p>A {@link ComposedComputationIdentifier} is a pair of {@link ClassBasedComputationIdentifier} * called the base identifier and a class of {@link ResultType}, which maps to a composed * computation that takes the result of the {@link * com.facebook.buck.core.graph.transformation.GraphComputation} of the base identifier and uses it * to compute a result of {@link ResultType}. * * <p>e.g. a {@code ComposedComputationIdentifer.of(Key1.IDENTIFIER, Result2.class)} identifies the * composed computation of a base computation that computes {@code Key1} to {@code Result1}, then * uses {@code Key1} and {@code Result1} to compute {@code Result2}. * * <p>The {@link ComposedComputationIdentifier} is only identified by the base computation it starts * with and the end {@link ResultType}. It does not matter what {@link ComputationIdentifier}s are * chained in the middle of getting from the base computation to the target result. */ public class ComposedComputationIdentifier<ResultType extends ComputeResult> implements ComputationIdentifier<ComposedResult<ComputeKey<ResultType>, ResultType>> { private static final Interner<ComposedComputationIdentifier<?>> INTERNER = Interners.newWeakInterner(); private final ClassBasedComputationIdentifier<?> originIdentifier; private final Class<ResultType> targetResultClass; private final int hash; private ComposedComputationIdentifier( ClassBasedComputationIdentifier<?> originIdentifier, Class<ResultType> targetResultClass) { this.originIdentifier = originIdentifier; this.targetResultClass = targetResultClass; this.hash = Objects.hashCode(originIdentifier, targetResultClass); } /** * @param originIdentifier the original {@link ClassBasedComputationIdentifier} that starts off a * chain of composition * @param targetClass the class of the result type of the computation that this {@link * ComputationIdentifier} identifies * @param <ResultType> the type of the result returned by the computation of this {@link * ComputationIdentifier} * @return a {@link ComposedComputationIdentifier} that represents the computation that given the * key of the computation of the base identifier and returns the final result */ @SuppressWarnings("unchecked") public static <ResultType extends ComputeResult> ComposedComputationIdentifier<ResultType> of( ClassBasedComputationIdentifier<?> originIdentifier, Class<ResultType> targetClass) { return (ComposedComputationIdentifier<ResultType>) INTERNER.intern(new ComposedComputationIdentifier<>(originIdentifier, targetClass)); } /** * @param originIdentifier the {@link ComposedComputationIdentifier} that this {@link * ComposedComputationIdentifier} is based off of. The supplied base computation is unwrapped * to the base computation it stores * @param targetClass the class of the result type of the computation that this {@link * ComputationIdentifier} identifies * @param <ResultType> the type of the result that th computation that this {@link * ComputationIdentifier} returns * @return a {@link ComposedComputationIdentifier} that represents the computation that starts at * the base identifier and returns the final result */ @SuppressWarnings("unchecked") public static <ResultType extends ComputeResult> ComposedComputationIdentifier<ResultType> of( ComposedComputationIdentifier<?> originIdentifier, Class<ResultType> targetClass) { return (ComposedComputationIdentifier<ResultType>) INTERNER.intern( new ComposedComputationIdentifier<>(originIdentifier.originIdentifier, targetClass)); } /** * Delegates appropriate to one of the above {@link #of(ClassBasedComputationIdentifier, Class)} * or {@link #of(ComposedComputationIdentifier, Class)} */ public static <ResultType extends ComputeResult> ComposedComputationIdentifier<ResultType> of( ComputationIdentifier<?> originIdentifier, Class<ResultType> targetClass) { // TODO(bobyf): split the types so we don't need these unsafe casts if (originIdentifier instanceof ComposedComputationIdentifier) { return of( ((ComposedComputationIdentifier<?>) originIdentifier).originIdentifier, targetClass); } if (originIdentifier instanceof ClassBasedComputationIdentifier) { return of((ClassBasedComputationIdentifier<?>) originIdentifier, targetClass); } throw new IllegalStateException( String.format("Unexpected ComputationIdentifier type: %s", originIdentifier.getClass())); } @Override @SuppressWarnings("unchecked") public Class<ComposedResult<ComputeKey<ResultType>, ResultType>> getResultTypeClass() { return (Class<ComposedResult<ComputeKey<ResultType>, ResultType>>) (Class<?>) ComposedResult.class; } /** * @return the class of the {@link ResultType} contained in the {@link ComposedResult} of the * computation that this identifier maps to. */ public Class<ResultType> getTargetResultClass() { return targetResultClass; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ComposedComputationIdentifier)) { return false; } return originIdentifier.equals(((ComposedComputationIdentifier<?>) o).originIdentifier) && targetResultClass == ((ComposedComputationIdentifier<?>) o).targetResultClass; } @Override public int hashCode() { return hash; } @Override public String toString() { return MoreObjects.toStringHelper("ComposedComputationIdentifier") .omitNullValues() .add("originIdentifier", originIdentifier) .add("targetResultClass", targetResultClass) .toString(); } }
2,081
1,909
package org.knowm.xchange.independentreserve.dto.trade; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Author: <NAME> Date: 4/15/15 */ public class IndependentReserveOpenOrdersResponse { private final int pageSize; private final long totalItems; private final int totalPages; private final List<IndependentReserveOpenOrder> independentReserveOrders; public IndependentReserveOpenOrdersResponse( @JsonProperty("PageSize") int pageSize, @JsonProperty("TotalItems") long totalItems, @JsonProperty("TotalPages") int totalPages, @JsonProperty("Data") List<IndependentReserveOpenOrder> independentReserveOrders) { this.independentReserveOrders = independentReserveOrders; this.pageSize = pageSize; this.totalItems = totalItems; this.totalPages = totalPages; } public List<IndependentReserveOpenOrder> getIndependentReserveOrders() { return independentReserveOrders; } public int getPageSize() { return pageSize; } public long getTotalItems() { return totalItems; } public int getTotalPages() { return totalPages; } }
360
5,411
#pragma once #include <msgpack.hpp> namespace fx { struct scrObject { const char* data; uintptr_t length; }; template<typename T> inline scrObject SerializeObject(const T& object) { static msgpack::sbuffer buf; buf.clear(); msgpack::packer<msgpack::sbuffer> packer(buf); packer.pack(object); scrObject packed; packed.data = buf.data(); packed.length = buf.size(); return packed; } }
168
1,083
<reponame>agxmaster/polarphp //===--- PatternNodes.def - Swift Pattern AST Metaprogramming ---*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines macros used for macro-metaprogramming with patterns. // //===----------------------------------------------------------------------===// /// PATTERN(Id, Parent) /// The pattern's enumerator value is PatternKind::Id. The pattern's /// class name is Id##Pattern, and the name of its base class is Parent. #ifndef PATTERN # error Included PatternNodes.def without defining PATTERN! #endif /// REFUTABLE_PATTERN(Id, Parent) /// Matching this pattern can fail. These patterns cannot appear syntactically /// in variable declarations, assignments, or function declarations. #ifndef REFUTABLE_PATTERN # define REFUTABLE_PATTERN(Id, Parent) PATTERN(Id, Parent) #endif #ifndef LAST_PATTERN #define LAST_PATTERN(Id) #endif // Metavars: x (variable), pat (pattern), e (expression) PATTERN(Paren, Pattern) // (pat) PATTERN(Tuple, Pattern) // (pat1, ..., patN), N >= 1 PATTERN(Named, Pattern) // let pat, var pat PATTERN(Any, Pattern) // _ PATTERN(Typed, Pattern) // pat : type PATTERN(Var, Pattern) // x REFUTABLE_PATTERN(Is, Pattern) // x is myclass REFUTABLE_PATTERN(EnumElement, Pattern) // .mycase(pat1, ..., patN) // MyType.mycase(pat1, ..., patN) REFUTABLE_PATTERN(OptionalSome, Pattern) // pat? nil REFUTABLE_PATTERN(Bool, Pattern) // true, false REFUTABLE_PATTERN(Expr, Pattern) // e LAST_PATTERN(Expr) #undef REFUTABLE_PATTERN #undef PATTERN #undef LAST_PATTERN
691
1,091
/* * Copyright 2019-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.k8snetworking.api; import org.onlab.packet.IpAddress; /** * Representation of kubernetes network. */ public interface K8sNetwork { /** * Lists of network type. */ enum Type { /** * VXLAN typed virtual network. */ VXLAN, /** * GRE typed virtual network. */ GRE, /** * GENEVE typed virtual network. */ GENEVE, } /** * Returns the kubernetes network ID. * * @return kubernetes network ID */ String networkId(); /** * Returns kubernetes network type. * * @return kubernetes network type */ Type type(); /** * Returns kubernetes network name. * * @return kubernetes network name */ String name(); /** * Returns maximum transmission unit (MTU) value to address fragmentation. * * @return maximum transmission unit (MTU) value to address fragmentation */ Integer mtu(); /** * Returns segmentation ID. * * @return segmentation ID */ String segmentId(); /** * Returns gateway IP address. * * @return gateway IP address */ IpAddress gatewayIp(); /** * Returns network CIDR. * * @return network CIDR */ String cidr(); /** * Builder of new network. */ interface Builder { /** * Builds an immutable network instance. * * @return kubernetes network */ K8sNetwork build(); /** * Returns network builder with supplied network ID. * * @param networkId network ID * @return network builder */ Builder networkId(String networkId); /** * Returns network builder with supplied network name. * * @param name network name * @return network builder */ Builder name(String name); /** * Returns network builder with supplied network type. * * @param type network type * @return network builder */ Builder type(Type type); /** * Returns network builder with supplied MTU. * * @param mtu maximum transmission unit * @return network builder */ Builder mtu(Integer mtu); /** * Returns network builder with supplied segment ID. * * @param segmentId segment ID * @return network builder */ Builder segmentId(String segmentId); /** * Returns network builder with supplied gateway IP address. * * @param ipAddress gateway IP address * @return network builder */ Builder gatewayIp(IpAddress ipAddress); /** * Returns network builder with supplied network CIDR. * * @param cidr Classless Inter-Domain Routing * @return network builder */ Builder cidr(String cidr); } }
1,527
3,401
<reponame>cogitate3/stock # -*- coding: utf-8 -*- # @Time : 2021/4/2 18:08 # @File : TushareUtil.py # @Author : Rocky <EMAIL> import tushare as ts import sys sys.path.append('..') from configure.settings import config from datetime import datetime import time class TushareBaseUtil: ''' tushare 常用调用 ''' def __init__(self): ts_token = config.get('ts_token') ts.set_token(ts_token) self.pro = ts.pro_api() self.cache = {} def get_trade_date(self, start_date=None, end_date=datetime.now().strftime('%Y%m%d')): ''' 返回交易日历 :param start_date: :param end_date: :return: ''' # if self.cache if 'cal_date' not in self.cache: df = self.pro.trade_cal(exchange='', is_open='1', start_date=start_date, end_date=end_date) self.cache['cal_date'] = df['cal_date'].tolist() return self.cache['cal_date'] def date_convertor(self, s): return datetime.strptime(s, '%Y%m%d').strftime('%Y-%m-%d') def get_last_trade_date(self): return self.get_trade_date()[-2] def get_last_week_trade_date(self): return self.get_trade_date()[-5] def clear_cache(self): self.cache = {} def main(): # today =datetime.now().strftime('%Y%m%d') app = TushareBaseUtil() df = app.get_trade_date() df = app.get_trade_date() df = app.get_trade_date() df = app.get_trade_date() d = app.get_last_trade_date() print(d) if __name__ == '__main__': start = time.time() main() print(f'time used {time.time() - start}')
784
392
<reponame>Da-Krause/settlers-remake /******************************************************************************* * Copyright (c) 2015 - 2017 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *******************************************************************************/ package jsettlers.network.common.packets; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import jsettlers.network.infrastructure.channel.packet.Packet; /** * * @author <NAME> * */ public class ArrayOfMatchInfosPacket extends Packet { private MatchInfoPacket[] matches; public ArrayOfMatchInfosPacket() { } public ArrayOfMatchInfosPacket(MatchInfoPacket[] matches) { this.matches = matches; } @Override public void serialize(DataOutputStream dos) throws IOException { dos.writeInt(matches.length); for (int i = 0; i < matches.length; i++) { matches[i].serialize(dos); } } @Override public void deserialize(DataInputStream dis) throws IOException { int length = dis.readInt(); matches = new MatchInfoPacket[length]; for (int i = 0; i < length; i++) { matches[i] = new MatchInfoPacket(); matches[i].deserialize(dis); } } public MatchInfoPacket[] getMatches() { return matches; } public void setMatches(MatchInfoPacket[] matches) { this.matches = matches; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(matches); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ArrayOfMatchInfosPacket other = (ArrayOfMatchInfosPacket) obj; return Arrays.equals(matches, other.matches); } }
851
1,256
<filename>plugins/common/CRT/free.cpp<gh_stars>1000+ #include "crt.hpp" #pragma warning (disable : 4005) #include <windows.h> void __cdecl free(void *block) { if (block) HeapFree(GetProcessHeap(),0,block); }
90
14,668
// Copyright 2018 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 "chromecast/device/bluetooth/le/scan_filter.h" #include "base/containers/contains.h" #include "chromecast/device/bluetooth/bluetooth_util.h" #include "third_party/re2/src/re2/re2.h" namespace chromecast { namespace bluetooth { // static ScanFilter ScanFilter::From16bitUuid(uint16_t service_uuid) { ScanFilter filter; filter.service_uuid = util::UuidFromInt16(service_uuid); return filter; } ScanFilter::ScanFilter() = default; ScanFilter::ScanFilter(const ScanFilter& other) = default; ScanFilter::ScanFilter(ScanFilter&& other) = default; ScanFilter::~ScanFilter() = default; bool ScanFilter::Matches(const LeScanResult& scan_result) const { if (name && name != scan_result.Name()) { return false; } if (service_uuid) { absl::optional<LeScanResult::UuidList> all_uuids = scan_result.AllServiceUuids(); if (!all_uuids) { return false; } if (!base::Contains(*all_uuids, *service_uuid)) { return false; } } if (!name && regex_name) { absl::optional<std::string> scan_name = scan_result.Name(); if (!scan_name || !RE2::PartialMatch(*scan_name, *regex_name)) { return false; } } return true; } } // namespace bluetooth } // namespace chromecast
510