max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
697
# Copyright 2018 <NAME> LLC, <<EMAIL>> # # 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 opsmop.core.field import Field from opsmop.core.fields import Fields from opsmop.types.type import Type class Directory(Type): def __init__(self, name=None, **kwargs): self.setup(name=name, **kwargs) if self.auto_dispatch: self.run() def fields(self): return Fields( self, name = Field(kind=str, help="path to the destination file"), owner = Field(kind=str, default=None, help="owner name"), group = Field(kind=str, default=None, help="group name"), mode = Field(kind=int, default=None, help="file mode, in hex/octal (not a string)"), absent = Field(kind=bool, default=False, help="if true, delete the file/directory"), recursive = Field(kind=bool, default=False, help="if true, owner, group, and mode become recursive and always run if set") ) def validate(self): pass def default_provider(self): from opsmop.providers.directory import Directory return Directory
571
1,700
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "mutex.h" #include "regression.h" #if defined(__WIN32__) && !defined(PTHREADS_WIN32) #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace embree { MutexSys::MutexSys() { mutex = new CRITICAL_SECTION; InitializeCriticalSection((CRITICAL_SECTION*)mutex); } MutexSys::~MutexSys() { DeleteCriticalSection((CRITICAL_SECTION*)mutex); delete (CRITICAL_SECTION*)mutex; } void MutexSys::lock() { EnterCriticalSection((CRITICAL_SECTION*)mutex); } bool MutexSys::try_lock() { return TryEnterCriticalSection((CRITICAL_SECTION*)mutex) != 0; } void MutexSys::unlock() { LeaveCriticalSection((CRITICAL_SECTION*)mutex); } } #endif #if defined(__UNIX__) || defined(PTHREADS_WIN32) #include <pthread.h> namespace embree { /*! system mutex using pthreads */ MutexSys::MutexSys() { mutex = new pthread_mutex_t; if (pthread_mutex_init((pthread_mutex_t*)mutex, nullptr) != 0) THROW_RUNTIME_ERROR("pthread_mutex_init failed"); } MutexSys::~MutexSys() { MAYBE_UNUSED bool ok = pthread_mutex_destroy((pthread_mutex_t*)mutex) == 0; assert(ok); delete (pthread_mutex_t*)mutex; } void MutexSys::lock() { if (pthread_mutex_lock((pthread_mutex_t*)mutex) != 0) THROW_RUNTIME_ERROR("pthread_mutex_lock failed"); } bool MutexSys::try_lock() { return pthread_mutex_trylock((pthread_mutex_t*)mutex) == 0; } void MutexSys::unlock() { if (pthread_mutex_unlock((pthread_mutex_t*)mutex) != 0) THROW_RUNTIME_ERROR("pthread_mutex_unlock failed"); } }; #endif
684
1,008
<reponame>CrazyForks/turms /* * Copyright (C) 2019 The Turms Project * https://github.com/turms-im/turms * * 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 im.turms.server.common.plugin; import org.springframework.context.ApplicationContext; /** * @author <NAME> */ public abstract class TurmsExtension { private ApplicationContext context; private boolean started; protected ApplicationContext getContext() { return context; } void setContext(ApplicationContext context) { this.context = context; } protected <T> T loadProperties(Class<T> propertiesClass) { return context.getBean(AbstractTurmsPluginManager.class).loadProperties(propertiesClass); } void start() { if (!started) { onStarted(); } started = true; } void stop() { if (started) { onStopped(); } started = false; } protected void onStarted() { } protected void onStopped() { } }
526
335
{ "word": "Print", "definitions": [ "Produce (books, newspapers, etc.), especially in large quantities, by a mechanical process involving the transfer of text or designs to paper.", "Produce (text or a picture) by a printing process.", "(of a newspaper or magazine) publish (a piece of writing) within its pages.", "(of a publisher or printer) arrange for (a book, manuscript, etc.) to be reproduced in large quantities.", "Produce a paper copy of (information stored on a computer)", "Produce (a photographic print) from a negative.", "Write (text) clearly without joining the letters together.", "Mark (a surface, typically a fabric or garment) with a coloured design or pattern.", "Transfer (a design or pattern) to a surface.", "Make (a mark or indentation) by pressing something on a surface or in a soft substance.", "Mark (the surface of a soft substance)", "Fix (something) firmly or indelibly in someone's mind." ], "parts-of-speech": "Verb" }
338
2,338
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <optional> // UNSUPPORTED: c++03, c++11, c++14 // template<class T> // optional(T) -> optional<T>; #include <optional> #include <cassert> #include "test_macros.h" struct A {}; int main(int, char**) { // Test the explicit deduction guides { // optional(T) std::optional opt(5); static_assert(std::is_same_v<decltype(opt), std::optional<int>>, ""); assert(static_cast<bool>(opt)); assert(*opt == 5); } { // optional(T) std::optional opt(A{}); static_assert(std::is_same_v<decltype(opt), std::optional<A>>, ""); assert(static_cast<bool>(opt)); } // Test the implicit deduction guides { // optional(optional); std::optional<char> source('A'); std::optional opt(source); static_assert(std::is_same_v<decltype(opt), std::optional<char>>, ""); assert(static_cast<bool>(opt) == static_cast<bool>(source)); assert(*opt == *source); } return 0; }
456
7,302
# # This source file is part of the EdgeDB open source project. # # Copyright 2012-present MagicStack Inc. and the EdgeDB 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. # import os.path from edb import errors from edb.testbase import lang as tb from edb.edgeql import compiler from edb.edgeql import parser as qlparser class TestEdgeQLIRScopeTree(tb.BaseEdgeQLCompilerTest): """Unit tests for scope tree logic.""" SCHEMA = os.path.join(os.path.dirname(__file__), 'schemas', 'cards.esdl') def run_test(self, *, source, spec, expected): qltree = qlparser.parse(source) ir = compiler.compile_ast_to_ir( qltree, self.schema, options=compiler.CompilerOptions( apply_query_rewrites=False, modaliases={None: 'default'}, ) ) root = ir.scope_tree if len(root.children) != 1: self.fail( f'Scope tree root is expected to have only one child, got' f' {len(root.children)}' f' \n{root.pformat()}' ) @tb.must_fail(errors.QueryError, "reference to 'User.name' changes the interpretation", line=3, col=9) def test_edgeql_ir_scope_tree_bad_01(self): """ SELECT User.deck FILTER User.name """ @tb.must_fail(errors.QueryError, "reference to 'User' changes the interpretation", line=3, col=9) def test_edgeql_ir_scope_tree_bad_02(self): """ SELECT User.deck FILTER User.deck@count """ @tb.must_fail(errors.QueryError, "reference to 'User' changes the interpretation", line=2, col=35) def test_edgeql_ir_scope_tree_bad_03(self): """ SELECT User.deck { foo := User } """ @tb.must_fail(errors.QueryError, "reference to 'User.name' changes the interpretation", line=2, col=40) def test_edgeql_ir_scope_tree_bad_04(self): """ UPDATE User.deck SET { name := User.name } """ @tb.must_fail(errors.QueryError, "reference to 'U.r' changes the interpretation", line=6, col=58) def test_edgeql_ir_scope_tree_bad_05(self): """ WITH U := User {id, r := random()} SELECT ( users := array_agg((SELECT U.id ORDER BY U.r LIMIT 10)) ) """
1,409
799
import json import demistomock as demisto # noqa: F401 import yaml from CommonServerPython import * # noqa: F401 def main(): try: incident = demisto.incident() assets = incident.get('CustomFields', {}).get('assettable', {}) if not assets: return '' if not isinstance(assets, dict): assets = json.loads(assets) if not isinstance(assets, list): assets = [assets] for asset in assets: if "interfaces" in asset: if isinstance(asset["interfaces"], str): asset["interfaces"] = json.loads(asset["interfaces"]) # using yaml to prettify the output of the field asset["interfaces"] = yaml.dump(asset["interfaces"]) markdown = tableToMarkdown("Asset Table", assets) return {'ContentsFormat': formats['markdown'], 'Type': entryTypes['note'], 'Contents': markdown} except Exception as exp: return_error('could not parse QRadar assets', error=exp) if __name__ in ('__main__', '__builtin__', 'builtins'): return_results(main())
474
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <utility> #include "base/threading/thread_task_runner_handle.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/service_manager/public/c/main.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_context.h" #include "services/service_manager/public/cpp/service_runner.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/default_capture_client.h" #include "ui/aura/env.h" #include "ui/aura/mus/property_converter.h" #include "ui/aura/mus/property_utils.h" #include "ui/aura/mus/window_manager_delegate.h" #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/mus/window_tree_client_delegate.h" #include "ui/aura/mus/window_tree_host_mus.h" #include "ui/aura/test/test_focus_client.h" #include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/display_list.h" #include "ui/display/screen_base.h" #include "ui/wm/core/capture_controller.h" #include "ui/wm/core/wm_state.h" namespace ui { namespace test { class TestWM : public service_manager::Service, public aura::WindowTreeClientDelegate, public aura::WindowManagerDelegate { public: TestWM() {} ~TestWM() override { default_capture_client_.reset(); // WindowTreeHost uses state from WindowTreeClient, so destroy it first. window_tree_host_.reset(); // WindowTreeClient destruction may callback to us. window_tree_client_.reset(); display::Screen::SetScreenInstance(nullptr); } private: // service_manager::Service: void OnStart() override { CHECK(!started_); started_ = true; screen_ = std::make_unique<display::ScreenBase>(); display::Screen::SetScreenInstance(screen_.get()); aura_env_ = aura::Env::CreateInstance(aura::Env::Mode::MUS); window_tree_client_ = aura::WindowTreeClient::CreateForWindowManager( context()->connector(), this, this); aura_env_->SetWindowTreeClient(window_tree_client_.get()); } void OnBindInterface(const service_manager::BindSourceInfo& source_info, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override {} // aura::WindowTreeClientDelegate: void OnEmbed( std::unique_ptr<aura::WindowTreeHostMus> window_tree_host) override { // WindowTreeClients configured as the window manager should never get // OnEmbed(). NOTREACHED(); } void OnLostConnection(aura::WindowTreeClient* client) override { window_tree_host_.reset(); window_tree_client_.reset(); } void OnEmbedRootDestroyed( aura::WindowTreeHostMus* window_tree_host) override { // WindowTreeClients configured as the window manager should never get // OnEmbedRootDestroyed(). NOTREACHED(); } void OnPointerEventObserved(const ui::PointerEvent& event, int64_t display_id, aura::Window* target) override { // Don't care. } aura::PropertyConverter* GetPropertyConverter() override { return &property_converter_; } // aura::WindowManagerDelegate: void SetWindowManagerClient(aura::WindowManagerClient* client) override { window_manager_client_ = client; } void OnWmConnected() override {} void OnWmAcceleratedWidgetAvailableForDisplay( int64_t display_id, gfx::AcceleratedWidget widget) override {} void OnWmSetBounds(aura::Window* window, const gfx::Rect& bounds) override { window->SetBounds(bounds); } bool OnWmSetProperty( aura::Window* window, const std::string& name, std::unique_ptr<std::vector<uint8_t>>* new_data) override { return true; } void OnWmSetModalType(aura::Window* window, ui::ModalType type) override {} void OnWmSetCanFocus(aura::Window* window, bool can_focus) override {} aura::Window* OnWmCreateTopLevelWindow( ui::mojom::WindowType window_type, std::map<std::string, std::vector<uint8_t>>* properties) override { aura::Window* window = new aura::Window(nullptr); window->SetProperty(aura::client::kEmbedType, aura::client::WindowEmbedType::TOP_LEVEL_IN_WM); SetWindowType(window, window_type); window->Init(LAYER_NOT_DRAWN); window->SetBounds(gfx::Rect(10, 10, 500, 500)); root_->AddChild(window); return window; } void OnWmClientJankinessChanged(const std::set<aura::Window*>& client_windows, bool janky) override { // Don't care. } void OnWmBuildDragImage(const gfx::Point& screen_location, const SkBitmap& drag_image, const gfx::Vector2d& drag_image_offset, ui::mojom::PointerKind source) override {} void OnWmMoveDragImage(const gfx::Point& screen_location) override {} void OnWmDestroyDragImage() override {} void OnWmWillCreateDisplay(const display::Display& display) override { // This class only deals with one display. DCHECK_EQ(0u, screen_->display_list().displays().size()); screen_->display_list().AddDisplay(display, display::DisplayList::Type::PRIMARY); } void OnWmNewDisplay(std::unique_ptr<aura::WindowTreeHostMus> window_tree_host, const display::Display& display) override { // Only handles a single root. DCHECK(!root_); window_tree_host_ = std::move(window_tree_host); root_ = window_tree_host_->window(); default_capture_client_ = std::make_unique<aura::client::DefaultCaptureClient>( root_->GetRootWindow()); DCHECK(window_manager_client_); window_manager_client_->AddActivationParent(root_); ui::mojom::FrameDecorationValuesPtr frame_decoration_values = ui::mojom::FrameDecorationValues::New(); frame_decoration_values->max_title_bar_button_width = 0; window_manager_client_->SetFrameDecorationValues( std::move(frame_decoration_values)); aura::client::SetFocusClient(root_, &focus_client_); } void OnWmDisplayRemoved(aura::WindowTreeHostMus* window_tree_host) override { DCHECK_EQ(window_tree_host, window_tree_host_.get()); root_ = nullptr; default_capture_client_.reset(); window_tree_host_.reset(); } void OnWmDisplayModified(const display::Display& display) override {} void OnCursorTouchVisibleChanged(bool enabled) override {} void OnWmPerformMoveLoop(aura::Window* window, mojom::MoveLoopSource source, const gfx::Point& cursor_location, const base::Callback<void(bool)>& on_done) override { // Don't care. } void OnWmCancelMoveLoop(aura::Window* window) override {} void OnWmSetClientArea( aura::Window* window, const gfx::Insets& insets, const std::vector<gfx::Rect>& additional_client_areas) override {} bool IsWindowActive(aura::Window* window) override { // Focus client interface doesn't expose this; assume true. return true; } void OnWmDeactivateWindow(aura::Window* window) override { aura::client::GetFocusClient(root_)->FocusWindow(nullptr); } std::unique_ptr<display::ScreenBase> screen_; std::unique_ptr<aura::Env> aura_env_; ::wm::WMState wm_state_; aura::PropertyConverter property_converter_; aura::test::TestFocusClient focus_client_; std::unique_ptr<aura::WindowTreeHostMus> window_tree_host_; aura::Window* root_ = nullptr; aura::WindowManagerClient* window_manager_client_ = nullptr; std::unique_ptr<aura::WindowTreeClient> window_tree_client_; std::unique_ptr<aura::client::DefaultCaptureClient> default_capture_client_; bool started_ = false; DISALLOW_COPY_AND_ASSIGN(TestWM); }; } // namespace test } // namespace ui MojoResult ServiceMain(MojoHandle service_request_handle) { service_manager::ServiceRunner runner(new ui::test::TestWM); return runner.Run(service_request_handle); }
3,113
357
<gh_stars>100-1000 #pragma once #include <vector> #include <memory> #include "Vulkan.h" namespace Vulkan { struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR Capabilities; std::vector<VkSurfaceFormatKHR> Formats; std::vector<VkPresentModeKHR> PresentModes; }; /* * The swap chain is essentially a queue of images that are waiting to be presented to the screen. * Our application will acquire such an image to draw to it, and then return it to the queue. * The general purpose of the swap chain is to synchronize the presentation of images * with the refresh rate of the screen. */ class SwapChain final { public: NON_COPIABLE(SwapChain) SwapChain(const class Device& device); ~SwapChain(); [[nodiscard]] VkSwapchainKHR Get() const { return swapChain; }; [[nodiscard]] const std::vector<VkImage>& GetImage() const { return images; } [[nodiscard]] const std::vector<std::unique_ptr<class ImageView>>& GetImageViews() const { return imageViews; } private: static uint32_t ChooseImageCount(const VkSurfaceCapabilitiesKHR& capabilities); static VkSurfaceFormatKHR ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); static VkPresentModeKHR ChooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); SwapChainSupportDetails QuerySwapChainSupport(VkPhysicalDevice device) const; VkExtent2D ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) const; void CreateImageViews(); std::vector<VkImage> images; std::vector<std::unique_ptr<class ImageView>> imageViews; VkSwapchainKHR swapChain; const class Device& device; const class Surface& surface; public: VkPresentModeKHR PresentMode{}; VkFormat Format{}; VkExtent2D Extent{}; uint32_t MinImageCount{}; }; }
641
1,338
/* * Copyright 2007, <NAME>, <EMAIL>. * All rights reserved. Distributed under the terms of the MIT license. */ #ifndef NAME_INDEX_H #define NAME_INDEX_H #include "EntryListener.h" #include "Index.h" #include "TwoKeyAVLTree.h" class NameIndexEntryIterator; // NameIndex class NameIndex : public Index, private EntryListener { public: NameIndex(Volume *volume); virtual ~NameIndex(); virtual int32 CountEntries() const; virtual status_t Changed(Entry *entry, const char *oldName); private: virtual void EntryAdded(Entry *entry); virtual void EntryRemoved(Entry *entry); protected: virtual AbstractIndexEntryIterator *InternalGetIterator(); virtual AbstractIndexEntryIterator *InternalFind(const uint8 *key, size_t length); private: class EntryTree; friend class NameIndexEntryIterator; void _UpdateLiveQueries(Entry* entry, const char* oldName, const char* newName); private: EntryTree *fEntries; }; #endif // NAME_INDEX_H
308
959
/* * Fadecandy driver for the APA102/APA102C/SK9822 via SPI. * * Copyright (c) 2013 <NAME> * Copyright (c) 2017 <NAME> <<EMAIL>> * * 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. */ #include "apa102spidevice.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include "opc.h" #include <sstream> #include <iostream> const char* APA102SPIDevice::DEVICE_TYPE = "apa102spi"; APA102SPIDevice::APA102SPIDevice(uint32_t numLights, bool verbose) : SPIDevice(DEVICE_TYPE, verbose), mConfigMap(0), mNumLights(numLights) { uint32_t bufferSize = sizeof(PixelFrame) * (numLights + 2); // Number of lights plus start and end frames mFrameBuffer = (PixelFrame*)malloc(bufferSize); uint32_t flushCount = (numLights / 2) + (numLights % 2); mFlushBuffer = (PixelFrame*)malloc(flushCount); // Initialize all buffers to zero memset(mFlushBuffer, 0, flushCount); memset(mFrameBuffer, 0, bufferSize); // Initialize start and end frames mFrameBuffer[0].value = START_FRAME; mFrameBuffer[numLights + 1].value = END_FRAME; } APA102SPIDevice::~APA102SPIDevice() { free(mFrameBuffer); free(mFlushBuffer); flush(); } void APA102SPIDevice::loadConfiguration(const Value &config) { mConfigMap = findConfigMap(config); } std::string APA102SPIDevice::getName() { std::ostringstream s; s << "APA102/APA102C/SK9822 via SPI Port " << mPort; return s.str(); } void APA102SPIDevice::flush() { /* * Flush the buffer by writing zeros through every LED * * This is nessecary in the event that we are not following up a writeBuffer() * with another writeBuffer immediately. * */ uint32_t flushCount = (mNumLights / 2) + (mNumLights % 2); SPIDevice::write(mFlushBuffer, flushCount); } void APA102SPIDevice::writeBuffer() { SPIDevice::write(mFrameBuffer, sizeof(PixelFrame) * (mNumLights + 2)); } void APA102SPIDevice::writeMessage(Document &msg) { /* * Dispatch a device-specific JSON command. * * This can be used to send frames or settings directly to one device, * bypassing the mapping we use for Open Pixel Control clients. This isn't * intended to be the fast path for regular applications, but it can be used * by configuration tools that need to operate regardless of the mapping setup. */ const char *type = msg["type"].GetString(); if (!strcmp(type, "device_pixels")) { // Write raw pixels, without any mapping writeDevicePixels(msg); flush(); return; } // Chain to default handler SPIDevice::writeMessage(msg); } void APA102SPIDevice::writeDevicePixels(Document &msg) { /* * Write pixels without mapping, from a JSON integer * array in msg["pixels"]. The pixel array is removed from * the reply to save network bandwidth. * * Pixel values are clamped to [0, 255], for convenience. */ const Value &pixels = msg["pixels"]; if (!pixels.IsArray()) { msg.AddMember("error", "Pixel array is missing", msg.GetAllocator()); } else { // Truncate to the framebuffer size, and only deal in whole pixels. uint32_t numPixels = pixels.Size() / 3; if (numPixels > mNumLights) numPixels = mNumLights; for (uint32_t i = 0; i < numPixels; i++) { PixelFrame *out = fbPixel(i); const Value &r = pixels[i * 3 + 0]; const Value &g = pixels[i * 3 + 1]; const Value &b = pixels[i * 3 + 2]; out->r = std::max(0, std::min(255, r.IsInt() ? r.GetInt() : 0)); out->g = std::max(0, std::min(255, g.IsInt() ? g.GetInt() : 0)); out->b = std::max(0, std::min(255, b.IsInt() ? b.GetInt() : 0)); out->l = 0xEF; // todo: fix so we actually pass brightness } writeBuffer(); } } void APA102SPIDevice::writeMessage(const OPC::Message &msg) { /* * Dispatch an incoming OPC command */ switch (msg.command) { case OPC::SetPixelColors: opcSetPixelColors(msg); writeBuffer(); return; case OPC::SystemExclusive: // No relevant SysEx for this device return; } if (mVerbose) { std::clog << "Unsupported OPC command: " << unsigned(msg.command) << "\n"; } } void APA102SPIDevice::opcSetPixelColors(const OPC::Message &msg) { /* * Parse through our device's mapping, and store any relevant portions of 'msg' * in the framebuffer. */ if (!mConfigMap) { // No mapping defined yet. This device is inactive. return; } const Value &map = *mConfigMap; for (unsigned i = 0, e = map.Size(); i != e; i++) { opcMapPixelColors(msg, map[i]); } } void APA102SPIDevice::opcMapPixelColors(const OPC::Message &msg, const Value &inst) { /* * Parse one JSON mapping instruction, and copy any relevant parts of 'msg' * into our framebuffer. This looks for any mapping instructions that we * recognize: * * [ OPC Channel, First OPC Pixel, First output pixel, Pixel count ] */ unsigned msgPixelCount = msg.length() / 3; if (inst.IsArray() && inst.Size() == 4) { // Map a range from an OPC channel to our framebuffer const Value &vChannel = inst[0u]; const Value &vFirstOPC = inst[1]; const Value &vFirstOut = inst[2]; const Value &vCount = inst[3]; if (vChannel.IsUint() && vFirstOPC.IsUint() && vFirstOut.IsUint() && vCount.IsInt()) { unsigned channel = vChannel.GetUint(); unsigned firstOPC = vFirstOPC.GetUint(); unsigned firstOut = vFirstOut.GetUint(); unsigned count; int direction; if (vCount.GetInt() >= 0) { count = vCount.GetInt(); direction = 1; } else { count = -vCount.GetInt(); direction = -1; } if (channel != msg.channel) { return; } // Clamping, overflow-safe firstOPC = std::min<unsigned>(firstOPC, msgPixelCount); firstOut = std::min<unsigned>(firstOut, mNumLights); count = std::min<unsigned>(count, msgPixelCount - firstOPC); count = std::min<unsigned>(count, direction > 0 ? mNumLights - firstOut : firstOut + 1); // Copy pixels const uint8_t *inPtr = msg.data + (firstOPC * 3); unsigned outIndex = firstOut; while (count--) { PixelFrame *outPtr = fbPixel(outIndex); outIndex += direction; outPtr->r = inPtr[0]; outPtr->g = inPtr[1]; outPtr->b = inPtr[2]; outPtr->l = 0xEF; // todo: fix so we actually pass brightness inPtr += 3; } return; } } // Still haven't found a match? if (mVerbose) { rapidjson::GenericStringBuffer<rapidjson::UTF8<> > buffer; rapidjson::Writer<rapidjson::GenericStringBuffer<rapidjson::UTF8<> > > writer(buffer); inst.Accept(writer); std::clog << "Unsupported JSON mapping instruction: " << buffer.GetString() << "\n"; } } void APA102SPIDevice::describe(rapidjson::Value &object, Allocator &alloc) { SPIDevice::describe(object, alloc); object.AddMember("numLights", mNumLights, alloc); }
3,516
1,633
<filename>arbitrage/public_markets/_gdax.py import urllib.request import urllib.error import urllib.parse import json from arbitrage.public_markets.market import Market class GDAX(Market): def __init__(self, currency, code): super().__init__(currency) self.code = code self.update_rate = 30 def update_depth(self): url = "https://api.gdax.com/products/%s/book?level=2" % self.code req = urllib.request.Request( url, headers={ "Content-Type": "application/x-www-form-urlencoded", "Accept": "*/*", "User-Agent": "curl/7.24.0 (x86_64-apple-darwin12.0)", }, ) res = urllib.request.urlopen(req) depth = json.loads(res.read().decode("utf8")) self.depth = self.format_depth(depth) def sort_and_format(self, l, reverse=False): l.sort(key=lambda x: float(x[0]), reverse=reverse) r = [] for i in l: r.append({"price": float(i[0]), "amount": float(i[1])}) return r def format_depth(self, depth): bids = self.sort_and_format(depth["bids"], True) asks = self.sort_and_format(depth["asks"], False) return {"asks": asks, "bids": bids}
597
419
#!/usr/bin/env python import argparse import os import sys import h5py import scipy.io as sio if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('matfile') parser.add_argument('save_file') parser.add_argument('--varname', default='boxes') args = parser.parse_args() if os.path.isfile(args.save_file): print "{} already exists.".format(args.save_file) sys.exit(0) if not os.path.isdir(os.path.dirname(args.save_file)): try: os.makedirs(os.path.dirname(args.save_file)) except OSError, e: if e.errno != 17: raise e boxes = sio.loadmat(args.matfile)[args.varname] sio.savemat(args.save_file, {'boxes': boxes}) print "Save boxes from {} to {}".format(args.matfile, args.save_file)
366
454
<gh_stars>100-1000 # Copyright 2021 TUNiB inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from argparse import ArgumentParser import torch from transformers import AutoModel, AutoTokenizer from parallelformers import parallelize class TestModel(unittest.TestCase): @torch.no_grad() def test_forward(self, model, use_pf, fp16): words = ["Hello", "world"] normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782] token_boxes = [] for word, box in zip(words, normalized_word_boxes): word_tokens = tokenizer.tokenize(word) token_boxes.extend([box] * len(word_tokens)) # add bounding boxes of cls + sep tokens token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]] encoding = tokenizer(" ".join(words), return_tensors="pt") input_ids = encoding["input_ids"] attention_mask = encoding["attention_mask"] token_type_ids = encoding["token_type_ids"] bbox = torch.tensor([token_boxes]) if not use_pf: input_ids = input_ids.cuda() attention_mask = attention_mask.cuda() bbox = bbox.cuda() token_type_ids = token_type_ids.cuda() output = model( input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, output_hidden_states=True, ) print("forward:", output.hidden_states[0][0]) torch.save( output.hidden_states, f"output-{'pf' if use_pf else 'non-pf'}-{'fp16' if fp16 else 'fp32'}.pt", ) assert isinstance(output.hidden_states[0][0], torch.Tensor) if __name__ == "__main__": os.environ["TOKENIZERS_PARALLELISM"] = "true" parser = ArgumentParser() parser.add_argument("--test-name", required=True, type=str) parser.add_argument("--name", required=True, type=str) parser.add_argument("--gpu-from", required=True, type=int) parser.add_argument("--gpu-to", required=True, type=int) parser.add_argument("--fp16", default=False, action="store_true") parser.add_argument("--use-pf", default=False, action="store_true") args = parser.parse_args() model = AutoModel.from_pretrained(args.name).eval() tokenizer = AutoTokenizer.from_pretrained(args.name) print(f"Test Name: [{model.__class__.__name__}]-[{args.test_name}]\n") gpus = [ _ for _ in range( args.gpu_from, args.gpu_to + 1, ) ] if args.use_pf: parallelize( model, num_gpus=args.gpu_to + 1, fp16=args.fp16, verbose="simple", ) else: if args.fp16: model = model.half() model = model.cuda() for i in gpus: print(f"GPU {i} alloc: {torch.cuda.memory_allocated(i)}") print(f"GPU {i} cached: { torch.cuda.memory_reserved(i)}") print() test = TestModel() test.test_forward(model, args.use_pf, args.fp16) print("=========================================================")
1,586
306
/*- * ---license-start * keycloak-config-cli * --- * Copyright (C) 2017 - 2021 adorsys GmbH & Co. KG @ https://adorsys.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. * ---license-end */ package de.adorsys.keycloak.config.util; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; public class ResponseUtil { ResponseUtil() { throw new IllegalStateException("Utility class"); } public static void validate(Response response) { if (!response.getStatusInfo().equals(Response.Status.CREATED)) { Response.StatusType statusInfo = response.getStatusInfo(); throw new WebApplicationException("Create method returned status " + statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); " + "expected status: Created (201)", response); } response.close(); } public static String getErrorMessage(WebApplicationException error) { return error.getMessage() + ": " + error.getResponse().readEntity(String.class).trim(); } }
537
1,273
{ "Name": "Turbidity", "BaseUnit": "NTU", "XmlDoc": "Turbidity is the cloudiness or haziness of a fluid caused by large numbers of individual particles that are generally invisible to the naked eye, similar to smoke in air. The measurement of turbidity is a key test of water quality.", "XmlDocRemarks": "https://en.wikipedia.org/wiki/Turbidity", "Units": [ { "SingularName": "NTU", "PluralName": "NTU", "FromUnitToBaseFunc": "x", "FromBaseToUnitFunc": "x", "Localization": [ { "Culture": "en-US", "Abbreviations": ["NTU"] } ] } ] }
263
675
#include "audio_listener_editor.h" #include "engine/core/editor/editor.h" #include "engine/core/main/Engine.h" namespace Echo { #ifdef ECHO_EDITOR_MODE AudioListenerEditor::AudioListenerEditor(Object* object) : ObjectEditor(object) { } AudioListenerEditor::~AudioListenerEditor() { } ImagePtr AudioListenerEditor::getThumbnail() const { return Image::loadFromFile(Engine::instance()->getRootPath() + "engine/modules/audio/editor/icon/audiolistener.png"); } #endif }
166
2,453
<reponame>haozhiyu1990/XVim2 // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class DVTFuzzyMatchCandidateBlock, DVTFuzzyMatchPattern, NSArray; @interface DVTTextCompletionSessionScoringStateChunk : NSObject { char *_matches; long long _matchesCount; DVTFuzzyMatchCandidateBlock *_textBlock; DVTFuzzyMatchPattern *_pattern; NSArray *_candidates; NSArray *_matchingCompletions; } - (void).cxx_destruct; @property(retain) NSArray *matchingCompletions; // @synthesize matchingCompletions=_matchingCompletions; @property(retain) NSArray *candidates; // @synthesize candidates=_candidates; @property(retain) DVTFuzzyMatchPattern *pattern; // @synthesize pattern=_pattern; - (void)updateWithPattern:(id)arg1 precision:(long long)arg2 capturingRanges:(BOOL)arg3; - (void)setAllMatchesTo:(BOOL)arg1; - (id)initWithCandidates:(id)arg1; @end
365
2,874
<filename>libvmaf/tools/vidinput.c /*Daala video codec Copyright (c) 2002-2013 Daala project contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ #include "vidinput.h" #include <stdlib.h> #include <string.h> extern video_input_vtbl Y4M_INPUT_VTBL; extern raw_input_vtbl YUV_INPUT_VTBL; int raw_input_open(video_input *_vid,FILE *_fin, unsigned width, unsigned height, int pix_fmt, unsigned bitdepth) { void *ctx; if((ctx = YUV_INPUT_VTBL.open(_fin, width, height, pix_fmt, bitdepth)) != NULL) { _vid->vtbl=&YUV_INPUT_VTBL; _vid->ctx=ctx; _vid->fin=_fin; return 0; } else fprintf(stderr,"Unknown file type.\n"); return -1; } int video_input_open(video_input *_vid,FILE *_fin){ void *ctx; if((ctx = Y4M_INPUT_VTBL.open(_fin))!=NULL){ _vid->vtbl=&Y4M_INPUT_VTBL; _vid->ctx=ctx; _vid->fin=_fin; return 0; } else fprintf(stderr,"Unknown file type.\n"); return -1; } void video_input_get_info(video_input *_vid,video_input_info *_info){ (*_vid->vtbl->get_info)(_vid->ctx,_info); } int video_input_fetch_frame(video_input *_vid, video_input_ycbcr _ycbcr,char _tag[5]){ return (*_vid->vtbl->fetch_frame)(_vid->ctx,_vid->fin,_ycbcr,_tag); } void video_input_close(video_input *_vid){ (*_vid->vtbl->close)(_vid->ctx); free(_vid->ctx); fclose(_vid->fin); }
986
375
package io.lumify.test; import com.altamiracorp.bigtable.model.ModelSession; import com.altamiracorp.bigtable.model.accumulo.AccumuloSession; import com.altamiracorp.bigtable.model.user.ModelUserContext; import io.lumify.core.bootstrap.InjectHelper; import io.lumify.core.bootstrap.LumifyBootstrap; import io.lumify.core.config.ConfigurationLoader; import io.lumify.core.config.LumifyTestClusterConfigurationLoader; import io.lumify.core.ingest.graphProperty.GraphPropertyRunner; import io.lumify.core.model.user.UserRepository; import io.lumify.core.model.notification.SystemNotificationRepository; import io.lumify.core.model.workQueue.WorkQueueRepository; import io.lumify.core.security.LumifyVisibility; import io.lumify.core.user.SystemUser; import io.lumify.core.util.LumifyLogger; import io.lumify.core.util.LumifyLoggerFactory; import io.lumify.core.util.ModelUtil; import io.lumify.tools.format.FormatLumify; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.ZooKeeperInstance; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.fate.zookeeper.ZooSession; import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.securegraph.Graph; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Properties; import java.util.Queue; import static com.google.common.base.Preconditions.checkNotNull; public class LumifyTestCluster { private static LumifyLogger LOGGER; private final int httpPort; private final int httpsPort; private TestAccumulo accumulo; private TestElasticSearch elasticsearch; private TestJettyServer jetty; private Properties config; private GraphPropertyRunner graphPropertyRunner; public LumifyTestCluster(int httpPort, int httpsPort) { this.httpPort = httpPort; this.httpsPort = httpsPort; System.setProperty(ConfigurationLoader.ENV_CONFIGURATION_LOADER, LumifyTestClusterConfigurationLoader.class.getName()); LOGGER = LumifyLoggerFactory.getLogger(LumifyTestCluster.class); } public static void main(String[] args) { LumifyTestCluster cluster = new LumifyTestCluster(8080, 8443); cluster.startup(); } public void startup() { try { config = LumifyTestClusterConfigurationLoader.getConfigurationProperties(); if (LumifyTestClusterConfigurationLoader.isTestServer()) { FormatLumify.deleteElasticSearchIndex(config); ZooKeeperInstance zooKeeperInstance = new ZooKeeperInstance(config.getProperty("bigtable.accumulo.instanceName"), config.getProperty("bigtable.accumulo.zookeeperServerNames")); Connector connector = zooKeeperInstance.getConnector(config.getProperty("bigtable.accumulo.username"), new PasswordToken(config.getProperty("bigtable.accumulo.password"))); ModelSession modelSession = new AccumuloSession(connector, true); ModelUserContext modelUserContext = modelSession.createModelUserContext(LumifyVisibility.SUPER_USER_VISIBILITY_STRING); SystemUser user = new SystemUser(modelUserContext); ModelUtil.deleteTables(modelSession, user); ModelUtil.initializeTables(modelSession, user); } else { setupHdfsFiles(); startAccumulo(); startElasticSearch(); } startWebServer(); setupGraphPropertyRunner(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); } catch (Exception ex) { throw new RuntimeException("Could not startup", ex); } } public void setupHdfsFiles() { try { File hdfsRoot = new File("/tmp/lumify-integration-test"); File localConfig = new File(getLumifyRootDir(), "./config"); File hdfsConfig = new File(hdfsRoot, "lumify/config"); copyFiles(localConfig, hdfsConfig); } catch (Exception ex) { throw new RuntimeException("Could not setup hdfs files", ex); } } public static File getLumifyRootDir() { File startingDir = new File(System.getProperty("user.dir")); File f = startingDir; while (f != null) { if (new File(f, "core").exists() && new File(f, "config").exists()) { return f; } f = f.getParentFile(); } f = new File(startingDir, "lumify-public"); if (f.exists()) { return f; } throw new RuntimeException("Could not find lumify root starting from " + startingDir.getAbsolutePath()); } private void copyFiles(File sourceDir, File destDir) throws IOException { destDir.mkdirs(); for (File sourceFile : sourceDir.listFiles()) { File destFile = new File(destDir, sourceFile.getName()); if (sourceFile.isDirectory()) { copyFiles(sourceFile, destFile); } else { LOGGER.info("copy file " + sourceFile + " " + destFile); FileUtils.copyFile(sourceFile, destFile); } } } private void setupGraphPropertyRunner() { graphPropertyRunner = InjectHelper.getInstance(GraphPropertyRunner.class); UserRepository userRepository = InjectHelper.getInstance(UserRepository.class); graphPropertyRunner.prepare(userRepository.getSystemUser()); } public void shutdown() { try { if (jetty != null) { jetty.shutdown(); } LOGGER.info("shutdown: graphPropertyRunner"); if (graphPropertyRunner != null) { graphPropertyRunner.shutdown(); } LOGGER.info("shutdown: ModelSession"); if (InjectHelper.hasInjector()) { ModelSession modelSession = InjectHelper.getInstance(ModelSession.class); try { modelSession.close(); } catch (IllegalStateException ex) { // ignore this, the model session is already closed. } } LOGGER.info("shutdown: Graph"); if (InjectHelper.hasInjector()) { SystemNotificationRepository systemNotificationRepository = InjectHelper.getInstance(SystemNotificationRepository.class); systemNotificationRepository.shutdown(); } LOGGER.info("shutdown: Graph"); if (InjectHelper.hasInjector()) { Graph graph = InjectHelper.getInstance(Graph.class); graph.shutdown(); } Thread.sleep(1000); if (!LumifyTestClusterConfigurationLoader.isTestServer()) { elasticsearch.shutdown(); accumulo.shutdown(); shutdownAndResetZooSession(); } LOGGER.info("shutdown: InjectHelper"); InjectHelper.shutdown(); LOGGER.info("shutdown: LumifyBootstrap"); LumifyBootstrap.shutdown(); LOGGER.info("shutdown: clear graph property queue"); getGraphPropertyQueue().clear(); Thread.sleep(1000); LOGGER.info("shutdown complete"); } catch (InterruptedException e) { throw new RuntimeException("failed to sleep", e); } } private void shutdownAndResetZooSession() { ZooSession.shutdown(); try { Field sessionsField = ZooSession.class.getDeclaredField("sessions"); sessionsField.setAccessible(true); sessionsField.set(null, new HashMap()); } catch (Exception ex) { throw new RuntimeException("Could not reset ZooSession internal state"); } } public Properties getLumifyConfig() { return config; } private void startAccumulo() { accumulo = new TestAccumulo(config); accumulo.startup(); } private void startElasticSearch() { elasticsearch = new TestElasticSearch(config); elasticsearch.startup(); } private void startWebServer() { File keyStoreFile = new File(getLumifyRootDir(), "core/test/src/main/resources/io/lumify/test/valid.jks"); File webAppDir = new File(getLumifyRootDir(), "web/war/src/main/webapp"); jetty = new TestJettyServer(webAppDir, httpPort, httpsPort, keyStoreFile.getAbsolutePath(), "password"); jetty.startup(); } public Queue<JSONObject> getGraphPropertyQueue() { return InMemoryWorkQueueRepository.getQueue(WorkQueueRepository.GRAPH_PROPERTY_QUEUE_NAME); } public void processGraphPropertyQueue() { Queue<JSONObject> graphPropertyQueue = getGraphPropertyQueue(); checkNotNull(graphPropertyQueue, "could not get graphPropertyQueue"); JSONObject graphPropertyQueueItem; while ((graphPropertyQueueItem = graphPropertyQueue.poll()) != null) { processGraphPropertyQueueItem(graphPropertyQueueItem); } } private void processGraphPropertyQueueItem(JSONObject graphPropertyQueueItem) { try { LOGGER.info("processGraphPropertyQueueItem: %s", graphPropertyQueueItem.toString(2)); graphPropertyRunner.process(graphPropertyQueueItem); } catch (Throwable ex) { throw new RuntimeException("graphPropertyRunner process: " + ex.getMessage(), ex); } } }
4,035
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. #ifndef COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_CONTROLLER_EMITTER_H_ #define COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_CONTROLLER_EMITTER_H_ #include "build/build_config.h" #include "components/keyed_service/core/keyed_service.h" #include "components/omnibox/browser/autocomplete_controller.h" #if !defined(OS_IOS) #include "content/public/browser/browser_context.h" #endif // !defined(OS_IOS) // This KeyedService is meant to observe multiple AutocompleteController // instances and forward the notifications to its own observers. // Its main purpose is to act as a bridge between the chrome://omnibox WebUI // handler, and the many usages of AutocompleteController (Views, NTP, Android). class OmniboxControllerEmitter : public KeyedService, public AutocompleteController::Observer { public: #if !defined(OS_IOS) static OmniboxControllerEmitter* GetForBrowserContext( content::BrowserContext* browser_context); #endif // !defined(OS_IOS) OmniboxControllerEmitter(); ~OmniboxControllerEmitter() override; OmniboxControllerEmitter(const OmniboxControllerEmitter&) = delete; OmniboxControllerEmitter& operator=(const OmniboxControllerEmitter&) = delete; // Add/remove observer. void AddObserver(AutocompleteController::Observer* observer); void RemoveObserver(AutocompleteController::Observer* observer); // AutocompleteController::Observer: void OnStart(AutocompleteController* controller, const AutocompleteInput& input) override; void OnResultChanged(AutocompleteController* controller, bool default_match_changed) override; private: base::ObserverList<AutocompleteController::Observer> observers_; }; #endif // COMPONENTS_OMNIBOX_BROWSER_OMNIBOX_CONTROLLER_EMITTER_H_
649
852
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 #include "HLTriggerOffline/Tau/interface/HLTTauRefCombiner.h" #include "Math/GenVector/VectorUtil.h" using namespace edm; using namespace std; HLTTauRefCombiner::HLTTauRefCombiner(const edm::ParameterSet &iConfig) : matchDeltaR_{iConfig.getParameter<double>("MatchDeltaR")}, outName_{iConfig.getParameter<string>("OutputCollection")} { std::vector<edm::InputTag> inputCollVector_ = iConfig.getParameter<std::vector<InputTag>>("InputCollections"); for (unsigned int ii = 0; ii < inputCollVector_.size(); ++ii) { inputColl_.push_back(consumes<LorentzVectorCollection>(inputCollVector_[ii])); } produces<LorentzVectorCollection>(outName_); } void HLTTauRefCombiner::produce(edm::StreamID, edm::Event &iEvent, const edm::EventSetup &iES) const { unique_ptr<LorentzVectorCollection> out_product(new LorentzVectorCollection); // Create The Handles.. std::vector<Handle<LorentzVectorCollection>> handles; bool allCollectionsExist = true; // Map the Handles to the collections if all collections exist for (size_t i = 0; i < inputColl_.size(); ++i) { edm::Handle<LorentzVectorCollection> tmp; if (iEvent.getByToken(inputColl_[i], tmp)) { handles.push_back(tmp); } else { allCollectionsExist = false; } } // The reference output object collection will be the first one.. if (allCollectionsExist) { // loop on the first collection for (size_t i = 0; i < (handles[0])->size(); ++i) { bool MatchedObj = true; // get reference Vector const LorentzVector lvRef = (*(handles[0]))[i]; // Loop on all other collections and match for (size_t j = 1; j < handles.size(); ++j) { if (!match(lvRef, *(handles[j]))) MatchedObj = false; } // If the Object is Matched Everywhere store if (MatchedObj) { out_product->push_back(lvRef); } } // Put product to file iEvent.put(std::move(out_product), outName_); } } bool HLTTauRefCombiner::match(const LorentzVector &lv, const LorentzVectorCollection &lvcol) const { bool matched = false; if (!lvcol.empty()) for (LorentzVectorCollection::const_iterator it = lvcol.begin(); it != lvcol.end(); ++it) { double delta = ROOT::Math::VectorUtil::DeltaR(lv, *it); if (delta < matchDeltaR_) { matched = true; } } return matched; }
917
831
<reponame>phpc0de/idea-android // generatedFilesHeader.txt package com.android.tools.idea.lang.multiDexKeep.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.android.tools.idea.lang.multiDexKeep.psi.MultiDexKeepPsiTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.android.tools.idea.lang.multiDexKeep.psi.*; public class MultiDexKeepClassNamesImpl extends ASTWrapperPsiElement implements MultiDexKeepClassNames { public MultiDexKeepClassNamesImpl(@NotNull ASTNode node) { super(node); } public void accept(@NotNull MultiDexKeepVisitor visitor) { visitor.visitClassNames(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof MultiDexKeepVisitor) accept((MultiDexKeepVisitor)visitor); else super.accept(visitor); } @Override @NotNull public List<MultiDexKeepClassName> getClassNameList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, MultiDexKeepClassName.class); } }
405
323
/* * Copyright (c) 2011-2022 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.oracleclient.impl; import io.vertx.oracleclient.OracleConnectOptions; import io.vertx.oracleclient.ServerMode; import oracle.jdbc.OracleConnection; import oracle.jdbc.datasource.OracleDataSource; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; import static io.vertx.oracleclient.impl.Helper.getOrHandleSQLException; import static io.vertx.oracleclient.impl.Helper.runOrHandleSQLException; import static oracle.jdbc.OracleConnection.CONNECTION_PROPERTY_TNS_ADMIN; public class OracleDatabaseHelper { public static OracleDataSource createDataSource(OracleConnectOptions options) { OracleDataSource oracleDataSource = getOrHandleSQLException(oracle.jdbc.pool.OracleDataSource::new); runOrHandleSQLException(() -> oracleDataSource.setURL(composeJdbcUrl(options))); configureStandardOptions(oracleDataSource, options); configureExtendedOptions(oracleDataSource, options); configureJdbcDefaults(oracleDataSource); return oracleDataSource; } /** * Composes an Oracle JDBC URL from {@code OracleConnectOptions}, as * specified in the javadoc of * {@link #createDataSource(OracleConnectOptions)} * * @param options Oracle Connection options. Must not be {@code null}. * @return An Oracle Connection JDBC URL */ private static String composeJdbcUrl(OracleConnectOptions options) { StringBuilder url = new StringBuilder("jdbc:oracle:thin:@"); String tnsAlias = options.getTnsAlias(); if (tnsAlias != null) { return url.append(tnsAlias).toString(); } if (options.isSsl()) { url.append("tcps://"); } String host = options.getHost(); if (host.indexOf(':') >= 0) { // IPv6 address url.append("[").append(host).append("]"); } else { url.append(encodeUrl(host)); } int port = options.getPort(); if (port > 0) { url.append(":").append(port); } String serviceId = options.getServiceId(); if (serviceId != null) { url.append(":").append(encodeUrl(serviceId)); } else { String database = Optional.ofNullable(options.getServiceName()).orElse(options.getDatabase()); if (database != null) { url.append("/").append(encodeUrl(database)); if (options.getServerMode() == ServerMode.SHARED) { url.append(":").append(ServerMode.SHARED); } } } return url.toString(); } /** * Configures an {@code OracleDataSource}. * * @param oracleDataSource An data source to configure * @param options OracleConnectOptions options. Not null. */ private static void configureStandardOptions(OracleDataSource oracleDataSource, OracleConnectOptions options) { Map<String, String> properties = options.getProperties(); if (properties != null && !properties.isEmpty()) { for (Map.Entry<String, String> entry : properties.entrySet()) { runOrHandleSQLException(() -> oracleDataSource.setConnectionProperty(entry.getKey(), entry.getValue())); } } String user = options.getUser(); if (user != null) { runOrHandleSQLException(() -> oracleDataSource.setUser(user)); } CharSequence password = options.getPassword(); if (password != null) { runOrHandleSQLException(() -> oracleDataSource.setPassword(password.toString())); } int connectTimeout = options.getConnectTimeout(); if (connectTimeout > 0) { runOrHandleSQLException(() -> oracleDataSource.setLoginTimeout(connectTimeout)); } } private static void configureExtendedOptions(OracleDataSource oracleDataSource, OracleConnectOptions options) { String tnsAdmin = options.getTnsAdmin(); if (tnsAdmin != null) { runOrHandleSQLException(() -> oracleDataSource.setConnectionProperty(CONNECTION_PROPERTY_TNS_ADMIN, tnsAdmin)); } // TODO Iterate over the other properties. } /** * Configures an {@code oracleDataSource} with any connection properties that * this adapter requires by default. * * @param oracleDataSource An data source to configure */ private static void configureJdbcDefaults(OracleDataSource oracleDataSource) { // Have the Oracle JDBC Driver implement behavior that the JDBC // Specification defines as correct. The javadoc for this property lists // all of it's effects. One effect is to have ResultSetMetaData describe // FLOAT columns as the FLOAT type, rather than the NUMBER type. This // effect allows the Oracle R2DBC Driver obtain correct metadata for // FLOAT type columns. The property is deprecated, but the deprecation note // explains that setting this to "false" is deprecated, and that it // should be set to true; If not set, the 21c driver uses a default value // of false. @SuppressWarnings("deprecation") String enableJdbcSpecCompliance = OracleConnection.CONNECTION_PROPERTY_J2EE13_COMPLIANT; runOrHandleSQLException(() -> oracleDataSource.setConnectionProperty(enableJdbcSpecCompliance, "true")); // Have the Oracle JDBC Driver cache PreparedStatements by default. runOrHandleSQLException(() -> { // Don't override a value set by user code String userValue = oracleDataSource.getConnectionProperty( OracleConnection.CONNECTION_PROPERTY_IMPLICIT_STATEMENT_CACHE_SIZE); if (userValue == null) { // The default value of the OPEN_CURSORS parameter in the 21c // and 19c databases is 50: // https://docs.oracle.com/en/database/oracle/oracle-database/21/refrn/OPEN_CURSORS.html#GUID-FAFD1247-06E5-4E64-917F-AEBD4703CF40 // Assuming this default, then a default cache size of 25 will keep // each session at or below 50% of it's cursor capacity, which seems // reasonable. oracleDataSource.setConnectionProperty( OracleConnection.CONNECTION_PROPERTY_IMPLICIT_STATEMENT_CACHE_SIZE, "25"); } }); // TODO: Disable the result set cache? This is needed to support the // SERIALIZABLE isolation level, which requires result set caching to be // disabled. } private static String encodeUrl(String url) { return URLEncoder.encode(url, StandardCharsets.UTF_8); } }
2,315
391
<reponame>DeNA/SRCNNKit from keras.models import Sequential from keras.layers import Conv2D, Input, BatchNormalization from keras.callbacks import ModelCheckpoint, Callback, TensorBoard from keras.optimizers import SGD, Adam import numpy as np import math import pred import os import random from os import listdir, makedirs from os.path import isfile, join, exists from PIL import Image def model(): SRCNN = Sequential() SRCNN.add(Conv2D(nb_filter=128, nb_row=9, nb_col=9, init='glorot_uniform', activation='relu', border_mode='same', bias=True, input_shape=(200, 200, 3))) SRCNN.add(Conv2D(nb_filter=64, nb_row=3, nb_col=3, init='glorot_uniform', activation='relu', border_mode='same', bias=True)) SRCNN.add(Conv2D(nb_filter=3, nb_row=5, nb_col=5, init='glorot_uniform', activation='linear', border_mode='same', bias=True)) adam = Adam(lr=0.0003) SRCNN.compile(optimizer=adam, loss='mean_squared_error', metrics=['mean_squared_error']) return SRCNN class MyDataGenerator(object): def flow_from_directory(self, input_dir, label_dir, batch_size=32): images = [] labels = [] while True: files = listdir(input_dir) random.shuffle(files) for f in files: images.append(self.load_image(input_dir, f)) labels.append(self.load_image(label_dir, f)) if len(images) == batch_size: x_inputs = np.asarray(images) x_labels = np.asarray(labels) images = [] labels = [] yield x_inputs, x_labels def load_image(self, src_dir, f): X = np.asarray(Image.open(join(src_dir, f)).convert('RGB'), dtype='float32') X /= 255. return X def train(log_dir, model_dir, train_dir, test_dir, eval_img): srcnn_model = model() print(srcnn_model.summary()) datagen = MyDataGenerator() train_gen = datagen.flow_from_directory(os.path.join( train_dir, 'input'), os.path.join(train_dir, 'label'), batch_size = 10) val_gen = datagen.flow_from_directory( os.path.join(test_dir, 'input'), os.path.join(test_dir, 'label'), batch_size = 10) class PredCallback(Callback): def on_epoch_end(self, epoch, logs=None): pass #pred.predict(self.model, eval_img, 'base-%d.png' % epoch, 'out-%d.png' % epoch, False) class PSNRCallback(Callback): def on_epoch_end(self, epoch, logs=None): loss = logs['loss'] * 255. val_loss = logs['val_loss'] * 255. psnr = 20 * math.log10(255. / math.sqrt(loss)) val_psnr = 20 * math.log10(255. / math.sqrt(val_loss)) print("\n") print("PSNR:%s" % psnr) print("PSNR(val):%s" % val_psnr) pd_cb = PredCallback() ps_cb = PSNRCallback() md_cb = ModelCheckpoint(os.path.join(model_dir,'check.h5'), monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='min', period=1) tb_cb = TensorBoard(log_dir=log_dir) srcnn_model.fit_generator( generator = train_gen, steps_per_epoch = 10, validation_data = val_gen, validation_steps = 10, epochs = 1, callbacks=[pd_cb, ps_cb, md_cb, tb_cb]) srcnn_model.save(os.path.join(model_dir,'model.h5')) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("log_dir") parser.add_argument("model_dir") parser.add_argument("train_dir") parser.add_argument("test_dir") parser.add_argument("--eval_img") args = parser.parse_args() print(args) if not exists(args.model_dir): makedirs(args.model_dir) train(args.log_dir, args.model_dir, args.train_dir, args.test_dir, args.eval_img)
1,783
792
<gh_stars>100-1000 { "name": "<NAME>", "location": "Ilorin, Nigeria", "country": "Nigeria", "region": "Africa", "organizers": ["jalasem", "kenkarmah", "jattoabdul"], "website": "http://nodeschool.io/ilorin", "twitter": "ilorinnodeschool", "repo": "http://github.com/nodeschool/ilorin" }
130
369
/** @file @brief Header providing a templated functor wrapping the holding and calling of function pointer and userdata callbacks. @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef INCLUDED_CallbackWrapper_h_GUID_6169ADE2_5BA1_4A81_47C9_9E492F6405ED #define INCLUDED_CallbackWrapper_h_GUID_6169ADE2_5BA1_4A81_47C9_9E492F6405ED // Internal Includes // - none // Library/third-party includes #include <boost/type_traits/function_traits.hpp> #include <boost/type_traits/remove_pointer.hpp> // Standard includes #include <type_traits> #include <utility> namespace osvr { namespace util { /// @brief A class template turning a callback with some number of /// arguments, /// with a userdata pointer last, into a function object. template <typename FunctionPtrType> class CallbackWrapper { public: /// @brief Constructor from function pointer and user data pointer. CallbackWrapper(FunctionPtrType f, void *userData) : m_f(f), m_ud(userData) {} /// @brief Function type (remove pointer - computed) typedef typename boost::remove_pointer<FunctionPtrType>::type FunctionType; /// @brief Return type of the function (computed) typedef typename boost::function_traits<FunctionType>::result_type ReturnType; /// @brief Function call operator with non-void return template <typename... Args> ReturnType operator()(Args &&... args) const { return (*m_f)(std::forward<Args>(args)..., m_ud); } private: FunctionPtrType m_f; void *m_ud; }; } // namespace util } // namespace osvr #endif // INCLUDED_CallbackWrapper_h_GUID_6169ADE2_5BA1_4A81_47C9_9E492F6405ED
851
2,143
package com.tngtech.archunit.core.importer.testexamples.classhierarchyimport; public interface YetAnotherInterface { }
36
387
<gh_stars>100-1000 #include "vector_streambuf.h" vector_streambuf::vector_streambuf(std::vector<char> &vec) { setg(vec.data(), vec.data(), vec.data() + vec.size()); } vector_streambuf::~vector_streambuf() { }
102
334
<reponame>bincrack666/BlackObfuscator package com.googlecode.dex2jar.test; import static com.googlecode.d2j.reader.Op.*; import com.googlecode.d2j.visitors.DexDebugVisitor; import org.junit.Test; import org.junit.runner.RunWith; import com.googlecode.d2j.DexLabel; import com.googlecode.d2j.Field; import com.googlecode.d2j.Method; import com.googlecode.d2j.visitors.DexClassVisitor; import com.googlecode.d2j.visitors.DexCodeVisitor; import com.googlecode.d2j.visitors.DexMethodVisitor; @RunWith(DexTranslatorRunner.class) public class EmptyTrapTest { @Test public static void m005_toJSONString(DexClassVisitor cv) { DexMethodVisitor mv = cv.visitMethod(0, new Method("LJSResponseTest;", "toJSONString", new String[] {}, "Ljava/lang/String;")); if (mv != null) { DexCodeVisitor code = mv.visitCode(); if (code != null) { code.visitRegister(6); DexLabel L8 = new DexLabel(); DexLabel L9 = new DexLabel(); DexLabel L10 = new DexLabel(); DexLabel L0 = new DexLabel(); DexLabel L1 = new DexLabel(); DexLabel L2 = new DexLabel(); code.visitTryCatch(L0, L1, new DexLabel[] { L2 }, new String[] { "Lorg/json/JSONException;" }); DexLabel L3 = new DexLabel(); DexLabel L4 = new DexLabel(); code.visitTryCatch(L3, L4, new DexLabel[] { L2 }, new String[] { "Lorg/json/JSONException;" }); DexLabel L5 = new DexLabel(); DexLabel L6 = new DexLabel(); code.visitTryCatch(L5, L6, new DexLabel[] { L2 }, new String[] { "Lorg/json/JSONException;" }); code.visitConstStmt(CONST_STRING, 2, "response"); code.visitConstStmt(CONST_STRING, 4, ""); code.visitLabel(L0); code.visitFieldStmt(IGET, 2, 5, new Field("LJSResponseTest;", "className", "Ljava/lang/String;")); code.visitJumpStmt(IF_EQZ, 2, -1, L8); code.visitFieldStmt(IGET, 2, 5, new Field("LJSResponseTest;", "methodName", "Ljava/lang/String;")); code.visitJumpStmt(IF_NEZ, 2, -1, L10); code.visitLabel(L8); code.visitConstStmt(CONST_STRING, 2, ""); code.visitStmt2R(MOVE, 2, 4); code.visitLabel(L9); code.visitStmt1R(RETURN_OBJECT, 2); code.visitLabel(L10); code.visitTypeStmt(NEW_INSTANCE, 1, -1, "Lorg/json/JSONObject;"); code.visitMethodStmt(INVOKE_DIRECT, new int[] { 1 }, new Method("Lorg/json/JSONObject;", "<init>", new String[] {}, "V")); code.visitConstStmt(CONST_STRING, 2, "class"); code.visitFieldStmt(IGET, 3, 5, new Field("LJSResponseTest;", "className", "Ljava/lang/String;")); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 1, 2, 3 }, new Method("Lorg/json/JSONObject;", "put", new String[] { "Ljava/lang/String;", "Ljava/lang/Object;" }, "Lorg/json/JSONObject;")); code.visitConstStmt(CONST_STRING, 2, "call"); code.visitFieldStmt(IGET, 3, 5, new Field("LJSResponseTest;", "methodName", "Ljava/lang/String;")); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 1, 2, 3 }, new Method("Lorg/json/JSONObject;", "put", new String[] { "Ljava/lang/String;", "Ljava/lang/Object;" }, "Lorg/json/JSONObject;")); code.visitConstStmt(CONST_STRING, 2, "result"); code.visitFieldStmt(IGET, 3, 5, new Field("LJSResponseTest;", "result", "I")); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 1, 2, 3 }, new Method("Lorg/json/JSONObject;", "put", new String[] { "Ljava/lang/String;", "I" }, "Lorg/json/JSONObject;")); code.visitFieldStmt(IGET, 2, 5, new Field("LJSResponseTest;", "response", "Ljava/lang/Object;")); code.visitJumpStmt(IF_EQZ, 2, -1, L3); code.visitConstStmt(CONST_STRING, 2, "response"); code.visitFieldStmt(IGET, 3, 5, new Field("LJSResponseTest;", "response", "Ljava/lang/Object;")); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 1, 2, 3 }, new Method("Lorg/json/JSONObject;", "put", new String[] { "Ljava/lang/String;", "Ljava/lang/Object;" }, "Lorg/json/JSONObject;")); code.visitLabel(L1); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 1 }, new Method("Lorg/json/JSONObject;", "toString", new String[] {}, "Ljava/lang/String;")); code.visitStmt1R(MOVE_RESULT_OBJECT, 2); code.visitJumpStmt(GOTO, -1, -1, L9); code.visitLabel(L3); code.visitFieldStmt(IGET, 2, 5, new Field("LJSResponseTest;", "dataResponse", "[B")); code.visitJumpStmt(IF_EQZ, 2, -1, L5); code.visitConstStmt(CONST_STRING, 2, "response"); code.visitFieldStmt(IGET, 3, 5, new Field("LJSResponseTest;", "dataResponse", "[B")); code.visitMethodStmt(INVOKE_STATIC, new int[] { 3 }, new Method("LBase64;", "encode", new String[] { "[B" }, "Ljava/lang/String;")); code.visitStmt1R(MOVE_RESULT, 3); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 1, 2, 3 }, new Method("Lorg/json/JSONObject;", "put", new String[] { "Ljava/lang/String;", "Ljava/lang/Object;" }, "Lorg/json/JSONObject;")); code.visitLabel(L4); code.visitJumpStmt(GOTO, -1, -1, L1); code.visitLabel(L2); code.visitStmt1R(MOVE_EXCEPTION, 2); code.visitStmt2R(MOVE, 0, 2); code.visitConstStmt(CONST_STRING, 2, "MillennialMediaSDK"); code.visitMethodStmt(INVOKE_VIRTUAL, new int[] { 0 }, new Method("Lorg/json/JSONException;", "getMessage", new String[] {}, "Ljava/lang/String;")); code.visitStmt1R(MOVE_RESULT, 3); code.visitMethodStmt(INVOKE_STATIC, new int[] { 2, 3 }, new Method("Landroid/util/Log;", "e", new String[] { "Ljava/lang/String;", "Ljava/lang/String;" }, "I")); code.visitConstStmt(CONST_STRING, 2, ""); code.visitStmt2R(MOVE, 2, 4); code.visitJumpStmt(GOTO, -1, -1, L9); code.visitLabel(L5); code.visitConstStmt(CONST_STRING, 2, ""); code.visitLabel(L6); code.visitStmt2R(MOVE, 2, 4); code.visitJumpStmt(GOTO, -1, -1, L9); code.visitEnd(); } mv.visitEnd(); } } }
3,631
5,169
<reponame>Gantios/Specs { "name": "Clare", "version": "3.2.4", "summary": "Clare iOS SDK V3.", "description": "TODO: Add long description of the pod here.", "homepage": "https://www.clare.ai", "license": { "type": "Commercial", "file": "LICENSE" }, "authors": { "Clare": "<EMAIL>" }, "source": { "git": "https://github.com/ClareAI/clare_ios_v3.git", "tag": "3.2.4" }, "platforms": { "ios": "9.0" }, "ios": { "vendored_frameworks": "Clare.framework" }, "preserve_paths": "Clare.framework/*", "module_map": "Clare.framework/Modules/module.modulemap", "resource_bundles": { "Clare": [ "Clare/Assets/*.png" ] }, "frameworks": [ "UIKit", "AVFoundation", "CoreGraphics", "Foundation", "QuartzCore", "SystemConfiguration", "AssetsLibrary", "CFNetwork", "CoreTelephony", "CoreText", "Photos", "Speech" ], "libraries": [ "c++", "icucore" ], "user_target_xcconfig": { "FRAMEWORK_SEARCH_PATHS": "$(PODS_ROOT)/Clare", "OTHER_LDFLAGS": "-l\"stdc++\" -l\"ObjC\" -l\"icucore\" -l\"c++\" -framework \"CoreGraphics\" -framework \"CoreText\" -framework \"CoreTelephony\" -framework \"QuartzCore\" -framework \"SystemConfiguration\" -framework \"Photos\" -framework \"UIKit\" -framework \"AVFoundation\" -framework \"Foundation\" -framework \"AssetsLibrary\" -framework \"CFNetwork\" -framework \"Speech\"" }, "dependencies": { "pop": [ "~> 1.0" ], "CMPopTipView": [ ], "SCSiriWaveformView": [ ], "DGActivityIndicatorView": [ ], "SocketRocket": [ ] } }
714
728
<reponame>JohannesLichtenberger/sirix /** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * Redistributions of source code must retain the * above copyright notice, this list of conditions and the following disclaimer. * Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sirix.io.file; import org.sirix.access.ResourceConfiguration; import org.sirix.exception.SirixIOException; import org.sirix.io.Reader; import org.sirix.io.IOStorage; import org.sirix.io.Writer; import org.sirix.io.bytepipe.ByteHandlePipeline; import org.sirix.io.bytepipe.ByteHandler; import org.sirix.page.PagePersister; import org.sirix.page.SerializationType; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; /** * Factory to provide File access as a backend. * * @author <NAME>, University of Konstanz. * */ public final class FileStorage implements IOStorage { /** Data file name. */ private static final String FILENAME = "sirix.data"; /** Revisions file name. */ private static final String REVISIONS_FILENAME = "sirix.revisions"; /** Instance to storage. */ private final Path file; /** Byte handler pipeline. */ private final ByteHandlePipeline byteHandlerPipeline; /** * Constructor. * * @param resourceConfig the resource configuration */ public FileStorage(final ResourceConfiguration resourceConfig) { assert resourceConfig != null : "resourceConfig must not be null!"; file = resourceConfig.resourcePath; byteHandlerPipeline = resourceConfig.byteHandlePipeline; } @Override public Reader createReader() { try { final Path dataFilePath = createDirectoriesAndFile(); final Path revisionsOffsetFilePath = getRevisionFilePath(); return new FileReader(new RandomAccessFile(dataFilePath.toFile(), "r"), new RandomAccessFile(revisionsOffsetFilePath.toFile(), "r"), new ByteHandlePipeline(byteHandlerPipeline), SerializationType.DATA, new PagePersister()); } catch (final IOException e) { throw new UncheckedIOException(e); } } private Path createDirectoriesAndFile() throws IOException { final Path concreteStorage = getDataFilePath(); if (!Files.exists(concreteStorage)) { Files.createDirectories(concreteStorage.getParent()); Files.createFile(concreteStorage); } return concreteStorage; } @Override public Writer createWriter() { try { final Path dataFilePath = createDirectoriesAndFile(); final Path revisionsOffsetFilePath = getRevisionFilePath(); return new FileWriter(new RandomAccessFile(dataFilePath.toFile(), "rw"), new RandomAccessFile(revisionsOffsetFilePath.toFile(), "rw"), new ByteHandlePipeline(byteHandlerPipeline), SerializationType.DATA, new PagePersister()); } catch (final IOException e) { throw new UncheckedIOException(e); } } @Override public void close() { // not used over here } /** * Getting path for data file. * * @return the path for this data file */ private Path getDataFilePath() { return file.resolve(ResourceConfiguration.ResourcePaths.DATA.getPath()).resolve(FILENAME); } /** * Getting concrete storage for this file. * * @return the concrete storage for this database */ private Path getRevisionFilePath() { return file.resolve(ResourceConfiguration.ResourcePaths.DATA.getPath()) .resolve(REVISIONS_FILENAME); } @Override public boolean exists() { final Path storage = getDataFilePath(); try { return Files.exists(storage) && Files.size(storage) > 0; } catch (final IOException e) { throw new UncheckedIOException(e); } } @Override public ByteHandler getByteHandler() { return byteHandlerPipeline; } }
1,624
402
# # Generate read-only SAS URLs for all LILA containers, to facilitate partial downloads. # # The results of this script end up here: # # http://lila.science/wp-content/uploads/2020/03/lila_sas_urls.txt # # Update: that file is manually maintained now, it can't be programmatically generated # #%% Imports from azure.storage.blob import BlobServiceClient from azure.storage.blob import generate_container_sas from azure.storage.blob import ContainerSasPermissions from datetime import datetime account_name = 'lilablobssc' storage_account_url_blob = 'https://' + account_name + '.blob.core.windows.net' # Read-only storage_account_sas_token = '' storage_account_key = '' output_file = r'd:\temp\lila_sas_urls.txt' #%% Enumerate containers blob_service_client = BlobServiceClient(account_url=storage_account_url_blob, credential=storage_account_sas_token) container_iter = blob_service_client.list_containers(include_metadata=False) containers = [] for container in container_iter: containers.append(container) containers = [c['name'] for c in containers] #%% Generate SAS tokens permissions = ContainerSasPermissions(read=True, write=False, delete=False, list=True) expiry_time = datetime(year=2034,month=1,day=1) start_time = datetime(year=2020,month=1,day=1) container_to_sas_token = {} for container_name in containers: sas_token = generate_container_sas(account_name,container_name,storage_account_key, permission=permissions,expiry=expiry_time,start=start_time) container_to_sas_token[container_name] = sas_token #%% Generate SAS URLs container_to_sas_url = {} for container_name in containers: sas_token = container_to_sas_token[container_name] url = storage_account_url_blob + '/' + container_name + '?' + sas_token container_to_sas_url[container_name] = url #%% Write to output file with open(output_file,'w') as f: for container_name in containers: f.write(container_name + ',' + container_to_sas_url[container_name] + '\n')
796
6,036
<reponame>dennyac/onnxruntime // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/common/common.h" #include "core/framework/op_kernel.h" #include "core/providers/cpu//tensor/concat.h" namespace onnxruntime { class ConcatFromSequence final : public OpKernel, public ConcatBase { public: explicit ConcatFromSequence(const OpKernelInfo& info) : OpKernel(info), ConcatBase(info, true) { } Status Compute(OpKernelContext* context) const override; }; } //namespace onnxruntime
185
1,083
#include "PtrLessThan.h" #include <vector> #include "../../../Function/Function.h" #include "../../../Node/Node.h" #include "../../../Operation/Destruct/Destruct.h" #include "../../../ParseResult/ParseResult.h" #include "../../../Units/Units.h" #include "../../../llvmUtils/llvmUtils.h" #include "../../../llvm_Function.h" #include "../Inst/Inst.h" namespace dale { bool FormProcPtrLessThanParse(Units *units, Function *fn, llvm::BasicBlock *block, Node *node, bool get_address, bool prefixed_with_core, ParseResult *pr) { Context *ctx = units->top()->ctx; if (!ctx->er->assertArgNums("p<", node, 2, 2)) { return false; } std::vector<Node *> *lst = node->list; Node *ptr1_node = (*lst)[1]; Node *ptr2_node = (*lst)[2]; ParseResult ptr_pr1; bool res = FormProcInstParse(units, fn, block, ptr1_node, get_address, false, NULL, &ptr_pr1); if (!res) { return false; } if (!ctx->er->assertIsPointerType("p<", ptr1_node, ptr_pr1.type, "1")) { return false; } ParseResult ptr_pr2; res = FormProcInstParse(units, fn, ptr_pr1.block, ptr2_node, get_address, false, NULL, &ptr_pr2); if (!res) { return false; } if (!ctx->er->assertIsPointerType("p<", ptr2_node, ptr_pr2.type, "2")) { return false; } llvm::IRBuilder<> builder(ptr_pr2.block); llvm::Value *cmp_res = builder.CreateZExt( llvm::cast<llvm::Value>(builder.CreateICmpULT( ptr_pr1.getValue(ctx), ptr_pr2.getValue(ctx))), llvm::Type::getInt8Ty(*getContext())); ptr_pr1.block = ptr_pr2.block; ParseResult destruct_pr; res = Operation::Destruct(ctx, &ptr_pr1, &destruct_pr); if (!res) { return false; } ptr_pr2.block = destruct_pr.block; res = Operation::Destruct(ctx, &ptr_pr2, &destruct_pr); if (!res) { return false; } pr->set(destruct_pr.block, ctx->tr->type_bool, cmp_res); return true; } }
1,094
14,668
// Copyright 2021 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/lacros/net/network_settings_translation.h" #include "components/proxy_config/proxy_config_pref_names.h" #include "components/proxy_config/proxy_prefs.h" #include "net/base/host_port_pair.h" #include "net/base/proxy_server.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_list.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace { constexpr net::NetworkTrafficAnnotationTag kAshProxyConfigTrafficAnnotation = net::DefineNetworkTrafficAnnotation("proxy_config_system", R"( semantics { sender: "Proxy Config" description: "Establishing a connection through a proxy server using system proxy " "settings." trigger: "Whenever a network request is made when the system proxy settings " "are used, and they indicate to use a proxy server." data: "Proxy configuration." destination: OTHER destination_other: "The proxy server specified in the configuration." } policy { cookies_allowed: NO setting: "User cannot override system proxy settings, but can change them " "through the Chrome OS Network Settings UI." policy_exception_justification: "Using either of 'ProxyMode', 'ProxyServer', or 'ProxyPacUrl' " "policies can set Chrome to use a specific proxy settings and avoid " "system proxy." })"); net::ProxyConfigWithAnnotation TranslatePacProxySettings( crosapi::mojom::ProxySettingsPacPtr proxy_settings) { if (!proxy_settings->pac_url.is_valid()) return net::ProxyConfigWithAnnotation::CreateDirect(); net::ProxyConfig proxy_config = net::ProxyConfig::CreateFromCustomPacURL(proxy_settings->pac_url); if (proxy_settings->pac_mandatory) proxy_config.set_pac_mandatory(proxy_settings->pac_mandatory); return net::ProxyConfigWithAnnotation(proxy_config, kAshProxyConfigTrafficAnnotation); } net::ProxyConfigWithAnnotation TranslateWpadProxySettings( crosapi::mojom::ProxySettingsWpadPtr proxy_settings) { // Ash-Chrome has it's own mechanisms for detecting the PAC URL when // configured via WPAD. net::ProxyConfig proxy_config = net::ProxyConfig::CreateAutoDetect(); return net::ProxyConfigWithAnnotation(proxy_config, kAshProxyConfigTrafficAnnotation); } net::ProxyConfigWithAnnotation TranslateManualProxySettings( crosapi::mojom::ProxySettingsManualPtr proxy_settings) { net::ProxyConfig proxy_config = net::ProxyConfig(); proxy_config.proxy_rules().type = net::ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME; for (auto const& proxy : proxy_settings->http_proxies) { proxy_config.proxy_rules().proxies_for_http.AddProxyServer( net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTP, net::HostPortPair(proxy->host, proxy->port))); } for (auto const& proxy : proxy_settings->secure_http_proxies) { proxy_config.proxy_rules().proxies_for_https.AddProxyServer( net::ProxyServer(net::ProxyServer::Scheme::SCHEME_HTTPS, net::HostPortPair(proxy->host, proxy->port))); } for (auto const& proxy : proxy_settings->socks_proxies) { // See `net::ProxyServer::GetSchemeFromPacTypeInternal()`. proxy_config.proxy_rules().fallback_proxies.AddProxyServer( net::ProxyServer(net::ProxyServer::Scheme::SCHEME_SOCKS4, net::HostPortPair(proxy->host, proxy->port))); } for (const auto& domains : proxy_settings->exclude_domains) { proxy_config.proxy_rules().bypass_rules.AddRuleFromString(domains); } return net::ProxyConfigWithAnnotation(proxy_config, kAshProxyConfigTrafficAnnotation); } } // namespace namespace chromeos { net::ProxyConfigWithAnnotation CrosapiProxyToNetProxy( crosapi::mojom::ProxyConfigPtr crosapi_proxy) { if (!crosapi_proxy) return net::ProxyConfigWithAnnotation::CreateDirect(); if (crosapi_proxy->proxy_settings->is_direct()) return net::ProxyConfigWithAnnotation::CreateDirect(); if (crosapi_proxy->proxy_settings->is_pac()) return TranslatePacProxySettings( std::move(crosapi_proxy->proxy_settings->get_pac())); if (crosapi_proxy->proxy_settings->is_wpad()) return TranslateWpadProxySettings( std::move(crosapi_proxy->proxy_settings->get_wpad())); if (crosapi_proxy->proxy_settings->is_manual()) return TranslateManualProxySettings( std::move(crosapi_proxy->proxy_settings->get_manual())); return net::ProxyConfigWithAnnotation::CreateDirect(); } } // namespace chromeos
1,847
861
package cn.springcloud.gray.event.listener; import cn.springcloud.gray.DataSet; import cn.springcloud.gray.GrayManager; import cn.springcloud.gray.event.RoutePolicyEvent; import cn.springcloud.gray.local.InstanceLocalInfo; import cn.springcloud.gray.local.InstanceLocalInfoObtainer; import cn.springcloud.gray.model.GrayInstance; import cn.springcloud.gray.model.GrayService; import cn.springcloud.gray.model.RoutePolicy; import cn.springcloud.gray.model.RoutePolicyType; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** * @author saleson * @date 2020-02-03 18:17 */ @Slf4j public class RoutePolicyEventListener extends AbstractGrayEventListener<RoutePolicyEvent> { private static final String DELETE_CONSUMER_PREFIX = "del_"; private static final String UPDATE_CONSUMER_PREFIX = "update_"; private GrayManager grayManager; private InstanceLocalInfoObtainer instanceLocalInfoObtainer; private Map<String, Consumer<RoutePolicyEvent>> consumerFuncs = new ConcurrentHashMap<>(); public RoutePolicyEventListener( GrayManager grayManager, InstanceLocalInfoObtainer instanceLocalInfoObtainer) { this.grayManager = grayManager; this.instanceLocalInfoObtainer = instanceLocalInfoObtainer; init(); } protected void init() { addUpdateConsumerFunc(RoutePolicyType.SERVICE_ROUTE.name(), this::invokeModifyServiceRouteEvent); addDeleteConsumerFunc(RoutePolicyType.SERVICE_ROUTE.name(), this::invokeDeleteServiceRouteEvent); addUpdateConsumerFunc(RoutePolicyType.SERVICE_MULTI_VER_ROUTE.name(), this::invokeModifyServiceMultiVersionRouteEvent); addDeleteConsumerFunc(RoutePolicyType.SERVICE_MULTI_VER_ROUTE.name(), this::invokeDeleteServiceMultiVersionRouteEvent); addUpdateConsumerFunc(RoutePolicyType.INSTANCE_ROUTE.name(), this::invokeModifyInstanceRouteEvent); addDeleteConsumerFunc(RoutePolicyType.INSTANCE_ROUTE.name(), this::invokeDeleteInstanceRouteEvent); } public void addUpdateConsumerFunc(String type, Consumer<RoutePolicyEvent> consumer) { addConsumerFunc(UPDATE_CONSUMER_PREFIX + type, consumer); } public void addDeleteConsumerFunc(String type, Consumer<RoutePolicyEvent> consumer) { addConsumerFunc(DELETE_CONSUMER_PREFIX + type, consumer); } public Consumer<RoutePolicyEvent> getUpdateConsumerFunc(String type) { return getConsumerFunc(UPDATE_CONSUMER_PREFIX + type); } public Consumer<RoutePolicyEvent> getDeleteConsumerFunc(String type) { return getConsumerFunc(DELETE_CONSUMER_PREFIX + type); } @Override protected void onUpdate(RoutePolicyEvent event) { invokeConsumerFunc(getUpdateConsumerFunc(event.getRoutePolicyType()), event); } @Override protected void onDelete(RoutePolicyEvent event) { invokeConsumerFunc(getDeleteConsumerFunc(event.getRoutePolicyType()), event); } @Override protected boolean validate(RoutePolicyEvent event) { return true; } protected void invokeConsumerFunc(Consumer<RoutePolicyEvent> consumer, RoutePolicyEvent event) { if (Objects.isNull(consumer)) { log.warn("type 为'{}'RoutePolicyEvent缺少消费方法, 请检查该类型的Update和Delete消费方法", event.getType()); return; } consumer.accept(event); } protected void addConsumerFunc(String key, Consumer<RoutePolicyEvent> consumer) { consumerFuncs.put(key.toLowerCase(), consumer); } protected Consumer<RoutePolicyEvent> getConsumerFunc(String key) { return consumerFuncs.get(key.toLowerCase()); } private void invokeModifyServiceRouteEvent(RoutePolicyEvent event) { invokeAndFilterSelfService(event.getRoutePolicy(), routePolicy -> { GrayService grayService = grayManager.getGrayService(routePolicy.getModuleId()); if (Objects.isNull(grayService)) { log.warn("没有找到GrayService, serviceId:{}, 创建GrayService", routePolicy.getModuleId()); grayService = grayManager.createGrayService(routePolicy.getModuleId()); } grayService.getRoutePolicies().addData(String.valueOf(routePolicy.getPolicyId())); }); } private void invokeDeleteServiceRouteEvent(RoutePolicyEvent event) { invokeAndFilterSelfService(event.getRoutePolicy(), routePolicy -> { GrayService grayService = grayManager.getGrayService(routePolicy.getModuleId()); if (Objects.isNull(grayService)) { log.warn("没有找到GrayService, serviceId:{}", routePolicy.getModuleId()); return; } grayService.getRoutePolicies().removeData(String.valueOf(routePolicy.getPolicyId())); }); } private void invokeModifyServiceMultiVersionRouteEvent(RoutePolicyEvent event) { invokeAndFilterSelfService(event.getRoutePolicy(), routePolicy -> { GrayService grayService = grayManager.getGrayService(routePolicy.getModuleId()); if (Objects.isNull(grayService)) { log.warn("没有找到GrayService, serviceId:{}", routePolicy.getModuleId()); return; } DataSet<String> routePolicies = grayService.getVersionRotePolicies(routePolicy.getResource()); if (Objects.isNull(routePolicies)) { routePolicies = grayService.createVersionRoutePolicies(routePolicy.getResource()); } routePolicies.addData(String.valueOf(routePolicy.getPolicyId())); }); } private void invokeDeleteServiceMultiVersionRouteEvent(RoutePolicyEvent event) { invokeAndFilterSelfService(event.getRoutePolicy(), routePolicy -> { GrayService grayService = grayManager.getGrayService(routePolicy.getModuleId()); if (Objects.isNull(grayService)) { log.warn("没有找到GrayService, serviceId:{}", routePolicy.getModuleId()); return; } DataSet<String> routePolicies = grayService.getMultiVersionRotePolicies().get(routePolicy.getResource()); if (Objects.isNull(routePolicies)) { log.warn("没有找到GrayService版本 '{} -- {}'路由策略列表", routePolicy.getModuleId(), routePolicy.getResource()); return; } routePolicies.removeData(String.valueOf(routePolicy.getPolicyId())); }); } private void invokeModifyInstanceRouteEvent(RoutePolicyEvent event) { invokeAndFilterSelfService(event.getRoutePolicy(), routePolicy -> { GrayInstance grayInstance = grayManager.getGrayInstance(routePolicy.getModuleId(), routePolicy.getResource()); if (Objects.isNull(grayInstance)) { log.warn("没有找到GrayInstance, serviceId:{}, instanceId:{}", routePolicy.getModuleId(), routePolicy.getResource()); return; } grayInstance.addRoutePolicy(String.valueOf(routePolicy.getPolicyId())); }); } private void invokeDeleteInstanceRouteEvent(RoutePolicyEvent event) { invokeAndFilterSelfService(event.getRoutePolicy(), routePolicy -> { GrayInstance grayInstance = grayManager.getGrayInstance(routePolicy.getModuleId(), routePolicy.getResource()); if (Objects.isNull(grayInstance)) { log.warn("没有找到GrayInstance, serviceId:{}, instanceId:{}", routePolicy.getModuleId(), routePolicy.getResource()); return; } grayInstance.removeRoutePolicy(String.valueOf(routePolicy.getPolicyId())); }); } private void invokeAndFilterSelfService(RoutePolicy routePolicy, Consumer<RoutePolicy> consumer) { if (isLocalSelfService(routePolicy.getModuleId())) { log.info("接收到本服务的事务, routePolicyId: {}", routePolicy.getId()); return; } if (Objects.isNull(consumer)) { return; } consumer.accept(routePolicy); } private boolean isLocalSelfService(String serviceId) { InstanceLocalInfo instanceLocalInfo = instanceLocalInfoObtainer.getInstanceLocalInfo(); return instanceLocalInfo == null || StringUtils.equals(serviceId, instanceLocalInfo.getServiceId()); } }
3,290
679
/************************************************************** * * 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. * *************************************************************/ #ifndef _CALC_HXX #define _CALC_HXX #include <svl/svarray.hxx> #include <unotools/syslocale.hxx> #ifndef __SBX_SBXVALUE //autogen #include <basic/sbxvar.hxx> #endif #include "swdllapi.h" class CharClass; class LocaleDataWrapper; class SwFieldType; class SwDoc; #define TBLSZ 47 // sollte Primzahl sein, wegen HashTable const sal_Unicode cListDelim = '|'; /****************************************************************************** * Calculate Operations ******************************************************************************/ enum SwCalcOper { CALC_NAME, CALC_NUMBER, CALC_ENDCALC, CALC_PLUS='+', CALC_MINUS='-', CALC_MUL='*', CALC_DIV='/', CALC_PRINT=';', CALC_ASSIGN='=', CALC_LP='(', CALC_RP=')', CALC_PHD='%', CALC_POW='^', CALC_LISTOP = cListDelim, CALC_NOT=256, CALC_AND=257, CALC_OR=258, CALC_XOR=259, CALC_EQ=260, CALC_NEQ=261, CALC_LEQ=262, CALC_GEQ=263, CALC_LES=264, CALC_GRE=265, CALC_SUM=266, CALC_MEAN=267, CALC_SQRT=268, CALC_MIN=269, CALC_MIN_IN=270, CALC_MAX=271, CALC_MAX_IN=272, CALC_SIN=273, CALC_COS=274, CALC_TAN=275, CALC_ASIN=276, CALC_ACOS=278, CALC_ATAN=279, CALC_TDIF=280, CALC_ROUND=281, CALC_DATE=282, CALC_MONTH=283, CALC_DAY=284 }; //-- Calculate Operations Strings ----------------------------------------- extern const sal_Char __FAR_DATA sCalc_Add[]; extern const sal_Char __FAR_DATA sCalc_Sub[]; extern const sal_Char __FAR_DATA sCalc_Mul[]; extern const sal_Char __FAR_DATA sCalc_Div[]; extern const sal_Char __FAR_DATA sCalc_Phd[]; extern const sal_Char __FAR_DATA sCalc_Sqrt[]; extern const sal_Char __FAR_DATA sCalc_Pow[]; extern const sal_Char __FAR_DATA sCalc_Or[]; extern const sal_Char __FAR_DATA sCalc_Xor[]; extern const sal_Char __FAR_DATA sCalc_And[]; extern const sal_Char __FAR_DATA sCalc_Not[]; extern const sal_Char __FAR_DATA sCalc_Eq[]; extern const sal_Char __FAR_DATA sCalc_Neq[]; extern const sal_Char __FAR_DATA sCalc_Leq[]; extern const sal_Char __FAR_DATA sCalc_Geq[]; extern const sal_Char __FAR_DATA sCalc_L[]; extern const sal_Char __FAR_DATA sCalc_G[]; extern const sal_Char __FAR_DATA sCalc_Sum[]; extern const sal_Char __FAR_DATA sCalc_Mean[]; extern const sal_Char __FAR_DATA sCalc_Min[]; extern const sal_Char __FAR_DATA sCalc_Max[]; extern const sal_Char __FAR_DATA sCalc_Sin[]; extern const sal_Char __FAR_DATA sCalc_Cos[]; extern const sal_Char __FAR_DATA sCalc_Tan[]; extern const sal_Char __FAR_DATA sCalc_Asin[]; extern const sal_Char __FAR_DATA sCalc_Acos[]; extern const sal_Char __FAR_DATA sCalc_Atan[]; extern const sal_Char __FAR_DATA sCalc_Tdif[]; extern const sal_Char __FAR_DATA sCalc_Round[]; extern const sal_Char __FAR_DATA sCalc_Date[]; /****************************************************************************** * Calculate ErrorCodes ******************************************************************************/ enum SwCalcError { CALC_NOERR=0, CALC_SYNTAX, // Syntax Fehler CALC_ZERODIV, // Division durch Null CALC_BRACK, // Fehlerhafte Klammerung CALC_POWERR, // Ueberlauf in Quadratfunktion CALC_VARNFND, // Variable wurde nicht gefunden CALC_OVERFLOW, // Ueberlauf CALC_WRONGTIME // falsches Zeitformat }; class SwSbxValue : public SbxValue { bool bVoid; public: //JP 03.02.99: immer auf eine Zahl defaulten, damit auch gerechnet wird. // Ansonsten wird daraus ein SbxEMPTY und damit ist nichts // anzufangen. SwSbxValue( long n = 0 ) : bVoid(false) { PutLong( n ); } SwSbxValue( const double& rD ) : bVoid(false) { PutDouble( rD ); } SwSbxValue( const SwSbxValue& rVal ) : SvRefBase( rVal ), SbxValue( rVal ), bVoid(rVal.bVoid) {} virtual ~SwSbxValue(); // Strings sonderbehandeln sal_Bool GetBool() const; // Strings sonderbehandeln BOOLs sonderbehandeln double GetDouble() const; SwSbxValue& MakeDouble(); bool IsVoidValue() {return bVoid;} void SetVoidValue(bool bSet) {bVoid = bSet;} }; /****************************************************************************** * Calculate HashTables fuer VarTable und Operations ******************************************************************************/ struct SwHash { SwHash( const String& rStr ); virtual ~SwHash(); String aStr; SwHash *pNext; }; struct SwCalcExp : public SwHash { SwSbxValue nValue; const SwFieldType* pFldType; SwCalcExp( const String& rStr, const SwSbxValue& rVal, const SwFieldType* pFldType = 0 ); }; SwHash* Find( const String& rSrch, SwHash** ppTable, sal_uInt16 nTblSize, sal_uInt16* pPos = 0 ); void DeleteHashTable( SwHash** ppTable, sal_uInt16 nTblSize ); // falls _CalcOp != 0, dann ist das ein gueltiger Operator struct _CalcOp; _CalcOp* FindOperator( const String& rSearch ); /****************************************************************************** * class SwCalc ******************************************************************************/ class SwCalc { SwHash* VarTable[ TBLSZ ]; String aVarName, sCurrSym; String sCommand; SvPtrarr aRekurStk; SwSbxValue nLastLeft; SwSbxValue nNumberValue; SwCalcExp aErrExpr; xub_StrLen nCommandPos; SwDoc& rDoc; SvtSysLocale m_aSysLocale; const LocaleDataWrapper* pLclData; CharClass* pCharClass; sal_uInt16 nListPor; SwCalcOper eCurrOper; SwCalcOper eCurrListOper; SwCalcError eError; SwCalcOper GetToken(); SwSbxValue Expr(); SwSbxValue Term(); SwSbxValue Prim(); sal_Bool ParseTime( sal_uInt16*, sal_uInt16*, sal_uInt16* ); String GetColumnName( const String& rName ); String GetDBName( const String& rName ); // dont call this methods SwCalc( const SwCalc& ); SwCalc& operator=( const SwCalc& ); public: SwCalc( SwDoc& rD ); ~SwCalc(); SwSbxValue Calculate( const String &rStr ); String GetStrResult( const SwSbxValue& rValue, sal_Bool bRound = sal_True ); String GetStrResult( double, sal_Bool bRound = sal_True ); SwCalcExp* VarInsert( const String& r ); SwCalcExp* VarLook( const String &rStr, sal_uInt16 ins = 0 ); void VarChange( const String& rStr, const SwSbxValue& rValue ); void VarChange( const String& rStr, double ); SwHash** GetVarTable() { return VarTable; } sal_Bool Push( const VoidPtr pPtr ); void Pop( const VoidPtr pPtr ); void SetCalcError( SwCalcError eErr ) { eError = eErr; } sal_Bool IsCalcError() const { return 0 != eError; } static bool Str2Double( const String& rStr, xub_StrLen& rPos, double& rVal, LocaleDataWrapper const*const pData = 0 ); static bool Str2Double( const String& rStr, xub_StrLen& rPos, double& rVal, SwDoc *const pDoc ); SW_DLLPUBLIC static sal_Bool IsValidVarName( const String& rStr, String* pValidName = 0 ); }; #endif
3,235
348
{"nom":"<NAME>","circ":"3ème circonscription","dpt":"Charente-Maritime","inscrits":1254,"abs":664,"votants":590,"blancs":65,"nuls":30,"exp":495,"res":[{"nuance":"REM","nom":"<NAME>","voix":288},{"nuance":"LR","nom":"M. <NAME>","voix":207}]}
96
9,680
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. ''' NNI example for supported TaylorFOWeight pruning algorithms. In this example, we show the end-to-end pruning process: pre-training -> pruning -> fine-tuning. Note that pruners use masks to simulate the real pruning. In order to obtain a real compressed model, model speed up is required. ''' import argparse import sys import torch from torchvision import datasets, transforms from torch.optim.lr_scheduler import MultiStepLR from nni.compression.pytorch import ModelSpeedup from nni.compression.pytorch.utils.counter import count_flops_params from nni.algorithms.compression.v2.pytorch.pruning.basic_pruner import TaylorFOWeightPruner from nni.algorithms.compression.v2.pytorch.utils import trace_parameters from pathlib import Path sys.path.append(str(Path(__file__).absolute().parents[2] / 'models')) from cifar10.vgg import VGG device = torch.device("cuda" if torch.cuda.is_available() else "cpu") normalize = transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) g_epoch = 0 train_loader = torch.utils.data.DataLoader( datasets.CIFAR10('./data', train=True, transform=transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, 4), transforms.ToTensor(), normalize, ]), download=True), batch_size=128, shuffle=True) test_loader = torch.utils.data.DataLoader( datasets.CIFAR10('./data', train=False, transform=transforms.Compose([ transforms.ToTensor(), normalize, ])), batch_size=128, shuffle=False) def trainer(model, optimizer, criterion): global g_epoch model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() if batch_idx and batch_idx % 100 == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( g_epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) g_epoch += 1 def evaluator(model): model.eval() correct = 0.0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() acc = 100 * correct / len(test_loader.dataset) print('Accuracy: {}%\n'.format(acc)) return acc def optimizer_scheduler_generator(model, _lr=0.1, _momentum=0.9, _weight_decay=5e-4, total_epoch=160): optimizer = torch.optim.SGD(model.parameters(), lr=_lr, momentum=_momentum, weight_decay=_weight_decay) scheduler = MultiStepLR(optimizer, milestones=[int(total_epoch * 0.5), int(total_epoch * 0.75)], gamma=0.1) return optimizer, scheduler if __name__ == '__main__': parser = argparse.ArgumentParser(description='PyTorch Example for model comporession') parser.add_argument('--pretrain-epochs', type=int, default=20, help='number of epochs to pretrain the model') parser.add_argument('--fine-tune-epochs', type=int, default=20, help='number of epochs to fine tune the model') args = parser.parse_args() print('\n' + '=' * 50 + ' START TO TRAIN THE MODEL ' + '=' * 50) model = VGG().to(device) optimizer, scheduler = optimizer_scheduler_generator(model, total_epoch=args.pretrain_epochs) criterion = torch.nn.CrossEntropyLoss() pre_best_acc = 0.0 best_state_dict = None for i in range(args.pretrain_epochs): trainer(model, optimizer, criterion) scheduler.step() acc = evaluator(model) if acc > pre_best_acc: pre_best_acc = acc best_state_dict = model.state_dict() print("Best accuracy: {}".format(pre_best_acc)) model.load_state_dict(best_state_dict) pre_flops, pre_params, _ = count_flops_params(model, torch.randn([128, 3, 32, 32]).to(device)) g_epoch = 0 # Start to prune and speedup print('\n' + '=' * 50 + ' START TO PRUNE THE BEST ACCURACY PRETRAINED MODEL ' + '=' * 50) config_list = [{ 'total_sparsity': 0.5, 'op_types': ['Conv2d'], }] # make sure you have used nni.algorithms.compression.v2.pytorch.utils.trace_parameters to wrap the optimizer class before initialize traced_optimizer = trace_parameters(torch.optim.SGD)(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4) pruner = TaylorFOWeightPruner(model, config_list, trainer, traced_optimizer, criterion, training_batches=20) _, masks = pruner.compress() pruner.show_pruned_weights() pruner._unwrap_model() ModelSpeedup(model, dummy_input=torch.rand([10, 3, 32, 32]).to(device), masks_file=masks).speedup_model() print('\n' + '=' * 50 + ' EVALUATE THE MODEL AFTER SPEEDUP ' + '=' * 50) evaluator(model) # Optimizer used in the pruner might be patched, so recommend to new an optimizer for fine-tuning stage. print('\n' + '=' * 50 + ' START TO FINE TUNE THE MODEL ' + '=' * 50) optimizer, scheduler = optimizer_scheduler_generator(model, _lr=0.01, total_epoch=args.fine_tune_epochs) best_acc = 0.0 g_epoch = 0 for i in range(args.fine_tune_epochs): trainer(model, optimizer, criterion) scheduler.step() best_acc = max(evaluator(model), best_acc) flops, params, results = count_flops_params(model, torch.randn([128, 3, 32, 32]).to(device)) print(f'Pretrained model FLOPs {pre_flops/1e6:.2f} M, #Params: {pre_params/1e6:.2f}M, Accuracy: {pre_best_acc: .2f}%') print(f'Finetuned model FLOPs {flops/1e6:.2f} M, #Params: {params/1e6:.2f}M, Accuracy: {best_acc: .2f}%')
2,433
339
#pragma once #include <WrpConsole.h> #include <shared/AfxMath.h> #include <string> #include <map> #include <vector> #include <list> class CommandSystem { public: bool Enabled; CommandSystem(); ~CommandSystem() { Clear(); } void Add(char const * command); void AddTick(char const * command); void AddAtTime(char const* command, double time); void AddAtTick(char const* command, double tick); void AddCurves(IWrpCommandArgs* args); void EditStart(double startTime); void EditStartTick(double startTick); void EditCommand(IWrpCommandArgs* args); bool Remove(int index); void Clear(void); bool Save(wchar_t const * fileName); bool Load(wchar_t const * fileName); void Console_List(void); void Do_Commands(void); void OnLevelInitPreEntityAllTools(void); double GetLastTime(void) { return m_LastTime; } double GetLastTick(void) { return m_LastTick; } private: class CDoubleInterp { public: enum Method_e { Method_Linear, Method_Cubic }; CDoubleInterp() : m_View(&m_Map, Selector) { } CDoubleInterp(const CDoubleInterp& copyFrom) : m_Map(copyFrom.m_Map) , m_View(&m_Map, Selector) , m_Interp(nullptr) { } ~CDoubleInterp() { delete m_Interp; } Method_e GetMethod() { return m_Method; } void SetMethod(Method_e value) { if (m_Method != value) { if (nullptr != m_Interp) { delete m_Interp; m_Interp = nullptr; } } m_Method = value; } bool CanEval(void) { EnsureInterp(); return m_Interp->CanEval(); } /// <remarks> /// Must not be called if CanEval() returns false!<br /> /// </remarks> double Eval(double t) { EnsureInterp(); return m_Interp->Eval(t); } Afx::Math::CInterpolationMap<double>& GetMap() { return m_Map; } void TriggerMapChanged() { if (m_Interp) m_Interp->InterpolationMapChanged(); } private: Afx::Math::CInterpolationMap<double> m_Map; Afx::Math::CInterpolationMapView<double, double> m_View; Afx::Math::CInterpolation<double>* m_Interp = nullptr; Method_e m_Method = Method_Linear; static double Selector(double const& value) { return value; } void EnsureInterp() { if (nullptr == m_Interp) m_Interp = m_Method == Method_Cubic ? static_cast<Afx::Math::CInterpolation<double>*>(new Afx::Math::CCubicDoubleInterpolation<double>(&m_View)) : static_cast<Afx::Math::CInterpolation<double>*>(new Afx::Math::CLinearDoubleInterpolation<double>(&m_View)); } }; class CCommand { public: CCommand() { } ~CCommand() { } size_t GetSize() { return m_Interp.size(); } void SetSize(size_t value) { m_Interp.resize(value); } bool GetFormated() { return m_Formated; } void SetFormated(bool value) { m_Formated = value; } const char* GetCommand() { return m_Command.c_str(); } void SetCommand(const char* value) { m_Command = value; } CDoubleInterp::Method_e GetInterp(int idx) { return m_Interp[idx].GetMethod(); } void SetInterp(int idx, CDoubleInterp::Method_e value) { m_Interp[idx].SetMethod(value); } Afx::Math::CInterpolationMap<double>& GetMap(int idx) { return m_Interp[idx].GetMap(); } void TriggerMapChanged(int idx) { m_Interp[idx].TriggerMapChanged(); } void Remove(int idx) { auto it = m_Interp.begin(); std::advance(it, idx); m_Interp.erase(it); } void Add(int idx) { auto it = m_Interp.begin(); std::advance(it, idx); m_Interp.insert(it, CDoubleInterp()); } void ClearCurves() { m_Interp.clear(); } bool DoCommand(double t01); private: bool m_OnlyOnce = false; bool m_Formated = false; std::string m_Command; std::vector<CDoubleInterp> m_Interp; }; struct Interval { Interval() { } Interval(double low, double high, bool epsilon) : Low(low) , High(high) , Epsilon(epsilon) { } double Low, High; bool Epsilon; bool operator<(const Interval& other) const { double cmp = Low - other.Low; if (cmp < 0) return true; return cmp == 0 && High < other.High; } }; struct ITNode { CCommand* Command; Interval i; double Max; struct ITNode* Left, * Right; }; ITNode* NewITNode(Interval i, CCommand * command) { ITNode* result = new ITNode(); result->Command = command; result->i = i; result->Max = i.High; result->Right = result->Left = nullptr; return result; } void DeleteNode(ITNode*root) { if (nullptr == root) return; DeleteNode(root->Left); DeleteNode(root->Right); } ITNode* Insert(ITNode* root, Interval i, CCommand * command) { if (nullptr == root) return NewITNode(i, command); double l = root->i.Low; if (i.Low < l) root->Left = Insert(root->Left, i, command); else root->Right = Insert(root->Right, i, command); if (root->Max < i.High) root->Max = i.High; return root; } bool DoOverlap(Interval i1, Interval i2) { if ((i2.Epsilon ? i1.Low <= i2.High : i1.Low < i2.High) && (i1.Epsilon ? i2.Low <= i1.High: i2.Low < i1.High)) return true; return false; } void OverlapExecute(ITNode* root, Interval i) { if (nullptr == root) return; if (DoOverlap(root->i, i)) { if (root->Command) { double d = (double)root->i.High - (double)root->i.Low; double t01 = 0 != d ? ((double)i.High - (double)root->i.Low) / d : 1; if (t01 < 0) t01 = 0; else if (1 < t01) t01 = 1; root->Command->DoCommand(t01); } } if (nullptr != root->Left && root->Left->Max >= i.Low) OverlapExecute(root->Left, i); else OverlapExecute(root->Right, i); } ITNode* m_TickTree = nullptr; ITNode* m_TimeTree = nullptr; std::multimap<Interval, CCommand*> m_TickMap; std::multimap<Interval, CCommand*> m_TimeMap; void DeleteTickTree() { DeleteNode(m_TickTree); m_TickTree = nullptr; } void DeleteTimeTree() { DeleteNode(m_TimeTree); m_TimeTree = nullptr; } void EnsureTickTree() { if (m_TickTree != nullptr) return; for (auto it = m_TickMap.begin(); it != m_TickMap.end(); ++it) { m_TickTree = Insert(m_TickTree, it->first, it->second); // TODO: This tree will degenerate really bad. } } void EnsureTimeTree() { if (m_TimeTree != nullptr) return; for (auto it = m_TimeMap.begin(); it != m_TimeMap.end(); ++it) { m_TimeTree = Insert(m_TimeTree, it->first, it->second); // TODO: This tree will degenerate really bad. } } double m_LastTime; double m_LastTick; bool m_GotCleared = false; bool IsSupportedByTime(void); bool IsSupportedByTick(void); void EditCommandCurves(Interval I, CCommand * c, IWrpCommandArgs* args); }; extern CommandSystem g_CommandSystem;
3,266
397
<reponame>SafetyCulture/quickblox-ios-sdk // // CallParticipants.h // sample-conference-videochat // // Created by Injoit on 21.09.2020. // Copyright © 2020 QuickBlox Team. All rights reserved. // #import <UIKit/UIKit.h> #import "CallParticipant.h" NS_ASSUME_NONNULL_BEGIN @interface CallParticipants : NSObject @property (nonatomic, assign, readonly) NSUInteger count; /// The current user id. @property (nonatomic, assign, readonly) NSNumber *localId; @property (nonatomic, strong, readonly) NSMutableArray<CallParticipant *>*participants; /// The key is a user id and the value is a user name. - (void)addParticipantWithId:(NSNumber *)userId fullName:(NSString *)fullName; - (NSUInteger)participantIndexWithId:(NSNumber *)userId; - (NSNumber *)participantIdWithIndex:(NSUInteger)index; - (CallParticipant * _Nullable)participantWithId:(NSNumber *)userId; - (CallParticipant * _Nullable)participantWithIndex:(NSUInteger)index; - (void)removeParticipantWithId:(NSNumber *)userId; - (UIView * _Nullable)videoViewWithIndex:(NSUInteger)index; - (UIView * _Nullable)videoViewWithId:(NSNumber *)userId; - (void)addVideView:(UIView *)view withId:(NSNumber *)userId; - (void)removeVideViewWithId:(NSNumber *)userId; @end NS_ASSUME_NONNULL_END
429
1,350
<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.security.keyvault.keys.cryptography; import com.azure.core.annotation.ServiceClientBuilder; import com.azure.core.credential.TokenCredential; import com.azure.core.cryptography.AsyncKeyEncryptionKey; import com.azure.core.cryptography.AsyncKeyEncryptionKeyResolver; import com.azure.core.cryptography.KeyEncryptionKey; import com.azure.core.cryptography.KeyEncryptionKeyResolver; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpPipeline; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpLoggingPolicy; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.policy.UserAgentPolicy; import com.azure.core.util.ClientOptions; import com.azure.core.util.Configuration; import com.azure.core.util.logging.ClientLogger; import com.azure.security.keyvault.keys.models.JsonWebKey; import reactor.core.publisher.Mono; /** * This class provides a fluent builder API to help aid the configuration and instantiation of the * {@link AsyncKeyEncryptionKey KeyEncryptionKey async client} and * {@link KeyEncryptionKey KeyEncryptionKey sync client}, by calling * {@link KeyEncryptionKeyClientBuilder#buildAsyncKeyEncryptionKey(String)} and * {@link KeyEncryptionKeyClientBuilder#buildKeyEncryptionKey(String)} respectively. It constructs an instance of the * desired client. * * <p>The minimal configuration options required by {@link KeyEncryptionKeyClientBuilder} to build * {@link AsyncKeyEncryptionKey} are {@link JsonWebKey jsonWebKey} or {@link String Azure Key Vault key identifier} * and {@link TokenCredential credential}.</p> * * <p>The {@link HttpLogDetailLevel log detail level}, multiple custom {@link HttpLoggingPolicy policies} and custom * {@link HttpClient http client} can be optionally configured in the {@link KeyEncryptionKeyClientBuilder}.</p> * * <p>Alternatively, a custom {@link HttpPipeline http pipeline} with custom {@link HttpPipelinePolicy} policies * can be specified. It provides finer control over the construction of {@link AsyncKeyEncryptionKey} and * {@link KeyEncryptionKey}</p> * * <p> The minimal configuration options required by {@link KeyEncryptionKeyClientBuilder keyEncryptionKeyClientBuilder} * to build {@link KeyEncryptionKey} are {@link JsonWebKey jsonWebKey} or * {@link String Azure Key Vault key identifier} and {@link TokenCredential credential}.</p> * * @see KeyEncryptionKeyAsyncClient * @see KeyEncryptionKeyClient */ @ServiceClientBuilder(serviceClients = {KeyEncryptionKeyClient.class, KeyEncryptionKeyAsyncClient.class}) public final class KeyEncryptionKeyClientBuilder implements KeyEncryptionKeyResolver, AsyncKeyEncryptionKeyResolver { private final ClientLogger logger = new ClientLogger(KeyEncryptionKeyClientBuilder.class); private final CryptographyClientBuilder builder; /** * The constructor with defaults. */ public KeyEncryptionKeyClientBuilder() { builder = new CryptographyClientBuilder(); } /** * Creates a {@link KeyEncryptionKey} based on options set in the builder. Every time * {@code buildKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKey} is created. * * <p>If {@link KeyEncryptionKeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} * and {@code keyId} are used to create the {@link KeyEncryptionKeyClient client}. All other builder settings are * ignored. If {@code pipeline} is not set, then an * {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential) Azure Key Vault credential} and {@code keyId} * are required to build the {@link KeyEncryptionKeyClient client}.</p> * * @return A {@link KeyEncryptionKeyClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential)} or * {@code keyId} have not been set. */ @Override public KeyEncryptionKey buildKeyEncryptionKey(String keyId) { return new KeyEncryptionKeyClient((KeyEncryptionKeyAsyncClient) buildAsyncKeyEncryptionKey(keyId).block()); } /** * Creates a local {@link KeyEncryptionKeyClient} for a given JSON Web Key. Every time * {@code buildKeyEncryptionKey(JsonWebKey)} is called, a new instance of {@link KeyEncryptionKey} is created. * For local clients, all other builder settings are ignored. * * <p>The {@code key} is required to build the {@link KeyEncryptionKeyClient client}.</p> * * @param key The {@link JsonWebKey} to be used for cryptography operations. * * @return A {@link KeyEncryptionKeyClient} with the options set from the builder. * * @throws IllegalStateException If {{@code key} is not set. */ public KeyEncryptionKey buildKeyEncryptionKey(JsonWebKey key) { return new KeyEncryptionKeyClient((KeyEncryptionKeyAsyncClient) buildAsyncKeyEncryptionKey(key).block()); } /** * Creates a {@link KeyEncryptionKeyAsyncClient} based on options set in the builder. Every time * {@code buildAsyncKeyEncryptionKey(String)} is called, a new instance of {@link KeyEncryptionKeyAsyncClient} is * created. * * <p>If {@link KeyEncryptionKeyClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} * and {@code keyId} are used to create the {@link KeyEncryptionKeyAsyncClient async client}. All other builder * settings are ignored. If {@code pipeline} is not set, then an * {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential) Azure Key Vault credentials} and * {@code keyId} are required to build the {@link KeyEncryptionKeyAsyncClient async client}.</p> * * @return A {@link KeyEncryptionKeyAsyncClient} with the options set from the builder. * * @throws IllegalStateException If {@link KeyEncryptionKeyClientBuilder#credential(TokenCredential)} is * {@code null} or {@code keyId} is empty or {@code null}. */ @Override public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(String keyId) { builder.keyIdentifier(keyId); if (Strings.isNullOrEmpty(keyId)) { throw logger.logExceptionAsError(new IllegalStateException( "An Azure Key Vault key identifier cannot be null and is required to build the key encryption key " + "client.")); } CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null ? builder.getServiceVersion() : CryptographyServiceVersion.getLatest(); if (builder.getPipeline() != null) { return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, builder.getPipeline(), serviceVersion))); } if (builder.getCredential() == null) { throw logger.logExceptionAsError(new IllegalStateException( "Azure Key Vault credentials cannot be null and are required to build a key encryption key client.")); } HttpPipeline pipeline = builder.setupPipeline(); return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(keyId, pipeline, serviceVersion))); } /** * Creates a local {@link KeyEncryptionKeyAsyncClient} based on options set in the builder. Every time * {@code buildAsyncKeyEncryptionKey(String)} is called, a new instance of * {@link KeyEncryptionKeyAsyncClient} is created. For local clients, all other builder settings are ignored. * * <p>The {@code key} is required to build the {@link KeyEncryptionKeyAsyncClient client}.</p> * * @param key The key to be used for cryptography operations. * * @return A {@link KeyEncryptionKeyAsyncClient} with the options set from the builder. * * @throws IllegalArgumentException If {@code key} has no id. * @throws IllegalStateException If {@code key} is {@code null}. */ public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(JsonWebKey key) { if (key == null) { throw logger.logExceptionAsError(new IllegalStateException( "JSON Web Key cannot be null and is required to build a local key encryption key async client.")); } else if (key.getId() == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "JSON Web Key's id property is not configured.")); } return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(key))); } /** * Sets the credential to use when authenticating HTTP requests. * * @param credential The credential to use for authenticating HTTP requests. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. * * @throws NullPointerException If {@code credential} is {@code null}. */ public KeyEncryptionKeyClientBuilder credential(TokenCredential credential) { if (credential == null) { throw logger.logExceptionAsError(new NullPointerException("'credential' cannot be null.")); } builder.credential(credential); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel#NONE} is set.</p> * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder httpLogOptions(HttpLogOptions logOptions) { builder.httpLogOptions(logOptions); return this; } /** * Adds a policy to the set of existing policies that are executed after the client required policies. * * @param policy The {@link HttpPipelinePolicy policy} to be added. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. * * @throws NullPointerException If {@code policy} is {@code null}. */ public KeyEncryptionKeyClientBuilder addPolicy(HttpPipelinePolicy policy) { if (policy == null) { throw logger.logExceptionAsError(new NullPointerException("'policy' cannot be null.")); } builder.addPolicy(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder httpClient(HttpClient client) { builder.httpClient(client); return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from jsonWebKey identifier * or jsonWebKey to build the clients. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder pipeline(HttpPipeline pipeline) { builder.pipeline(pipeline); return this; } /** * Sets the configuration store that is used during construction of the service client. * * The default configuration store is a clone of the * {@link Configuration#getGlobalConfiguration() global configuration store}, use {@link Configuration#NONE} to * bypass using configuration settings during construction. * * @param configuration The configuration store used to get configuration details. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder configuration(Configuration configuration) { builder.configuration(configuration); return this; } /** * Sets the {@link CryptographyServiceVersion} that is used when making API requests. * <p> * If a service version is not provided, the service version that will be used will be the latest known service * version based on the version of the client library being used. If no service version is specified, updating to a * newer version the client library will have the result of potentially moving to a newer service version. * * @param version {@link CryptographyServiceVersion} of the service to be used when making requests. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder serviceVersion(CryptographyServiceVersion version) { builder.serviceVersion(version); return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. The default retry policy will be used in * the pipeline, if not provided. * * @param retryPolicy User's retry policy applied to each request. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder retryPolicy(RetryPolicy retryPolicy) { builder.retryPolicy(retryPolicy); return this; } /** * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an * {@code applicationId} using {@link ClientOptions#setApplicationId(String)} to configure the * {@link UserAgentPolicy} for telemetry/monitoring purposes. * * <p>More About <a href="https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy">Azure Core: * Telemetry policy</a> * * @param clientOptions The {@link ClientOptions} to be set on the client. * * @return The updated {@link KeyEncryptionKeyClientBuilder} object. */ public KeyEncryptionKeyClientBuilder clientOptions(ClientOptions clientOptions) { builder.clientOptions(clientOptions); return this; } }
4,716
605
package com.sohu.tv.mq.cloud.service; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.sohu.tv.mq.cloud.Application; import com.sohu.tv.mq.cloud.bo.UserMessage; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class UserMessageServiceTest { @Autowired private UserMessageService userMessageService; @Test public void testSave() { UserMessage userMessage = new UserMessage(); userMessage.setUid(40); userMessage.setMessage("测试一下"); userMessageService.save(userMessage); } @Test public void testQueryUnread() { fail("Not yet implemented"); } @Test public void testQueryAll() { fail("Not yet implemented"); } @Test public void testSetToRead() { fail("Not yet implemented"); } @Test public void testSetToReadByUid() { fail("Not yet implemented"); } }
499
7,567
#ifndef _SDK_OVERRIDE_EAGLE_SOC_H_ #define _SDK_OVERRIDE_EAGLE_SOC_H_ #include_next "eagle_soc.h" #define GPIO_SIGMA_DELTA 0x00000068 //defined in gpio register.xls #define GPIO_SIGMA_DELTA_SETTING_MASK (0x00000001ff) #define GPIO_SIGMA_DELTA_ENABLE 1 #define GPIO_SIGMA_DELTA_DISABLE (~GPIO_SIGMA_DELTA_ENABLE) #define GPIO_SIGMA_DELTA_MSB 16 #define GPIO_SIGMA_DELTA_LSB 16 #define GPIO_SIGMA_DELTA_MASK (0x00000001<<GPIO_SIGMA_DELTA_LSB) #define GPIO_SIGMA_DELTA_GET(x) (((x) & GPIO_SIGMA_DELTA_MASK) >> GPIO_SIGMA_DELTA_LSB) #define GPIO_SIGMA_DELTA_SET(x) (((x) << GPIO_SIGMA_DELTA_LSB) & GPIO_SIGMA_DELTA_MASK) #define GPIO_SIGMA_DELTA_TARGET_MSB 7 #define GPIO_SIGMA_DELTA_TARGET_LSB 0 #define GPIO_SIGMA_DELTA_TARGET_MASK (0x000000FF<<GPIO_SIGMA_DELTA_TARGET_LSB) #define GPIO_SIGMA_DELTA_TARGET_GET(x) (((x) & GPIO_SIGMA_DELTA_TARGET_MASK) >> GPIO_SIGMA_DELTA_TARGET_LSB) #define GPIO_SIGMA_DELTA_TARGET_SET(x) (((x) << GPIO_SIGMA_DELTA_TARGET_LSB) & GPIO_SIGMA_DELTA_TARGET_MASK) #define GPIO_SIGMA_DELTA_PRESCALE_MSB 15 #define GPIO_SIGMA_DELTA_PRESCALE_LSB 8 #define GPIO_SIGMA_DELTA_PRESCALE_MASK (0x000000FF<<GPIO_SIGMA_DELTA_PRESCALE_LSB) #define GPIO_SIGMA_DELTA_PRESCALE_GET(x) (((x) & GPIO_SIGMA_DELTA_PRESCALE_MASK) >> GPIO_SIGMA_DELTA_PRESCALE_LSB) #define GPIO_SIGMA_DELTA_PRESCALE_SET(x) (((x) << GPIO_SIGMA_DELTA_PRESCALE_LSB) & GPIO_SIGMA_DELTA_PRESCALE_MASK) #endif
763
314
// // NSArray+ZJHelperKit.h // ZJUIKit // // Created by dzj on 2018/1/19. // Copyright © 2018年 kapokcloud. All rights reserved. // @interface NSArray (ZJHelperKit) /** * 返回安全的索引 @param index 索引 */ -(id)zj_objectAtIndex:(NSInteger)index; /** * 该数组是否包含这个字符串 @param string 字符串 @return Bool */ -(BOOL)zj_isContainsString:(NSString *)string; /** * 数组倒序 */ -(NSArray *)zj_reverseArray; @end
220
306
<filename>Sketchbots/sw/labqueue/config.py<gh_stars>100-1000 # Copyright 2013 Google Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This is the labqueue configuration file. It contains various settings which allow the customization of the system's behavior. """ import os import datetime # This is the worker GUID used to signify topics, tasks, etc. which # were created internally by this system (as opposed to, say, a # sketchbot connecting over the REST interface). # API_WORKER_GUID = 'api.openweblab' # This setting specifies the maximum size of a file which can be POSTed # directly to the binary storage section of the queue. Any content which # exceeds this amount must be uploaded to a special dynamic URL generated by # the server. Such URLs must be requested from the server just prior to # uploading the content. MAX_DIRECT_UPLOAD_FILE_SIZE_BYTES = 800000 # If ALLOW_UNAUTHENTICATED_USE_WITH_WARNING is True, the server will # allow connection from sketchbots, etc. without any kind of security # or authorization. In that case, the server will complain with a # warning, but allow such requests to proceed. # # If it is False, then the server will require an authorization header # with pre-shared security key to be included with all requests. # ALLOW_UNAUTHENTICATED_USE_WITH_WARNING = True # The HELP_TEMPLATES_PATH and ADMIN_TEMPLATES_PATH settings should point # to the location of the template source files used to render online API # help and browser-based admin UI. # HELP_TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), 'templates', 'help' ) ADMIN_TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), 'templates', 'admin' ) # If LDCS_ONLY_EDITABLE_BY_ORIGINAL_CREATOR is True, then an LDC can only # be modified by the same worker that created it. If False, then any worker # can edit any LDC. # LDCS_ONLY_EDITABLE_BY_ORIGINAL_CREATOR = False # The number of seconds a Task reservation will be held before being # automatically released by the system. # TASK_RESERVATION_MAX_HOLD_TIME_SEC = 500 # If True, then Topics with task policies using a 'max_num_tasks' # rule will get max_num_tasks new 'slots' each hour for new Tasks, # even if the Tasks from the previous hour have not been completed. # If False, then the topic will have an absolute cap at 'max_num_tasks' # so that Tasks must be completed for new ones to get in." # TASK_POLICY_MAX_NUM_TASKS_USES_SLOT_MODE = False # Records are kept to check the last time the system was contacted # by a particular worker. Set DISABLE_WORKER_STATUS_WRITES to silently # disable updates to these records. This can be useful for debugging # or reducing the number of datastore writes. # DISABLE_WORKER_STATUS_WRITES = False # The minimum time between allowed worker status updates, in seconds. # If a worker tries to update its own status less than MIN_WORKER_STATUS_UPDATE_PERIOD_SEC # since its last update the server will return an error. This is used # to prevent over-active workers from gobbling up app engine quota. # To reduce quota use, set this to a higher number (or better yet, make # your robots check in less frequently). # MIN_WORKER_STATUS_UPDATE_PERIOD_SEC = 5 # When listing the recent status of all workers that have contacted # the system, ANCIENT_WORKER_STATUS_CUTOFF_DAYS can be used to automatically # filter out old entries. If non-None, then this should indicate the # maximum age of a workrer before they are dropped from status lists. # Even ancient workers can have their status queried via directly # requesting that single worker's status. # ANCIENT_WORKER_STATUS_CUTOFF_DAYS = None # 10 # This is the canonical list of valid touchpoint names. A touchpoint # is a grouping of closely-related interactive exhibit pieces. # VALID_TOUCHPOINT_NAMES = [ 'rob', ] # This is the canonical list of valid activity space names. An activity # space is a logical grouping of touchpoints. # VALID_ACTIVITY_SPACES = [ 'www', ] # If HTTP_RAISE_EXCEPTIONS_IN_REQUESTS is True, the RESTful HTTP interface # will allow any Exceptions encountered in the labqueue code to bubble up # as true Python Exceptions. This will cause any Exception-generating request # to respond as HTTP status 500. That will potentially obscure any bugs from # users connecting via HTTP, in exchange for allowing the system to be debugged # via a live debugger. If it is False, however, the Exceptions will be caught # and (hopefully) userful error responses will be returned over HTTP, with # appropriate status codes. # HTTP_RAISE_EXCEPTIONS_IN_REQUESTS = False # If HTTP_HELP is True, then a built-in human interface to the RESTful API # will be accessible by appending ?HELP=GET (to try out GET requests) or # ?HELP=POST (for POST requests) to any API URL. # HTTP_HELP = True LDC_THUMBNAIL_PARAMS = { 'small': { 'all': { 'max_source_height': None, 'min_source_height': None, 'max_source_width': None, 'min_source_width': None, 'width': 140, 'height': 110, 'overlay_path': None, 'valign': 'middle', # these are good for robot portraits: 'top_crop_pct': None, 'bottom_crop_pct': None, 'left_crop_pct': None, 'right_crop_pct': None, 'crop_x': None, 'crop_y': None, 'post_crop_uniform_scale_pct': None, }, }, } # The number of seconds to allow edge cache to hold LDC public media content PUBLIC_MEDIA_CACHE_MAX_AGE_SEC = 61
1,960
310
{ "name": "V-4000", "description": "A tractor winch.", "url": "https://www.fransgard.dk/all-products/forest/v-winch<Paste>" }
55
317
<reponame>realcredit1/drafter // // refract/ExpandVisitor.cc // librefract // // Created by <NAME> on 21/05/15. // Copyright (c) 2015 Apiary Inc. All rights reserved. // #include "Element.h" #include "Registry.h" #include <stack> #include <functional> #include <sstream> #include "SourceAnnotation.h" #include "IsExpandableVisitor.h" #include "ExpandVisitor.h" #include "TypeQueryVisitor.h" #include "VisitorUtils.h" #define VISIT_IMPL(ELEMENT) \ void ExpandVisitor::operator()(const ELEMENT##Element& e) \ { \ result = Expand(e, context); \ } namespace refract { namespace { bool Expandable(const IElement& e) { IsExpandableVisitor v; VisitBy(e, v); return v.get(); } void CopyMetaId(IElement& dst, const IElement& src) { auto name = src.meta().find("id"); if (name != src.meta().end() && name->second && !name->second->empty()) { dst.meta().set("id", name->second->clone()); } } void MetaIdToRef(IElement& e) { auto name = e.meta().find("id"); if (name != e.meta().end() && name->second && !name->second->empty()) { e.meta().set("ref", name->second->clone()); e.meta().erase("id"); } } template <typename T, bool IsIterable = dsd::is_iterable<T>::value> struct ExpandValueImpl { template <typename Functor> T operator()(const T& value, Functor&) { return value; } }; template <> struct ExpandValueImpl<dsd::Enum> { template <typename Functor> dsd::Enum operator()(const dsd::Enum& v, Functor& expand) { return dsd::Enum{ expand(v.value()) }; } }; template <> struct ExpandValueImpl<dsd::Holder> { template <typename Functor> dsd::Holder operator()(const dsd::Holder& v, Functor& expand) { return dsd::Holder{ expand(v.data()) }; } }; template <typename T> struct ExpandValueImpl<T, true> { template <typename Functor> T operator()(const T& value, Functor& expand) { T members; std::transform(value.begin(), value.end(), std::back_inserter(members), [&expand](const typename T::value_type& el) { return expand(el.get()); }); return members; } }; template <typename It> std::reverse_iterator<It> make_reverse(It&& it) { return std::reverse_iterator<It>(std::forward<It>(it)); } std::unique_ptr<ExtendElement> GetInheritanceTree(const std::string& name, const Registry& registry) { using inheritance_map = std::vector<std::pair<std::string, std::unique_ptr<IElement> > >; inheritance_map inheritance; std::string en = name; // walk recursive in registry and expand inheritance tree for (const IElement* parent = registry.find(en); parent && !isReserved(en); en = parent->element(), parent = registry.find(en)) { if (inheritance.end() != std::find_if(inheritance.begin(), // inheritance.end(), // [en](const inheritance_map::value_type& other) { return en == other.first; })) // { return make_empty<ExtendElement>(); } inheritance.emplace_back( en, clone(*parent, ((IElement::cAll ^ IElement::cElement) | IElement::cNoMetaId))); inheritance.back().second->meta().set("ref", from_primitive(en)); } if (inheritance.empty()) return make_empty<ExtendElement>(); auto e = make_element<ExtendElement>(); auto& content = e->get(); std::for_each( // make_reverse(inheritance.end()), make_reverse(inheritance.begin()), [&content](inheritance_map::value_type& entry) { content.push_back(std::move(entry.second)); }); // FIXME: posible solution while referenced type is not found in regisry // \see test/fixtures/mson-resource-unresolved-reference.apib // // if (e->value.empty()) { // e->meta["ref"] = IElement::Create(name); //} return e; } } // anonymous namespace struct ExpandVisitor::Context { const Registry& registry; ExpandVisitor* expand; std::deque<std::string> members; Context(const Registry& registry, ExpandVisitor* expand) : registry(registry), expand(expand) {} std::unique_ptr<IElement> ExpandOrClone(const IElement* e) const { if (!e) { return nullptr; } VisitBy(*e, *expand); auto result = expand->get(); if (!result) { result = e->clone(); } return result; } template <typename V> V ExpandValue(const V& v) { auto expandOrClone = [this](const IElement* el) { return this->ExpandOrClone(el); }; return ExpandValueImpl<V>()(v, expandOrClone); } template <typename T> std::unique_ptr<T> ExpandMembers(const T& e) { auto o = e.empty() ? // make_empty<T>() : make_element<T>(ExpandValue(e.get())); o->attributes() = e.attributes(); o->meta() = e.meta(); return o; } template <typename T> std::unique_ptr<IElement> ExpandNamedType(const T& e) { // Look for Circular Reference thro members if (std::find(members.begin(), members.end(), e.element()) != members.end()) { // To avoid unfinised recursion just clone const IElement* root = FindRootAncestor(e.element(), registry); // FIXME: if not found root assert(root); auto result = clone(*root, IElement::cMeta | IElement::cAttributes | IElement::cNoMetaId); result->meta().set("ref", from_primitive(e.element())); return result; } members.push_back(e.element()); auto extend = ExpandMembers(*GetInheritanceTree(e.element(), registry)); CopyMetaId(*extend, e); members.pop_back(); auto origin = ExpandMembers(e); origin->meta().erase("id"); if (extend->empty()) extend->set(); extend->get().push_back(std::move(origin)); return std::move(extend); } std::unique_ptr<RefElement> ExpandReference(const RefElement& e) { auto ref = clone(e); const auto& symbol = ref->get().symbol(); if (symbol.empty()) { return ref; } if (std::find(members.begin(), members.end(), symbol) != members.end()) { std::stringstream msg; msg << "named type '"; msg << symbol; msg << "' is circularly referencing itself by mixin"; throw snowcrash::Error(msg.str(), snowcrash::MSONError); } members.push_back(symbol); if (auto referenced = registry.find(symbol)) { auto expanded = ExpandOrClone(std::move(referenced)); MetaIdToRef(*expanded); ref->attributes().set("resolved", std::move(expanded)); } members.pop_back(); return ref; } }; template <typename T, typename V = typename T::ValueType, bool IsIterable = dsd::is_iterable<V>::value> struct ExpandElement { std::unique_ptr<IElement> operator()(const T& e, ExpandVisitor::Context* context) { if (!isReserved(e.element().c_str())) { // expand named type return context->ExpandNamedType(e); } return nullptr; } }; template <> struct ExpandElement<RefElement, RefElement::ValueType, false> { std::unique_ptr<IElement> operator()(const RefElement& e, ExpandVisitor::Context* context) { return context->ExpandReference(e); // expand reference } }; template <> struct ExpandElement<EnumElement, EnumElement::ValueType, false> { std::unique_ptr<IElement> operator()(const EnumElement& e, ExpandVisitor::Context* context) { if (!isReserved(e.element().c_str())) return context->ExpandNamedType(e); auto o = e.empty() ? // make_empty<EnumElement>() : make_element<EnumElement>(context->ExpandValue(e.get())); o->meta() = e.meta(); for (const auto& attribute : e.attributes()) { if (attribute.first == "enumerations") { const auto* enums = TypeQueryVisitor::as<const ArrayElement>(attribute.second.get()); assert(enums); assert(!enums->empty()); dsd::Array expanded; for (const auto& entry : enums->get()) { assert(entry); expanded.push_back(context->ExpandOrClone(entry.get())); } o->attributes().set("enumerations", make_element<ArrayElement>(std::move(expanded))); } else { o->attributes().set(attribute.first, attribute.second->clone()); } } return std::move(o); } }; template <typename T> struct ExpandElement<T, dsd::Select, true> { std::unique_ptr<IElement> operator()(const T& e, ExpandVisitor::Context* context) { if (!Expandable(e)) { // do we have some expandable members? return nullptr; } auto o = make_element<T>(); auto& content = o->get(); o->meta() = e.meta(); // clone for (const auto& opt : e.get()) { content.push_back(std::unique_ptr<OptionElement>( static_cast<OptionElement*>(context->ExpandOrClone(opt.get()).release()))); } return std::move(o); } }; template <typename T, typename V> struct ExpandElement<T, V, true> { std::unique_ptr<IElement> operator()(const T& e, ExpandVisitor::Context* context) { if (!Expandable(e)) { // do we have some expandable members? return nullptr; } std::string en = e.element(); if (!isReserved(en.c_str())) { // expand named type return context->ExpandNamedType(e); } else { // walk throught members and expand them return context->ExpandMembers(e); } // it should never happen assert(0); } }; template <typename T> struct ExpandElement<T, dsd::Member, false> { std::unique_ptr<IElement> operator()(const T& e, ExpandVisitor::Context* context) { if (!Expandable(e)) { return nullptr; } auto expanded = clone(e, IElement::cAll ^ IElement::cValue); expanded->set( dsd::Member{ context->ExpandOrClone(e.get().key()), context->ExpandOrClone(e.get().value()) }); return std::move(expanded); } }; template <typename T> inline std::unique_ptr<IElement> Expand(const T& e, ExpandVisitor::Context* context) { return ExpandElement<T>()(e, context); } ExpandVisitor::ExpandVisitor(const Registry& registry) : result(nullptr), context(new Context(registry, this)){}; ExpandVisitor::~ExpandVisitor() { delete context; } void ExpandVisitor::operator()(const IElement& e) { VisitBy(e, *this); } // do nothing, DirectElements are not expandable void ExpandVisitor::operator()(const HolderElement& e) {} // do nothing, NullElements are not expandable void ExpandVisitor::operator()(const NullElement& e) {} VISIT_IMPL(String) VISIT_IMPL(Number) VISIT_IMPL(Boolean) VISIT_IMPL(Member) VISIT_IMPL(Array) VISIT_IMPL(Enum) VISIT_IMPL(Object) VISIT_IMPL(Ref) VISIT_IMPL(Extend) VISIT_IMPL(Option) VISIT_IMPL(Select) std::unique_ptr<IElement> ExpandVisitor::get() { return std::move(result); } }; // namespace refract #undef VISIT_IMPL
6,825
435
{ "abstract": "Selinon is a task flow manager that enhances Celery and gives you an\nability to create advanced task flows serving large workflows in your\ncluster.\n\n*Tags:* Big Data, Infrastructure, Parallel Programming, Programming,\nPython\n\nScheduled on `wednesday 14:50 </schedule/#wed-14:50-lecture>`__ in room\nlecture\n", "copyright_text": null, "description": "Have you ever tried to define and process complex workflows for data\nprocessing? If the answer is yes, you might have struggled to find the\nright framework for that. You've probably came across Celery - popular\ntask flow management for Python. Celery is great, but it does not\nprovide enough flexibility and dynamic features needed badly in complex\nflows. As we discovered all the limitations, we decided to implement\nSelinon.\n\nHave you ever tried to define and process complex workflows for data\nprocessing? If the answer is yes, you might have struggled to find the\nright framework for that. You've probably came across Celery - popular\ntask flow management for Python. Celery is great, but it does not\nprovide enough flexibility and dynamic features needed badly in complex\nflows. As we discovered all the limitations, we decided to implement\nSelinon.\n\nSelinon enhances Celery task flow management and allows you to create\nand model task flows in your distributed environment that can\ndynamically change behavior based on computed results in your cluster,\nautomatically resolve tasks that need to be executed in case of\nselective task runs, automatic tracing mechanism and many others.\n", "duration": 2726, "language": "eng", "recorded": "2018-10-24", "related_urls": [ { "label": "Conference schedule", "url": "https://de.pycon.org/schedule/" } ], "speakers": [ "Fridol\u00edn Pokorn\u00fd" ], "tags": [ "Big Data", "Infrastructure", "Parallel Programming", "Programming", "Python" ], "thumbnail_url": "https://i.ytimg.com/vi/UDr9Lp_0rp0/maxresdefault.jpg", "title": "Selinon - dynamic distributed task flows", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=UDr9Lp_0rp0" } ] }
676
338
package com.nurkiewicz.asyncretry.backoff; import com.nurkiewicz.asyncretry.RetryContext; /** * @author <NAME> * @since 7/16/13, 6:14 PM */ public class FixedIntervalBackoff implements Backoff { public static final long DEFAULT_PERIOD_MILLIS = 1000; private final long intervalMillis; public FixedIntervalBackoff() { this(DEFAULT_PERIOD_MILLIS); } public FixedIntervalBackoff(long intervalMillis) { this.intervalMillis = intervalMillis; } @Override public long delayMillis(RetryContext context) { return intervalMillis; } }
195
647
<gh_stars>100-1000 /* PURPOSE: (The Trick simulation executive MAIN program.) REFERENCE: ((Bailey, R.W, and Paddock, E.J.) (Trick Simulation Environment) (JSC / Automation and Robotics Division) (June 1994)) ASSUMPTIONS AND LIMITATIONS: (It all starts here) PROGRAMMERS: ( (<NAME>) (LinCom) (April 1992) ) */ #include <iostream> #include <locale.h> #include "trick/Executive.hh" #include "trick/command_line_protos.h" #include "trick/exec_proto.hh" //TODO move to proto void memory_init(void); int master( int nargs, char **args) { int ret ; /* Set the locale */ if (setlocale(LC_CTYPE, "") == NULL) { fprintf(stderr, "Unable to set the locale.\n"); fprintf(stderr, "Please check LANG, LC_CTYPE and LC_ALL.\n"); return 1; } /* adds sim objects including the executive defined at CP time */ memory_init() ; /* process generic command line arguments */ //Trick::CommandLineArguments * cmd_args = exec_get_cmd_args() ; command_line_args_process_sim_args(nargs, args) ; /* get the exec pointer */ Trick::Executive * exec = exec_get_exec_cpp() ; ret = exec->init() ; if ( ret == 0 ) { exec->loop() ; } ret = exec->shutdown() ; //TODO: add call to free all memory from memory manager return ret ; }
640
764
{"symbol": "PGT","address": "0x9b3E946E1a8ea0112b147aF4E6e020752F2446BC","overview":{"en": ""},"email": "<EMAIL>","website": "https://puregold.io","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/Puregold_SG","telegram": "https://t.me/joinchat/G0WpKFEKijI_lSVpn1Mb0Q","github": ""}}
131
601
/* * Copyright 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.data.jdbc.core.convert; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Set; import org.springframework.core.ResolvableType; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.GenericConverter; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; import org.springframework.data.jdbc.core.mapping.AggregateReference; import org.springframework.lang.Nullable; /** * Converters for aggregate references. They need a {@link ConversionService} in order to delegate the conversion of the * content of the {@link AggregateReference}. * * @author <NAME> * @author <NAME> * @since 2.3 */ class AggregateReferenceConverters { /** * Returns the converters to be registered. * * @return a collection of converters. Guaranteed to be not {@literal null}. */ public static Collection<GenericConverter> getConvertersToRegister(ConversionService conversionService) { return Arrays.asList(new AggregateReferenceToSimpleTypeConverter(conversionService), new SimpleTypeToAggregateReferenceConverter(conversionService)); } /** * Converts from an AggregateReference to its id, leaving the conversion of the id to the ultimate target type to the * delegate {@link ConversionService}. */ @WritingConverter private static class AggregateReferenceToSimpleTypeConverter implements GenericConverter { private static final Set<ConvertiblePair> CONVERTIBLE_TYPES = Collections .singleton(new ConvertiblePair(AggregateReference.class, Object.class)); private final ConversionService delegate; AggregateReferenceToSimpleTypeConverter(ConversionService delegate) { this.delegate = delegate; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return CONVERTIBLE_TYPES; } @Override public Object convert(@Nullable Object source, TypeDescriptor sourceDescriptor, TypeDescriptor targetDescriptor) { if (source == null) { return null; } // if the target type is an AggregateReference we are going to assume it is of the correct type, // because it was already converted. Class<?> objectType = targetDescriptor.getObjectType(); if (objectType.isAssignableFrom(AggregateReference.class)) { return source; } Object id = ((AggregateReference<?, ?>) source).getId(); if (id == null) { throw new IllegalStateException( String.format("Aggregate references id must not be null when converting to %s from %s to %s", source, sourceDescriptor, targetDescriptor)); } return delegate.convert(id, TypeDescriptor.valueOf(id.getClass()), targetDescriptor); } } /** * Convert any simple type to an {@link AggregateReference}. If the {@literal targetDescriptor} contains information * about the generic type id will properly get converted to the desired type by the delegate * {@link ConversionService}. */ @ReadingConverter private static class SimpleTypeToAggregateReferenceConverter implements GenericConverter { private static final Set<ConvertiblePair> CONVERTIBLE_TYPES = Collections .singleton(new ConvertiblePair(Object.class, AggregateReference.class)); private final ConversionService delegate; SimpleTypeToAggregateReferenceConverter(ConversionService delegate) { this.delegate = delegate; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return CONVERTIBLE_TYPES; } @Override public Object convert(@Nullable Object source, TypeDescriptor sourceDescriptor, TypeDescriptor targetDescriptor) { if (source == null) { return null; } ResolvableType componentType = targetDescriptor.getResolvableType().getGenerics()[1]; TypeDescriptor targetType = TypeDescriptor.valueOf(componentType.resolve()); Object convertedId = delegate.convert(source, TypeDescriptor.valueOf(source.getClass()), targetType); return AggregateReference.to(convertedId); } } }
1,420
574
/* * Copyright 2019 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://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.sql.legacy.unittest.executor.join; import com.amazon.opendistroforelasticsearch.sql.legacy.executor.join.ElasticUtils; import com.amazon.opendistroforelasticsearch.sql.legacy.executor.join.MetaSearchResult; import org.apache.lucene.search.TotalHits; import org.apache.lucene.search.TotalHits.Relation; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.io.IOException; @RunWith(MockitoJUnitRunner.class) public class ElasticUtilsTest { @Mock MetaSearchResult metaSearchResult; /** * test handling {@link TotalHits} correctly. */ @Test public void hitsAsStringResult() throws IOException { final SearchHits searchHits = new SearchHits(new SearchHit[]{}, new TotalHits(1, Relation.EQUAL_TO), 0); final String result = ElasticUtils.hitsAsStringResult(searchHits, metaSearchResult); Assert.assertEquals(1, new JSONObject(result).query("/hits/total/value")); Assert.assertEquals(Relation.EQUAL_TO.toString(), new JSONObject(result).query("/hits/total/relation")); } /** * test handling {@link TotalHits} with null value correctly. */ @Test public void test_hitsAsStringResult_withNullTotalHits() throws IOException { final SearchHits searchHits = new SearchHits(new SearchHit[]{}, null, 0); final String result = ElasticUtils.hitsAsStringResult(searchHits, metaSearchResult); Assert.assertEquals(0, new JSONObject(result).query("/hits/total/value")); Assert.assertEquals(Relation.EQUAL_TO.toString(), new JSONObject(result).query("/hits/total/relation")); } }
860
1,686
// Copyright (c) 2015 The Chromium Embedded Framework 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 CEF_TESTS_CEFCLIENT_BROWSER_ROOT_WINDOW_MANAGER_H_ #define CEF_TESTS_CEFCLIENT_BROWSER_ROOT_WINDOW_MANAGER_H_ #pragma once #include <memory> #include <set> #include "include/cef_command_line.h" #include "include/cef_request_context_handler.h" #include "tests/cefclient/browser/image_cache.h" #include "tests/cefclient/browser/root_window.h" #include "tests/cefclient/browser/temp_window.h" namespace client { // Used to create/manage RootWindow instances. The methods of this class can be // called from any browser process thread unless otherwise indicated. class RootWindowManager : public RootWindow::Delegate { public: // If |terminate_when_all_windows_closed| is true quit the main message loop // after all windows have closed. explicit RootWindowManager(bool terminate_when_all_windows_closed); // Create a new top-level native window. This method can be called from // anywhere. scoped_refptr<RootWindow> CreateRootWindow( std::unique_ptr<RootWindowConfig> config); // Create a new native popup window. // If |with_controls| is true the window will show controls. // If |with_osr| is true the window will use off-screen rendering. // This method is called from ClientHandler::CreatePopupWindow() to // create a new popup or DevTools window. Must be called on the UI thread. scoped_refptr<RootWindow> CreateRootWindowAsPopup( bool with_controls, bool with_osr, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client, CefBrowserSettings& settings); // Create a new top-level native window to host |extension|. // If |with_controls| is true the window will show controls. // If |with_osr| is true the window will use off-screen rendering. // This method can be called from anywhere. scoped_refptr<RootWindow> CreateRootWindowAsExtension( CefRefPtr<CefExtension> extension, const CefRect& source_bounds, CefRefPtr<CefWindow> parent_window, base::OnceClosure close_callback, bool with_controls, bool with_osr); // Returns true if a window hosting |extension| currently exists. Must be // called on the main thread. bool HasRootWindowAsExtension(CefRefPtr<CefExtension> extension); // Returns the RootWindow associated with the specified browser ID. Must be // called on the main thread. scoped_refptr<RootWindow> GetWindowForBrowser(int browser_id) const; // Returns the currently active/foreground RootWindow. May return nullptr. // Must be called on the main thread. scoped_refptr<RootWindow> GetActiveRootWindow() const; // Returns the currently active/foreground browser. May return nullptr. Safe // to call from any thread. CefRefPtr<CefBrowser> GetActiveBrowser() const; // Close all existing windows. If |force| is true onunload handlers will not // be executed. void CloseAllWindows(bool force); // Manage the set of loaded extensions. RootWindows will be notified via the // OnExtensionsChanged method. void AddExtension(CefRefPtr<CefExtension> extension); bool request_context_per_browser() const { return request_context_per_browser_; } private: // Allow deletion via std::unique_ptr only. friend std::default_delete<RootWindowManager>; ~RootWindowManager(); void OnRootWindowCreated(scoped_refptr<RootWindow> root_window); void NotifyExtensionsChanged(); // RootWindow::Delegate methods. CefRefPtr<CefRequestContext> GetRequestContext( RootWindow* root_window) override; scoped_refptr<ImageCache> GetImageCache() override; void OnTest(RootWindow* root_window, int test_id) override; void OnExit(RootWindow* root_window) override; void OnRootWindowDestroyed(RootWindow* root_window) override; void OnRootWindowActivated(RootWindow* root_window) override; void OnBrowserCreated(RootWindow* root_window, CefRefPtr<CefBrowser> browser) override; void CreateExtensionWindow(CefRefPtr<CefExtension> extension, const CefRect& source_bounds, CefRefPtr<CefWindow> parent_window, base::OnceClosure close_callback, bool with_osr) override; void CleanupOnUIThread(); const bool terminate_when_all_windows_closed_; bool request_context_per_browser_; bool request_context_shared_cache_; // Existing root windows. Only accessed on the main thread. typedef std::set<scoped_refptr<RootWindow>> RootWindowSet; RootWindowSet root_windows_; // The currently active/foreground RootWindow. Only accessed on the main // thread. scoped_refptr<RootWindow> active_root_window_; // The currently active/foreground browser. Access is protected by // |active_browser_lock_; mutable base::Lock active_browser_lock_; CefRefPtr<CefBrowser> active_browser_; // Singleton window used as the temporary parent for popup browsers. std::unique_ptr<TempWindow> temp_window_; CefRefPtr<CefRequestContext> shared_request_context_; // Loaded extensions. Only accessed on the main thread. ExtensionSet extensions_; scoped_refptr<ImageCache> image_cache_; DISALLOW_COPY_AND_ASSIGN(RootWindowManager); }; } // namespace client #endif // CEF_TESTS_CEFCLIENT_BROWSER_ROOT_WINDOW_MANAGER_H_
1,804
785
/* * Copyright © 2020 Apple Inc. and the ServiceTalk project 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 io.servicetalk.http.netty; import io.servicetalk.http.netty.H2ProtocolConfig.KeepAlivePolicy; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.EventLoop; import io.netty.channel.socket.DuplexChannel; import io.netty.handler.codec.http2.DefaultHttp2GoAwayFrame; import io.netty.handler.codec.http2.DefaultHttp2PingFrame; import io.netty.handler.codec.http2.Http2PingFrame; import io.netty.handler.ssl.SslHandler; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.function.Predicate; import javax.annotation.Nullable; import static io.netty.buffer.Unpooled.EMPTY_BUFFER; import static io.netty.channel.ChannelOption.ALLOW_HALF_CLOSURE; import static io.netty.handler.codec.http2.Http2Error.NO_ERROR; import static io.servicetalk.http.netty.H2KeepAlivePolicies.DEFAULT_ACK_TIMEOUT; import static java.lang.Boolean.TRUE; import static java.lang.Math.min; import static java.util.concurrent.TimeUnit.NANOSECONDS; /** * An implementation of {@link KeepAlivePolicy} per {@link Channel}. */ final class KeepAliveManager { private static final Logger LOGGER = LoggerFactory.getLogger(KeepAliveManager.class); private static final AtomicIntegerFieldUpdater<KeepAliveManager> activeChildChannelsUpdater = AtomicIntegerFieldUpdater.newUpdater(KeepAliveManager.class, "activeChildChannels"); private static final long GRACEFUL_CLOSE_PING_CONTENT = ThreadLocalRandom.current().nextLong(); private static final long KEEP_ALIVE_PING_CONTENT = ThreadLocalRandom.current().nextLong(); private static final Object CLOSED = new Object(); private static final Object GRACEFUL_CLOSE_START = new Object(); private static final Object GRACEFUL_CLOSE_SECOND_GO_AWAY_SENT = new Object(); private static final Object KEEP_ALIVE_ACK_PENDING = new Object(); private static final Object KEEP_ALIVE_ACK_TIMEDOUT = new Object(); private volatile int activeChildChannels; private final Channel channel; private final long pingAckTimeoutNanos; private final boolean disallowKeepAliveWithoutActiveStreams; private final Scheduler scheduler; // below state should only be accessed from eventloop /** * This stores the following possible values: * <ul> * <li>{@code null} if graceful close has not started.</li> * <li>{@link #GRACEFUL_CLOSE_START} if graceful close process has been initiated.</li> * <li>{@link Future} instance to timeout ack of PING sent to measure RTT.</li> * <li>{@link #GRACEFUL_CLOSE_SECOND_GO_AWAY_SENT} if we have sent the second go away frame.</li> * <li>{@link #CLOSED} if the channel is closed.</li> * </ul> */ @Nullable private Object gracefulCloseState; /** * This stores the following possible values: * <ul> * <li>{@code null} if keep-alive PING process is not started.</li> * <li>{@link #KEEP_ALIVE_ACK_PENDING} if a keep-alive PING has been sent but ack is not received.</li> * <li>{@link Future} instance to timeout ack of PING sent.</li> * <li>{@link #KEEP_ALIVE_ACK_TIMEDOUT} if we fail to receive a PING ack for the configured timeout.</li> * <li>{@link #CLOSED} if the channel is closed.</li> * </ul> */ @Nullable private Object keepAliveState; @Nullable private final GenericFutureListener<Future<? super Void>> pingWriteCompletionListener; KeepAliveManager(final Channel channel, @Nullable final KeepAlivePolicy keepAlivePolicy) { this(channel, keepAlivePolicy, (task, delay, unit) -> channel.eventLoop().schedule(task, delay, unit), (ch, idlenessThresholdSeconds, onIdle) -> ch.pipeline().addLast( new IdleStateHandler(idlenessThresholdSeconds, idlenessThresholdSeconds, 0) { @Override protected void channelIdle(final ChannelHandlerContext ctx, final IdleStateEvent evt) { onIdle.run(); } })); } KeepAliveManager(final Channel channel, @Nullable final KeepAlivePolicy keepAlivePolicy, final Scheduler scheduler, final IdlenessDetector idlenessDetector) { if (channel instanceof DuplexChannel) { channel.config().setOption(ALLOW_HALF_CLOSURE, TRUE); channel.config().setAutoClose(false); } this.channel = channel; this.scheduler = scheduler; if (keepAlivePolicy != null) { disallowKeepAliveWithoutActiveStreams = !keepAlivePolicy.withoutActiveStreams(); pingAckTimeoutNanos = keepAlivePolicy.ackTimeout().toNanos(); pingWriteCompletionListener = future -> { if (future.isSuccess() && keepAliveState == KEEP_ALIVE_ACK_PENDING) { // Schedule a task to verify ping ack within the pingAckTimeoutMillis keepAliveState = scheduler.afterDuration(() -> { if (keepAliveState != null) { keepAliveState = KEEP_ALIVE_ACK_TIMEDOUT; LOGGER.debug( "channel={}, timeout {}ns waiting for keep-alive PING(ACK), writing GO_AWAY.", this.channel, pingAckTimeoutNanos); channel.writeAndFlush(new DefaultHttp2GoAwayFrame(NO_ERROR)) .addListener(f -> { if (f.isSuccess()) { LOGGER.debug("Closing channel={}, after keep-alive timeout.", this.channel); KeepAliveManager.this.close0(); } }); } }, pingAckTimeoutNanos, NANOSECONDS); } }; int idleInSeconds = (int) min(keepAlivePolicy.idleDuration().getSeconds(), Integer.MAX_VALUE); idlenessDetector.configure(channel, idleInSeconds, this::channelIdle); } else { disallowKeepAliveWithoutActiveStreams = false; pingAckTimeoutNanos = DEFAULT_ACK_TIMEOUT.toNanos(); pingWriteCompletionListener = null; } } void pingReceived(final Http2PingFrame pingFrame) { assert channel.eventLoop().inEventLoop(); if (pingFrame.ack()) { long pingAckContent = pingFrame.content(); if (pingAckContent == GRACEFUL_CLOSE_PING_CONTENT) { LOGGER.debug("channel={}, graceful close ping ack received.", channel); cancelIfStateIsAFuture(gracefulCloseState); gracefulCloseWriteSecondGoAway(); } else if (pingAckContent == KEEP_ALIVE_PING_CONTENT) { cancelIfStateIsAFuture(keepAliveState); keepAliveState = null; } } else { // Send an ack for the received ping channel.writeAndFlush(new DefaultHttp2PingFrame(pingFrame.content(), true)); } } void trackActiveStream(final Channel streamChannel) { activeChildChannelsUpdater.incrementAndGet(this); streamChannel.closeFuture().addListener(f -> { if (activeChildChannelsUpdater.decrementAndGet(this) == 0 && gracefulCloseState == GRACEFUL_CLOSE_SECOND_GO_AWAY_SENT) { close0(); } }); } void channelClosed() { assert channel.eventLoop().inEventLoop(); cancelIfStateIsAFuture(gracefulCloseState); cancelIfStateIsAFuture(keepAliveState); gracefulCloseState = CLOSED; keepAliveState = CLOSED; } void initiateGracefulClose(final Runnable whenInitiated) { EventLoop eventLoop = channel.eventLoop(); if (eventLoop.inEventLoop()) { doCloseAsyncGracefully0(whenInitiated); } else { eventLoop.execute(() -> doCloseAsyncGracefully0(whenInitiated)); } } void channelIdle() { assert channel.eventLoop().inEventLoop(); assert pingWriteCompletionListener != null; if (keepAliveState != null || disallowKeepAliveWithoutActiveStreams && activeChildChannels == 0) { return; } // idleness detected for the first time, send a ping to detect closure, if any. keepAliveState = KEEP_ALIVE_ACK_PENDING; channel.writeAndFlush(new DefaultHttp2PingFrame(KEEP_ALIVE_PING_CONTENT, false)) .addListener(pingWriteCompletionListener); } void channelOutputShutdown() { assert channel.eventLoop().inEventLoop(); channelHalfShutdown(DuplexChannel::isInputShutdown); } void channelInputShutdown() { assert channel.eventLoop().inEventLoop(); channelHalfShutdown(DuplexChannel::isOutputShutdown); } /** * Scheduler of {@link Runnable}s. */ @FunctionalInterface interface Scheduler { /** * Run the passed {@link Runnable} after {@code delay} milliseconds. * * @param task {@link Runnable} to run. * @param delay after which the task is to be run. * @param unit {@link TimeUnit} for the delay. * @return {@link Future} for the scheduled task. */ Future<?> afterDuration(Runnable task, long delay, TimeUnit unit); } /** * Scheduler of {@link Runnable}s. */ @FunctionalInterface interface IdlenessDetector { /** * Configure idleness detection for the passed {@code channel}. * * @param channel {@link Channel} for which idleness detection is to be configured. * @param idlenessThresholdSeconds Seconds of idleness after which {@link Runnable#run()} should be called on * the passed {@code onIdle}. * @param onIdle {@link Runnable} to call when the channel is idle more than {@code idlenessThresholdSeconds}. */ void configure(Channel channel, int idlenessThresholdSeconds, Runnable onIdle); } private void channelHalfShutdown(Predicate<DuplexChannel> otherSideShutdown) { if (channel instanceof DuplexChannel) { final DuplexChannel duplexChannel = (DuplexChannel) channel; if (otherSideShutdown.test(duplexChannel) || (gracefulCloseState != GRACEFUL_CLOSE_SECOND_GO_AWAY_SENT && gracefulCloseState != CLOSED)) { // If we have not started the graceful close process, or waiting for ack/read to complete the graceful // close process just force a close now because we will not read any more data. duplexChannel.close(); } } else { channel.close(); } } private void doCloseAsyncGracefully0(final Runnable whenInitiated) { assert channel.eventLoop().inEventLoop(); if (gracefulCloseState != null) { // either we are already closed or have already initiated graceful closure. return; } whenInitiated.run(); // Set the pingState before doing the write, because we will reference the state // when we receive the PING(ACK) to determine if action is necessary, and it is conceivable that the // write future may not be executed which sets the timer. gracefulCloseState = GRACEFUL_CLOSE_START; // The graceful close process is described in [1]. It involves sending 2 GOAWAY frames. The first // GOAWAY has last-stream-id=<maximum stream ID> to indicate no new streams can be created, wait for 2 RTT // time duration for inflight frames to land, and the second GOAWAY includes the maximum known stream ID. // To account for 2 RTTs we can send a PING and when the PING(ACK) comes back we can send the second GOAWAY. // [1] https://tools.ietf.org/html/rfc7540#section-6.8 DefaultHttp2GoAwayFrame goAwayFrame = new DefaultHttp2GoAwayFrame(NO_ERROR); goAwayFrame.setExtraStreamIds(Integer.MAX_VALUE); channel.write(goAwayFrame); channel.writeAndFlush(new DefaultHttp2PingFrame(GRACEFUL_CLOSE_PING_CONTENT)).addListener(future -> { // If gracefulCloseState is not GRACEFUL_CLOSE_START that means we have already received the PING(ACK) and // there is no need to apply the timeout. if (future.isSuccess() && gracefulCloseState == GRACEFUL_CLOSE_START) { gracefulCloseState = scheduler.afterDuration(() -> { // If the PING(ACK) times out we may have under estimated the 2RTT time so we // optimistically keep the connection open and rely upon higher level timeouts to tear // down the connection. LOGGER.debug("channel={} timeout {}ns waiting for PING(ACK) during graceful close.", channel, pingAckTimeoutNanos); gracefulCloseWriteSecondGoAway(); }, pingAckTimeoutNanos, NANOSECONDS); } }); } private void gracefulCloseWriteSecondGoAway() { assert channel.eventLoop().inEventLoop(); if (gracefulCloseState == GRACEFUL_CLOSE_SECOND_GO_AWAY_SENT) { return; } gracefulCloseState = GRACEFUL_CLOSE_SECOND_GO_AWAY_SENT; channel.writeAndFlush(new DefaultHttp2GoAwayFrame(NO_ERROR)).addListener(future -> { if (activeChildChannels == 0) { close0(); } }); } private void close0() { assert channel.eventLoop().inEventLoop(); if (gracefulCloseState == CLOSED && keepAliveState == CLOSED) { return; } gracefulCloseState = CLOSED; keepAliveState = CLOSED; // The way netty H2 stream state machine works, we may trigger stream closures during writes with flushes // pending behind the writes. In such cases, we may close too early ignoring the writes. Hence we flush before // closure, if there is no write pending then flush is a noop. channel.writeAndFlush(EMPTY_BUFFER).addListener(f -> { SslHandler sslHandler = channel.pipeline().get(SslHandler.class); if (sslHandler != null) { // send close_notify: https://tools.ietf.org/html/rfc5246#section-7.2.1 sslHandler.closeOutbound().addListener(f2 -> doShutdownOutput()); } else { doShutdownOutput(); } }); } private void doShutdownOutput() { if (channel instanceof DuplexChannel) { final DuplexChannel duplexChannel = (DuplexChannel) channel; duplexChannel.shutdownOutput().addListener(f -> { if (duplexChannel.isInputShutdown()) { channel.close(); } }); } else { channel.close(); } } private void cancelIfStateIsAFuture(@Nullable final Object state) { if (state instanceof Future) { try { ((Future<?>) state).cancel(true); } catch (Throwable t) { LOGGER.debug("Failed to cancel {} scheduled future.", state == keepAliveState ? "keep-alive" : "graceful close", t); } } } }
6,924
1,697
package iot.technology.custom.client.console; import io.netty.channel.Channel; import iot.technology.custom.util.SessionUtil; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * @author <NAME> * @date 2020/8/10 18:12 */ public class ConsoleCommandManager implements ConsoleCommand { private Map<String, ConsoleCommand> consoleCommandMap; public ConsoleCommandManager() { consoleCommandMap = new HashMap<>(); consoleCommandMap.put("sendToClient", new SendToUserConsoleCommand()); consoleCommandMap.put("logout", new LogoutConsoleCommand()); consoleCommandMap.put("sendToServer", new SendToServerConsoleCommand()); } @Override public void exec(Scanner scanner, Channel channel) { // 获取第一个指令 String command = scanner.next(); if (!SessionUtil.hasLogin(channel)) { return; } ConsoleCommand consoleCommand = consoleCommandMap.get(command); if (consoleCommand != null) { consoleCommand.exec(scanner, channel); } else { System.err.println("无法识别[" + command + "]指令,请重新输入!"); } } }
468
530
<gh_stars>100-1000 package org.carlspring.strongbox.services; import java.io.IOException; import java.nio.file.Path; import java.util.Map; import org.carlspring.strongbox.domain.DirectoryListing; import org.carlspring.strongbox.providers.io.RepositoryPath; import org.carlspring.strongbox.storage.Storage; import org.carlspring.strongbox.storage.repository.Repository; public interface DirectoryListingService { DirectoryListing fromStorages(Map<String, ? extends Storage> storages) throws IOException; DirectoryListing fromRepositories(Map<String, ? extends Repository> repositories) throws IOException; DirectoryListing fromRepositoryPath(RepositoryPath path) throws IOException; DirectoryListing fromPath(Path root, Path path) throws IOException; }
257
985
/* * (C) 2007-2012 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Authors: * wuhua <<EMAIL>> , boyan <<EMAIL>> */ package com.taobao.metamorphosis.server.assembly; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.taobao.metamorphosis.server.Service; import com.taobao.metamorphosis.server.utils.MetaConfig; import com.taobao.metamorphosis.utils.NamedThreadFactory; public class ExecutorsManager implements Service { ThreadPoolExecutor getExecutor; ThreadPoolExecutor unOrderedPutExecutor; public ExecutorsManager(final MetaConfig metaConfig) { super(); this.getExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(metaConfig.getGetProcessThreadCount(), new NamedThreadFactory("GetProcess")); this.unOrderedPutExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(metaConfig.getPutProcessThreadCount(), new NamedThreadFactory("PutProcess")); } public ThreadPoolExecutor getGetExecutor() { return this.getExecutor; } public ThreadPoolExecutor getUnOrderedPutExecutor() { return this.unOrderedPutExecutor; } @Override public void dispose() { if (this.getExecutor != null) { this.getExecutor.shutdown(); } if (this.unOrderedPutExecutor != null) { this.unOrderedPutExecutor.shutdown(); } try { this.getExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); this.unOrderedPutExecutor.awaitTermination(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // ignore } } @Override public void init() { } }
893
775
{ "#env-function": { "current": { "number": "3", "spec": "CSS Environment Variables 1", "text": "Using Environment Variables: the env() notation", "url": "https://drafts.csswg.org/css-env-1/#env-function" } }, "#env-in-shorthands": { "current": { "number": "3.1", "spec": "CSS Environment Variables 1", "text": "Environment Variables in Shorthand Properties", "url": "https://drafts.csswg.org/css-env-1/#env-in-shorthands" } }, "#environment": { "current": { "number": "2", "spec": "CSS Environment Variables 1", "text": "Environment Variables", "url": "https://drafts.csswg.org/css-env-1/#environment" } }, "#intro": { "current": { "number": "1", "spec": "CSS Environment Variables 1", "text": "Introduction", "url": "https://drafts.csswg.org/css-env-1/#intro" } }, "#safe-area-insets": { "current": { "number": "2.1", "spec": "CSS Environment Variables 1", "text": "Safe area inset variables", "url": "https://drafts.csswg.org/css-env-1/#safe-area-insets" } } }
511
1,738
<filename>dev/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "StdAfx.h" #include <AzCore/Asset/AssetTypeInfoBus.h> #include <AzToolsFramework/AssetBrowser/AssetBrowserEntry.h> #include <AzToolsFramework/AssetBrowser/EBusFindAssetTypeByName.h> #include <Editor/AzAssetBrowser/Preview/LegacyPreviewer.h> #include <Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h> AzToolsFramework::AssetBrowser::Previewer* LegacyPreviewerFactory::CreatePreviewer(QWidget* parent) const { return new LegacyPreviewer(parent); } bool LegacyPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const { using namespace AzToolsFramework::AssetBrowser; EBusFindAssetTypeByName meshAssetTypeResult("Static Mesh"); AZ::AssetTypeInfoBus::BroadcastResult(meshAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); EBusFindAssetTypeByName textureAssetTypeResult("Texture"); AZ::AssetTypeInfoBus::BroadcastResult(textureAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); switch (entry->GetEntryType()) { case AssetBrowserEntry::AssetEntryType::Source: { const auto* source = azrtti_cast < const SourceAssetBrowserEntry * > (entry); if (source->GetPrimaryAssetType() == textureAssetTypeResult.GetAssetType()) { return true; } AZStd::vector < const ProductAssetBrowserEntry * > products; source->GetChildrenRecursively < ProductAssetBrowserEntry > (products); for (auto* product : products) { if (product->GetAssetType() == textureAssetTypeResult.GetAssetType() || product->GetAssetType() == meshAssetTypeResult.GetAssetType()) { return true; } } break; } case AssetBrowserEntry::AssetEntryType::Product: const auto* product = azrtti_cast < const ProductAssetBrowserEntry * > (entry); return product->GetAssetType() == textureAssetTypeResult.GetAssetType() || product->GetAssetType() == meshAssetTypeResult.GetAssetType(); } return false; } const QString& LegacyPreviewerFactory::GetName() const { return LegacyPreviewer::Name; }
932
1,338
<reponame>Yn0ga/haiku /* * Copyright © 2007-2009 <NAME> <<EMAIL>> * All rights reserved. Distributed under the terms of the MIT license. */ #include "RemovePLItemsCommand.h" #include <new> #include <stdio.h> #include <Alert.h> #include <Autolock.h> #include <Catalog.h> #include <Locale.h> #include "Playlist.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "MediaPlayer-RemovePLItemsCmd" using std::nothrow; RemovePLItemsCommand::RemovePLItemsCommand(Playlist* playlist, BList indices, bool moveFilesToTrash) : PLItemsCommand(), fPlaylist(playlist), fCount(indices.CountItems()), fItems(fCount > 0 ? new (nothrow) PlaylistItem*[fCount] : NULL), fIndices(fCount > 0 ? new (nothrow) int32[fCount] : NULL), fMoveFilesToTrash(moveFilesToTrash), fMoveErrorShown(false), fItemsRemoved(false) { if (indices.IsEmpty()) { // indicate a bad object state delete[] fItems; fItems = NULL; return; } memset(fItems, 0, fCount * sizeof(PlaylistItem*)); // init original entry indices for (int32 i = 0; i < fCount; i++) { fIndices[i] = (int32)(addr_t)indices.ItemAt(i); fItems[i] = fPlaylist->ItemAt(fIndices[i]); if (fItems[i] == NULL) { delete[] fItems; fItems = NULL; return; } } } RemovePLItemsCommand::~RemovePLItemsCommand() { _CleanUp(fItems, fCount, fItemsRemoved); delete[] fIndices; } status_t RemovePLItemsCommand::InitCheck() { if (!fPlaylist || !fItems || !fIndices) return B_NO_INIT; return B_OK; } status_t RemovePLItemsCommand::Perform() { BAutolock _(fPlaylist); fItemsRemoved = true; int32 lastRemovedIndex = -1; // remove refs from playlist for (int32 i = 0; i < fCount; i++) { // "- i" to account for the items already removed lastRemovedIndex = fIndices[i] - i; fPlaylist->RemoveItem(lastRemovedIndex); } // in case we removed the currently playing file if (fPlaylist->CurrentItemIndex() == -1) fPlaylist->SetCurrentItemIndex(lastRemovedIndex); if (fMoveFilesToTrash) { BString errorFiles; status_t moveError = B_OK; bool errorOnAllFiles = true; for (int32 i = 0; i < fCount; i++) { status_t err = fItems[i]->MoveIntoTrash(); if (err != B_OK) { moveError = err; if (errorFiles.Length() > 0) errorFiles << ' '; errorFiles << fItems[i]->Name(); } else errorOnAllFiles = false; } // Show an error alert if necessary if (!fMoveErrorShown && moveError != B_OK) { fMoveErrorShown = true; BString message; if (errorOnAllFiles) message << B_TRANSLATE("All files could not be moved into Trash."); else message << B_TRANSLATE("Some files could not be moved into Trash."); message << "\n\n" << B_TRANSLATE("Error: ") << strerror(moveError); BAlert* alert = new BAlert(B_TRANSLATE("Move into trash error"), message.String(), B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(NULL); } } return B_OK; } status_t RemovePLItemsCommand::Undo() { BAutolock _(fPlaylist); fItemsRemoved = false; if (fMoveFilesToTrash) { for (int32 i = 0; i < fCount; i++) { fItems[i]->RestoreFromTrash(); } } // remember currently playling item in case we move it PlaylistItem* current = fPlaylist->ItemAt(fPlaylist->CurrentItemIndex()); // add items to playlist at remembered indices status_t ret = B_OK; for (int32 i = 0; i < fCount; i++) { if (!fPlaylist->AddItem(fItems[i], fIndices[i])) { ret = B_NO_MEMORY; break; } } if (ret < B_OK) return ret; // take care about currently played ref if (current != NULL) fPlaylist->SetCurrentItemIndex(fPlaylist->IndexOf(current), false); return B_OK; } void RemovePLItemsCommand::GetName(BString& name) { if (fMoveFilesToTrash) { if (fCount > 1) name << B_TRANSLATE("Remove Entries into Trash"); else name << B_TRANSLATE("Remove Entry into Trash"); } else { if (fCount > 1) name << B_TRANSLATE("Remove Entries"); else name << B_TRANSLATE("Remove Entry"); } }
1,631
852
#ifndef Alignment_CommonAlignment_AlignableDetUnit_H #define Alignment_CommonAlignment_AlignableDetUnit_H #include "Alignment/CommonAlignment/interface/Alignable.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" /// A concrete class that allows to (mis)align a DetUnit. /// /// Typically all AlignableComposites have (directly or /// indirectly) this one as the ultimate component. class AlignableDetUnit : public Alignable { public: /// Constructor from GeomDetUnit - must not be NULL pointer! AlignableDetUnit(const GeomDetUnit* geomDetUnit); /// Destructor ~AlignableDetUnit() override; /// Updater from GeomDetUnit /// The given GeomDetUnit id has to match the current id. void update(const GeomDetUnit* geomDetUnit); /// No components here => exception! void addComponent(Alignable*) final; /// Returns a null vector (no components here) const Alignables& components() const override { return emptyComponents_; } /// Do nothing (no components here, so no subcomponents either...) void recursiveComponents(Alignables& result) const override {} /// Move with respect to the global reference frame void move(const GlobalVector& displacement) override; /// Rotation with respect to the global reference frame void rotateInGlobalFrame(const RotationType& rotation) override; /// Set the AlignmentPositionError (no components => second argument ignored) void setAlignmentPositionError(const AlignmentPositionError& ape, bool /*propDown*/) final; /// Add (or set if it does not exist yet) the AlignmentPositionError /// (no components => second argument without effect) void addAlignmentPositionError(const AlignmentPositionError& ape, bool /*propDown*/) final; /// Add (or set if it does not exist yet) the AlignmentPositionError /// resulting from a rotation in the global reference frame /// (no components => second argument without effect) void addAlignmentPositionErrorFromRotation(const RotationType& rot, bool /*propDown*/) final; /// Add (or set if it does not exist yet) the AlignmentPositionError /// resulting from a rotation in the local reference frame /// (no components => second argument without effect) void addAlignmentPositionErrorFromLocalRotation(const RotationType& rot, bool /*propDown*/) final; /// Set surface deformation parameters (2nd argument without effect) void setSurfaceDeformation(const SurfaceDeformation* deformation, bool) final; /// Add surface deformation parameters to the existing ones (2nd argument without effect) void addSurfaceDeformation(const SurfaceDeformation* deformation, bool) final; /// Return the alignable type identifier StructureType alignableObjectId() const override { return align::AlignableDetUnit; } /// Printout information about GeomDet void dump() const override; /// Return vector of alignment data Alignments* alignments() const override; /// Return vector of alignment errors AlignmentErrorsExtended* alignmentErrors() const override; /// Return surface deformations int surfaceDeformationIdPairs(std::vector<std::pair<int, SurfaceDeformation*> >&) const override; /// cache the current position, rotation and other parameters (e.g. surface deformations) void cacheTransformation() override; /// cache for the given run the current position, rotation and other parameters (e.g. surface deformations) void cacheTransformation(const align::RunNumber&) override; /// restore the previously cached transformation void restoreCachedTransformation() override; /// restore for the given run the previously cached transformation void restoreCachedTransformation(const align::RunNumber&) override; /// alignment position error - for checking only, otherwise use alignmentErrors() above! const AlignmentPositionError* alignmentPositionError() const { return theAlignmentPositionError; } private: static const Alignables emptyComponents_; AlignmentPositionError* theAlignmentPositionError; SurfaceDeformation* theSurfaceDeformation; SurfaceDeformation* theCachedSurfaceDeformation; Cache<SurfaceDeformation*> surfaceDeformationsCache_; }; #endif
1,057
14,668
// Copyright 2021 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/ui/views/autofill/payments/offer_notification_bubble_views_test_base.h" #include "build/build_config.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/window_open_disposition.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget.h" namespace autofill { class OfferNotificationBubbleViewsBrowserTest : public OfferNotificationBubbleViewsTestBase { public: OfferNotificationBubbleViewsBrowserTest() = default; ~OfferNotificationBubbleViewsBrowserTest() override = default; OfferNotificationBubbleViewsBrowserTest( const OfferNotificationBubbleViewsBrowserTest&) = delete; OfferNotificationBubbleViewsBrowserTest& operator=( const OfferNotificationBubbleViewsBrowserTest&) = delete; }; // Tests that the offer notification bubble will not be shown if the offer data // is invalid (does not have a linked card or a promo code). IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, InvalidOfferData) { auto offer_data = CreateCardLinkedOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); offer_data->eligible_instrument_id.clear(); personal_data()->AddOfferDataForTest(std::move(offer_data)); personal_data()->NotifyPersonalDataObserver(); // Neither icon nor bubble should be visible. NavigateTo("https://www.example.com/first/"); EXPECT_FALSE(IsIconVisible()); EXPECT_FALSE(GetOfferNotificationBubbleViews()); } IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, OpenNewTab) { SetUpCardLinkedOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); NavigateTo(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("https://www.example.com/"), WindowOpenDisposition::NEW_BACKGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); browser()->tab_strip_model()->ActivateTabAt(1); EXPECT_TRUE(IsIconVisible()); EXPECT_FALSE(GetOfferNotificationBubbleViews()); } // TODO(crbug.com/1270516): Does not work for Wayland-based tests. // TODO(crbug.com/1256480): Disabled on Mac, Win, ChromeOS, and Lacros due to // flakiness. IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, DISABLED_PromoCodeOffer) { auto offer_data = CreatePromoCodeOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); personal_data()->AddOfferDataForTest(std::move(offer_data)); personal_data()->NotifyPersonalDataObserver(); ResetEventWaiterForSequence({DialogEvent::BUBBLE_SHOWN}); NavigateTo("https://www.example.com/first/"); WaitForObservedEvent(); EXPECT_TRUE(IsIconVisible()); EXPECT_TRUE(GetOfferNotificationBubbleViews()); } // TODO(crbug.com/1256480): Disabled due to flakiness. IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, DISABLED_PromoCodeOffer_FromCouponService) { auto offer_data = CreatePromoCodeOfferDataWithDomains({GURL("https://www.example.com/")}); SetUpFreeListingCouponOfferDataForCouponService(std::move(offer_data)); ResetEventWaiterForSequence({DialogEvent::BUBBLE_SHOWN}); NavigateTo("https://www.example.com/first/"); WaitForObservedEvent(); EXPECT_TRUE(IsIconVisible()); EXPECT_TRUE(GetOfferNotificationBubbleViews()); } IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, PromoCodeOffer_FromCouponService_WithinTimeGap) { const GURL orgin("https://www.example.com/"); SetUpFreeListingCouponOfferDataForCouponService( CreatePromoCodeOfferDataWithDomains({orgin})); UpdateFreeListingCouponDisplayTime( CreatePromoCodeOfferDataWithDomains({orgin})); NavigateTo("https://www.example.com/first/"); EXPECT_TRUE(IsIconVisible()); EXPECT_FALSE(GetOfferNotificationBubbleViews()); } // TODO(crbug.com/1270516): Disabled due to flakiness with linux-wayland-rel. // Tests that the offer notification bubble will not be shown if bubble has been // shown for kAutofillBubbleSurviveNavigationTime (5 seconds) and the user has // opened another tab on the same website. IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, DISABLED_BubbleNotShowingOnDuplicateTab) { SetUpCardLinkedOfferDataWithDomains({GURL("https://www.example.com/")}); TestAutofillClock test_clock; test_clock.SetNow(base::Time::Now()); NavigateTo("https://www.example.com/first/"); test_clock.Advance(kAutofillBubbleSurviveNavigationTime - base::Seconds(1)); NavigateTo("https://www.example.com/second/"); // Ensure the bubble is still there if // kOfferNotificationBubbleSurviveNavigationTime hasn't been reached yet. EXPECT_TRUE(IsIconVisible()); EXPECT_TRUE(GetOfferNotificationBubbleViews()); test_clock.Advance(base::Seconds(2)); NavigateTo("https://www.example.com/second/"); // As kAutofillBubbleSurviveNavigationTime has been reached, the bubble should // no longer be showing. EXPECT_TRUE(IsIconVisible()); EXPECT_FALSE(GetOfferNotificationBubbleViews()); } // TODO(crbug.com/1256480): Disabled due to flakiness. IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTest, DISABLED_PromoCodeOffer_DeleteCoupon) { auto offer_data = CreatePromoCodeOfferDataWithDomains({GURL("https://www.example.com/")}); SetUpFreeListingCouponOfferDataForCouponService(std::move(offer_data)); ResetEventWaiterForSequence({DialogEvent::BUBBLE_SHOWN}); NavigateTo("https://www.example.com/first/"); WaitForObservedEvent(); EXPECT_TRUE(IsIconVisible()); EXPECT_TRUE(GetOfferNotificationBubbleViews()); DeleteFreeListingCouponForUrl(GURL("https://www.example.com/")); EXPECT_FALSE(IsIconVisible()); EXPECT_FALSE(GetOfferNotificationBubbleViews()); } class OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes : public OfferNotificationBubbleViewsTestBase { public: OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes() : OfferNotificationBubbleViewsTestBase( /*promo_code_flag_enabled=*/false) {} ~OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes() override = default; OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes( const OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes&) = delete; OfferNotificationBubbleViewsBrowserTest& operator=( const OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes&) = delete; }; // Tests that the offer notification bubble will not be shown for a promo code // offer if the feature flag is disabled. IN_PROC_BROWSER_TEST_F(OfferNotificationBubbleViewsBrowserTestWithoutPromoCodes, NoPromoCodeOffer) { auto offer_data = CreatePromoCodeOfferDataWithDomains( {GURL("https://www.example.com/"), GURL("https://www.test.com/")}); personal_data()->AddOfferDataForTest(std::move(offer_data)); personal_data()->NotifyPersonalDataObserver(); // Neither icon nor bubble should be visible. NavigateTo("https://www.example.com/first/"); EXPECT_FALSE(IsIconVisible()); EXPECT_FALSE(GetOfferNotificationBubbleViews()); } } // namespace autofill
2,810
746
<reponame>fari-99/apicurio-studio<filename>tools/release/src/main/java/io/apicurio/studio/tools/release/ReleaseTool.java /* * Copyright 2017 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.apicurio.studio.tools.release; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; /** * @author <EMAIL> */ public class ReleaseTool { /** * Main method. * @param args */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("n", "release-name", true, "The name of the new release."); options.addOption("p", "prerelease", false, "Indicate that this is a pre-release."); options.addOption("t", "release-tag", true, "The tag name of the new release."); options.addOption("o", "previous-tag", true, "The tag name of the previous release."); options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization)."); options.addOption("a", "artifact", true, "The binary release artifact (full path)."); options.addOption("d", "output-directory", true, "Where to store output file(s)."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if ( !cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g") || !cmd.hasOption("a") ) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "release-studio", options ); System.exit(1); } // Arguments (command line) String releaseName = cmd.getOptionValue("n"); boolean isPrerelease = cmd.hasOption("p"); String releaseTag = cmd.getOptionValue("t"); String oldReleaseTag = cmd.getOptionValue("o"); String githubPAT = cmd.getOptionValue("g"); String artifact = cmd.getOptionValue("a"); File outputDir = new File(""); if (cmd.hasOption("d")) { outputDir = new File(cmd.getOptionValue("d")); if (!outputDir.exists()) { outputDir.mkdirs(); } } File releaseArtifactFile = new File(artifact); File releaseArtifactSigFile = new File(artifact + ".asc"); String releaseArtifact = releaseArtifactFile.getName(); String releaseArtifactSig = releaseArtifactSigFile.getName(); if (!releaseArtifactFile.isFile()) { System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath()); System.exit(1); } if (!releaseArtifactSigFile.isFile()) { System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath()); System.exit(1); } System.out.println("========================================="); System.out.println("Creating Release: " + releaseTag); System.out.println("Previous Release: " + oldReleaseTag); System.out.println(" Name: " + releaseName); System.out.println(" Artifact: " + releaseArtifact); System.out.println(" Pre-Release: " + isPrerelease); System.out.println("========================================="); String releaseNotes = ""; // Step #1 - Generate Release Notes // * Grab info about the previous release (extract publish date) // * Query all Issues for ones closed since that date // * Generate Release Notes from the resulting Issues try { System.out.println("Getting info about release " + oldReleaseTag); HttpResponse<JsonNode> response = Unirest.get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag) .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get old release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for previous release " + oldReleaseTag); } System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate); List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT); System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag); System.out.println("Generating Release Notes"); releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues); System.out.println("------------ Release Notes --------------"); System.out.println(releaseNotes); System.out.println("-----------------------------------------"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String assetUploadUrl = null; // Step #2 - Create a GitHub Release try { System.out.println("\nCreating GitHub Release " + releaseTag); JSONObject body = new JSONObject(); body.put("tag_name", "v" + releaseTag); body.put("name", releaseName); body.put("body", releaseNotes); body.put("prerelease", isPrerelease); HttpResponse<JsonNode> response = Unirest.post("https://api.github.com/repos/apicurio/apicurio-studio/releases") .header("Accept", "application/json") .header("Content-Type", "application/json") .header("Authorization", "token " + githubPAT) .body(body).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to create release in GitHub: " + response.getStatusText()); } assetUploadUrl = response.getBody().getObject().getString("upload_url"); if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) { throw new Exception("Failed to get Asset Upload URL for newly created release!"); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Step #3 - Upload Release Artifact (zip file) System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact); try { String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact); byte [] artifactData = loadArtifactData(releaseArtifactFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl) .header("Accept", "application/json") .header("Content-Type", "application/zip") .header("Authorization", "token " + githubPAT) .body(artifactData) .asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifact, new Exception(response.getStatus() + "::" + response.getStatusText())); } Thread.sleep(1000); artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig); artifactData = loadArtifactData(releaseArtifactSigFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); response = Unirest.post(artifactUploadUrl) .header("Accept", "application/json") .header("Content-Type", "text/plain") .header("Authorization", "token " + githubPAT) .body(artifactData) .asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifactSig, new Exception(response.getStatus() + "::" + response.getStatusText())); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } Thread.sleep(1000); // Step #4 - Download Latest Release JSON for inclusion in the project web site try { System.out.println("Getting info about the release."); HttpResponse<JsonNode> response = Unirest.get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest") .header("Accept", "application/json").asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for release."); } String fname = publishedDate.replace(':', '-'); File outFile = new File(outputDir, fname + ".json"); System.out.println("Writing latest release info to: " + outFile.getAbsolutePath()); String output = body.getObject().toString(4); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(output.getBytes("UTF-8")); fos.flush(); } System.out.println("Release info successfully written."); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.out.println("========================================="); System.out.println("All Done!"); System.out.println("========================================="); } /** * Generates the release notes for a release. * @param releaseName * @param releaseTag * @param issues */ private static String generateReleaseNotes(String releaseName, String releaseTag, List<JSONObject> issues) { StringBuilder builder = new StringBuilder(); builder.append("This represents the official release of Apicurio Studio, version "); builder.append(releaseTag); builder.append(".\n\n"); builder.append("The following issues have been resolved in this release:\n\n"); issues.forEach(issue -> { builder.append(String.format("* [#%d](%s) %s", issue.getInt("number"), issue.getString("html_url"), issue.getString("title"))); builder.append("\n"); }); builder.append("\n\n"); builder.append("For more information, please see the Apicurio Studio's official project site:\n\n"); builder.append("* [General Information](http://www.apicur.io/)\n"); builder.append("* [Download/Quickstart](http://www.apicur.io/download)\n"); builder.append("* [Blog](http://www.apicur.io/blog)\n"); return builder.toString(); } /** * Returns all issues (as JSON nodes) that were closed since the given date. * @param since * @param githubPAT */ private static List<JSONObject> getIssuesForRelease(String since, String githubPAT) throws Exception { List<JSONObject> rval = new ArrayList<>(); String currentPageUrl = "https://api.github.com/repos/apicurio/apicurio-studio/issues"; int pageNum = 1; while (currentPageUrl != null) { System.out.println("Querying page " + pageNum + " of issues."); HttpResponse<JsonNode> response = Unirest.get(currentPageUrl) .queryString("since", since) .queryString("state", "closed") .header("Accept", "application/json") .header("Authorization", "token " + githubPAT).asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to list Issues: " + response.getStatusText()); } JSONArray issueNodes = response.getBody().getArray(); issueNodes.forEach(issueNode -> { JSONObject issue = (JSONObject) issueNode; String closedOn = issue.getString("closed_at"); if (since.compareTo(closedOn) < 0) { if (!isIssueExcluded(issue)) { rval.add(issue); } else { System.out.println("Skipping issue (excluded): " + issue.getString("title")); } } else { System.out.println("Skipping issue (old release): " + issue.getString("title")); } }); System.out.println("Processing page " + pageNum + " of issues."); System.out.println(" Found " + issueNodes.length() + " issues on page."); String allLinks = response.getHeaders().getFirst("Link"); Map<String, Link> links = Link.parseAll(allLinks); if (links.containsKey("next")) { currentPageUrl = links.get("next").getUrl(); } else { currentPageUrl = null; } pageNum++; } return rval; } /** * Tests whether an issue should be excluded from the release notes based on * certain labels the issue might have (e.g. dependabot issues). * @param issueNode */ private static boolean isIssueExcluded(JSONObject issueNode) { JSONArray labelsArray = issueNode.getJSONArray("labels"); if (labelsArray != null) { Set<String> labels = labelsArray.toList().stream().map( label -> { return ((Map<?,?>) label).get("name").toString(); }).collect(Collectors.toSet()); return labels.contains("dependencies") || labels.contains("question") || labels.contains("invalid") || labels.contains("wontfix")|| labels.contains("duplicate"); } return false; } /** * @param assetUploadUrl * @param assetName */ private static String createUploadUrl(String assetUploadUrl, String assetName) throws Exception { int idx = assetUploadUrl.indexOf("{?name"); if (idx < 0) { throw new Exception("Invalid Asset Upload URL Pattern: " + assetUploadUrl); } return String.format("%s?name=%s", assetUploadUrl.substring(0, idx), assetName); } /** * @param releaseArtifactFile */ private static byte[] loadArtifactData(File releaseArtifactFile) throws Exception { System.out.println("Loading artifact content: " + releaseArtifactFile.getName()); byte [] buffer = new byte[(int) releaseArtifactFile.length()]; try (InputStream is = new FileInputStream(releaseArtifactFile)) { IOUtils.readFully(is, buffer); return buffer; } catch (IOException e) { throw new Exception(e); } } // public static void testMain(String[] args) throws Exception { // String pat = "XXXYYYZZZ"; // String since = "2019-03-01T12:00:00Z"; // List<JSONObject> list = getIssuesForRelease(since, pat); // System.out.println("Found " + list.size() + " issues!"); // } }
6,973
2,077
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ #ifndef __plist_Null_h #define __plist_Null_h #include <plist/Base.h> #include <plist/Object.h> namespace plist { class Null : public Object { private: Null() { } public: static std::unique_ptr<Null> New(); public: static std::unique_ptr<Null> Coerce(Object const *obj); public: virtual ObjectType type() const { return Null::Type(); } static inline ObjectType Type() { return ObjectType::Null; } protected: virtual std::unique_ptr<Object> _copy() const; public: std::unique_ptr<Null> copy() const { return plist::static_unique_pointer_cast<Null>(_copy()); } public: virtual bool equals(Object const *obj) const { if (Object::equals(obj)) return true; Null const *objt = CastTo <Null> (obj); return (objt != nullptr && equals(objt)); } virtual bool equals(Null const *obj) const { return (obj != nullptr && obj == this); } }; } #endif // !__plist_Null_h
476
589
<filename>inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/handlers/CopyLogMessageHandler.java<gh_stars>100-1000 package rocks.inspectit.ui.rcp.handlers; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.handlers.HandlerUtil; import rocks.inspectit.shared.all.communication.data.InvocationSequenceData; import rocks.inspectit.shared.all.communication.data.LoggingData; import rocks.inspectit.ui.rcp.util.ClipboardUtil; /** * Handler that copies the logging message to the clipboard. * * @author <NAME> */ public class CopyLogMessageHandler extends AbstractHandler implements IHandler { /** * {@inheritDoc} */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { Object firstElement = ((StructuredSelection) HandlerUtil.getCurrentSelection(event)).getFirstElement(); if (firstElement instanceof LoggingData) { LoggingData loggingData = (LoggingData) firstElement; ClipboardUtil.textToClipboard(HandlerUtil.getActiveShell(event).getDisplay(), loggingData.getMessage()); } else if (firstElement instanceof InvocationSequenceData) { LoggingData loggingData = ((InvocationSequenceData) firstElement).getLoggingData(); ClipboardUtil.textToClipboard(HandlerUtil.getActiveShell(event).getDisplay(), loggingData.getMessage()); } return null; } }
488
682
// Not PJs code, but very useful and used everywhere */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "vtr_util.h" #include "vtr_memory.h" #include "string_cache.h" unsigned long string_hash(STRING_CACHE* sc, const char* string); void generate_sc_hash(STRING_CACHE* sc); unsigned long string_hash(STRING_CACHE* sc, const char* string) { long a, i, mod, mul; a = 0; mod = sc->mod; mul = sc->mul; for (i = 0; string[i]; i++) a = (a * mul + (unsigned char)string[i]) % mod; return a; } void generate_sc_hash(STRING_CACHE* sc) { long i; long hash; if (sc->string_hash != NULL) vtr::free(sc->string_hash); if (sc->next_string != NULL) vtr::free(sc->next_string); sc->string_hash_size = sc->size * 2 + 11; sc->string_hash = (long*)sc_do_alloc(sc->string_hash_size, sizeof(long)); sc->next_string = (long*)sc_do_alloc(sc->size, sizeof(long)); memset(sc->string_hash, 0xff, sc->string_hash_size * sizeof(long)); memset(sc->next_string, 0xff, sc->size * sizeof(long)); for (i = 0; i < sc->free; i++) { hash = string_hash(sc, sc->string[i]) % sc->string_hash_size; sc->next_string[i] = sc->string_hash[hash]; sc->string_hash[hash] = i; } } STRING_CACHE* sc_new_string_cache(void) { STRING_CACHE* sc; sc = (STRING_CACHE*)sc_do_alloc(1, sizeof(STRING_CACHE)); sc->size = 100; sc->string_hash_size = 0; sc->string_hash = NULL; sc->next_string = NULL; sc->free = 0; sc->string = (char**)sc_do_alloc(sc->size, sizeof(char*)); sc->data = (void**)sc_do_alloc(sc->size, sizeof(void*)); sc->mod = 834535547; sc->mul = 247999; generate_sc_hash(sc); return sc; } long sc_lookup_string(STRING_CACHE* sc, const char* string) { long i, hash; if (sc == NULL) { return -1; } else { hash = string_hash(sc, string) % sc->string_hash_size; i = sc->string_hash[hash]; while (i >= 0) { if (!strcmp(sc->string[i], string)) return i; i = sc->next_string[i]; } return -1; } } bool sc_remove_string(STRING_CACHE* sc, const char* string) { long i, hash; if (sc != NULL) { hash = string_hash(sc, string) % sc->string_hash_size; i = sc->string_hash[hash]; while (i >= 0) { if (!strcmp(sc->string[i], string)) { vtr::free(sc->string[i]); if (sc->data[i] != NULL) { vtr::free(sc->data[i]); sc->data = NULL; } sc->string[i] = vtr::strdup("REMOVED_NAME_FROM_SC_CACHE"); return true; } i = sc->next_string[i]; } } return false; } long sc_add_string(STRING_CACHE* sc, const char* string) { long i; long hash; void* a; i = sc_lookup_string(sc, string); if (i >= 0) return i; if (sc->free >= sc->size) { sc->size = sc->size * 2 + 10; a = sc_do_alloc(sc->size, sizeof(char*)); if (sc->free > 0) memcpy(a, sc->string, sc->free * sizeof(char*)); vtr::free(sc->string); sc->string = (char**)a; a = sc_do_alloc(sc->size, sizeof(void*)); if (sc->free > 0) memcpy(a, sc->data, sc->free * sizeof(void*)); vtr::free(sc->data); sc->data = (void**)a; generate_sc_hash(sc); } i = sc->free; sc->free++; sc->string[i] = vtr::strdup(string); sc->data[i] = NULL; hash = string_hash(sc, string) % sc->string_hash_size; sc->next_string[i] = sc->string_hash[hash]; sc->string_hash[hash] = i; return i; } int sc_valid_id(STRING_CACHE* sc, long string_id) { if (string_id < 0) return 0; if (string_id >= sc->free) return 0; return 1; } void* sc_do_alloc(long a, long b) { void* r; if (a < 1) a = 1; if (b < 1) b = 1; r = vtr::calloc(a, b); while (r == NULL) { fprintf(stderr, "Failed to allocated %ld chunks of %ld bytes (%ld bytes total)\n", a, b, a * b); r = vtr::calloc(a, b); } return r; } STRING_CACHE* sc_free_string_cache(STRING_CACHE* sc) { if (sc != NULL) { if (sc->string != NULL) { for (long i = 0; i < sc->free; i++) { if (sc->string[i] != NULL) { vtr::free(sc->string[i]); } sc->string[i] = NULL; } vtr::free(sc->string); } sc->string = NULL; if (sc->data != NULL) { vtr::free(sc->data); } sc->data = NULL; if (sc->string_hash != NULL) { vtr::free(sc->string_hash); } sc->string_hash = NULL; if (sc->next_string != NULL) { vtr::free(sc->next_string); } sc->next_string = NULL; vtr::free(sc); } sc = NULL; return sc; } void sc_merge_string_cache(STRING_CACHE** source_ref, STRING_CACHE* destination) { STRING_CACHE* source = (*source_ref); for (int source_spot = 0; source_spot < source->free; source_spot++) { long destination_spot = sc_add_string(destination, source->string[source_spot]); destination->data[destination_spot] = source->data[source_spot]; source->data[source_spot] = NULL; } /* now cleanup */ sc_free_string_cache(source); (*source_ref) = NULL; }
2,926
918
/* * Copyright 2017 CodiLime * * 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 "ui/connectionmanager.h" #include <QAction> #include <QFileDialog> #include <QTimer> #include "ui/dialogs/connectiondialog.h" #include "ui/logwidget.h" #include "util/settings/connection_client.h" #include "util/settings/shortcuts.h" #include "util/version.h" namespace veles { namespace ui { using util::settings::shortcuts::ShortcutsModel; /*****************************************************************************/ /* ConnectionManager */ /*****************************************************************************/ ConnectionManager::ConnectionManager(QWidget* parent) : QObject(parent) { connection_dialog_ = new ConnectionDialog(parent); show_connection_dialog_action_ = ShortcutsModel::getShortcutsModel()->createQAction( util::settings::shortcuts::SHOW_CONNECT_DIALOG, this, Qt::ApplicationShortcut); disconnect_action_ = ShortcutsModel::getShortcutsModel()->createQAction( util::settings::shortcuts::DISCONNECT_FROM_SERVER, this, Qt::ApplicationShortcut); kill_locally_created_server_action_ = ShortcutsModel::getShortcutsModel()->createQAction( util::settings::shortcuts::KILL_LOCAL_SERVER, this, Qt::ApplicationShortcut); kill_locally_created_server_action_->setEnabled(false); disconnect_action_->setEnabled(false); connect(show_connection_dialog_action_, &QAction::triggered, connection_dialog_, &QDialog::show); connect(connection_dialog_, &QDialog::accepted, this, &ConnectionManager::connectionDialogAccepted); connect(kill_locally_created_server_action_, &QAction::triggered, this, &ConnectionManager::killLocalServer); connect(disconnect_action_, &QAction::triggered, this, &ConnectionManager::disconnect); network_client_ = new client::NetworkClient(this); network_client_output_ = new QTextStream(LogWidget::output()); network_client_output_->setCodec("UTF-8"); network_client_->setOutput(network_client_output_); connect(network_client_, &client::NetworkClient::connectionStatusChanged, this, &ConnectionManager::updateConnectionStatus); connect(network_client_, &client::NetworkClient::messageReceived, this, &ConnectionManager::messageReceived); } ConnectionManager::~ConnectionManager() { if (server_process_ != nullptr) { killLocalServer(); } connection_dialog_->deleteLater(); delete network_client_output_; } client::NetworkClient* ConnectionManager::networkClient() { return network_client_; } QAction* ConnectionManager::showConnectionDialogAction() { return show_connection_dialog_action_; } QAction* ConnectionManager::disconnectAction() { return disconnect_action_; } QAction* ConnectionManager::killLocallyCreatedServerAction() { return kill_locally_created_server_action_; } void ConnectionManager::locallyCreatedServerStarted() { QTextStream out(veles::ui::LogWidget::output()); out << "Process of locally created server started." << endl; kill_locally_created_server_action_->setEnabled(true); } void ConnectionManager::locallyCreatedServerFinished( int exit_code, QProcess::ExitStatus exit_status) { serverProcessReadyRead(); QTextStream out(LogWidget::output()); out << "Process of locally created server finished."; if (exit_status == QProcess::NormalExit) { out << " Exit code: " << exit_code << "." << endl; } else { // QProcess::CrashExit out << " Exit status: crashed or killed." << endl; } kill_locally_created_server_action_->setEnabled(false); server_process_->deleteLater(); server_process_ = nullptr; is_server_process_running_ = false; if (restart_server_after_kill_) { restart_server_after_kill_ = false; startLocalServer(); } disconnect(); } void ConnectionManager::connectionDialogAccepted() { is_local_server_ = connection_dialog_->runANewServer(); if (is_local_server_) { if (is_server_process_running_) { restart_server_after_kill_ = true; killLocalServer(); } else { startLocalServer(); QTextStream out(LogWidget::output()); out << "Waiting for a new server to start..." << endl; } } else { startClient(); } } void ConnectionManager::startClient() { network_client_->connect( connection_dialog_->serverUrl(), connection_dialog_->clientName(), veles::util::version::string, "Veles UI", "Veles UI", is_local_server_); } void ConnectionManager::startLocalServer() { assert(server_process_ == nullptr); assert(!is_server_process_running_); is_server_process_running_ = true; server_process_ = new QProcess(this); server_process_->setProcessChannelMode(QProcess::MergedChannels); connect(server_process_, &QProcess::started, this, &ConnectionManager::locallyCreatedServerStarted); connect(server_process_, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>( &QProcess::finished), this, &ConnectionManager::locallyCreatedServerFinished); connect(server_process_, &QIODevice::readyRead, this, &ConnectionManager::serverProcessReadyRead); #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) connect(server_process_, &QProcess::errorOccurred, this, &ConnectionManager::serverProcessErrorOccurred); #else connect( server_process_, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error), this, &ConnectionManager::serverProcessErrorOccurred); #endif QString server_file_path = connection_dialog_->serverScript(); QFileInfo server_file(server_file_path); QString directory_path = server_file.absoluteDir().path(); QString server_file_name = server_file.fileName(); server_process_->setWorkingDirectory(directory_path); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("PYTHONUNBUFFERED", "1"); env.insert("PYTHONIOENCODING", "UTF-8"); server_process_->setProcessEnvironment(env); QString scheme; if (connection_dialog_->sslEnabled()) { scheme = client::SCHEME_SSL; } else { scheme = client::SCHEME_TCP; } QStringList arguments; arguments << server_file_name << "--cert-dir" << connection_dialog_->certificateDir() << QString("%1://%2@%3:%4") .arg(scheme) .arg(connection_dialog_->authenticationKey()) .arg(connection_dialog_->serverHost()) .arg(connection_dialog_->serverPort()) << connection_dialog_->databaseFile(); #if defined(Q_OS_LINUX) QString python_interpreter_executable( "/usr/share/veles-server/venv/bin/python3"); QFileInfo check_file(python_interpreter_executable); if (!check_file.exists()) { python_interpreter_executable = QString("python3"); } #elif defined(Q_OS_WIN) QString python_interpreter_executable(qApp->applicationDirPath() + "/../veles-server/python/python.exe"); QFileInfo check_file(python_interpreter_executable); if (!check_file.exists()) { python_interpreter_executable = QString("py.exe"); } #elif defined(Q_OS_MAC) QString python_interpreter_executable( qApp->applicationDirPath() + "/../Resources/veles-server/venv/bin/python3"); QFileInfo check_file(python_interpreter_executable); if (!check_file.exists()) { python_interpreter_executable = QString("python3"); } #elif defined(Q_OS_FREEBSD) QString python_interpreter_executable("/usr/local/bin/python3"); QFileInfo check_file(python_interpreter_executable); if (!check_file.exists()) { python_interpreter_executable = QString("python3"); } #else #warning \ "This OS is not officially supported, you may need to set this string manually." QString python_interpreter_executable("python3"); #endif QTextStream out(veles::ui::LogWidget::output()); out << "Trying to start a new server..." << endl << " working directory: " << directory_path << endl << " python script name: " << server_file_name << endl << " python interpreter executable: " << python_interpreter_executable << endl << " arguments:" << endl; for (const auto& arg : arguments) { out << " " << arg << endl; } out << endl; server_process_->start(python_interpreter_executable, arguments, QIODevice::ReadWrite | QIODevice::Text); } void ConnectionManager::killLocalServer() { disconnect(); if (server_process_ != nullptr) { #ifdef Q_OS_WIN server_process_->kill(); #else server_process_->terminate(); #endif server_process_->waitForFinished(1000); } } void ConnectionManager::disconnect() { if (network_client_ != nullptr) { network_client_->disconnect(); } } void ConnectionManager::serverProcessReadyRead() { if (server_process_ != nullptr && server_process_->bytesAvailable() > 0) { QByteArray out = server_process_->read(server_process_->bytesAvailable()); if (out.size() > 0) { if (network_client_->connectionStatus() == client::NetworkClient::ConnectionStatus::NotConnected) { QString marker("Client url: "); int start_pos = out.indexOf(marker); if (start_pos != -1) { start_pos += marker.length(); int end_pos = out.indexOf("\n", start_pos); if (end_pos == -1) { server_process_->waitForReadyRead(); QByteArray additional = server_process_->readLine(server_process_->bytesAvailable()); out += additional; end_pos = out.indexOf("\n", start_pos); } QByteArray url = out.mid(start_pos, end_pos - start_pos); network_client_->connect(QString::fromUtf8(url), connection_dialog_->clientName(), veles::util::version::string, "Veles UI", "Veles UI", is_local_server_); } } LogWidget::output()->write(out); } } } void ConnectionManager::serverProcessErrorOccurred( QProcess::ProcessError error) { QTextStream out(veles::ui::LogWidget::output()); if (error == QProcess::FailedToStart) { out << "*************************************" << endl << "Failed to run python interpreter." << endl << "Make sure that python >= 3.5 is installed and" << endl << "server script location is set correctly." << endl << "*************************************" << endl; } } void ConnectionManager::updateConnectionStatus( client::NetworkClient::ConnectionStatus connection_status) { emit connectionStatusChanged(connection_status); disconnect_action_->setEnabled( connection_status != client::NetworkClient::ConnectionStatus::NotConnected); if (connection_status == client::NetworkClient::ConnectionStatus::Connected) { sendListConnectionsMessage(); } } void ConnectionManager::raiseConnectionDialog() { connection_dialog_->raise(); connection_dialog_->activateWindow(); } void ConnectionManager::sendListConnectionsMessage() { if (network_client_ != nullptr) { std::shared_ptr<proto::MsgListConnections> list_connections_message = std::make_shared<proto::MsgListConnections>(network_client_->nextQid(), true); network_client_->sendMessage(list_connections_message); } } void ConnectionManager::messageReceived(const client::msg_ptr& message) { if (message->object_type == "connections_reply") { std::shared_ptr<proto::MsgConnectionsReply> connections_reply = std::dynamic_pointer_cast<proto::MsgConnectionsReply>(message); if (connections_reply) { QTextStream& out = *network_client_output_; out << "ConnectionManager: received updated list of connections:" << endl; if (connections_reply->connections) { for (const auto& connection : *connections_reply->connections) { out << " id = " << connection->client_id << " name = \"" << QString::fromStdString(*connection->client_name) << "\"" << " type = \"" << QString::fromStdString(*connection->client_type) << "\"" << endl; } } else { out << " -" << endl; } emit connectionsChanged(connections_reply->connections); } } } /*****************************************************************************/ /* ConnectionNotificationWidget */ /*****************************************************************************/ ConnectionNotificationWidget::ConnectionNotificationWidget(QWidget* parent) : QWidget(parent) { ui_ = new Ui::ConnectionNotificationWidget; ui_->setupUi(this); icon_connected_ = QPixmap(":/images/connection_connected.png"); icon_not_connected_ = QPixmap(":/images/connection_not_connected.png"); icon_alarm_ = QPixmap(":/images/connection_alarm.png"); updateConnectionStatus(connection_status_); startTimer(500); } ConnectionNotificationWidget::~ConnectionNotificationWidget() {} void ConnectionNotificationWidget::updateConnectionStatus( client::NetworkClient::ConnectionStatus connection_status) { if (connection_status != connection_status_) { last_status_change_ = frame_; } switch (connection_status) { case client::NetworkClient::ConnectionStatus::NotConnected: ui_->connection_status_text_label->setText("Not Connected"); ui_->connection_status_icon_label->setPixmap(icon_not_connected_); break; case client::NetworkClient::ConnectionStatus::Connecting: ui_->connection_status_text_label->setText( "Connecting: " + util::settings::connection::currentProfile()); ui_->connection_status_icon_label->setPixmap(icon_not_connected_); break; case client::NetworkClient::ConnectionStatus::Connected: ui_->connection_status_text_label->setText( "Connected: " + util::settings::connection::currentProfile()); ui_->connection_status_icon_label->setPixmap(icon_connected_); break; } connection_status_ = connection_status; } void ConnectionNotificationWidget::timerEvent(QTimerEvent* /*event*/) { ++frame_; if (connection_status_ == client::NetworkClient::ConnectionStatus::Connecting) { ui_->connection_status_icon_label->setPixmap( frame_ % 2 == 1 ? icon_connected_ : icon_not_connected_); } else if (connection_status_ == client::NetworkClient::ConnectionStatus::NotConnected) { if (frame_ - last_status_change_ < 10) { ui_->connection_status_icon_label->setPixmap( frame_ % 2 == 1 ? icon_alarm_ : icon_not_connected_); } else { ui_->connection_status_icon_label->setPixmap(icon_not_connected_); } } } /*****************************************************************************/ /* ConnectionsWidget */ /*****************************************************************************/ ConnectionsWidget::ConnectionsWidget(QWidget* parent) : QWidget(parent) { users_icon_ = QPixmap(":/images/clients.png"); users_icon_label_ = new QLabel(this); users_icon_label_->setPixmap(users_icon_); layout_ = new QHBoxLayout(this); setLayout(layout_); auto* scroll_area = new QScrollArea(this); scroll_area->setFrameShape(QFrame::NoFrame); scroll_area->setWidgetResizable(true); QWidget* scroll_area_contents = new QWidget(scroll_area); scroll_area_layout_ = new QHBoxLayout(scroll_area_contents); scroll_area_contents->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); scroll_area->setMaximumHeight(users_icon_label_->sizeHint().height()); scroll_area_contents->setLayout(scroll_area_layout_); scroll_area_layout_->setSizeConstraint(QLayout::SetMinAndMaxSize); scroll_area_layout_->setMargin(0); scroll_area_layout_->addStretch(1); scroll_area_layout_->addWidget(users_icon_label_); scroll_area->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); scroll_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll_area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll_area->setWidget(scroll_area_contents); layout_->addWidget(scroll_area); layout_->setStretchFactor(scroll_area, 1); layout_->addSpacing(10); users_icon_label_->hide(); label_stylesheet_ = QString( "QLabel {" "background : palette(highlight);" "color : palette(highlighted-text);" "border-radius: 4px;" "border-width: 0px;" "padding-left: 5px;" "padding-right: 5px;" "}"); } ConnectionsWidget::~ConnectionsWidget() {} void ConnectionsWidget::updateConnectionStatus( client::NetworkClient::ConnectionStatus connection_status) { if (connection_status == client::NetworkClient::ConnectionStatus::NotConnected) { clear(); } } void ConnectionsWidget::updateConnections( const std::shared_ptr<std::vector<std::shared_ptr<proto::Connection>>>& connections) { clear(); if (connections != nullptr && !connections->empty()) { users_icon_label_->show(); for (const auto& connection : *connections) { QLabel* client_label = new QLabel; client_label->setText(QString::fromStdString(*connection->client_name)); client_label->setToolTip( QString("<p><b>Client name:</b> %1</p>" "<p><b>Client type:</b> %2</p>" "<p><b>Client version:</b> %3</p>" "<p><b>Client description:</b> %4</p>") .arg(QString::fromStdString(*connection->client_name)) .arg(QString::fromStdString(*connection->client_type)) .arg(QString::fromStdString(*connection->client_version)) .arg(QString::fromStdString(*connection->client_description))); client_label->setStyleSheet(label_stylesheet_); scroll_area_layout_->addWidget(client_label); user_labels_.push_back(client_label); } } } void ConnectionsWidget::clear() { for (auto label : user_labels_) { label->deleteLater(); } user_labels_.clear(); users_icon_label_->hide(); } } // namespace ui } // namespace veles
6,754
563
<reponame>philippguertler/mesh { "type" : "object", "id" : "urn:jsonschema:com:gentics:mesh:core:rest:project:ProjectCreateRequest", "properties" : { "name" : { "type" : "string", "required" : true, "description" : "Name of the project" }, "schema" : { "type" : "object", "id" : "urn:jsonschema:com:gentics:mesh:core:rest:schema:SchemaReference", "required" : true, "description" : "Reference to the schema of the root node. Creating a project will also automatically create the base node of the project and link the schema to the initial branch of the project.", "properties" : { "version" : { "type" : "string" }, "versionUuid" : { "type" : "string" }, "uuid" : { "type" : "string" }, "name" : { "type" : "string" }, "set" : { "type" : "boolean" } } }, "hostname" : { "type" : "string", "description" : "The hostname of the project can be used to generate links across multiple projects. The hostname will be stored along the initial branch of the project." }, "ssl" : { "type" : "boolean", "description" : "SSL flag of the project which will be used to generate links across multiple projects. The flag will be stored along the intial branch of the project." }, "pathPrefix" : { "type" : "string", "description" : "Optional path prefix for webroot path and rendered links." } } }
652
399
from openrec.tf1.modules.interactions.pairwise_log import PairwiseLog from openrec.tf1.modules.interactions.pairwise_eu_dist import PairwiseEuDist from openrec.tf1.modules.interactions.pointwise_mse import PointwiseMSE from openrec.tf1.modules.interactions.mlp_softmax import MLPSoftmax from openrec.tf1.modules.interactions.rnn_softmax import RNNSoftmax from openrec.tf1.modules.interactions.pointwise_mlp_ce import PointwiseMLPCE
141
65,371
<reponame>apokalyzr/bitcoin /*********************************************************************** * Copyright (c) 2013, 2014, 2015 <NAME>, <NAME> * * Distributed under the MIT software license, see the accompanying * * file COPYING or https://www.opensource.org/licenses/mit-license.php.* ***********************************************************************/ #include <inttypes.h> #include <stdio.h> #include "../include/secp256k1.h" #include "assumptions.h" #include "util.h" #include "group.h" #include "ecmult_gen.h" #include "ecmult_gen_prec_impl.h" int main(int argc, char **argv) { const char outfile[] = "src/ecmult_gen_static_prec_table.h"; FILE* fp; int bits; (void)argc; (void)argv; fp = fopen(outfile, "w"); if (fp == NULL) { fprintf(stderr, "Could not open %s for writing!\n", outfile); return -1; } fprintf(fp, "/* This file was automatically generated by gen_ecmult_gen_static_prec_table. */\n"); fprintf(fp, "/* See ecmult_gen_impl.h for details about the contents of this file. */\n"); fprintf(fp, "#ifndef SECP256K1_ECMULT_GEN_STATIC_PREC_TABLE_H\n"); fprintf(fp, "#define SECP256K1_ECMULT_GEN_STATIC_PREC_TABLE_H\n"); fprintf(fp, "#include \"group.h\"\n"); fprintf(fp, "#define S(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) " "SECP256K1_GE_STORAGE_CONST(0x##a##u,0x##b##u,0x##c##u,0x##d##u,0x##e##u,0x##f##u,0x##g##u," "0x##h##u,0x##i##u,0x##j##u,0x##k##u,0x##l##u,0x##m##u,0x##n##u,0x##o##u,0x##p##u)\n"); fprintf(fp, "#ifdef EXHAUSTIVE_TEST_ORDER\n"); fprintf(fp, "static secp256k1_ge_storage secp256k1_ecmult_gen_prec_table[ECMULT_GEN_PREC_N(ECMULT_GEN_PREC_BITS)][ECMULT_GEN_PREC_G(ECMULT_GEN_PREC_BITS)];\n"); fprintf(fp, "#else\n"); fprintf(fp, "static const secp256k1_ge_storage secp256k1_ecmult_gen_prec_table[ECMULT_GEN_PREC_N(ECMULT_GEN_PREC_BITS)][ECMULT_GEN_PREC_G(ECMULT_GEN_PREC_BITS)] = {\n"); for (bits = 2; bits <= 8; bits *= 2) { int g = ECMULT_GEN_PREC_G(bits); int n = ECMULT_GEN_PREC_N(bits); int inner, outer; secp256k1_ge_storage* table = checked_malloc(&default_error_callback, n * g * sizeof(secp256k1_ge_storage)); secp256k1_ecmult_gen_create_prec_table(table, &secp256k1_ge_const_g, bits); fprintf(fp, "#if ECMULT_GEN_PREC_BITS == %d\n", bits); for(outer = 0; outer != n; outer++) { fprintf(fp,"{"); for(inner = 0; inner != g; inner++) { fprintf(fp, "S(%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32 ",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32",%"PRIx32")", SECP256K1_GE_STORAGE_CONST_GET(table[outer * g + inner])); if (inner != g - 1) { fprintf(fp,",\n"); } } if (outer != n - 1) { fprintf(fp,"},\n"); } else { fprintf(fp,"}\n"); } } fprintf(fp, "#endif\n"); free(table); } fprintf(fp, "};\n"); fprintf(fp, "#endif /* EXHAUSTIVE_TEST_ORDER */\n"); fprintf(fp, "#undef SC\n"); fprintf(fp, "#endif /* SECP256K1_ECMULT_GEN_STATIC_PREC_TABLE_H */\n"); fclose(fp); return 0; }
1,716
1,738
// Modifications copyright Amazon.com, Inc. or its affiliates // Modifications copyright Crytek GmbH #ifndef TIMER_H #define TIMER_H #ifdef _WIN32 #include <Windows.h> #else #include <sys/time.h> #endif typedef struct { #ifdef _WIN32 LARGE_INTEGER frequency; LARGE_INTEGER startCount; LARGE_INTEGER endCount; #else struct timeval startCount; struct timeval endCount; #endif } Timer_t; void InitTimer(Timer_t* psTimer); void ResetTimer(Timer_t* psTimer); double ReadTimer(Timer_t* psTimer); #endif
200
414
<gh_stars>100-1000 from enum import Enum from peewee import * from ..models import * from ..redis import rd, with_lock class Status(Enum): FREE = 0 IN_QUEUE = 1 MATCHED = 2 class RedisQueue: def __init__(self, name): self.name = name @with_lock("matching") def __len__(self): return rd.llen('queue:{}'.format(self.name)) @with_lock("matching") def push(self, v): rd.rpush('queue:{}'.format(self.name), v) @with_lock("matching") def pop(self): return int(rd.lpop('queue:{}'.format(self.name))) @with_lock("matching") def remove(self, v): rd.lrem('queue:{}'.format(self.name), 0, v) def create_room(system, client): user0 = User.get(User.id == system) user1 = User.get(User.id == client) task = Task.select().where(Task.finished == False).order_by(fn.Random()).get() print(task.content) task.finished = True task.save() room = Room.create( task=task, user0=user0, user1=user1, status=Room.Status.RUNNING ) @with_lock("matching") def get_status(uid): s = rd.get('user_status:{}'.format(uid)) or 0 return Status(int(s)) @with_lock("matching") def set_status(uid, status: Status): s = status.value rd.set('user_status:{}'.format(uid), s)
581
603
<gh_stars>100-1000 package net.maxbraun.mirror; import android.content.Context; import android.location.Location; import android.util.Log; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import net.maxbraun.mirror.Air.AirData; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * A helper class to regularly retrieve air quality information. */ public class Air extends DataUpdater<AirData> { private static final String TAG = Air.class.getSimpleName(); /** * The time in milliseconds between API calls to update the air quality. */ private static final long UPDATE_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(15); /** * The base URL for all AirNow API requests. */ private static final String AIR_NOW_BASE_URL = "https://www.airnowapi.org"; /** * The context used to load string resources. */ private final Context context; /** * A {@link Map} from the air quality index category the corresponding drawable resource ID. */ private final Map<Integer, Integer> iconResources = new HashMap<Integer, Integer>() {{ put(1, R.drawable.aqi_good); put(2, R.drawable.aqi_moderate); put(3, R.drawable.aqi_usg); put(4, R.drawable.aqi_unhealthy); put(5, R.drawable.aqi_very_unhealthy); put(6, R.drawable.aqi_hazardous); }}; /** * The data structure containing the air quality information we are interested in. */ public class AirData { /** * The air quality index number. */ public final int aqi; /** * The air quality index category name. */ public final String category; /** * The air quality index category icon. */ public final int icon; public AirData(int aqi, String category, int icon) { this.aqi = aqi; this.category = category; this.icon = icon; } } public Air(Context context, UpdateListener<AirData> updateListener) { super(updateListener, UPDATE_INTERVAL_MILLIS); this.context = context; } @Override protected AirData getData() { Location location = GeoLocation.getLocation(); Log.d(TAG, "Using location for air quality: " + location); // Get the latest data from the AirNow API. try { String requestUrl = getRequestUrl(location); JSONArray response = Network.getJsonArray(requestUrl); if (response == null) { return null; } // Parse the data we are interested in from the response JSON. for (int i = 0; i < response.length(); i++) { JSONObject observation = response.getJSONObject(i); // Skip everything but particulate matter observations. if (!"PM2.5".equals(observation.getString("ParameterName"))) { continue; } int aqi = observation .getInt("AQI"); String category = observation .getJSONObject("Category") .getString("Name"); int categoryNumber = observation .getJSONObject("Category") .getInt("Number"); return new AirData( aqi, category, iconResources.get(categoryNumber) ); } Log.e(TAG, "No particulate matter observation found: " + response); return null; } catch (JSONException e) { Log.e(TAG, "Failed to parse air quality JSON.", e); return null; } } /** * Creates the URL for an AirNow API request based on the specified location or {@code null} if * the location is unknown. */ private String getRequestUrl(Location location) { if (location == null) { return null; } return String.format( Locale.US, "%s/aq/observation/latLong/current" + "?format=application/json" + "&latitude=%f" + "&longitude=%f" + "&API_KEY=%s", AIR_NOW_BASE_URL, location.getLatitude(), location.getLongitude(), context.getString(R.string.air_now_api_key)); } @Override protected String getTag() { return TAG; } }
1,582
407
<filename>paas/appmanager/tesla-appmanager-domain/src/main/java/com/alibaba/tesla/appmanager/domain/dto/AppMetaDTO.java package com.alibaba.tesla.appmanager.domain.dto; import com.alibaba.fastjson.JSONObject; import lombok.Data; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 应用元信息 DTO * * @author <EMAIL> */ @Data public class AppMetaDTO { /** * 创建时间 */ private Date gmtCreate; /** * 最后修改时间 */ private Date gmtModified; /** * 应用唯一标识 */ private String appId; /** * 应用 Options */ private JSONObject options; /** * 应用部署环境列表 */ private List<AppDeployEnvironmentDTO> environments = new ArrayList<>(); }
363
646
package com.dimple.project.log.service; import com.dimple.project.log.domain.LoginLog; import java.util.List; /** * @className: LoginLogService * @description: 系统访问日志情况信息 服务层 * @author: Dimple * @date: 10/22/19 */ public interface LoginLogService { /** * 新增系统登录日志 * * @param loginLog 访问日志对象 */ void insertLoginLog(LoginLog loginLog); /** * 查询系统登录日志集合 * * @param loginLog 访问日志对象 * @return 登录记录集合 */ List<LoginLog> selectLoginLogList(LoginLog loginLog); /** * 批量删除系统登录日志 * * @param ids 需要删除的数据 * @return */ int deleteLoginLogByIds(String ids); /** * 清空系统登录日志 */ void cleanLoginLog(); }
453
457
<gh_stars>100-1000 // // bridge.h // Safe // // Created by <NAME> on 7/1/15. // Copyright © 2015 ONcast. All rights reserved. // #import <Foundation/Foundation.h> typedef void (^ AnyBlock)(); NSException *_try(AnyBlock block); bool __builtin_uadd_overflow (unsigned x, unsigned y, unsigned *sum); bool __builtin_uaddl_overflow (unsigned long x, unsigned long y, unsigned long *sum); bool __builtin_uaddll_overflow(unsigned long long x, unsigned long long y, unsigned long long *sum); bool __builtin_usub_overflow (unsigned x, unsigned y, unsigned *diff); bool __builtin_usubl_overflow (unsigned long x, unsigned long y, unsigned long *diff); bool __builtin_usubll_overflow(unsigned long long x, unsigned long long y, unsigned long long *diff); bool __builtin_umul_overflow (unsigned x, unsigned y, unsigned *prod); bool __builtin_umull_overflow (unsigned long x, unsigned long y, unsigned long *prod); bool __builtin_umulll_overflow(unsigned long long x, unsigned long long y, unsigned long long *prod); bool __builtin_sadd_overflow (int x, int y, int *sum); bool __builtin_saddl_overflow (long x, long y, long *sum); bool __builtin_saddll_overflow(long long x, long long y, long long *sum); bool __builtin_ssub_overflow (int x, int y, int *diff); bool __builtin_ssubl_overflow (long x, long y, long *diff); bool __builtin_ssubll_overflow(long long x, long long y, long long *diff); bool __builtin_smul_overflow (int x, int y, int *prod); bool __builtin_smull_overflow (long x, long y, long *prod); bool __builtin_smulll_overflow(long long x, long long y, long long *prod);
543
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. package org.chromium.components.payments.test_support; import androidx.annotation.Nullable; import org.mockito.Mockito; import org.chromium.components.payments.BrowserPaymentRequest; import org.chromium.components.payments.JourneyLogger; import org.chromium.components.payments.PaymentAppService; import org.chromium.components.payments.PaymentRequestService; import org.chromium.components.payments.PaymentRequestService.Delegate; import org.chromium.components.payments.PaymentRequestSpec; import org.chromium.content_public.browser.RenderFrameHost; import org.chromium.content_public.browser.WebContents; import org.chromium.payments.mojom.PaymentCurrencyAmount; import org.chromium.payments.mojom.PaymentDetails; import org.chromium.payments.mojom.PaymentItem; import org.chromium.payments.mojom.PaymentMethodData; import org.chromium.payments.mojom.PaymentOptions; import org.chromium.payments.mojom.PaymentRequestClient; import org.chromium.url.GURL; import org.chromium.url.JUnitTestGURLs; import org.chromium.url.Origin; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** A builder of PaymentRequestService for testing. */ public class PaymentRequestServiceBuilder implements Delegate { private static final String TWA_PACKAGE_NAME = "twa.package.name"; private final Delegate mDelegate; private final RenderFrameHost mRenderFrameHost; private final Runnable mOnClosedListener; private final PaymentAppService mPaymentAppService; private final BrowserPaymentRequest mBrowserPaymentRequest; private WebContents mWebContents; private boolean mIsOffTheRecord = true; private PaymentRequestClient mClient; private PaymentMethodData[] mMethodData; private PaymentDetails mDetails; private PaymentOptions mOptions; private boolean mGooglePayBridgeEligible; private boolean mPrefsCanMakePayment; private String mInvalidSslCertificateErrorMessage; private boolean mIsOriginSecure = true; private JourneyLogger mJourneyLogger; private String mTopLevelOrigin; private String mFrameOrigin; private boolean mIsOriginAllowedToUseWebPaymentApis = true; private boolean mIsPaymentDetailsValid = true; private PaymentRequestSpec mSpec; public static PaymentRequestServiceBuilder defaultBuilder(Runnable onClosedListener, PaymentRequestClient client, PaymentAppService appService, BrowserPaymentRequest browserPaymentRequest, JourneyLogger journeyLogger) { return new PaymentRequestServiceBuilder( onClosedListener, client, appService, browserPaymentRequest, journeyLogger); } public PaymentRequestServiceBuilder(Runnable onClosedListener, PaymentRequestClient client, PaymentAppService appService, BrowserPaymentRequest browserPaymentRequest, JourneyLogger journeyLogger) { mDelegate = this; mWebContents = Mockito.mock(WebContents.class); setTopLevelOrigin(JUnitTestGURLs.getGURL(JUnitTestGURLs.URL_1)); mRenderFrameHost = Mockito.mock(RenderFrameHost.class); setFrameOrigin(JUnitTestGURLs.getGURL(JUnitTestGURLs.URL_2)); Origin origin = Mockito.mock(Origin.class); Mockito.doReturn(origin).when(mRenderFrameHost).getLastCommittedOrigin(); mJourneyLogger = journeyLogger; mMethodData = new PaymentMethodData[1]; mMethodData[0] = new PaymentMethodData(); mMethodData[0].supportedMethod = "https://www.chromium.org"; mDetails = new PaymentDetails(); mDetails.id = "testId"; mDetails.total = new PaymentItem(); mOptions = new PaymentOptions(); mOptions.requestShipping = true; mSpec = Mockito.mock(PaymentRequestSpec.class); PaymentCurrencyAmount amount = new PaymentCurrencyAmount(); amount.currency = "CNY"; amount.value = "123"; PaymentItem total = new PaymentItem(); total.amount = amount; Mockito.doReturn(total).when(mSpec).getRawTotal(); Map<String, PaymentMethodData> methodDataMap = new HashMap<>(); Mockito.doReturn(methodDataMap).when(mSpec).getMethodData(); mBrowserPaymentRequest = browserPaymentRequest; mOnClosedListener = onClosedListener; mClient = client; mPaymentAppService = appService; } @Override public BrowserPaymentRequest createBrowserPaymentRequest( PaymentRequestService paymentRequestService) { return mBrowserPaymentRequest; } @Override public boolean isOffTheRecord() { return mIsOffTheRecord; } @Override public String getInvalidSslCertificateErrorMessage() { return mInvalidSslCertificateErrorMessage; } @Override public boolean prefsCanMakePayment() { return mPrefsCanMakePayment; } @Nullable @Override public String getTwaPackageName() { return TWA_PACKAGE_NAME; } @Override public WebContents getLiveWebContents(RenderFrameHost renderFrameHost) { return mWebContents; } @Override public boolean isOriginSecure(GURL url) { return mIsOriginSecure; } @Override public JourneyLogger createJourneyLogger(boolean isIncognito, WebContents webContents) { return mJourneyLogger; } @Override public String formatUrlForSecurityDisplay(GURL url) { return url.getSpec(); } @Override public byte[][] getCertificateChain(WebContents webContents) { return new byte[0][]; } @Override public boolean isOriginAllowedToUseWebPaymentApis(GURL lastCommittedUrl) { return mIsOriginAllowedToUseWebPaymentApis; } @Override public boolean validatePaymentDetails(PaymentDetails details) { return mIsPaymentDetailsValid; } @Override public PaymentRequestSpec createPaymentRequestSpec(PaymentOptions paymentOptions, PaymentDetails details, Collection<PaymentMethodData> values, String defaultLocaleString) { return mSpec; } @Override public PaymentAppService getPaymentAppService() { return mPaymentAppService; } public PaymentRequestServiceBuilder setRenderFrameHostLastCommittedOrigin(Origin origin) { Mockito.doReturn(origin).when(mRenderFrameHost).getLastCommittedOrigin(); return this; } public PaymentRequestServiceBuilder setRenderFrameHostLastCommittedURL(GURL url) { Mockito.doReturn(url).when(mRenderFrameHost).getLastCommittedURL(); return this; } public PaymentRequestServiceBuilder setOffTheRecord(boolean isOffTheRecord) { mIsOffTheRecord = isOffTheRecord; return this; } public PaymentRequestServiceBuilder setOriginSecure(boolean isSecure) { mIsOriginSecure = isSecure; return this; } public PaymentRequestServiceBuilder setJourneyLogger(JourneyLogger journeyLogger) { mJourneyLogger = journeyLogger; return this; } public PaymentRequestServiceBuilder setPaymentRequestClient(PaymentRequestClient client) { mClient = client; return this; } public PaymentRequestServiceBuilder setMethodData(PaymentMethodData[] methodData) { mMethodData = methodData; return this; } public PaymentRequestServiceBuilder setPaymentDetailsInit(PaymentDetails details) { mDetails = details; return this; } public PaymentRequestServiceBuilder setPaymentDetailsInitId(String id) { mDetails.id = id; return this; } public PaymentRequestServiceBuilder setPaymentDetailsInitTotal(PaymentItem total) { mDetails.total = total; return this; } public PaymentRequestServiceBuilder setOptions(PaymentOptions options) { mOptions = options; return this; } public PaymentRequestServiceBuilder setGooglePayBridgeEligible(boolean eligible) { mGooglePayBridgeEligible = eligible; return this; } public PaymentRequestServiceBuilder setWebContents(WebContents webContents) { mWebContents = webContents; return this; } public PaymentRequestServiceBuilder setTopLevelOrigin(GURL topLevelOrigin) { Mockito.doReturn(topLevelOrigin).when(mWebContents).getLastCommittedUrl(); return this; } public PaymentRequestServiceBuilder setFrameOrigin(GURL frameOrigin) { Mockito.doReturn(frameOrigin).when(mRenderFrameHost).getLastCommittedURL(); return this; } public PaymentRequestServiceBuilder setInvalidSslCertificateErrorMessage( String invalidSslCertificateErrorMessage) { mInvalidSslCertificateErrorMessage = invalidSslCertificateErrorMessage; return this; } public PaymentRequestServiceBuilder setOriginAllowedToUseWebPaymentApis(boolean isAllowed) { mIsOriginAllowedToUseWebPaymentApis = isAllowed; return this; } public PaymentRequestServiceBuilder setIsPaymentDetailsValid(boolean isValid) { mIsPaymentDetailsValid = isValid; return this; } public PaymentRequestServiceBuilder setPaymentRequestSpec(PaymentRequestSpec spec) { mSpec = spec; return this; } public PaymentRequestService build() { PaymentRequestService service = new PaymentRequestService(mRenderFrameHost, mClient, mOnClosedListener, mDelegate); boolean success = service.init(mMethodData, mDetails, mOptions, mGooglePayBridgeEligible); return success ? service : null; } }
3,443
5,535
/*------------------------------------------------------------------------- * * isolationtester.h * include file for isolation tests * * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/test/isolation/isolationtester.h * *------------------------------------------------------------------------- */ #ifndef ISOLATIONTESTER_H #define ISOLATIONTESTER_H typedef struct Session Session; typedef struct Step Step; struct Session { char *name; char *setupsql; char *teardownsql; Step **steps; int nsteps; }; struct Step { int session; char *name; char *sql; char *errormsg; }; typedef struct { int nsteps; char **stepnames; } Permutation; typedef struct { char **setupsqls; int nsetupsqls; char *teardownsql; Session **sessions; int nsessions; Permutation **permutations; int npermutations; Step **allsteps; int nallsteps; } TestSpec; extern TestSpec parseresult; extern int spec_yyparse(void); extern int spec_yylex(void); extern void spec_yyerror(const char *str); #endif /* ISOLATIONTESTER_H */
442
831
/* * Copyright (C) 2017 The Android Open Source Project * * 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.android.tools.profilers.stacktrace; import org.junit.Test; import static com.android.tools.profilers.stacktrace.ThreadId.DISPLAY_FORMAT; import static com.android.tools.profilers.stacktrace.ThreadId.INVALID_THREAD_ID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class ThreadIdTest { @Test public void threadEqualityTest() { ThreadId threadId0 = new ThreadId(0); ThreadId threadId1 = new ThreadId(0); ThreadId threadId2 = new ThreadId(5); assertEquals(threadId0, threadId0); assertEquals(threadId1, threadId1); assertEquals(threadId2, threadId2); assertEquals(INVALID_THREAD_ID, INVALID_THREAD_ID); assertEquals(threadId0, threadId1); assertNotEquals(threadId0, threadId2); assertNotEquals(threadId0, INVALID_THREAD_ID); assertNotEquals(threadId2, INVALID_THREAD_ID); } @Test public void displayNameTest() { assertEquals(String.format(DISPLAY_FORMAT, "Unknown"), INVALID_THREAD_ID.toString()); assertEquals(String.format(DISPLAY_FORMAT, "1"), new ThreadId(1).toString()); assertEquals(String.format(DISPLAY_FORMAT, "TestThread"), new ThreadId("TestThread").toString()); } }
603
12,278
// Copyright 2014 the V8 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. #include "src/codegen/code-factory.h" #include "src/builtins/builtins-descriptors.h" #include "src/ic/ic.h" #include "src/init/bootstrapper.h" #include "src/objects/allocation-site-inl.h" #include "src/objects/objects-inl.h" namespace v8 { namespace internal { // static Handle<Code> CodeFactory::RuntimeCEntry(Isolate* isolate, int result_size) { return CodeFactory::CEntry(isolate, result_size); } #define CENTRY_CODE(RS, SD, AM, BE) \ BUILTIN_CODE(isolate, CEntry_##RS##_##SD##_##AM##_##BE) // static Handle<Code> CodeFactory::CEntry(Isolate* isolate, int result_size, SaveFPRegsMode save_doubles, ArgvMode argv_mode, bool builtin_exit_frame) { // Aliases for readability below. const int rs = result_size; const SaveFPRegsMode sd = save_doubles; const ArgvMode am = argv_mode; const bool be = builtin_exit_frame; if (rs == 1 && sd == kDontSaveFPRegs && am == kArgvOnStack && !be) { return CENTRY_CODE(Return1, DontSaveFPRegs, ArgvOnStack, NoBuiltinExit); } else if (rs == 1 && sd == kDontSaveFPRegs && am == kArgvOnStack && be) { return CENTRY_CODE(Return1, DontSaveFPRegs, ArgvOnStack, BuiltinExit); } else if (rs == 1 && sd == kDontSaveFPRegs && am == kArgvInRegister && !be) { return CENTRY_CODE(Return1, DontSaveFPRegs, ArgvInRegister, NoBuiltinExit); } else if (rs == 1 && sd == kSaveFPRegs && am == kArgvOnStack && !be) { return CENTRY_CODE(Return1, SaveFPRegs, ArgvOnStack, NoBuiltinExit); } else if (rs == 1 && sd == kSaveFPRegs && am == kArgvOnStack && be) { return CENTRY_CODE(Return1, SaveFPRegs, ArgvOnStack, BuiltinExit); } else if (rs == 2 && sd == kDontSaveFPRegs && am == kArgvOnStack && !be) { return CENTRY_CODE(Return2, DontSaveFPRegs, ArgvOnStack, NoBuiltinExit); } else if (rs == 2 && sd == kDontSaveFPRegs && am == kArgvOnStack && be) { return CENTRY_CODE(Return2, DontSaveFPRegs, ArgvOnStack, BuiltinExit); } else if (rs == 2 && sd == kDontSaveFPRegs && am == kArgvInRegister && !be) { return CENTRY_CODE(Return2, DontSaveFPRegs, ArgvInRegister, NoBuiltinExit); } else if (rs == 2 && sd == kSaveFPRegs && am == kArgvOnStack && !be) { return CENTRY_CODE(Return2, SaveFPRegs, ArgvOnStack, NoBuiltinExit); } else if (rs == 2 && sd == kSaveFPRegs && am == kArgvOnStack && be) { return CENTRY_CODE(Return2, SaveFPRegs, ArgvOnStack, BuiltinExit); } UNREACHABLE(); } #undef CENTRY_CODE // static Callable CodeFactory::ApiGetter(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallApiGetter); } // static Callable CodeFactory::CallApiCallback(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallApiCallback); } // static Callable CodeFactory::LoadGlobalIC(Isolate* isolate, TypeofMode typeof_mode) { return typeof_mode == NOT_INSIDE_TYPEOF ? Builtins::CallableFor(isolate, Builtins::kLoadGlobalICTrampoline) : Builtins::CallableFor( isolate, Builtins::kLoadGlobalICInsideTypeofTrampoline); } // static Callable CodeFactory::LoadGlobalICInOptimizedCode(Isolate* isolate, TypeofMode typeof_mode) { return typeof_mode == NOT_INSIDE_TYPEOF ? Builtins::CallableFor(isolate, Builtins::kLoadGlobalIC) : Builtins::CallableFor(isolate, Builtins::kLoadGlobalICInsideTypeof); } Callable CodeFactory::StoreOwnIC(Isolate* isolate) { // TODO(ishell): Currently we use StoreOwnIC only for storing properties that // already exist in the boilerplate therefore we can use StoreIC. return Builtins::CallableFor(isolate, Builtins::kStoreICTrampoline); } Callable CodeFactory::StoreOwnICInOptimizedCode(Isolate* isolate) { // TODO(ishell): Currently we use StoreOwnIC only for storing properties that // already exist in the boilerplate therefore we can use StoreIC. return Builtins::CallableFor(isolate, Builtins::kStoreIC); } Callable CodeFactory::KeyedStoreIC_SloppyArguments(Isolate* isolate, KeyedAccessStoreMode mode) { Builtins::Name builtin_index; switch (mode) { case STANDARD_STORE: builtin_index = Builtins::kKeyedStoreIC_SloppyArguments_Standard; break; case STORE_AND_GROW_HANDLE_COW: builtin_index = Builtins::kKeyedStoreIC_SloppyArguments_GrowNoTransitionHandleCOW; break; case STORE_IGNORE_OUT_OF_BOUNDS: builtin_index = Builtins::kKeyedStoreIC_SloppyArguments_NoTransitionIgnoreOOB; break; case STORE_HANDLE_COW: builtin_index = Builtins::kKeyedStoreIC_SloppyArguments_NoTransitionHandleCOW; break; default: UNREACHABLE(); } return isolate->builtins()->CallableFor(isolate, builtin_index); } Callable CodeFactory::KeyedStoreIC_Slow(Isolate* isolate, KeyedAccessStoreMode mode) { Builtins::Name builtin_index; switch (mode) { case STANDARD_STORE: builtin_index = Builtins::kKeyedStoreIC_Slow_Standard; break; case STORE_AND_GROW_HANDLE_COW: builtin_index = Builtins::kKeyedStoreIC_Slow_GrowNoTransitionHandleCOW; break; case STORE_IGNORE_OUT_OF_BOUNDS: builtin_index = Builtins::kKeyedStoreIC_Slow_NoTransitionIgnoreOOB; break; case STORE_HANDLE_COW: builtin_index = Builtins::kKeyedStoreIC_Slow_NoTransitionHandleCOW; break; default: UNREACHABLE(); } return isolate->builtins()->CallableFor(isolate, builtin_index); } Callable CodeFactory::StoreInArrayLiteralIC_Slow(Isolate* isolate, KeyedAccessStoreMode mode) { Builtins::Name builtin_index; switch (mode) { case STANDARD_STORE: builtin_index = Builtins::kStoreInArrayLiteralIC_Slow_Standard; break; case STORE_AND_GROW_HANDLE_COW: builtin_index = Builtins::kStoreInArrayLiteralIC_Slow_GrowNoTransitionHandleCOW; break; case STORE_IGNORE_OUT_OF_BOUNDS: builtin_index = Builtins::kStoreInArrayLiteralIC_Slow_NoTransitionIgnoreOOB; break; case STORE_HANDLE_COW: builtin_index = Builtins::kStoreInArrayLiteralIC_Slow_NoTransitionHandleCOW; break; default: UNREACHABLE(); } return isolate->builtins()->CallableFor(isolate, builtin_index); } Callable CodeFactory::ElementsTransitionAndStore(Isolate* isolate, KeyedAccessStoreMode mode) { Builtins::Name builtin_index; switch (mode) { case STANDARD_STORE: builtin_index = Builtins::kElementsTransitionAndStore_Standard; break; case STORE_AND_GROW_HANDLE_COW: builtin_index = Builtins::kElementsTransitionAndStore_GrowNoTransitionHandleCOW; break; case STORE_IGNORE_OUT_OF_BOUNDS: builtin_index = Builtins::kElementsTransitionAndStore_NoTransitionIgnoreOOB; break; case STORE_HANDLE_COW: builtin_index = Builtins::kElementsTransitionAndStore_NoTransitionHandleCOW; break; default: UNREACHABLE(); } return isolate->builtins()->CallableFor(isolate, builtin_index); } Callable CodeFactory::StoreFastElementIC(Isolate* isolate, KeyedAccessStoreMode mode) { Builtins::Name builtin_index; switch (mode) { case STANDARD_STORE: builtin_index = Builtins::kStoreFastElementIC_Standard; break; case STORE_AND_GROW_HANDLE_COW: builtin_index = Builtins::kStoreFastElementIC_GrowNoTransitionHandleCOW; break; case STORE_IGNORE_OUT_OF_BOUNDS: builtin_index = Builtins::kStoreFastElementIC_NoTransitionIgnoreOOB; break; case STORE_HANDLE_COW: builtin_index = Builtins::kStoreFastElementIC_NoTransitionHandleCOW; break; default: UNREACHABLE(); } return isolate->builtins()->CallableFor(isolate, builtin_index); } // static Callable CodeFactory::BinaryOperation(Isolate* isolate, Operation op) { switch (op) { case Operation::kShiftRight: return Builtins::CallableFor(isolate, Builtins::kShiftRight); case Operation::kShiftLeft: return Builtins::CallableFor(isolate, Builtins::kShiftLeft); case Operation::kShiftRightLogical: return Builtins::CallableFor(isolate, Builtins::kShiftRightLogical); case Operation::kAdd: return Builtins::CallableFor(isolate, Builtins::kAdd); case Operation::kSubtract: return Builtins::CallableFor(isolate, Builtins::kSubtract); case Operation::kMultiply: return Builtins::CallableFor(isolate, Builtins::kMultiply); case Operation::kDivide: return Builtins::CallableFor(isolate, Builtins::kDivide); case Operation::kModulus: return Builtins::CallableFor(isolate, Builtins::kModulus); case Operation::kBitwiseOr: return Builtins::CallableFor(isolate, Builtins::kBitwiseOr); case Operation::kBitwiseAnd: return Builtins::CallableFor(isolate, Builtins::kBitwiseAnd); case Operation::kBitwiseXor: return Builtins::CallableFor(isolate, Builtins::kBitwiseXor); default: break; } UNREACHABLE(); } // static Callable CodeFactory::NonPrimitiveToPrimitive(Isolate* isolate, ToPrimitiveHint hint) { return Callable(isolate->builtins()->NonPrimitiveToPrimitive(hint), TypeConversionDescriptor{}); } // static Callable CodeFactory::OrdinaryToPrimitive(Isolate* isolate, OrdinaryToPrimitiveHint hint) { return Callable(isolate->builtins()->OrdinaryToPrimitive(hint), TypeConversionDescriptor{}); } // static Callable CodeFactory::StringAdd(Isolate* isolate, StringAddFlags flags) { switch (flags) { case STRING_ADD_CHECK_NONE: return Builtins::CallableFor(isolate, Builtins::kStringAdd_CheckNone); case STRING_ADD_CONVERT_LEFT: return Builtins::CallableFor(isolate, Builtins::kStringAddConvertLeft); case STRING_ADD_CONVERT_RIGHT: return Builtins::CallableFor(isolate, Builtins::kStringAddConvertRight); } UNREACHABLE(); } // static Callable CodeFactory::ResumeGenerator(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kResumeGeneratorTrampoline); } // static Callable CodeFactory::FrameDropperTrampoline(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kFrameDropperTrampoline); } // static Callable CodeFactory::HandleDebuggerStatement(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kHandleDebuggerStatement); } // static Callable CodeFactory::FastNewFunctionContext(Isolate* isolate, ScopeType scope_type) { switch (scope_type) { case ScopeType::EVAL_SCOPE: return Builtins::CallableFor(isolate, Builtins::kFastNewFunctionContextEval); case ScopeType::FUNCTION_SCOPE: return Builtins::CallableFor(isolate, Builtins::kFastNewFunctionContextFunction); default: UNREACHABLE(); } } // static Callable CodeFactory::ArgumentAdaptor(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kArgumentsAdaptorTrampoline); } // static Callable CodeFactory::Call(Isolate* isolate, ConvertReceiverMode mode) { return Callable(isolate->builtins()->Call(mode), CallTrampolineDescriptor{}); } // static Callable CodeFactory::CallWithArrayLike(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallWithArrayLike); } // static Callable CodeFactory::CallWithSpread(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallWithSpread); } // static Callable CodeFactory::CallFunction(Isolate* isolate, ConvertReceiverMode mode) { return Callable(isolate->builtins()->CallFunction(mode), CallTrampolineDescriptor{}); } // static Callable CodeFactory::CallVarargs(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallVarargs); } // static Callable CodeFactory::CallForwardVarargs(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallForwardVarargs); } // static Callable CodeFactory::CallFunctionForwardVarargs(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kCallFunctionForwardVarargs); } // static Callable CodeFactory::Construct(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kConstruct); } // static Callable CodeFactory::ConstructWithSpread(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kConstructWithSpread); } // static Callable CodeFactory::ConstructFunction(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kConstructFunction); } // static Callable CodeFactory::ConstructVarargs(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kConstructVarargs); } // static Callable CodeFactory::ConstructForwardVarargs(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kConstructForwardVarargs); } // static Callable CodeFactory::ConstructFunctionForwardVarargs(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kConstructFunctionForwardVarargs); } // static Callable CodeFactory::InterpreterPushArgsThenCall( Isolate* isolate, ConvertReceiverMode receiver_mode, InterpreterPushArgsMode mode) { switch (mode) { case InterpreterPushArgsMode::kArrayFunction: // There is no special-case handling of calls to Array. They will all go // through the kOther case below. UNREACHABLE(); case InterpreterPushArgsMode::kWithFinalSpread: return Builtins::CallableFor( isolate, Builtins::kInterpreterPushArgsThenCallWithFinalSpread); case InterpreterPushArgsMode::kOther: switch (receiver_mode) { case ConvertReceiverMode::kNullOrUndefined: return Builtins::CallableFor( isolate, Builtins::kInterpreterPushUndefinedAndArgsThenCall); case ConvertReceiverMode::kNotNullOrUndefined: case ConvertReceiverMode::kAny: return Builtins::CallableFor(isolate, Builtins::kInterpreterPushArgsThenCall); } } UNREACHABLE(); } // static Callable CodeFactory::InterpreterPushArgsThenConstruct( Isolate* isolate, InterpreterPushArgsMode mode) { switch (mode) { case InterpreterPushArgsMode::kArrayFunction: return Builtins::CallableFor( isolate, Builtins::kInterpreterPushArgsThenConstructArrayFunction); case InterpreterPushArgsMode::kWithFinalSpread: return Builtins::CallableFor( isolate, Builtins::kInterpreterPushArgsThenConstructWithFinalSpread); case InterpreterPushArgsMode::kOther: return Builtins::CallableFor(isolate, Builtins::kInterpreterPushArgsThenConstruct); } UNREACHABLE(); } // static Callable CodeFactory::InterpreterCEntry(Isolate* isolate, int result_size) { // Note: If we ever use fpregs in the interpreter then we will need to // save fpregs too. Handle<Code> code = CodeFactory::CEntry(isolate, result_size, kDontSaveFPRegs, kArgvInRegister); if (result_size == 1) { return Callable(code, InterpreterCEntry1Descriptor{}); } else { DCHECK_EQ(result_size, 2); return Callable(code, InterpreterCEntry2Descriptor{}); } } // static Callable CodeFactory::InterpreterOnStackReplacement(Isolate* isolate) { return Builtins::CallableFor(isolate, Builtins::kInterpreterOnStackReplacement); } // static Callable CodeFactory::ArrayNoArgumentConstructor( Isolate* isolate, ElementsKind kind, AllocationSiteOverrideMode override_mode) { #define CASE(kind_caps, kind_camel, mode_camel) \ case kind_caps: \ return Builtins::CallableFor( \ isolate, \ Builtins::kArrayNoArgumentConstructor_##kind_camel##_##mode_camel); if (override_mode == DONT_OVERRIDE && AllocationSite::ShouldTrack(kind)) { DCHECK(IsSmiElementsKind(kind)); switch (kind) { CASE(PACKED_SMI_ELEMENTS, PackedSmi, DontOverride); CASE(HOLEY_SMI_ELEMENTS, HoleySmi, DontOverride); default: UNREACHABLE(); } } else { DCHECK(override_mode == DISABLE_ALLOCATION_SITES || !AllocationSite::ShouldTrack(kind)); switch (kind) { CASE(PACKED_SMI_ELEMENTS, PackedSmi, DisableAllocationSites); CASE(HOLEY_SMI_ELEMENTS, HoleySmi, DisableAllocationSites); CASE(PACKED_ELEMENTS, Packed, DisableAllocationSites); CASE(HOLEY_ELEMENTS, Holey, DisableAllocationSites); CASE(PACKED_DOUBLE_ELEMENTS, PackedDouble, DisableAllocationSites); CASE(HOLEY_DOUBLE_ELEMENTS, HoleyDouble, DisableAllocationSites); default: UNREACHABLE(); } } #undef CASE } // static Callable CodeFactory::ArraySingleArgumentConstructor( Isolate* isolate, ElementsKind kind, AllocationSiteOverrideMode override_mode) { #define CASE(kind_caps, kind_camel, mode_camel) \ case kind_caps: \ return Builtins::CallableFor( \ isolate, \ Builtins::kArraySingleArgumentConstructor_##kind_camel##_##mode_camel) if (override_mode == DONT_OVERRIDE && AllocationSite::ShouldTrack(kind)) { DCHECK(IsSmiElementsKind(kind)); switch (kind) { CASE(PACKED_SMI_ELEMENTS, PackedSmi, DontOverride); CASE(HOLEY_SMI_ELEMENTS, HoleySmi, DontOverride); default: UNREACHABLE(); } } else { DCHECK(override_mode == DISABLE_ALLOCATION_SITES || !AllocationSite::ShouldTrack(kind)); switch (kind) { CASE(PACKED_SMI_ELEMENTS, PackedSmi, DisableAllocationSites); CASE(HOLEY_SMI_ELEMENTS, HoleySmi, DisableAllocationSites); CASE(PACKED_ELEMENTS, Packed, DisableAllocationSites); CASE(HOLEY_ELEMENTS, Holey, DisableAllocationSites); CASE(PACKED_DOUBLE_ELEMENTS, PackedDouble, DisableAllocationSites); CASE(HOLEY_DOUBLE_ELEMENTS, HoleyDouble, DisableAllocationSites); default: UNREACHABLE(); } } #undef CASE } } // namespace internal } // namespace v8
7,627
2,567
package ru.lanwen.verbalregex.matchers; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.TypeSafeMatcher; import ru.lanwen.verbalregex.VerbalExpression; /** * User: lanwen * Date: 29.05.14 * Time: 20:06 */ public class TestMatchMatcher extends TypeSafeMatcher<VerbalExpression> { private String toTest; private TestMatchMatcher(String toTest) { this.toTest = toTest; } @Override protected boolean matchesSafely(VerbalExpression verbalExpression) { return verbalExpression.test(toTest); } @Override public void describeTo(Description description) { description.appendText("regex should match to ").appendValue(toTest); } @Override protected void describeMismatchSafely(VerbalExpression item, Description mismatchDescription) { mismatchDescription.appendText(item.toString()).appendText(" don't matches this string"); } @Factory public static TestMatchMatcher matchesTo(String test) { return new TestMatchMatcher(test); } }
364
368
package ezvcard.io.scribe; import java.util.Date; import ezvcard.VCardDataType; import ezvcard.VCardVersion; import ezvcard.io.CannotParseException; import ezvcard.io.ParseContext; import ezvcard.io.html.HCardElement; import ezvcard.io.json.JCardValue; import ezvcard.io.text.WriteContext; import ezvcard.io.xml.XCardElement; import ezvcard.parameter.VCardParameters; import ezvcard.property.Revision; /* Copyright (c) 2012-2021, <NAME> 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 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. */ /** * Marshals {@link Revision} properties. * @author <NAME> */ public class RevisionScribe extends VCardPropertyScribe<Revision> { public RevisionScribe() { super(Revision.class, "REV"); } @Override protected VCardDataType _defaultDataType(VCardVersion version) { return VCardDataType.TIMESTAMP; } @Override protected String _writeText(Revision property, WriteContext context) { boolean extended = (context.getVersion() == VCardVersion.V3_0); return write(property, extended); } @Override protected Revision _parseText(String value, VCardDataType dataType, VCardParameters parameters, ParseContext context) { return parse(value); } @Override protected void _writeXml(Revision property, XCardElement parent) { parent.append(VCardDataType.TIMESTAMP, write(property, false)); } @Override protected Revision _parseXml(XCardElement element, VCardParameters parameters, ParseContext context) { String value = element.first(VCardDataType.TIMESTAMP); if (value != null) { return parse(value); } throw missingXmlElements(VCardDataType.TIMESTAMP); } @Override protected Revision _parseHtml(HCardElement element, ParseContext context) { String value = null; if ("time".equals(element.tagName())) { String datetime = element.attr("datetime"); if (datetime.length() > 0) { value = datetime; } } if (value == null) { value = element.value(); } return parse(value); } @Override protected JCardValue _writeJson(Revision property) { return JCardValue.single(write(property, true)); } @Override protected Revision _parseJson(JCardValue value, VCardDataType dataType, VCardParameters parameters, ParseContext context) { String valueStr = value.asSingle(); return parse(valueStr); } private String write(Revision property, boolean extended) { Date timestamp = property.getValue(); if (timestamp == null) { return ""; } return date(timestamp).time(true).utc(true).extended(extended).write(); } private Revision parse(String value) { if (value == null || value.isEmpty()) { return new Revision((Date) null); } try { return new Revision(calendar(value)); } catch (IllegalArgumentException e) { throw new CannotParseException(5); } } }
1,269
1,056
<filename>php/php.editor/src/org/netbeans/modules/php/editor/verification/PHP71UnhandledError.java /* * 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.modules.php.editor.verification; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.netbeans.modules.csl.api.Error; import org.netbeans.modules.csl.spi.support.CancelSupport; import org.netbeans.modules.php.api.PhpVersion; import org.netbeans.modules.php.editor.CodeUtils; import org.netbeans.modules.php.editor.parser.PHPParseResult; import org.netbeans.modules.php.editor.parser.astnodes.ASTNode; import org.netbeans.modules.php.editor.parser.astnodes.ArrayElement; import org.netbeans.modules.php.editor.parser.astnodes.BodyDeclaration; import org.netbeans.modules.php.editor.parser.astnodes.CatchClause; import org.netbeans.modules.php.editor.parser.astnodes.ConstantDeclaration; import org.netbeans.modules.php.editor.parser.astnodes.Expression; import org.netbeans.modules.php.editor.parser.astnodes.ListVariable; import org.netbeans.modules.php.editor.parser.astnodes.NullableType; import org.netbeans.modules.php.editor.parser.astnodes.visitors.DefaultVisitor; import org.openide.filesystems.FileObject; import org.openide.util.NbBundle; public class PHP71UnhandledError extends UnhandledErrorRule { @NbBundle.Messages("PHP71UnhandledError.displayName=Language feature not compatible with PHP version indicated in project settings") @Override public String getDisplayName() { return Bundle.PHP71UnhandledError_displayName(); } @Override public void invoke(PHPRuleContext context, List<Error> errors) { PHPParseResult phpParseResult = (PHPParseResult) context.parserResult; if (phpParseResult.getProgram() == null) { return; } FileObject fileObject = phpParseResult.getSnapshot().getSource().getFileObject(); if (fileObject != null && appliesTo(fileObject)) { if (CancelSupport.getDefault().isCancelled()) { return; } CheckVisitor checkVisitor = new CheckVisitor(fileObject); phpParseResult.getProgram().accept(checkVisitor); if (CancelSupport.getDefault().isCancelled()) { return; } errors.addAll(checkVisitor.getErrors()); } } private static boolean appliesTo(FileObject fileObject) { return CodeUtils.isPhpVersionLessThan(fileObject, PhpVersion.PHP_71); } //~ Inner classes private static final class CheckVisitor extends DefaultVisitor { private final List<VerificationError> errors = new ArrayList<>(); private final FileObject fileObject; public CheckVisitor(FileObject fileObject) { this.fileObject = fileObject; } public Collection<VerificationError> getErrors() { return Collections.unmodifiableCollection(errors); } @Override public void visit(NullableType nullable) { if (CancelSupport.getDefault().isCancelled()) { return; } checkNullableType(nullable); super.visit(nullable); } @Override public void visit(CatchClause catchClause) { if (CancelSupport.getDefault().isCancelled()) { return; } checkMultiCatch(catchClause); super.visit(catchClause); } @Override public void visit(ConstantDeclaration node) { if (CancelSupport.getDefault().isCancelled()) { return; } if (!node.isGlobal()) { checkConstantVisibility(node); } super.visit(node); } @Override public void visit(ListVariable node) { if (CancelSupport.getDefault().isCancelled()) { return; } checkNewSyntax(node); checkKeyedList(node.getElements()); super.visit(node); } private void checkNullableType(NullableType nullableType) { if (nullableType != null) { createError(nullableType); } } private void checkMultiCatch(CatchClause catchClause) { List<Expression> classNames = catchClause.getClassNames(); if (classNames.size() > 1) { createError(catchClause); } } private void checkConstantVisibility(ConstantDeclaration node) { if (!BodyDeclaration.Modifier.isImplicitPublic(node.getModifier())) { createError(node); } } private void checkKeyedList(List<ArrayElement> elements) { // list("id" => $id, "name" => $name) = $data[0]; for (ArrayElement element : elements) { if (element.getKey() != null) { createError(element); break; } } } private void checkNewSyntax(ListVariable node) { // [$a, $b] = [1, 2]; if (node.getSyntaxType() == ListVariable.SyntaxType.NEW) { createError(node); } } private void createError(int startOffset, int endOffset) { errors.add(new PHP71VersionError(fileObject, startOffset, endOffset)); } private void createError(ASTNode node) { createError(node.getStartOffset(), node.getEndOffset()); } } private static final class PHP71VersionError extends VerificationError { private static final String KEY = "Php.Version.71"; // NOI18N private PHP71VersionError(FileObject fileObject, int startOffset, int endOffset) { super(fileObject, startOffset, endOffset); } @NbBundle.Messages("PHP71VersionError.displayName=Language feature not compatible with PHP version indicated in project settings") @Override public String getDisplayName() { return Bundle.PHP71VersionError_displayName(); } @NbBundle.Messages("PHP71VersionError.description=Detected language features not compatible with PHP version indicated in project settings") @Override public String getDescription() { return Bundle.PHP71VersionError_description(); } @Override public String getKey() { return KEY; } } }
2,989
1,986
/** * Create a sample BLE client that connects to a BLE server and then retrieves the current * characteristic value. It will then periodically update the value of the characteristic on the * remote server with the current time since boot. */ #include <esp_log.h> #include <string> #include <sstream> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> extern "C" { // See issue 1069: https://github.com/espressif/esp-idf/issues/1069 #include <esp_vfs_dev.h> } #include "BLEDevice.h" #include "Task.h" #include "sdkconfig.h" static const char* LOG_TAG = "SampleClientAndServer"; // See the following for generating UUIDs: // https://www.uuidgenerator.net/ // The remote service we wish to connect to. static BLEUUID serviceUUID("91bad492-b950-4226-aa2b-4ede9fa42f59"); // The characteristic of the remote service we are interested in. static BLEUUID charUUID("0d563a58-196a-48ce-ace2-dfec78acc814"); class MyServer: public Task { void run(void *data) { ESP_LOGD(LOG_TAG, "Starting to be a BLE Server"); BLEDevice::init("MYDEVICE"); BLEServer* pServer = BLEDevice::createServer(); BLEService* pService = pServer->createService(serviceUUID); BLECharacteristic* pCharacteristic = pService->createCharacteristic( charUUID, BLECharacteristic::PROPERTY_BROADCAST | BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_INDICATE ); pCharacteristic->setValue("Hello World!"); pService->start(); BLEAdvertising* pAdvertising = pServer->getAdvertising(); pAdvertising->addServiceUUID(pService->getUUID()); pAdvertising->start(); ESP_LOGD(LOG_TAG, "Advertising started!"); delay(1000000); } }; /** * Become a BLE client to a remote BLE server. We are passed in the address of the BLE server * as the input parameter when the task is created. */ class MyClient: public Task { void run(void* data) { BLEAddress* pAddress = (BLEAddress*)data; BLEClient* pClient = BLEDevice::createClient(); // Connect to the remove BLE Server. pClient->connect(*pAddress); // Obtain a reference to the service we are after in the remote BLE server. BLERemoteService* pRemoteService = pClient->getService(serviceUUID); if (pRemoteService == nullptr) { ESP_LOGD(LOG_TAG, "Failed to find our service UUID: %s", serviceUUID.toString().c_str()); return; } // Obtain a reference to the characteristic in the service of the remote BLE server. BLERemoteCharacteristic* pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID); if (pRemoteCharacteristic == nullptr) { ESP_LOGD(LOG_TAG, "Failed to find our characteristic UUID: %s", charUUID.toString().c_str()); return; } // Read the value of the characteristic. std::string value = pRemoteCharacteristic->readValue(); ESP_LOGD(LOG_TAG, "The characteristic value was: %s", value.c_str()); while(1) { // Set a new value of the characteristic ESP_LOGD(LOG_TAG, "Setting the new value"); std::ostringstream stringStream; struct timeval tv; gettimeofday(&tv, nullptr); stringStream << "Time since boot: " << tv.tv_sec; pRemoteCharacteristic->writeValue(stringStream.str()); FreeRTOS::sleep(1000); } pClient->disconnect(); ESP_LOGD(LOG_TAG, "%s", pClient->toString().c_str()); ESP_LOGD(LOG_TAG, "-- End of task"); } // run }; // MyClient /** * Scan for BLE servers and find the first one that advertises the service we are looking for. */ class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { /** * Called for each advertising BLE server. */ void onResult(BLEAdvertisedDevice advertisedDevice) { ESP_LOGD(LOG_TAG, "Advertised Device: %s", advertisedDevice.toString().c_str()); if (!advertisedDevice.haveServiceUUID()) { ESP_LOGD(LOG_TAG, "Found device is not advertising a service ... ignoring"); return; } if (advertisedDevice.getServiceUUID().equals(serviceUUID)) { advertisedDevice.getScan()->stop(); ESP_LOGD(LOG_TAG, "Found our device! address: %s", advertisedDevice.getAddress().toString().c_str()); MyClient* pMyClient = new MyClient(); pMyClient->setStackSize(18000); pMyClient->start(new BLEAddress(*advertisedDevice.getAddress().getNative())); return; } // Found our server ESP_LOGD(LOG_TAG, "Found device advertised %s which is not %s ... ignoring", advertisedDevice.getServiceUUID().toString().c_str(), serviceUUID.toString().c_str()); } // onResult }; // MyAdvertisedDeviceCallbacks /** * Perform the work of a sample BLE client. */ void SampleClientAndServer(void) { ESP_LOGD(LOG_TAG, "SampleClientAndServer starting"); esp_vfs_dev_uart_register(); int fd = open("/dev/uart/0", O_RDONLY); if (fd == -1) { ESP_LOGE(LOG_TAG, "Failed to open file %s", strerror(errno)); return; } ESP_LOGD(LOG_TAG, "Enter:"); ESP_LOGD(LOG_TAG, "C - Client"); ESP_LOGD(LOG_TAG, "S - Server"); bool isServer; while(1) { uint8_t val; ssize_t rc; // Read a character from the UART. Since the UART is non-blocking, we loop until we have // a character available. do { rc = read(fd, &val, 1); if (rc == -1) { //ESP_LOGE(LOG_TAG, "Failed to read file %s", strerror(errno)); FreeRTOS::sleep(100); //return; } } while(rc == -1); // See if the character is an indication of being a server or a client. if (val == 'c' || val == 'C') { isServer = false; break; } if (val == 's' || val == 'S') { isServer = true; break; } } close(fd); // Close the UART file as we don't need it any more. ESP_LOGD(LOG_TAG, "Chosen: %s", isServer?"Server":"Client"); if (isServer) { MyServer* pMyServer = new MyServer(); pMyServer->setStackSize(20000); pMyServer->start(); } else { BLEDevice::init(""); BLEScan *pBLEScan = BLEDevice::getScan(); pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); pBLEScan->setActiveScan(true); pBLEScan->start(15); } } // SampleClient
2,229
17,275
<filename>core/src/test/java/hudson/scheduler/CronTabEventualityTest.java package hudson.scheduler; import static org.junit.Assert.fail; import antlr.ANTLRException; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.GregorianCalendar; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.jvnet.hudson.test.For; import org.jvnet.hudson.test.Issue; @RunWith(Parameterized.class) @For({CronTab.class, Hash.class}) public class CronTabEventualityTest { @Parameterized.Parameters public static Collection<Object[]> parameters() { Collection<Object[]> parameters = new ArrayList<>(); parameters.add(new Object[]{"zero", Hash.zero()}); parameters.add(new Object[]{"seed1", Hash.from("seed1")}); parameters.add(new Object[]{"seed2", Hash.from("seed2")}); return parameters; } private Calendar createLimit(Calendar start, int field, int amount){ Calendar limit = (Calendar)start.clone(); limit.add(field, amount); return limit; } private String name; private Hash hash; public CronTabEventualityTest(String name, Hash hash) { this.name = name; this.hash = hash; } @Test @Issue("JENKINS-12388") public void testYearlyWillBeEventuallyTriggeredWithinOneYear() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.YEAR, 1); checkEventuality(start, "@yearly", limit); } @Test @Issue("JENKINS-12388") public void testAnnuallyWillBeEventuallyTriggeredWithinOneYear() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.YEAR, 1); checkEventuality(start, "@annually", limit); } @Test public void testMonthlyWillBeEventuallyTriggeredWithinOneMonth() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.MONTH, 1); checkEventuality(start, "@monthly", limit); } @Test public void testWeeklyWillBeEventuallyTriggeredWithinOneWeek() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.WEEK_OF_YEAR, 1); checkEventuality(start, "@weekly", limit); } @Test public void testDailyWillBeEventuallyTriggeredWithinOneDay() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.DAY_OF_MONTH, 1); checkEventuality(start, "@daily", limit); } @Test public void testMidnightWillBeEventuallyTriggeredWithinOneDay() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.DAY_OF_MONTH, 1); checkEventuality(start, "@midnight", limit); } @Test public void testHourlyWillBeEventuallyTriggeredWithinOneHour() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.HOUR, 1); checkEventuality(start, "@hourly", limit); } @Test public void testFirstDayOfMonthWillBeEventuallyTriggeredWithinOneMonth() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.MONTH, 1); checkEventuality(start, "H H 1 * *", limit); } @Test public void testFirstSundayOfMonthWillBeEventuallyTriggeredWithinOneMonthAndOneWeek() throws ANTLRException { Calendar start = new GregorianCalendar(2012, Calendar.JANUARY, 11, 22, 33); // Jan 11th 2012 22:33 Calendar limit = createLimit(start, Calendar.DAY_OF_MONTH, 31+7); // If both day of month and day of week are specified: // UNIX: triggered when either matches // Jenkins: triggered when both match checkEventuality(start, "H H 1-7 * 0", limit); } private void checkEventuality(Calendar start, String crontabFormat, Calendar limit) throws ANTLRException { CronTab cron = new CronTab(crontabFormat, hash); Calendar next = cron.ceil(start); if(next.after(limit)) { DateFormat f = DateFormat.getDateTimeInstance(); String msg = "Name: " + name + " Limit: " + f.format(limit.getTime()) + " Next: " + f.format(next.getTime()); fail(msg); } } }
1,926
310
#include "clar_libgit2.h" #include "patch/patch_common.h" static void verify_patch_id(const char *diff_content, const char *expected_id) { git_oid expected_oid, actual_oid; git_diff *diff; cl_git_pass(git_oid_fromstr(&expected_oid, expected_id)); cl_git_pass(git_diff_from_buffer(&diff, diff_content, strlen(diff_content))); cl_git_pass(git_diff_patchid(&actual_oid, diff, NULL)); cl_assert_equal_oid(&expected_oid, &actual_oid); git_diff_free(diff); } void test_diff_patchid__simple_commit(void) { verify_patch_id(PATCH_SIMPLE_COMMIT, "06094b1948b878b7d9ff7560b4eae672a014b0ec"); } void test_diff_patchid__filename_with_spaces(void) { verify_patch_id(PATCH_APPEND_NO_NL, "f0ba05413beaef743b630e796153839462ee477a"); } void test_diff_patchid__multiple_hunks(void) { verify_patch_id(PATCH_MULTIPLE_HUNKS, "81e26c34643d17f521e57c483a6a637e18ba1f57"); } void test_diff_patchid__multiple_files(void) { verify_patch_id(PATCH_MULTIPLE_FILES, "192d1f49d23f2004517963aecd3f8a6c467f50ff"); } void test_diff_patchid__same_diff_with_differing_whitespace_has_same_id(void) { const char *tabs = "diff --git a/file.txt b/file.txt\n" "index 8fecc09..1d43a92 100644\n" "--- a/file.txt\n" "+++ b/file.txt\n" "@@ -1 +1 @@\n" "-old text\n" "+ new text\n"; const char *spaces = "diff --git a/file.txt b/file.txt\n" "index 8fecc09..1d43a92 100644\n" "--- a/file.txt\n" "+++ b/file.txt\n" "@@ -1 +1 @@\n" "-old text\n" "+ new text\n"; const char *id = "11ef<PASSWORD>6<PASSWORD>"; verify_patch_id(tabs, id); verify_patch_id(spaces, id); }
778
348
{"nom":"Issy-les-Moulineaux","circ":"10ème circonscription","dpt":"Hauts-de-Seine","inscrits":45375,"abs":19009,"votants":26366,"blancs":517,"nuls":0,"exp":25849,"res":[{"nuance":"REM","nom":"<NAME>","voix":10951},{"nuance":"UDI","nom":"<NAME>","voix":5968},{"nuance":"DIV","nom":"M. <NAME>","voix":2024},{"nuance":"FI","nom":"<NAME>","voix":1940},{"nuance":"SOC","nom":"<NAME>","voix":1408},{"nuance":"ECO","nom":"Mme <NAME>","voix":1189},{"nuance":"FN","nom":"Mme <NAME>","voix":836},{"nuance":"DIV","nom":"Mme <NAME>","voix":282},{"nuance":"DVD","nom":"Mme <NAME>","voix":259},{"nuance":"COM","nom":"M. <NAME>","voix":220},{"nuance":"DVG","nom":"M. <NAME>","voix":219},{"nuance":"DLF","nom":"Mme <NAME>","voix":163},{"nuance":"DIV","nom":"M. <NAME>","voix":139},{"nuance":"EXG","nom":"Mme <NAME>","voix":96},{"nuance":"DIV","nom":"Mme <NAME>","voix":73},{"nuance":"DIV","nom":"<NAME>","voix":58},{"nuance":"ECO","nom":"<NAME>","voix":24}]}
379
12,278
// Copyright 2015-2019 <NAME> // // 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 <benchmark/benchmark.h> #include <boost/histogram/axis.hpp> #include <boost/histogram/axis/traits.hpp> #include <boost/histogram/detail/axes.hpp> #include <boost/mp11/algorithm.hpp> #include <tuple> #include <type_traits> #include <vector> #include "../test/throw_exception.hpp" #include "generator.hpp" #include <boost/assert.hpp> struct assert_check { assert_check() { BOOST_ASSERT(false); // don't run with asserts enabled } } _; using namespace boost::histogram; using reg = axis::regular<>; using integ = axis::integer<>; using var = axis::variable<>; using vector_of_variant = std::vector<axis::variant<reg, integ, var>>; template <class T, class U> auto make_storage(const U& axes) { return std::vector<T>(detail::bincount(axes), 0); } template <class T> auto make_strides(const T& axes) { std::vector<std::size_t> strides(detail::axes_rank(axes) + 1, 1); auto sit = strides.begin(); detail::for_each_axis(axes, [&](const auto& a) { *++sit *= axis::traits::extent(a); }); return strides; } template <class Axes, class Storage, class Tuple> void fill_b(const Axes& axes, Storage& storage, const Tuple& t) { using namespace boost::mp11; std::size_t stride = 1, index = 0; mp_for_each<mp_iota<mp_size<Tuple>>>([&](auto i) { const auto& a = boost::histogram::detail::axis_get<i>(axes); const auto& v = std::get<i>(t); index += (a.index(v) + 1) * stride; stride *= axis::traits::extent(a); }); ++storage[index]; } template <class Axes, class Storage, class Tuple> void fill_c(const Axes& axes, const std::size_t* strides, Storage& storage, const Tuple& t) { using namespace boost::mp11; std::size_t index = 0; assert(boost::histogram::detail::axes_rank(axes) == boost::histogram::detail::axes_rank(t)); mp_for_each<mp_iota<mp_size<Tuple>>>([&](auto i) { const auto& a = boost::histogram::detail::axis_get<i>(axes); const auto& v = std::get<i>(t); index += (a.index(v) + 1) * *strides++; }); ++storage[index]; } template <class T, class Distribution> static void fill_1d_a(benchmark::State& state) { auto axes = std::make_tuple(reg(100, 0, 1)); generator<Distribution> gen; auto storage = make_storage<T>(axes); for (auto _ : state) { const auto i = std::get<0>(axes).index(gen()); ++storage[i + 1]; } } template <class T, class Distribution> static void fill_1d_b(benchmark::State& state) { auto axes = std::make_tuple(reg(100, 0, 1)); generator<Distribution> gen; auto storage = make_storage<T>(axes); for (auto _ : state) { fill_b(axes, storage, std::forward_as_tuple(gen())); } } template <class T, class Distribution> static void fill_1d_c(benchmark::State& state) { auto axes = std::make_tuple(reg(100, 0, 1)); generator<Distribution> gen; auto storage = make_storage<T>(axes); auto strides = make_strides(axes); for (auto _ : state) { fill_c(axes, strides.data(), storage, std::forward_as_tuple(gen())); } } template <class T, class Distribution> static void fill_1d_c_dyn(benchmark::State& state) { auto axes = vector_of_variant({reg(100, 0, 1)}); generator<Distribution> gen; auto storage = make_storage<T>(axes); auto strides = make_strides(axes); for (auto _ : state) { fill_c(axes, strides.data(), storage, std::forward_as_tuple(gen())); } } template <class T, class Distribution> static void fill_2d_a(benchmark::State& state) { auto axes = std::make_tuple(reg(100, 0, 1), reg(100, 0, 1)); generator<Distribution> gen; auto storage = make_storage<T>(axes); for (auto _ : state) { const auto i0 = std::get<0>(axes).index(gen()); const auto i1 = std::get<1>(axes).index(gen()); const auto stride = axis::traits::extent(std::get<0>(axes)); ++storage[(i0 + 1) * stride + (i1 + 1)]; } } template <class T, class Distribution> static void fill_2d_b(benchmark::State& state) { auto axes = std::make_tuple(reg(100, 0, 1), reg(100, 0, 1)); generator<Distribution> gen; auto storage = make_storage<T>(axes); for (auto _ : state) { fill_b(axes, storage, std::forward_as_tuple(gen(), gen())); } } template <class T, class Distribution> static void fill_2d_c(benchmark::State& state) { auto axes = std::make_tuple(reg(100, 0, 1), reg(100, 0, 1)); generator<Distribution> gen; auto storage = make_storage<T>(axes); auto strides = make_strides(axes); assert(strides.size() == 3); assert(strides[0] == 1); assert(strides[1] == 102); for (auto _ : state) { fill_c(axes, strides.data(), storage, std::forward_as_tuple(gen(), gen())); } } template <class T, class Distribution> static void fill_2d_c_dyn(benchmark::State& state) { auto axes = vector_of_variant({reg(100, 0, 1), reg(100, 0, 1)}); generator<Distribution> gen; auto storage = make_storage<T>(axes); auto strides = make_strides(axes); assert(strides.size() == 3); assert(strides[0] == 1); assert(strides[1] == 102); for (auto _ : state) { fill_c(axes, strides.data(), storage, std::forward_as_tuple(gen(), gen())); } } BENCHMARK_TEMPLATE(fill_1d_a, int, uniform); BENCHMARK_TEMPLATE(fill_1d_a, double, uniform); BENCHMARK_TEMPLATE(fill_1d_b, double, uniform); BENCHMARK_TEMPLATE(fill_1d_c, double, uniform); BENCHMARK_TEMPLATE(fill_1d_c_dyn, double, uniform); BENCHMARK_TEMPLATE(fill_2d_a, double, uniform); BENCHMARK_TEMPLATE(fill_2d_b, double, uniform); BENCHMARK_TEMPLATE(fill_2d_c, double, uniform); BENCHMARK_TEMPLATE(fill_2d_c_dyn, double, uniform); BENCHMARK_TEMPLATE(fill_1d_a, double, normal); BENCHMARK_TEMPLATE(fill_1d_b, double, normal); BENCHMARK_TEMPLATE(fill_1d_c, double, normal); BENCHMARK_TEMPLATE(fill_2d_a, double, normal); BENCHMARK_TEMPLATE(fill_2d_b, double, normal); BENCHMARK_TEMPLATE(fill_2d_c, double, normal);
2,340
4,901
<reponame>VSaliy/j2objc /* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.timestamp; import java.io.IOException; import java.math.BigInteger; import java.util.Date; import sun.security.util.DerValue; import sun.security.util.ObjectIdentifier; import sun.security.x509.AlgorithmId; /** * This class provides the timestamp token info resulting from a successful * timestamp request, as defined in * <a href="http://www.ietf.org/rfc/rfc3161.txt">RFC 3161</a>. * * The timestampTokenInfo ASN.1 type has the following definition: * <pre> * * TSTInfo ::= SEQUENCE { * version INTEGER { v1(1) }, * policy TSAPolicyId, * messageImprint MessageImprint, * -- MUST have the same value as the similar field in * -- TimeStampReq * serialNumber INTEGER, * -- Time-Stamping users MUST be ready to accommodate integers * -- up to 160 bits. * genTime GeneralizedTime, * accuracy Accuracy OPTIONAL, * ordering BOOLEAN DEFAULT FALSE, * nonce INTEGER OPTIONAL, * -- MUST be present if the similar field was present * -- in TimeStampReq. In that case it MUST have the same value. * tsa [0] GeneralName OPTIONAL, * extensions [1] IMPLICIT Extensions OPTIONAL } * * Accuracy ::= SEQUENCE { * seconds INTEGER OPTIONAL, * millis [0] INTEGER (1..999) OPTIONAL, * micros [1] INTEGER (1..999) OPTIONAL } * * </pre> * * @since 1.5 * @see Timestamper * @author <NAME> */ public class TimestampToken { private int version; private ObjectIdentifier policy; private BigInteger serialNumber; private AlgorithmId hashAlgorithm; private byte[] hashedMessage; private Date genTime; private BigInteger nonce; /** * Constructs an object to store a timestamp token. * * @param status A buffer containing the ASN.1 BER encoding of the * TSTInfo element defined in RFC 3161. */ public TimestampToken(byte[] timestampTokenInfo) throws IOException { if (timestampTokenInfo == null) { throw new IOException("No timestamp token info"); } parse(timestampTokenInfo); } /** * Extract the date and time from the timestamp token. * * @return The date and time when the timestamp was generated. */ public Date getDate() { return genTime; } public AlgorithmId getHashAlgorithm() { return hashAlgorithm; } // should only be used internally, otherwise return a clone public byte[] getHashedMessage() { return hashedMessage; } public BigInteger getNonce() { return nonce; } public String getPolicyID() { return policy.toString(); } public BigInteger getSerialNumber() { return serialNumber; } /* * Parses the timestamp token info. * * @param timestampTokenInfo A buffer containing an ASN.1 BER encoded * TSTInfo. * @throws IOException The exception is thrown if a problem is encountered * while parsing. */ private void parse(byte[] timestampTokenInfo) throws IOException { DerValue tstInfo = new DerValue(timestampTokenInfo); if (tstInfo.tag != DerValue.tag_Sequence) { throw new IOException("Bad encoding for timestamp token info"); } // Parse version version = tstInfo.data.getInteger(); // Parse policy policy = tstInfo.data.getOID(); // Parse messageImprint DerValue messageImprint = tstInfo.data.getDerValue(); hashAlgorithm = AlgorithmId.parse(messageImprint.data.getDerValue()); hashedMessage = messageImprint.data.getOctetString(); // Parse serialNumber serialNumber = tstInfo.data.getBigInteger(); // Parse genTime genTime = tstInfo.data.getGeneralizedTime(); // Parse optional elements, if present while (tstInfo.data.available() > 0) { DerValue d = tstInfo.data.getDerValue(); if (d.tag == DerValue.tag_Integer) { // must be the nonce nonce = d.getBigInteger(); break; } // Additional fields: // Parse accuracy // Parse ordering // Parse tsa // Parse extensions } } }
2,341
435
/* * Copyright (C) 2014 <NAME> * * 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.h6ah4i.android.media.openslmediaplayer.methodtest; import java.util.ArrayList; import java.util.List; import junit.framework.TestSuite; import com.h6ah4i.android.media.IBasicMediaPlayer; import com.h6ah4i.android.media.IMediaPlayerFactory; import com.h6ah4i.android.media.openslmediaplayer.base.BasicMediaPlayerStateTestCaseBase; import com.h6ah4i.android.media.openslmediaplayer.utils.CompletionListenerObject; import com.h6ah4i.android.media.openslmediaplayer.utils.ErrorListenerObject; import com.h6ah4i.android.media.openslmediaplayer.testing.ParameterizedTestArgs; import com.h6ah4i.android.media.openslmediaplayer.testing.ParameterizedTestSuiteBuilder; public class BasicMediaPlayerTestCase_SetAuxEffectSendLevelMethod extends BasicMediaPlayerStateTestCaseBase { public static TestSuite buildTestSuite(Class<? extends IMediaPlayerFactory> factoryClazz) { List<TestParams> params = new ArrayList<TestParams>(); params.add(new TestParams(factoryClazz, 0.0f, true)); params.add(new TestParams(factoryClazz, 1.0f, true)); params.add(new TestParams(factoryClazz, -0.1f, false)); params.add(new TestParams(factoryClazz, 1.1f, false)); params.add(new TestParams(factoryClazz, Float.MIN_VALUE, true)); params.add(new TestParams(factoryClazz, Float.MAX_VALUE, false)); params.add(new TestParams(factoryClazz, Float.NEGATIVE_INFINITY, false)); params.add(new TestParams(factoryClazz, Float.POSITIVE_INFINITY, false)); params.add(new TestParams(factoryClazz, Float.NaN, false)); return ParameterizedTestSuiteBuilder.build( BasicMediaPlayerTestCase_SetAuxEffectSendLevelMethod.class, params); } private static final class TestParams extends BasicTestParams { public final float level; public final boolean valid; public TestParams( Class<? extends IMediaPlayerFactory> factoryClass, float level, boolean valid) { super(factoryClass); this.level = level; this.valid = valid; } @Override public String toString() { return super.toString() + ", " + level + ", " + valid; } } public BasicMediaPlayerTestCase_SetAuxEffectSendLevelMethod(ParameterizedTestArgs args) { super(args); } @Override protected IMediaPlayerFactory onCreateFactory() { return ((TestParams) getTestParams()).createFactory(getContext()); } private void expectsNoErrors(IBasicMediaPlayer player, TestParams params) { final String failmsg = "Level = " + params.level; Object sharedSyncObj = new Object(); ErrorListenerObject err = new ErrorListenerObject(sharedSyncObj, false); CompletionListenerObject comp = new CompletionListenerObject(sharedSyncObj); player.setOnErrorListener(err); player.setOnCompletionListener(comp); player.setAuxEffectSendLevel(params.level); if (comp.await(SHORT_EVENT_WAIT_DURATION)) { fail(failmsg + ", " + comp + ", " + err); } assertFalse(failmsg, comp.occurred()); assertFalse(failmsg, err.occurred()); } private void expectsErrorCallback(IBasicMediaPlayer player, TestParams params) { final String failmsg = "Level = " + params.level; Object sharedSyncObj = new Object(); ErrorListenerObject err = new ErrorListenerObject(sharedSyncObj, false); CompletionListenerObject comp = new CompletionListenerObject(sharedSyncObj); player.setOnErrorListener(err); player.setOnCompletionListener(comp); player.setAuxEffectSendLevel(params.level); if (!comp.await(determineWaitCompletionTime(player))) { // expects err.what = -22 (-EINVAL) fail(failmsg + ", " + comp + ", " + err); } assertTrue(failmsg, comp.occurred()); assertTrue(failmsg, err.occurred()); } private void expectsErrorCallbackWhenIllegalValue(IBasicMediaPlayer player, TestParams params) { if (params.valid) { expectsNoErrors(player, params); } else { expectsErrorCallback(player, params); } } private void expectsIllegalStateException(IBasicMediaPlayer player, TestParams params) { try { player.setAuxEffectSendLevel(params.level); } catch (IllegalStateException e) { return; } fail(); } @Override protected void onTestStateIdle(IBasicMediaPlayer player, Object args) throws Throwable { expectsNoErrors(player, (TestParams) args); } @Override protected void onTestStateInitialized(IBasicMediaPlayer player, Object args) throws Throwable { expectsNoErrors(player, (TestParams) args); } @Override protected void onTestStatePreparing(IBasicMediaPlayer player, Object args) throws Throwable { expectsNoErrors(player, (TestParams) args); } @Override protected void onTestStatePrepared(IBasicMediaPlayer player, Object args) throws Throwable { // expectsErrorCallbackWhenIllegalValue(player, (TestParams) args); expectsNoErrors(player, (TestParams) args); } @Override protected void onTestStateStarted(IBasicMediaPlayer player, Object args) throws Throwable { expectsErrorCallbackWhenIllegalValue(player, (TestParams) args); } @Override protected void onTestStatePaused(IBasicMediaPlayer player, Object args) throws Throwable { // XXX: On Android 5.0 with StandardMediaPlayer, error callback won't be // called expectsErrorCallbackWhenIllegalValue(player, (TestParams) args); } @Override protected void onTestStateStopped(IBasicMediaPlayer player, Object args) throws Throwable { expectsErrorCallbackWhenIllegalValue(player, (TestParams) args); } @Override protected void onTestStatePlaybackCompleted(IBasicMediaPlayer player, Object args) throws Throwable { expectsErrorCallbackWhenIllegalValue(player, (TestParams) args); } @Override protected void onTestStateErrorBeforePrepared(IBasicMediaPlayer player, Object args) throws Throwable { expectsNoErrors(player, (TestParams) args); } @Override protected void onTestStateErrorAfterPrepared(IBasicMediaPlayer player, Object args) throws Throwable { expectsNoErrors(player, (TestParams) args); } @Override protected void onTestStateEnd(IBasicMediaPlayer player, Object args) throws Throwable { expectsIllegalStateException(player, (TestParams) args); } }
2,719
335
<filename>C/Craft_noun.json { "word": "Craft", "definitions": [ "An activity involving skill in making things by hand.", "Work or objects made by hand.", "Skills involved in carrying out one's work.", "Denoting or relating to food or drink made in a traditional or non-mechanized way by an individual or a small company.", "The members of a skilled profession.", "The brotherhood of Freemasons.", "Skill used in deceiving others.", "A boat or ship.", "An aircraft or spaceship." ], "parts-of-speech": "Noun" }
220
874
package com.jnape.palatable.lambda.optics.prisms; import com.jnape.palatable.lambda.adt.Either; import com.jnape.palatable.lambda.adt.coproduct.CoProduct2; import com.jnape.palatable.lambda.optics.Prism; import static com.jnape.palatable.lambda.optics.Prism.simplePrism; /** * {@link Prism Prisms} for {@link Either}. */ public final class EitherPrism { private EitherPrism() { } /** * A {@link Prism} that focuses on the {@link Either#left(Object) left} value of an {@link Either}. * * @param <L> the left type * @param <R> the right type * @return the {@link Prism} */ public static <L, R> Prism.Simple<Either<L, R>, L> _left() { return simplePrism(CoProduct2::projectA, Either::left); } /** * A {@link Prism} that focuses on the {@link Either#right(Object) right} value of an {@link Either}. * * @param <L> the left type * @param <R> the right type * @return the {@link Prism} */ public static <L, R> Prism.Simple<Either<L, R>, R> _right() { return simplePrism(CoProduct2::projectB, Either::right); } }
451
313
// Copyright 2021 The AIBENCH Authors. 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. #include "aibench/port/env.h" #include <sstream> #include "aibench/utils/memory.h" #include "aibench/public/aibench.h" namespace aibench { namespace port { Status Env::AdviseFree(void *addr, size_t length) { return Status::UNSUPPORTED; } Status Env::GetCPUMaxFreq(std::vector<float> *max_freqs) { return Status::UNSUPPORTED; } Status Env::SchedSetAffinity(const std::vector<size_t> &cpu_ids) { return Status::UNSUPPORTED; } std::unique_ptr<MallocLogger> Env::NewMallocLogger( std::ostringstream *oss, const std::string &name) { return make_unique<MallocLogger>(); } } // namespace port } // namespace aibench
412
575
// Copyright (c) 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/safe_browsing_subresource_tab_helper.h" #include "base/memory/ptr_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/browser/safe_browsing/ui_manager.h" #include "components/security_interstitials/content/security_interstitial_tab_helper.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "net/base/net_errors.h" namespace safe_browsing { SafeBrowsingSubresourceTabHelper::~SafeBrowsingSubresourceTabHelper() {} void SafeBrowsingSubresourceTabHelper::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->GetNetErrorCode() == net::ERR_BLOCKED_BY_CLIENT) { safe_browsing::SafeBrowsingService* service = g_browser_process->safe_browsing_service(); if (!service) return; security_interstitials::UnsafeResource resource; scoped_refptr<safe_browsing::SafeBrowsingUIManager> manager = service->ui_manager(); if (manager->PopUnsafeResourceForURL(navigation_handle->GetURL(), &resource)) { safe_browsing::SafeBrowsingBlockingPage* blocking_page = safe_browsing::SafeBrowsingBlockingPage::CreateBlockingPage( manager.get(), navigation_handle->GetWebContents(), navigation_handle->GetURL(), resource, /*should_trigger_reporting=*/true); security_interstitials::SecurityInterstitialTabHelper:: AssociateBlockingPage(navigation_handle->GetWebContents(), navigation_handle->GetNavigationId(), base::WrapUnique(blocking_page)); } } } SafeBrowsingSubresourceTabHelper::SafeBrowsingSubresourceTabHelper( content::WebContents* web_contents) : WebContentsObserver(web_contents) {} WEB_CONTENTS_USER_DATA_KEY_IMPL(SafeBrowsingSubresourceTabHelper) } // namespace safe_browsing
888
734
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { HostedMidiInputDeviceNode::HostedMidiInputDeviceNode (InputDeviceInstance& idi, MidiInputDevice&, MidiMessageArray::MPESourceID msi, tracktion_graph::PlayHeadState&) : instance (idi), midiSourceID (msi) { } HostedMidiInputDeviceNode::~HostedMidiInputDeviceNode() { instance.removeConsumer (this); } tracktion_graph::NodeProperties HostedMidiInputDeviceNode::getNodeProperties() { tracktion_graph::NodeProperties props; props.hasMidi = true; return props; } void HostedMidiInputDeviceNode::prepareToPlay (const tracktion_graph::PlaybackInitialisationInfo& info) { sampleRate = info.sampleRate; instance.addConsumer (this); } bool HostedMidiInputDeviceNode::isReadyToProcess() { return true; } void HostedMidiInputDeviceNode::process (ProcessContext& pc) { SCOPED_REALTIME_CHECK const auto localTimeRange = tracktion_graph::sampleToTime (pc.referenceSampleRange, sampleRate).withStart (0.0); auto& destMidi = pc.buffers.midi; const std::lock_guard<tracktion_graph::RealTimeSpinLock> lock (bufferMutex); for (auto m : incomingMessages) if (localTimeRange.contains (m.getTimeStamp())) destMidi.add (m); // Subtract time from messages and trim any negative incomingMessages.addToTimestamps (-localTimeRange.getLength()); for (int i = incomingMessages.size(); --i >= 0;) if (incomingMessages[i].getTimeStamp() < 0.0) incomingMessages.remove (i); } void HostedMidiInputDeviceNode::handleIncomingMidiMessage (const juce::MidiMessage& message) { // Timestamps will be offsets form the next buffer in seconds const std::lock_guard<tracktion_graph::RealTimeSpinLock> lock (bufferMutex); incomingMessages.addMidiMessage (message, midiSourceID); } }
966
1,134
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ from test.unit.rules import BaseRuleTestCase from cfnlint.rules.resources.UniqueNames import UniqueNames # pylint: disable=E0401 class TestUniqueNames(BaseRuleTestCase): def setUp(self): super(TestUniqueNames, self).setUp() self.collection.register(UniqueNames()) def test_file_positive(self): self.helper_file_positive() def test_file_negative(self): self.helper_file_negative('test/fixtures/templates/bad/resources/uniqueNames.yaml', 1)
208
575
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_SCHEDULER_H_ #define CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_SCHEDULER_H_ #include <map> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "build/build_config.h" #include "content/common/content_export.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "third_party/blink/public/mojom/background_sync/background_sync.mojom.h" namespace content { class StoragePartitionImpl; // This contains the logic to schedule delayed processing of (periodic) // Background Sync registrations. // It keeps track of all storage partitions, and the soonest time we should // attempt to fire (periodic)sync events for it. class CONTENT_EXPORT BackgroundSyncScheduler : public base::RefCountedThreadSafe<BackgroundSyncScheduler, BrowserThread::DeleteOnUIThread> { public: static BackgroundSyncScheduler* GetFor(BrowserContext* browser_context); BackgroundSyncScheduler(); // Schedules delayed_processing for |sync_type| for |storage_partition|. // On non-Android platforms, runs |delayed_task| after |delay| has passed. // TODO(crbug.com/996166): Add logic to schedule browser wakeup on Android. // Must be called on the UI thread. virtual void ScheduleDelayedProcessing( StoragePartitionImpl* storage_partition, blink::mojom::BackgroundSyncType sync_type, base::TimeDelta delay, base::OnceClosure delayed_task); // Cancels delayed_processing for |sync_type| for |storage_partition|. // Must be called on the UI thread. virtual void CancelDelayedProcessing( StoragePartitionImpl* storage_partition, blink::mojom::BackgroundSyncType sync_type); private: virtual ~BackgroundSyncScheduler(); friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>; friend class base::DeleteHelper<BackgroundSyncScheduler>; friend class BackgroundSyncSchedulerTest; std::map<StoragePartitionImpl*, std::unique_ptr<base::OneShotTimer>>& GetDelayedProcessingInfoMap(blink::mojom::BackgroundSyncType sync_type); void RunDelayedTaskAndPruneInfoMap(blink::mojom::BackgroundSyncType sync_type, StoragePartitionImpl* storage_partition, base::OnceClosure delayed_task); #if defined(OS_ANDROID) void ScheduleOrCancelBrowserWakeupForSyncType( blink::mojom::BackgroundSyncType sync_type, StoragePartitionImpl* storage_partition); #endif std::map<StoragePartitionImpl*, std::unique_ptr<base::OneShotTimer>> delayed_processing_info_one_shot_; std::map<StoragePartitionImpl*, std::unique_ptr<base::OneShotTimer>> delayed_processing_info_periodic_; std::map<blink::mojom::BackgroundSyncType, base::TimeTicks> scheduled_wakeup_time_{ {blink::mojom::BackgroundSyncType::ONE_SHOT, base::TimeTicks::Max()}, {blink::mojom::BackgroundSyncType::PERIODIC, base::TimeTicks::Max()}, }; base::WeakPtrFactory<BackgroundSyncScheduler> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(BackgroundSyncScheduler); }; } // namespace content #endif // CONTENT_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_SCHEDULER_H_
1,228