max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
365
<gh_stars>100-1000 /* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "BKE_node.h" #include "NOD_geometry.h" #include "NOD_common.h" #include "node_common.h" #include "node_geometry_util.hh" void register_node_type_geo_group(void) { static bNodeType ntype; node_type_base_custom(&ntype, "GeometryNodeGroup", "Group", NODE_CLASS_GROUP, 0); ntype.type = NODE_GROUP; ntype.poll = geo_node_poll_default; ntype.poll_instance = node_group_poll_instance; ntype.insert_link = node_insert_link_default; ntype.update_internal_links = node_update_internal_links_default; ntype.rna_ext.srna = RNA_struct_find("GeometryNodeGroup"); BLI_assert(ntype.rna_ext.srna != nullptr); RNA_struct_blender_type_set(ntype.rna_ext.srna, &ntype); node_type_socket_templates(&ntype, nullptr, nullptr); node_type_size(&ntype, 140, 60, 400); node_type_label(&ntype, node_group_label); node_type_group_update(&ntype, node_group_update); nodeRegisterType(&ntype); }
546
559
<filename>examples/proxy/src/main/java/com/netflix/msl/ProxyMslException.java /** * Copyright (c) 2015 Netflix, Inc. All rights reserved. */ package com.netflix.msl; /** * <p>Thrown by the proxy when a MSL exception has occurred.</p> * * @author <NAME> <<EMAIL>> */ public class ProxyMslException extends ProxyException { private static final long serialVersionUID = 2621303915896379638L; /** * <p>Creates a new {@code ProxyMslException} with the specified detail * message and cause.</p> * * @param message the detail message. * @param cause the cause. May be {@code null}. */ public ProxyMslException(final String message, final MslException cause) { super(message, cause); } }
259
678
<filename>iOSOpenDev/frameworks/WebCore.framework/Headers/WebCoreViewFactory.h /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/WebCore.framework/WebCore */ #import <WebCore/XXUnknownSuperclass.h> @interface WebCoreViewFactory : XXUnknownSuperclass { } + (id)sharedFactory; // 0x6dc9 - (id)init; // 0x6dd9 @end
130
777
<reponame>google-ar/chromium // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_COMMON_SYSTEM_BRIGHTNESS_CONTROL_DELEGATE_H_ #define ASH_COMMON_SYSTEM_BRIGHTNESS_CONTROL_DELEGATE_H_ #include "base/callback.h" namespace ui { class Accelerator; } // namespace ui namespace ash { // Delegate for controlling the brightness. class BrightnessControlDelegate { public: virtual ~BrightnessControlDelegate() {} // Handles an accelerator-driven request to decrease or increase the screen // brightness. virtual void HandleBrightnessDown(const ui::Accelerator& accelerator) = 0; virtual void HandleBrightnessUp(const ui::Accelerator& accelerator) = 0; // Requests that the brightness be set to |percent|, in the range // [0.0, 100.0]. |gradual| specifies whether the transition to the new // brightness should be animated or instantaneous. virtual void SetBrightnessPercent(double percent, bool gradual) = 0; // Asynchronously invokes |callback| with the current brightness, in the range // [0.0, 100.0]. virtual void GetBrightnessPercent( const base::Callback<void(double)>& callback) = 0; }; } // namespace ash #endif // ASH_COMMON_SYSTEM_BRIGHTNESS_CONTROL_DELEGATE_H_
414
2,603
<filename>FreeRTOS/Demo/RX600_RX64M_RSK_Renesas_e2studio/Source/Renesas_Code/RegisterWriteProtect.c /* * RegisterWriteProtect.c * * Created on: 4 Mar 2014 * Author: WarnerR */ #include "../iodefine.h" #include "stdint.h" #define PRC0_BIT 0x0001 #define PRC1_BIT 0x0002 #define PRC3_BIT 0x0008 void EnablePRCR( uint16_t protect ) { /* * PRCR Bit Register to be Protected * ----------------------------------------------------------------------------------------------------------------------------------------- * PRC0 Registers related to the clock generation circuit: * SCKCR, SCKCR2, SCKCR3, PLLCR, PLLCR2, BCKCR, MOSCCR, SOSCCR, LOCOCR, ILOCOCR, HOCOCR, HOCOCR2, OSTDCR, OSTDSR * * PRC1 Registers related to the operating modes: * SYSCR0, SYSCR1 * * Registers related to the low power consumption functions: * SBYCR, MSTPCRA, MSTPCRB, MSTPCRC, MSTPCRD, OPCCR, RSTCKCR, DPSBYCR, DPSIER0 to DPSIER3, DPSIFR0 to DPSIFR3, DPSIEGR0 to DPSIEGR3 * * Registers related to clock generation circuit: * MOSCWTCR, SOSCWTCR, MOFCR, HOCOPCR * * Software reset register: * SWRR * * PRC3 Registers related to the LVD: * LVCMPCR, LVDLVLR, LVD1CR0, LVD1CR1, LVD1SR, LVD2CR0, LVD2CR1, LVD2SR */ SYSTEM.PRCR.WORD = (uint16_t)( 0xA500 | protect ); } void DisablePRCR( uint16_t protect ) { /* * PRCR Bit Register to be Protected * ----------------------------------------------------------------------------------------------------------------------------------------- * PRC0 Registers related to the clock generation circuit: * SCKCR, SCKCR2, SCKCR3, PLLCR, PLLCR2, BCKCR, MOSCCR, SOSCCR, LOCOCR, ILOCOCR, HOCOCR, HOCOCR2, OSTDCR, OSTDSR * * PRC1 Registers related to the operating modes: * SYSCR0, SYSCR1 * * Registers related to the low power consumption functions: * SBYCR, MSTPCRA, MSTPCRB, MSTPCRC, MSTPCRD, OPCCR, RSTCKCR, DPSBYCR, DPSIER0 to DPSIER3, DPSIFR0 to DPSIFR3, DPSIEGR0 to DPSIEGR3 * * Registers related to clock generation circuit: * MOSCWTCR, SOSCWTCR, MOFCR, HOCOPCR * * Software reset register: * SWRR * * PRC3 Registers related to the LVD: * LVCMPCR, LVDLVLR, LVD1CR0, LVD1CR1, LVD1SR, LVD2CR0, LVD2CR1, LVD2SR */ uint16_t current_value; current_value = (uint16_t)( SYSTEM.PRCR.WORD & 0x00ff ); current_value = (uint16_t)( current_value & ~protect ); SYSTEM.PRCR.WORD = (uint16_t)( 0xA500 | current_value ); }
1,112
2,003
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "load_balancer/cost_functions.h" #include <algorithm> #include <vector> namespace tera { namespace load_balancer { MoveCountCostFunction::MoveCountCostFunction(const LBOptions& options) : CostFunction(options, "MoveCountCostFunction"), kExpensiveCost(1000000), tablet_max_move_num_(options.tablet_max_move_num) { SetWeight(options.move_count_cost_weight); } MoveCountCostFunction::~MoveCountCostFunction() {} double MoveCountCostFunction::Cost() { double cost = cluster_->tablet_moved_num_; if (cost > static_cast<double>(tablet_max_move_num_)) { // return an expensive cost VLOG(20) << "[lb] reach max move num limit: " << tablet_max_move_num_; return kExpensiveCost; } return Scale(0, std::max(cluster_->tablet_num_, tablet_max_move_num_), cost); } TabletCountCostFunction::TabletCountCostFunction(const LBOptions& options) : CostFunction(options, "TabletCountCostFunction") { SetWeight(options.tablet_count_cost_weight); } TabletCountCostFunction::~TabletCountCostFunction() {} double TabletCountCostFunction::Cost() { std::vector<double> tablet_nums_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { tablet_nums_per_node.emplace_back(cluster_->tablets_per_node_[i].size()); } return ScaleFromArray(tablet_nums_per_node); } SizeCostFunction::SizeCostFunction(const LBOptions& options) : CostFunction(options, "SizeCostFunction") { SetWeight(options.size_cost_weight); } SizeCostFunction::~SizeCostFunction() {} double SizeCostFunction::Cost() { std::vector<double> size_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { size_per_node.emplace_back(cluster_->size_per_node_[i]); } return ScaleFromArray(size_per_node); } FlashSizeCostFunction::FlashSizeCostFunction(const LBOptions& options) : CostFunction(options, "FlashSizeCostFunction") { SetWeight(options.flash_size_cost_weight); } FlashSizeCostFunction::~FlashSizeCostFunction() {} double FlashSizeCostFunction::Cost() { std::vector<double> flash_size_percent_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { uint64_t node_flash_capacity = cluster_->nodes_[i]->tablet_node_ptr->GetPersistentCacheSize(); if (node_flash_capacity == 0) { // skip the node which does not has ssd continue; } assert(node_flash_capacity > 0); flash_size_percent_per_node.emplace_back(100.0 * cluster_->flash_size_per_node_[i] / node_flash_capacity); } return ScaleFromArray(flash_size_percent_per_node); } ReadLoadCostFunction::ReadLoadCostFunction(const LBOptions& options) : CostFunction(options, "ReadLoadCostFunction") { SetWeight(options.read_load_cost_weight); } ReadLoadCostFunction::~ReadLoadCostFunction() {} double ReadLoadCostFunction::Cost() { std::vector<double> read_load_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { read_load_per_node.emplace_back(cluster_->read_load_per_node_[i]); } return ScaleFromArray(read_load_per_node); } WriteLoadCostFunction::WriteLoadCostFunction(const LBOptions& options) : CostFunction(options, "WriteLoadCostFunction") { SetWeight(options.write_load_cost_weight); } WriteLoadCostFunction::~WriteLoadCostFunction() {} double WriteLoadCostFunction::Cost() { std::vector<double> write_load_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { write_load_per_node.emplace_back(cluster_->write_load_per_node_[i]); } return ScaleFromArray(write_load_per_node); } ScanLoadCostFunction::ScanLoadCostFunction(const LBOptions& options) : CostFunction(options, "ScanLoadCostFunction") { SetWeight(options.scan_load_cost_weight); } ScanLoadCostFunction::~ScanLoadCostFunction() {} double ScanLoadCostFunction::Cost() { std::vector<double> scan_load_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { scan_load_per_node.emplace_back(cluster_->scan_load_per_node_[i]); } return ScaleFromArray(scan_load_per_node); } LReadCostFunction::LReadCostFunction(const LBOptions& options) : CostFunction(options, "LReadCostFunction") { SetWeight(options.lread_cost_weight); } LReadCostFunction::~LReadCostFunction() {} double LReadCostFunction::Cost() { std::vector<double> lread_per_node; for (uint32_t i = 0; i < cluster_->tablet_node_num_; ++i) { lread_per_node.emplace_back(cluster_->lread_per_node_[i]); } return ScaleFromArray(lread_per_node); } } // namespace load_balancer } // namespace tera
1,724
1,886
from compiler.errors import TypedSyntaxError from compiler.static.types import ( TYPED_INT8, TYPED_INT16, PRIM_OP_DIV_INT, PRIM_OP_ADD_INT, ) from .common import StaticTestBase try: import cinderjit except ImportError: cinderjit = None class BinopTests(StaticTestBase): def test_pow_of_int64s_returns_double(self): codestr = """ from __static__ import int64 def foo(): x: int64 = 0 y: int64 = 1 z: int64 = x ** y """ with self.assertRaisesRegex( TypedSyntaxError, "double cannot be assigned to int64" ): self.compile(codestr, modname="foo") def test_int_binop(self): tests = [ ("int8", 1, 2, "/", 0), ("int8", 4, 2, "/", 2), ("int8", 4, -2, "/", -2), ("uint8", 0xFF, 0x7F, "/", 2), ("int16", 4, -2, "/", -2), ("uint16", 0xFF, 0x7F, "/", 2), ("uint32", 0xFFFF, 0x7FFF, "/", 2), ("int32", 4, -2, "/", -2), ("uint32", 0xFF, 0x7F, "/", 2), ("uint32", 0xFFFFFFFF, 0x7FFFFFFF, "/", 2), ("int64", 4, -2, "/", -2), ("uint64", 0xFF, 0x7F, "/", 2), ("uint64", 0xFFFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, "/", 2), ("int8", 1, -2, "-", 3), ("int8", 1, 2, "-", -1), ("int16", 1, -2, "-", 3), ("int16", 1, 2, "-", -1), ("int32", 1, -2, "-", 3), ("int32", 1, 2, "-", -1), ("int64", 1, -2, "-", 3), ("int64", 1, 2, "-", -1), ("int8", 1, -2, "*", -2), ("int8", 1, 2, "*", 2), ("int16", 1, -2, "*", -2), ("int16", 1, 2, "*", 2), ("int32", 1, -2, "*", -2), ("int32", 1, 2, "*", 2), ("int64", 1, -2, "*", -2), ("int64", 1, 2, "*", 2), ("int8", 1, -2, "&", 0), ("int8", 1, 3, "&", 1), ("int16", 1, 3, "&", 1), ("int16", 1, 3, "&", 1), ("int32", 1, 3, "&", 1), ("int32", 1, 3, "&", 1), ("int64", 1, 3, "&", 1), ("int64", 1, 3, "&", 1), ("int8", 1, 2, "|", 3), ("uint8", 1, 2, "|", 3), ("int16", 1, 2, "|", 3), ("uint16", 1, 2, "|", 3), ("int32", 1, 2, "|", 3), ("uint32", 1, 2, "|", 3), ("int64", 1, 2, "|", 3), ("uint64", 1, 2, "|", 3), ("int8", 1, 3, "^", 2), ("uint8", 1, 3, "^", 2), ("int16", 1, 3, "^", 2), ("uint16", 1, 3, "^", 2), ("int32", 1, 3, "^", 2), ("uint32", 1, 3, "^", 2), ("int64", 1, 3, "^", 2), ("uint64", 1, 3, "^", 2), ("int8", 1, 3, "%", 1), ("uint8", 1, 3, "%", 1), ("int16", 1, 3, "%", 1), ("uint16", 1, 3, "%", 1), ("int32", 1, 3, "%", 1), ("uint32", 1, 3, "%", 1), ("int64", 1, 3, "%", 1), ("uint64", 1, 3, "%", 1), ("int8", 1, -3, "%", 1), ("uint8", 1, 0xFF, "%", 1), ("int16", 1, -3, "%", 1), ("uint16", 1, 0xFFFF, "%", 1), ("int32", 1, -3, "%", 1), ("uint32", 1, 0xFFFFFFFF, "%", 1), ("int64", 1, -3, "%", 1), ("uint64", 1, 0xFFFFFFFFFFFFFFFF, "%", 1), ("int8", 1, 2, "<<", 4), ("uint8", 1, 2, "<<", 4), ("int16", 1, 2, "<<", 4), ("uint16", 1, 2, "<<", 4), ("int32", 1, 2, "<<", 4), ("uint32", 1, 2, "<<", 4), ("int64", 1, 2, "<<", 4), ("uint64", 1, 2, "<<", 4), ("int8", 4, 1, ">>", 2), ("int8", -1, 1, ">>", -1), ("uint8", 0xFF, 1, ">>", 127), ("int16", 4, 1, ">>", 2), ("int16", -1, 1, ">>", -1), ("uint16", 0xFFFF, 1, ">>", 32767), ("int32", 4, 1, ">>", 2), ("int32", -1, 1, ">>", -1), ("uint32", 0xFFFFFFFF, 1, ">>", 2147483647), ("int64", 4, 1, ">>", 2), ("int64", -1, 1, ">>", -1), ("uint64", 0xFFFFFFFFFFFFFFFF, 1, ">>", 9223372036854775807), ("int64", 2, 2, "**", 4.0, "double"), ("int16", -1, 1, "**", -1, "double"), ("int32", -1, 1, "**", -1, "double"), ("int64", -1, 1, "**", -1, "double"), ("int64", -2, -3, "**", -0.125, "double"), ("uint8", 0xFF, 2, "**", float(0xFF * 0xFF), "double"), ("uint16", 0xFFFF, 2, "**", float(0xFFFF * 0xFFFF), "double"), ("uint32", 0xFFFFFFFF, 2, "**", float(0xFFFFFFFF * 0xFFFFFFFF), "double"), ( "uint64", 0xFFFFFFFFFFFFFFFF, 1, "**", float(0xFFFFFFFFFFFFFFFF), "double", ), ] for type, x, y, op, res, *output_type_option in tests: if len(output_type_option) == 0: output_type = type else: output_type = output_type_option[0] codestr = f""" from __static__ import {type}, box from __static__ import {output_type} def testfunc(tst): x: {type} = {x} y: {type} = {y} if tst: x = x + 1 y = y + 2 z: {output_type} = x {op} y return box(z), box(x {op} y) """ with self.subTest(type=type, x=x, y=y, op=op, res=res): with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual( f(False), (res, res), f"{type} {x} {op} {y} {res} {output_type}" ) def test_primitive_arithmetic(self): cases = [ ("int8", 127, "*", 1, 127), ("int8", -64, "*", 2, -128), ("int8", 0, "*", 4, 0), ("uint8", 51, "*", 5, 255), ("uint8", 5, "*", 0, 0), ("int16", 3123, "*", -10, -31230), ("int16", -32767, "*", -1, 32767), ("int16", -32768, "*", 1, -32768), ("int16", 3, "*", 0, 0), ("uint16", 65535, "*", 1, 65535), ("uint16", 0, "*", 4, 0), ("int32", (1 << 31) - 1, "*", 1, (1 << 31) - 1), ("int32", -(1 << 30), "*", 2, -(1 << 31)), ("int32", 0, "*", 1, 0), ("uint32", (1 << 32) - 1, "*", 1, (1 << 32) - 1), ("uint32", 0, "*", 4, 0), ("int64", (1 << 63) - 1, "*", 1, (1 << 63) - 1), ("int64", -(1 << 62), "*", 2, -(1 << 63)), ("int64", 0, "*", 1, 0), ("uint64", (1 << 64) - 1, "*", 1, (1 << 64) - 1), ("uint64", 0, "*", 4, 0), ("int8", 127, "//", 4, 31), ("int8", -128, "//", 4, -32), ("int8", 0, "//", 4, 0), ("uint8", 255, "//", 5, 51), ("uint8", 0, "//", 5, 0), ("int16", 32767, "//", -1000, -32), ("int16", -32768, "//", -1000, 32), ("int16", 0, "//", 4, 0), ("uint16", 65535, "//", 5, 13107), ("uint16", 0, "//", 4, 0), ("int32", (1 << 31) - 1, "//", (1 << 31) - 1, 1), ("int32", -(1 << 31), "//", 1, -(1 << 31)), ("int32", 0, "//", 1, 0), ("uint32", (1 << 32) - 1, "//", 500, 8589934), ("uint32", 0, "//", 4, 0), ("int64", (1 << 63) - 1, "//", 2, (1 << 62) - 1), ("int64", -(1 << 63), "//", 2, -(1 << 62)), ("int64", 0, "//", 1, 0), ("uint64", (1 << 64) - 1, "//", (1 << 64) - 1, 1), ("uint64", 0, "//", 4, 0), ("int8", 127, "%", 4, 3), ("int8", -128, "%", 4, 0), ("int8", 0, "%", 4, 0), ("uint8", 255, "%", 6, 3), ("uint8", 0, "%", 5, 0), ("int16", 32767, "%", -1000, 767), ("int16", -32768, "%", -1000, -768), ("int16", 0, "%", 4, 0), ("uint16", 65535, "%", 7, 1), ("uint16", 0, "%", 4, 0), ("int32", (1 << 31) - 1, "%", (1 << 31) - 1, 0), ("int32", -(1 << 31), "%", 1, 0), ("int32", 0, "%", 1, 0), ("uint32", (1 << 32) - 1, "%", 500, 295), ("uint32", 0, "%", 4, 0), ("int64", (1 << 63) - 1, "%", 2, 1), ("int64", -(1 << 63), "%", 2, 0), ("int64", 0, "%", 1, 0), ("uint64", (1 << 64) - 1, "%", (1 << 64) - 1, 0), ("uint64", 0, "%", 4, 0), ] for typ, a, op, b, res in cases: for const in ["noconst", "constfirst", "constsecond"]: if const == "noconst": codestr = f""" from __static__ import {typ} def f(a: {typ}, b: {typ}) -> {typ}: return a {op} b """ elif const == "constfirst": codestr = f""" from __static__ import {typ} def f(b: {typ}) -> {typ}: return {a} {op} b """ elif const == "constsecond": codestr = f""" from __static__ import {typ} def f(a: {typ}) -> {typ}: return a {op} {b} """ with self.subTest(typ=typ, a=a, op=op, b=b, res=res, const=const): with self.in_module(codestr) as mod: f = mod.f act = None if const == "noconst": act = f(a, b) elif const == "constfirst": act = f(b) elif const == "constsecond": act = f(a) self.assertEqual(act, res) def test_int_binop_type_context(self): codestr = f""" from __static__ import box, int8, int16 def f(x: int8, y: int8) -> int: z: int16 = x * y return box(z) """ with self.in_module(codestr) as mod: f = mod.f self.assertInBytecode( f, "CONVERT_PRIMITIVE", TYPED_INT8 | (TYPED_INT16 << 4) ) self.assertEqual(f(120, 120), 14400) def test_mixed_binop(self): with self.assertRaisesRegex( TypedSyntaxError, "cannot add int64 and Literal\\[1\\]" ): self.bind_module( """ from __static__ import ssize_t def f(): x: ssize_t = 1 y = 1 x + y """ ) with self.assertRaisesRegex( TypedSyntaxError, "cannot add Literal\\[1\\] and int64" ): self.bind_module( """ from __static__ import ssize_t def f(): x: ssize_t = 1 y = 1 y + x """ ) def test_mixed_binop_okay(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 1 y = x + 1 return box(y) """ with self.in_module(codestr) as mod: f = mod.f self.assertEqual(f(), 2) def test_mixed_binop_okay_1(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 1 y = 1 + x return box(y) """ with self.in_module(codestr) as mod: f = mod.f self.assertEqual(f(), 2) def test_inferred_primitive_type(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 1 y = x return box(y) """ with self.in_module(codestr) as mod: f = mod.f self.assertEqual(f(), 1) def test_mixed_binop_sign(self): """mixed signed/unsigned ops should be promoted to signed""" codestr = """ from __static__ import int8, uint8, box def testfunc(): x: uint8 = 42 y: int8 = 2 return box(x / y) """ code = self.compile(codestr) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_DIV_INT) with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 21) codestr = """ from __static__ import int8, uint8, box def testfunc(): x: int8 = 42 y: uint8 = 2 return box(x / y) """ code = self.compile(codestr) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_DIV_INT) with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 21) codestr = """ from __static__ import uint32, box def testfunc(): x: uint32 = 2 a = box(x / -2) return box(x ** -2) """ with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 0.25) codestr = """ from __static__ import int32, box def testfunc(): x: int32 = 2 return box(x ** -2) """ with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 0.25) codestr = """ from __static__ import uint32, box def testfunc(): x: uint32 = 2 return box(x ** -2) """ with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 0.25) codestr = """ from __static__ import int8, uint8, box def testfunc(): x: int8 = 4 y: uint8 = 2 return box(x ** y) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot pow int8 and uint8"): self.compile(codestr) codestr = """ from __static__ import int8, uint8, box def testfunc(): x: uint8 = 2 y: int8 = -3 return box(x ** y) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot pow uint8 and int8"): self.compile(codestr) codestr = """ from __static__ import uint8, box, double def testfunc(): x: uint8 = 2 y: double = -3.0 return box(x ** y) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot pow uint8 and double"): self.compile(codestr) def test_double_binop(self): tests = [ (1.732, 2.0, "+", 3.732), (1.732, 2.0, "-", -0.268), (1.732, 2.0, "/", 0.866), (1.732, 2.0, "*", 3.464), (1.732, 2, "+", 3.732), (2.5, 2, "**", 6.25), (2.5, 2.5, "**", 9.882117688026186), ] if cinderjit is not None: # test for division by zero tests.append((1.732, 0.0, "/", float("inf"))) for x, y, op, res in tests: codestr = f""" from __static__ import double, box def testfunc(tst): x: double = {x} y: double = {y} z: double = x {op} y return box(z) """ with self.subTest(type=type, x=x, y=y, op=op, res=res): with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(False), res, f"{type} {x} {op} {y} {res}") def test_double_binop_with_literal(self): codestr = f""" from __static__ import double, unbox def f(): y: double = 1.2 y + 1.0 """ f = self.run_code(codestr)["f"] f() def test_subclass_binop(self): codestr = """ class C: pass class D(C): pass def f(x: C, y: D): return x + y """ code = self.compile(codestr, modname="foo") f = self.find_code(code, "f") self.assertInBytecode(f, "BINARY_ADD") def test_mixed_add_reversed(self): codestr = """ from __static__ import int8, uint8, int64, box, int16 def testfunc(tst=False): x: int8 = 42 y: int16 = 2 if tst: x += 1 y += 1 return box(y + x) """ code = self.compile(codestr) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 44) def test_mixed_tri_add(self): codestr = """ from __static__ import int8, uint8, int64, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 z: int64 = 3 if tst: x += 1 y += 1 return box(x + y + z) """ code = self.compile(codestr) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) with self.in_module(codestr) as mod: f = mod.testfunc self.assertEqual(f(), 47) def test_mixed_tri_add_unsigned(self): """promote int/uint to int, can't add to uint64""" codestr = """ from __static__ import int8, uint8, uint64, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 z: uint64 = 3 return box(x + y + z) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot add int16 and uint64"): self.compile(codestr) def test_literal_int_binop_inferred_type(self): """primitive literal doesn't wrongly carry through arithmetic""" for rev in [False, True]: with self.subTest(rev=rev): op = "1 + x" if rev else "x + 1" codestr = f""" from __static__ import int64 def f(x: int64): reveal_type({op}) """ self.type_error(codestr, "'int64'", f"reveal_type({op})") def test_error_type_ctx_left_operand_mismatch(self): codestr = f""" from __static__ import int64 def f(k: int64): l = [1, 2, 3] # slices cannot be primitives, so this is invalid l[:k + 1] = [0] return l """ self.type_error(codestr, "int64 cannot be assigned to dynamic", f"k + 1")
11,832
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search/background/ntp_background_service.h" #include <utility> #include <vector> #include "base/run_loop.h" #include "base/test/bind_test_util.h" #include "base/test/scoped_task_environment.h" #include "chrome/browser/search/background/ntp_background_data.h" #include "content/public/test/test_browser_thread_bundle.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" using testing::Eq; namespace { // The options to be added to end of an image URL, specifying resolution, etc. constexpr char kImageOptions[] = "=imageOptions"; } // namespace class NtpBackgroundServiceTest : public testing::Test { public: NtpBackgroundServiceTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), test_shared_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)) {} ~NtpBackgroundServiceTest() override {} void SetUp() override { testing::Test::SetUp(); service_ = std::make_unique<NtpBackgroundService>( test_shared_loader_factory_, base::nullopt, base::nullopt, kImageOptions); } void SetUpResponseWithData(const GURL& load_url, const std::string& response) { test_url_loader_factory_.SetInterceptor(base::BindLambdaForTesting( [&](const network::ResourceRequest& request) {})); test_url_loader_factory_.AddResponse(load_url.spec(), response); } void SetUpResponseWithNetworkError(const GURL& load_url) { test_url_loader_factory_.AddResponse( load_url, network::ResourceResponseHead(), std::string(), network::URLLoaderCompletionStatus(net::HTTP_NOT_FOUND)); } NtpBackgroundService* service() { return service_.get(); } private: // Required to run tests from UI and threads. content::TestBrowserThreadBundle thread_bundle_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; std::unique_ptr<NtpBackgroundService> service_; }; TEST_F(NtpBackgroundServiceTest, CollectionInfoNetworkError) { SetUpResponseWithNetworkError(service()->GetCollectionsLoadURLForTesting()); ASSERT_TRUE(service()->collection_info().empty()); base::RunLoop loop; service()->FetchCollectionInfo(); loop.RunUntilIdle(); ASSERT_TRUE(service()->collection_info().empty()); } TEST_F(NtpBackgroundServiceTest, BadCollectionsResponse) { SetUpResponseWithData(service()->GetCollectionsLoadURLForTesting(), "bad serialized GetCollectionsResponse"); ASSERT_TRUE(service()->collection_info().empty()); base::RunLoop loop; service()->FetchCollectionInfo(); loop.RunUntilIdle(); EXPECT_TRUE(service()->collection_info().empty()); } TEST_F(NtpBackgroundServiceTest, GoodCollectionsResponse) { ntp::background::Collection collection; collection.set_collection_id("shapes"); collection.set_collection_name("Shapes"); collection.add_preview()->set_image_url("https://wallpapers.co/some_image"); ntp::background::GetCollectionsResponse response; *response.add_collections() = collection; std::string response_string; response.SerializeToString(&response_string); SetUpResponseWithData(service()->GetCollectionsLoadURLForTesting(), response_string); ASSERT_TRUE(service()->collection_info().empty()); base::RunLoop loop; service()->FetchCollectionInfo(); loop.RunUntilIdle(); CollectionInfo collection_info; collection_info.collection_id = collection.collection_id(); collection_info.collection_name = collection.collection_name(); collection_info.preview_image_url = GURL(collection.preview(0).image_url()); EXPECT_FALSE(service()->collection_info().empty()); EXPECT_THAT(service()->collection_info().at(0), Eq(collection_info)); } TEST_F(NtpBackgroundServiceTest, CollectionImagesNetworkError) { SetUpResponseWithNetworkError(service()->GetImagesURLForTesting()); ASSERT_TRUE(service()->collection_images().empty()); base::RunLoop loop; service()->FetchCollectionImageInfo("shapes"); loop.RunUntilIdle(); ASSERT_TRUE(service()->collection_images().empty()); } TEST_F(NtpBackgroundServiceTest, BadCollectionImagesResponse) { SetUpResponseWithData(service()->GetImagesURLForTesting(), "bad serialized GetImagesInCollectionResponse"); ASSERT_TRUE(service()->collection_images().empty()); base::RunLoop loop; service()->FetchCollectionImageInfo("shapes"); loop.RunUntilIdle(); EXPECT_TRUE(service()->collection_images().empty()); } TEST_F(NtpBackgroundServiceTest, GoodCollectionImagesResponse) { ntp::background::Image image; image.set_asset_id(12345); image.set_image_url("https://wallpapers.co/some_image"); image.add_attribution()->set_text("attribution text"); ntp::background::GetImagesInCollectionResponse response; *response.add_images() = image; std::string response_string; response.SerializeToString(&response_string); SetUpResponseWithData(service()->GetImagesURLForTesting(), response_string); ASSERT_TRUE(service()->collection_images().empty()); base::RunLoop loop; service()->FetchCollectionImageInfo("shapes"); loop.RunUntilIdle(); CollectionImage collection_image; collection_image.collection_id = "shapes"; collection_image.asset_id = image.asset_id(); collection_image.thumbnail_image_url = GURL(image.image_url()); collection_image.image_url = GURL(image.image_url() + kImageOptions); collection_image.attribution.push_back(image.attribution(0).text()); EXPECT_FALSE(service()->collection_images().empty()); EXPECT_THAT(service()->collection_images().at(0), Eq(collection_image)); } TEST_F(NtpBackgroundServiceTest, MultipleRequests) { ntp::background::Collection collection; collection.set_collection_id("shapes"); collection.set_collection_name("Shapes"); collection.add_preview()->set_image_url("https://wallpapers.co/some_image"); ntp::background::GetCollectionsResponse collection_response; *collection_response.add_collections() = collection; std::string collection_response_string; collection_response.SerializeToString(&collection_response_string); ntp::background::Image image; image.set_asset_id(12345); image.set_image_url("https://wallpapers.co/some_image"); image.add_attribution()->set_text("attribution text"); ntp::background::GetImagesInCollectionResponse image_response; *image_response.add_images() = image; std::string image_response_string; image_response.SerializeToString(&image_response_string); SetUpResponseWithData(service()->GetCollectionsLoadURLForTesting(), collection_response_string); SetUpResponseWithData(service()->GetImagesURLForTesting(), image_response_string); ASSERT_TRUE(service()->collection_info().empty()); ASSERT_TRUE(service()->collection_images().empty()); base::RunLoop loop; service()->FetchCollectionInfo(); service()->FetchCollectionImageInfo("shapes"); // Subsequent requests are ignored while the loader is in use. service()->FetchCollectionImageInfo("colors"); loop.RunUntilIdle(); CollectionInfo collection_info; collection_info.collection_id = collection.collection_id(); collection_info.collection_name = collection.collection_name(); collection_info.preview_image_url = GURL(collection.preview(0).image_url()); CollectionImage collection_image; collection_image.collection_id = "shapes"; collection_image.asset_id = image.asset_id(); collection_image.thumbnail_image_url = GURL(image.image_url()); collection_image.image_url = GURL(image.image_url() + kImageOptions); collection_image.attribution.push_back(image.attribution(0).text()); EXPECT_FALSE(service()->collection_info().empty()); EXPECT_THAT(service()->collection_info().at(0), Eq(collection_info)); EXPECT_FALSE(service()->collection_images().empty()); EXPECT_THAT(service()->collection_images().at(0), Eq(collection_image)); }
2,746
9,425
""" Simple text outputter ===================== The ``txt`` outputter has been developed to make the output from shell commands on minions appear as they do when the command is executed on the minion. CLI Example: .. code-block:: bash salt '*' foo.bar --out=txt """ import pprint def output(data, **kwargs): # pylint: disable=unused-argument """ Output the data in lines, very nice for running commands """ ret = "" if hasattr(data, "keys"): for key in data: value = data[key] # Don't blow up on non-strings try: for line in value.splitlines(): ret += "{}: {}\n".format(key, line) except AttributeError: ret += "{}: {}\n".format(key, value) else: try: ret += data + "\n" except TypeError: # For non-dictionary, non-string data, just use print ret += "{}\n".format(pprint.pformat(data)) return ret
429
2,212
<reponame>paulo-sampaio/detect-secrets import argparse from typing import cast from . import baseline from ...settings import get_settings from .common import initialize_plugin_settings def add_scan_action(parent: argparse._SubParsersAction) -> argparse.ArgumentParser: parser = parent.add_parser( 'scan', help='Creates a baseline by scanning a repository for secrets.', description=( 'Scans a repository for secrets in code. The generated output is compatible with ' '`detect-secrets-hook --baseline`.' ), ) _add_adhoc_scanning(parser) _add_pragma_scanning(parser) _add_initialize_baseline_options(parser) return parser def _add_adhoc_scanning(parser: argparse.ArgumentParser) -> None: parser.add_argument( '--string', nargs='?', const=True, help=( 'Scans an individual string, and displays configured plugins\' verdict.' ), ) def _add_pragma_scanning(parser: argparse.ArgumentParser) -> None: parser.add_argument( '--only-allowlisted', action='store_true', help=( 'Only scans the lines that are flagged with `allowlist secret`. This helps ' 'verify that individual exceptions are indeed non-secrets.' ), ) def _add_initialize_baseline_options(parser: argparse.ArgumentParser) -> None: parser.add_argument( 'path', nargs='*', default=['.'], help=( 'Scans the entire codebase and outputs a snapshot of ' 'currently identified secrets.' ), ) group = parser.add_argument_group(title='scan options') group.add_argument( '--all-files', action='store_true', help='Scan all files recursively (as compared to only scanning git tracked files).', ) baseline.add_baseline_option( cast(argparse.ArgumentParser, group), help='If provided, will update existing baseline by importing settings from it.', ) group.add_argument( '--force-use-all-plugins', action='store_true', help=( 'If a baseline is provided, detect-secrets will default to loading the plugins ' 'specified by that baseline. However, this may also mean it doesn\'t perform the ' 'scan with the latest plugins. If this flag is provided, it will always use the ' 'latest plugins' ), ) group.add_argument( '--slim', action='store_true', help=( 'Slim baselines are created with the intention of minimizing differences between ' 'commits. However, they are not compatible with the `audit` functionality, and ' 'slim baselines will need to be remade to be audited.' ), ) def parse_args(args: argparse.Namespace) -> None: if args.action != 'scan': return # NOTE: This is assumed to run *after* the baseline argument processor, and before # the plugin argument processor. if args.baseline is not None and args.force_use_all_plugins: get_settings().plugins.clear() initialize_plugin_settings(args)
1,258
429
/* vim: tabstop=4 shiftwidth=4 noexpandtab * This file is part of ToaruOS and is released under the terms * of the NCSA / University of Illinois License - see LICENSE.md * Copyright (C) 2016-2018 <NAME> * * VirtualBox Guest Additions driver */ #include <kernel/system.h> #include <kernel/fs.h> #include <kernel/printf.h> #include <kernel/types.h> #include <kernel/logging.h> #include <kernel/pci.h> #include <kernel/module.h> #include <kernel/video.h> #include <kernel/pipe.h> #include <kernel/mouse.h> #include <kernel/args.h> #define VBOX_VENDOR_ID 0x80EE #define VBOX_DEVICE_ID 0xCAFE static void vbox_scan_pci(uint32_t device, uint16_t v, uint16_t d, void * extra) { if (v == VBOX_VENDOR_ID && d == VBOX_DEVICE_ID) { *((uint32_t *)extra) = device; } } #define VMM_GetMouseState 1 #define VMM_SetMouseState 2 #define VMM_SetPointerShape 3 #define VMM_AcknowledgeEvents 41 #define VMM_ReportGuestInfo 50 #define VMM_GetDisplayChangeRequest 51 #define VMM_ReportGuestCapabilities 55 #define VMM_VideoSetVisibleRegion 72 #define VMMCAP_SeamlessMode (1 << 0) #define VMMCAP_HostWindows (1 << 1) #define VMMCAP_Graphics (1 << 2) #define VMMDEV_VERSION 0x00010003 #define VBOX_REQUEST_HEADER_VERSION 0x10001 struct vbox_header { uint32_t size; uint32_t version; uint32_t requestType; int32_t rc; uint32_t reserved1; uint32_t reserved2; }; struct vbox_guest_info { struct vbox_header header; uint32_t version; uint32_t ostype; }; struct vbox_guest_caps { struct vbox_header header; uint32_t caps; }; struct vbox_ack_events { struct vbox_header header; uint32_t events; }; struct vbox_display_change { struct vbox_header header; uint32_t xres; uint32_t yres; uint32_t bpp; uint32_t eventack; }; struct vbox_mouse { struct vbox_header header; uint32_t features; int32_t x; int32_t y; }; struct vbox_rtrect { int32_t xLeft; int32_t yTop; int32_t xRight; int32_t yBottom; }; struct vbox_visibleregion { struct vbox_header header; uint32_t count; struct vbox_rtrect rect[1]; }; struct vbox_pointershape { struct vbox_header header; uint32_t flags; uint32_t xHot; uint32_t yHot; uint32_t width; uint32_t height; unsigned char data[]; }; #define EARLY_LOG_DEVICE 0x504 static uint32_t _vbox_write(fs_node_t *node, uint64_t offset, uint32_t size, uint8_t *buffer) { for (unsigned int i = 0; i < size; ++i) { outportb(EARLY_LOG_DEVICE, buffer[i]); } return size; } static fs_node_t vb = { .write = &_vbox_write }; static uint32_t vbox_device = 0; static uint32_t vbox_port = 0x0; static int vbox_irq = 0; static struct vbox_ack_events * vbox_irq_ack; static uint32_t vbox_phys_ack; static struct vbox_display_change * vbox_disp; static uint32_t vbox_phys_disp; static struct vbox_mouse * vbox_m; static uint32_t vbox_phys_mouse; static struct vbox_mouse * vbox_mg; static uint32_t vbox_phys_mouse_get; static struct vbox_visibleregion * vbox_visibleregion; static uint32_t vbox_phys_visibleregion; static struct vbox_pointershape * vbox_pointershape = NULL; static uint32_t vbox_phys_pointershape; static volatile uint32_t * vbox_vmmdev = 0; static fs_node_t * mouse_pipe; static fs_node_t * rect_pipe; static fs_node_t * pointer_pipe; static int mouse_state; #define PACKETS_IN_PIPE 1024 #define DISCARD_POINT 32 static int vbox_irq_handler(struct regs *r) { if (!vbox_vmmdev[2]) return 0; vbox_irq_ack->events = vbox_vmmdev[2]; outportl(vbox_port, vbox_phys_ack); irq_ack(vbox_irq); outportl(vbox_port, vbox_phys_mouse_get); unsigned int x, y; if (lfb_vid_memory && lfb_resolution_x && lfb_resolution_y && vbox_mg->x && vbox_mg->y) { x = ((unsigned int)vbox_mg->x * lfb_resolution_x) / 0xFFFF; y = ((unsigned int)vbox_mg->y * lfb_resolution_y) / 0xFFFF; } else { x = vbox_mg->x; y = vbox_mg->y; } mouse_device_packet_t packet; packet.magic = MOUSE_MAGIC; packet.x_difference = x; packet.y_difference = y; packet.buttons = 0; mouse_device_packet_t bitbucket; while (pipe_size(mouse_pipe) > (int)(DISCARD_POINT * sizeof(packet))) { read_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&bitbucket); } write_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&packet); outportl(vbox_port, vbox_phys_disp); if (lfb_resolution_x && vbox_disp->xres && (vbox_disp->xres != lfb_resolution_x || vbox_disp->yres != lfb_resolution_y)) { lfb_set_resolution(vbox_disp->xres, vbox_disp->yres); } return 1; } void vbox_set_log(void) { debug_file = &vb; } #define VBOX_MOUSE_ON (1 << 0) | (1 << 4) #define VBOX_MOUSE_OFF (0) static void mouse_on_off(unsigned int status) { mouse_state = status; vbox_m->header.size = sizeof(struct vbox_mouse); vbox_m->header.version = VBOX_REQUEST_HEADER_VERSION; vbox_m->header.requestType = VMM_SetMouseState; vbox_m->header.rc = 0; vbox_m->header.reserved1 = 0; vbox_m->header.reserved2 = 0; vbox_m->features = status; vbox_m->x = 0; vbox_m->y = 0; outportl(vbox_port, vbox_phys_mouse); } static int ioctl_mouse(fs_node_t * node, int request, void * argp) { if (request == 1) { /* Disable */ mouse_on_off(VBOX_MOUSE_OFF); return 0; } if (request == 2) { /* Enable */ mouse_on_off(VBOX_MOUSE_ON); return 0; } if (request == 3) { return mouse_state == (VBOX_MOUSE_ON); } return -1; } uint32_t write_pointer(fs_node_t * node, uint64_t offset, uint32_t size, uint8_t *buffer) { if (!mouse_state) { return -1; } memcpy(&vbox_pointershape->data[288], buffer, 48*48*4); outportl(vbox_port, vbox_phys_pointershape); return size; } uint32_t write_rectpipe(fs_node_t *node, uint64_t offset, uint32_t size, uint8_t *buffer) { (void)node; (void)offset; /* TODO should check size */ /* This is kinda special and always assumes everything was written at once. */ uint32_t count = ((uint32_t *)buffer)[0]; vbox_visibleregion->count = count; if (count > 254) count = 254; /* enforce maximum */ #if 0 fprintf(&vb, "Writing %d rectangles\n", count); #endif buffer += sizeof(uint32_t); for (unsigned int i = 0; i < count; ++i) { memcpy(&vbox_visibleregion->rect[i], buffer, sizeof(struct vbox_rtrect)); #if 0 fprintf(&vb, "Rectangle %d is [%d,%d,%d,%d]\n", i, vbox_visibleregion->rect[i].xLeft, vbox_visibleregion->rect[i].yTop, vbox_visibleregion->rect[i].xRight, vbox_visibleregion->rect[i].yBottom); #endif buffer += sizeof(struct vbox_rtrect); } vbox_visibleregion->header.size = sizeof(struct vbox_header) + sizeof(uint32_t) + sizeof(int32_t) * count * 4; outportl(vbox_port, vbox_phys_visibleregion); return size; } static int vbox_check(void) { pci_scan(vbox_scan_pci, -1, &vbox_device); if (vbox_device) { fprintf(&vb, "VirtualBox host detected, switching log to VirtualBox.\n"); if (args_present("vboxdebug")) { vbox_set_log(); } fprintf(&vb, "HELLO WORLD\n"); uintptr_t t = pci_read_field(vbox_device, PCI_BAR0, 4); if (t > 0) { vbox_port = (t & 0xFFFFFFF0); } uint16_t c = pci_read_field(vbox_device, PCI_COMMAND, 2); fprintf(&vb, "Command register: 0x%4x\n", c); if (!!(c & (1 << 10))) { fprintf(&vb, "Interrupts are disabled\n"); } mouse_pipe = make_pipe(sizeof(mouse_device_packet_t) * PACKETS_IN_PIPE); mouse_pipe->flags = FS_CHARDEVICE; mouse_pipe->ioctl = ioctl_mouse; vfs_mount("/dev/absmouse", mouse_pipe); vbox_irq = pci_get_interrupt(vbox_device); debug_print(WARNING, "(vbox) device IRQ is set to %d", vbox_irq); fprintf(&vb, "irq line is %d\n", vbox_irq); irq_install_handler(vbox_irq, vbox_irq_handler, "vbox"); uint32_t vbox_phys = 0; struct vbox_guest_info * packet = (void*)kvmalloc_p(0x1000, &vbox_phys); packet->header.size = sizeof(struct vbox_guest_info); packet->header.version = VBOX_REQUEST_HEADER_VERSION; packet->header.requestType = VMM_ReportGuestInfo; packet->header.rc = 0; packet->header.reserved1 = 0; packet->header.reserved2 = 0; packet->version = VMMDEV_VERSION; packet->ostype = 0; outportl(vbox_port, vbox_phys); struct vbox_guest_caps * caps = (void*)kvmalloc_p(0x1000, &vbox_phys); caps->header.size = sizeof(struct vbox_guest_caps); caps->header.version = VBOX_REQUEST_HEADER_VERSION; caps->header.requestType = VMM_ReportGuestCapabilities; caps->header.rc = 0; caps->header.reserved1 = 0; caps->header.reserved2 = 0; caps->caps = VMMCAP_Graphics | (args_present("novboxseamless") ? 0 : VMMCAP_SeamlessMode); outportl(vbox_port, vbox_phys); vbox_irq_ack = (void*)kvmalloc_p(0x1000, &vbox_phys_ack); vbox_irq_ack->header.size = sizeof(struct vbox_ack_events); vbox_irq_ack->header.version = VBOX_REQUEST_HEADER_VERSION; vbox_irq_ack->header.requestType = VMM_AcknowledgeEvents; vbox_irq_ack->header.rc = 0; vbox_irq_ack->header.reserved1 = 0; vbox_irq_ack->header.reserved2 = 0; vbox_irq_ack->events = 0; vbox_disp = (void*)kvmalloc_p(0x1000, &vbox_phys_disp); vbox_disp->header.size = sizeof(struct vbox_display_change); vbox_disp->header.version = VBOX_REQUEST_HEADER_VERSION; vbox_disp->header.requestType = VMM_GetDisplayChangeRequest; vbox_disp->header.rc = 0; vbox_disp->header.reserved1 = 0; vbox_disp->header.reserved2 = 0; vbox_disp->xres = 0; vbox_disp->yres = 0; vbox_disp->bpp = 0; vbox_disp->eventack = 1; vbox_m = (void*)kvmalloc_p(0x1000, &vbox_phys_mouse); mouse_on_off(VBOX_MOUSE_ON); /* For use with later receives */ vbox_mg = (void*)kvmalloc_p(0x1000, &vbox_phys_mouse_get); vbox_mg->header.size = sizeof(struct vbox_mouse); vbox_mg->header.version = VBOX_REQUEST_HEADER_VERSION; vbox_mg->header.requestType = VMM_GetMouseState; vbox_mg->header.rc = 0; vbox_mg->header.reserved1 = 0; vbox_mg->header.reserved2 = 0; if (!args_present("novboxpointer")) { vbox_pointershape = (void*)kvmalloc_p(0x4000, &vbox_phys_pointershape); if (vbox_pointershape) { fprintf(&vb, "Got a valid set of pages to load up a cursor.\n"); vbox_pointershape->header.version = VBOX_REQUEST_HEADER_VERSION; vbox_pointershape->header.requestType = VMM_SetPointerShape; vbox_pointershape->header.rc = 0; vbox_pointershape->header.reserved1 = 0; vbox_pointershape->header.reserved2 = 0; vbox_pointershape->flags = (1 << 0) | (1 << 1) | (1 << 2); vbox_pointershape->xHot = 26; vbox_pointershape->yHot = 26; vbox_pointershape->width = 48; vbox_pointershape->height = 48; unsigned int mask_bytes = ((vbox_pointershape->width + 7) / 8) * vbox_pointershape->height; for (uint32_t i = 0; i < mask_bytes; ++i) { vbox_pointershape->data[i] = 0x00; } while (mask_bytes & 3) { mask_bytes++; } int base = mask_bytes; fprintf(&vb, "mask_bytes = %d\n", mask_bytes); vbox_pointershape->header.size = sizeof(struct vbox_pointershape) + (48*48*4)+mask_bytes; /* update later */ for (int i = 0; i < 48 * 48; ++i) { vbox_pointershape->data[base+i*4] = 0x00; /* blue */ vbox_pointershape->data[base+i*4+1] = 0x00; /* red */ vbox_pointershape->data[base+i*4+2] = 0x00; /* green */ vbox_pointershape->data[base+i*4+3] = 0x00; /* alpha */ } outportl(vbox_port, vbox_phys_pointershape); if (vbox_pointershape->header.rc < 0) { fprintf(&vb, "Bad response code: -%d\n", -vbox_pointershape->header.rc); } else { /* Success, let's install the device file */ fprintf(&vb, "Successfully initialized cursor, going to allow compositor to set it.\n"); pointer_pipe = malloc(sizeof(fs_node_t)); memset(pointer_pipe, 0, sizeof(fs_node_t)); pointer_pipe->mask = 0666; pointer_pipe->flags = FS_CHARDEVICE; pointer_pipe->write = write_pointer; vfs_mount("/dev/vboxpointer", pointer_pipe); } } } if (!args_present("novboxseamless")) { vbox_visibleregion = (void*)kvmalloc_p(0x1000, &vbox_phys_visibleregion); vbox_visibleregion->header.size = sizeof(struct vbox_header) + sizeof(uint32_t) + sizeof(int32_t) * 4; /* TODO + more for additional rects? */ vbox_visibleregion->header.version = VBOX_REQUEST_HEADER_VERSION; vbox_visibleregion->header.requestType = VMM_VideoSetVisibleRegion; vbox_visibleregion->header.rc = 0; vbox_visibleregion->header.reserved1 = 0; vbox_visibleregion->header.reserved2 = 0; vbox_visibleregion->count = 1; vbox_visibleregion->rect[0].xLeft = 0; vbox_visibleregion->rect[0].yTop = 0; vbox_visibleregion->rect[0].xRight = 1440; vbox_visibleregion->rect[0].yBottom = 900; outportl(vbox_port, vbox_phys_visibleregion); rect_pipe = malloc(sizeof(fs_node_t)); memset(rect_pipe, 0, sizeof(fs_node_t)); rect_pipe->mask = 0666; rect_pipe->flags = FS_CHARDEVICE; rect_pipe->write = write_rectpipe; vfs_mount("/dev/vboxrects", rect_pipe); } /* device memory region mapping? */ { uintptr_t t = pci_read_field(vbox_device, PCI_BAR1, 4); fprintf(&vb, "mapping vmm_dev = 0x%x\n", t); if (t > 0) { vbox_vmmdev = (void *)(t & 0xFFFFFFF0); } uintptr_t fb_offset = (uintptr_t)vbox_vmmdev; for (uintptr_t i = fb_offset; i <= fb_offset + 0x2000; i += 0x1000) { dma_frame(get_page(i, 1, kernel_directory), 0, 1, i); } } vbox_vmmdev[3] = 0xFFFFFFFF; /* Enable all for now */ } return 0; } static int fini(void) { return 0; } MODULE_DEF(vboxguest, vbox_check, fini); MODULE_DEPENDS(lfbvideo);
5,751
403
package org.camunda.bpm.example.task_name_beautifier.nonarquillian; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineTestCase; /** * Test case starting an in-memory database-backed Process Engine. */ public class InMemoryH2Test extends ProcessEngineTestCase { private static final String PROCESS_DEFINITION_KEY = "task-name-beautifier"; /** * Just tests if the process definition is deployable. */ @Deployment(resources = "process.bpmn") public void testParsingAndDeployment() { // nothing is done here, as we just want to check for exceptions during deployment } @Deployment(resources = "process.bpmn") public void testTaskNameBeautification() { runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY); Task task = taskService.createTaskQuery().list().get(0); assertEquals("Task with terribly long name", task.getName()); } }
300
10,225
package io.quarkus.runtime.annotations; public enum ConfigPhase { /** * Values are read and available for usage at build time. */ BUILD_TIME(true, false, false, "Build time"), /** * Values are read and available for usage at build time, and available on a read-only basis at run time. */ BUILD_AND_RUN_TIME_FIXED(true, true, false, "Build time and run time fixed"), /** * Values are read and available for usage at run time and are re-read on each program execution. These values * are used to configure ConfigSourceProvider implementations */ BOOTSTRAP(false, true, true, "Bootstrap"), /** * Values are read and available for usage at run time and are re-read on each program execution. */ RUN_TIME(false, true, true, "Run time"), ; private final boolean availableAtBuild; private final boolean availableAtRun; private final boolean readAtMain; private final String name; ConfigPhase(final boolean availableAtBuild, final boolean availableAtRun, final boolean readAtMain, final String name) { this.availableAtBuild = availableAtBuild; this.availableAtRun = availableAtRun; this.readAtMain = readAtMain; this.name = name; } public boolean isAvailableAtBuild() { return availableAtBuild; } public boolean isAvailableAtRun() { return availableAtRun; } public boolean isReadAtStaticInit() { return isAvailableAtBuild() && isAvailableAtRun(); } public boolean isReadAtMain() { return readAtMain; } @Override public String toString() { return name; } }
577
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.chrome.browser.omnibox.suggestions; import android.os.Debug; import org.chromium.base.metrics.RecordHistogram; import java.util.concurrent.TimeUnit; /** * This class collects a variety of different Suggestions related metrics. */ class SuggestionsMetrics { // The expected range for measure and layout durations. // If the combination of (N*Create)+Measure+Layout, where N is a maximum number of suggestions // exceeds: // - 16'000us (16ms), the suggestion list will take more than a single frame on modern devices, // - 33'000us (33ms), the suggestion list will take more than a single frame on all devices. // We expect the reported values to be within 2milliseconds range. // The upper range here is deliberately smaller than the limits mentioned above; any stage // taking more time than the limit chosen here is an indication of a problem. private static final long MIN_HISTOGRAM_DURATION_US = 100; private static final long MAX_HISTOGRAM_DURATION_US = TimeUnit.MILLISECONDS.toMicros(10); private static final int NUM_DURATION_BUCKETS = 100; /** Class for reporting timing metrics using try-with-resources block. */ public static class TimingMetric implements AutoCloseable { private final String mMetricName; private final long mStartTime; /** * Creates an instance and starts the timer. * @param metricName The name of the metric to be reported on close. */ public TimingMetric(String metricName) { mMetricName = metricName; mStartTime = Debug.threadCpuTimeNanos(); } @Override public void close() { final long endTime = Debug.threadCpuTimeNanos(); final long duration = getDurationInMicroseconds(mStartTime, endTime); if (duration < 0) return; RecordHistogram.recordCustomTimesHistogram(mMetricName, duration, MIN_HISTOGRAM_DURATION_US, MAX_HISTOGRAM_DURATION_US, NUM_DURATION_BUCKETS); } } /** * Measure duration between two timestamps in microseconds. * * @param startTimeNs Operation start timestamp (nanoseconds). * @param endTimeNs Operation end time (nanoseconds). * @return Duration in hundreds of microseconds or -1, if timestamps were invalid. */ private static final long getDurationInMicroseconds(long startTimeNs, long endTimeNs) { if (startTimeNs == -1 || endTimeNs == -1) return -1; return TimeUnit.NANOSECONDS.toMicros(endTimeNs - startTimeNs); } /** * Record how long the Suggestion List needed to layout its content and children. */ static final SuggestionsMetrics.TimingMetric recordSuggestionListLayoutTime() { return new TimingMetric("Android.Omnibox.SuggestionList.LayoutTime"); } /** * Record how long the Suggestion List needed to measure its content and children. */ static final SuggestionsMetrics.TimingMetric recordSuggestionListMeasureTime() { return new TimingMetric("Android.Omnibox.SuggestionList.MeasureTime"); } /** * Record the amount of time needed to create a new suggestion view. * The type of view is intentionally ignored for this call. */ static final SuggestionsMetrics.TimingMetric recordSuggestionViewCreateTime() { return new TimingMetric("Android.Omnibox.SuggestionView.CreateTime"); } /** * Record whether suggestion view was successfully reused. * * @param reused Whether suggestion view was reused. */ static final void recordSuggestionViewReused(boolean reused) { RecordHistogram.recordBooleanHistogram("Android.Omnibox.SuggestionView.Reused", reused); } /** * Record whether the interaction with the Omnibox resulted with a navigation (true) or user * leaving the omnibox and suggestions list. * * @param focusResultedInNavigation Whether the user completed interaction with navigation. */ static final void recordOmniboxFocusResultedInNavigation(boolean focusResultedInNavigation) { RecordHistogram.recordBooleanHistogram( "Omnibox.FocusResultedInNavigation", focusResultedInNavigation); } /** * Record the length of time between when omnibox gets focused and when a omnibox match is open. */ static final void recordFocusToOpenTime(long focusToOpenTimeInMillis) { RecordHistogram.recordMediumTimesHistogram( "Omnibox.FocusToOpenTimeAnyPopupState3", focusToOpenTimeInMillis); } }
1,630
427
<gh_stars>100-1000 /** * Provides utility classes. */ package fr.tikione.ini.util;
31
504
package org.dayatang.datasource4saas.dscreator; import org.apache.commons.beanutils.BeanUtils; import org.dayatang.configuration.Configuration; import org.dayatang.configuration.ConfigurationFactory; import org.dayatang.datasource4saas.Constants; import org.dayatang.datasource4saas.dsregistry.DataSourceCreator; import javax.sql.DataSource; import java.lang.reflect.InvocationTargetException; import java.util.Map.Entry; import java.util.Properties; /** * 抽象数据源创建器实现 * @author yyang (<a href="mailto:<EMAIL>"><EMAIL></a>) * */ public abstract class AbstractDataSourceCreator implements DataSourceCreator { private Configuration dsConfiguration; //数据源配置 private Configuration tenantDbMapping; //租户到数据库链接参数的映射 private DbType dbType; private TenantDbMappingStrategy mappingStrategy; /** * 获取数据源配置 * @return */ private Configuration getDsConfiguration() { if (dsConfiguration == null) { dsConfiguration = new ConfigurationFactory().fromClasspath(Constants.DB_CONF_FILE); } return dsConfiguration; } /** * 设置数据源配置 * @param dsConfiguration */ public void setDsConfiguration(Configuration dsConfiguration) { this.dsConfiguration = dsConfiguration; } private Configuration getTenantDbMapping() { if (tenantDbMapping == null) { tenantDbMapping = new ConfigurationFactory().fromClasspath(Constants.DB_MAPPING_FILE); } return tenantDbMapping; } /** * 设置租户数据源映射 * @param tenantDbMapping */ public void setTenantDbMapping(Configuration tenantDbMapping) { this.tenantDbMapping = tenantDbMapping; } private TenantDbMappingStrategy getMappingStrategy() { if (mappingStrategy == null) { mappingStrategy = TenantDbMappingStrategy.of(getDsConfiguration().getString(Constants.TENANT_MAPPING_STRATEGY)); } return mappingStrategy; } public void setMappingStrategy(TenantDbMappingStrategy mappingStrategy) { this.mappingStrategy = mappingStrategy; } private DbType getDbType() { if (dbType == null) { dbType = DbType.of(getDsConfiguration().getString(Constants.DB_TYPE)); } return dbType; } public void setDbType(DbType dbType) { this.dbType = dbType; } @Override public DataSource createDataSourceForTenant(String tenant) { DataSource result = createDataSource(); fillProperties(result); DbInfo dbInfo = getDbInfo(tenant); setProperty(result, getDriverClassPropName(), getDbType().getDriverClassName()); setProperty(result, getUrlPropName(), getDbType().getUrl(dbInfo)); setProperty(result, getUsernamePropName(), dbInfo.getUsername()); setProperty(result, getPasswordPropName(), dbInfo.getPassword()); return result; } private DbInfo getDbInfo(String tenant) { DbInfo dbInfo = new DbInfo(getDsConfiguration()); getMappingStrategy().process(dbInfo, tenant, getTenantDbMapping()); return dbInfo; } protected abstract DataSource createDataSource(); protected abstract String getDriverClassPropName(); protected abstract String getUrlPropName(); protected abstract String getUsernamePropName(); protected abstract String getPasswordPropName(); /** * 填充数据库连接池特定的数据源配置。 * @param dataSource * @throws IllegalAccessException * @throws InvocationTargetException */ private void fillProperties(DataSource dataSource) { Properties dsProperties = getDsConfiguration().getProperties(); for (Entry<Object, Object> entry : dsProperties.entrySet()) { setProperty(dataSource, entry.getKey().toString(), entry.getValue()); } } private void setProperty(Object obj, String propName, Object propValue) { try { BeanUtils.setProperty(obj, propName, propValue); } catch (IllegalAccessException e) { throw new DataSourceCreationException("Datasource property setting failed", e); } catch (InvocationTargetException e) { throw new DataSourceCreationException("Datasource property setting failed", e); } } }
1,397
304
<filename>GRichLabelExample/DemoTextMenuConfig.h // // DemoTextMenuConfig.h // GRichLabelExample // // Created by GIKI on 2017/11/7. // Copyright © 2017年 GIKI. All rights reserved. // #import <Foundation/Foundation.h> #import "GMenuContextProtocol.h" @interface DemoTextMenuConfig : NSObject<GMenuContextProtocol> @end
116
1,059
<filename>core/core_engine/php/engine.py #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/7/5 15:34 # @Author : LoRexxar # @File : engine.py # @Contact : <EMAIL> import traceback from phply import phpast as php from utils.log import logger def init_match_rule(data): """ 处理新生成规则初始化正则匹配 :param data: :return: """ try: object = data[0] match = "" if isinstance(object, php.Method) or isinstance(object, php.Function): function_params = object.params function_name = object.name param = data[1] index = 0 for function_param in function_params: if function_param.name == param.name: break index += 1 # curl_setopt\s*\(.*,\s*CURLOPT_URL\s*,(.*)\) match = "(?:\A|\s|\\b)" + function_name + "\s*\(" for i in range(len(function_params)): if i != 0: match += "," if function_params[i].default is not None: match += "?" if i == index: match += "([^,\)]*)" else: match += "[^,\)]*" match += "\)" # 去除定义函数 match2 = "function\s+" + function_name vul_function = function_name origin_func_name = data[2] elif isinstance(object, php.Class): class_params = data[2] class_name = object.name param = data[1] index = 0 for class_param in class_params: if class_param.name == param.name: break index += 1 # $A = new a($x, $y); match = "new\s*" + class_name + "\s*\(" for i in range(len(class_params)): if i != 0: match += "," if class_params[i].default is not None: match += "?" if i == index: match += "([^,\)]*)" else: match += "[^,\)]*" match += "\)" # 去除定义类,类定义和调用方式不一样,但是为了不影响结构,依然赋值 match2 = "class\s+" + class_name + "\s*{" vul_function = class_name origin_func_name = data[3] except: logger.error('[New Rule] Error to unpack function param, Something error') traceback.print_exc() match = None match2 = None index = 0 vul_function = None origin_func_name = "None" return match, match2, vul_function, index, origin_func_name
1,571
3,705
#pragma once #include "chainerx/array.h" namespace chainerx { Array Sinh(const Array& x); Array Cosh(const Array& x); Array Tanh(const Array& x); Array Arcsinh(const Array& x); Array Arccosh(const Array& x); } // namespace chainerx
94
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/css/properties/longhands/text_size_adjust.h" #include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h" #include "third_party/blink/renderer/core/css_value_keywords.h" #include "third_party/blink/renderer/core/style/computed_style.h" namespace blink { namespace CSSLonghand { const CSSValue* TextSizeAdjust::ParseSingleValue( CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&) const { if (range.Peek().Id() == CSSValueAuto) return CSSPropertyParserHelpers::ConsumeIdent(range); if (range.Peek().Id() == CSSValueNone) return CSSPropertyParserHelpers::ConsumeIdent(range); return CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative); } const CSSValue* TextSizeAdjust::CSSValueFromComputedStyleInternal( const ComputedStyle& style, const SVGComputedStyle&, const LayoutObject*, Node* styled_node, bool allow_visited_style) const { if (style.GetTextSizeAdjust().IsAuto()) return CSSIdentifierValue::Create(CSSValueAuto); return CSSPrimitiveValue::Create(style.GetTextSizeAdjust().Multiplier() * 100, CSSPrimitiveValue::UnitType::kPercentage); } } // namespace CSSLonghand } // namespace blink
556
1,602
<filename>third-party/llvm/llvm-src/unittests/Analysis/DDGTest.cpp //===- DDGTest.cpp - DDGAnalysis unit tests -------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #include "llvm/Analysis/DDG.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Dominators.h" #include "llvm/Support/SourceMgr.h" #include "gtest/gtest.h" using namespace llvm; /// Build the DDG analysis for a loop and run the given test \p Test. static void runTest(Module &M, StringRef FuncName, function_ref<void(Function &F, LoopInfo &LI, DependenceInfo &DI, ScalarEvolution &SE)> Test) { auto *F = M.getFunction(FuncName); ASSERT_NE(F, nullptr) << "Could not find " << FuncName; TargetLibraryInfoImpl TLII; TargetLibraryInfo TLI(TLII); AssumptionCache AC(*F); DominatorTree DT(*F); LoopInfo LI(DT); ScalarEvolution SE(*F, TLI, AC, DT, LI); AAResults AA(TLI); DependenceInfo DI(F, &AA, &SE, &LI); Test(*F, LI, DI, SE); } static std::unique_ptr<Module> makeLLVMModule(LLVMContext &Context, const char *ModuleStr) { SMDiagnostic Err; return parseAssemblyString(ModuleStr, Err, Context); } TEST(DDGTest, getDependencies) { const char *ModuleStr = "target datalayout = \"e-m:e-i64:64-n32:64\"\n" "target triple = \"powerpc64le-unknown-linux-gnu\"\n" "\n" "define dso_local void @foo(i32 signext %n, i32* noalias %A, i32* " "noalias %B) {\n" "entry:\n" " %cmp1 = icmp sgt i32 %n, 0\n" " br i1 %cmp1, label %for.body.preheader, label %for.end\n" "\n" "for.body.preheader:\n" " %wide.trip.count = zext i32 %n to i64\n" " br label %for.body\n" " \n" " for.body:\n" " %indvars.iv = phi i64 [ 0, %for.body.preheader ], [ " "%indvars.iv.next, %for.body ]\n" " %arrayidx = getelementptr inbounds i32, i32* %A, i64 %indvars.iv\n" " %0 = trunc i64 %indvars.iv to i32\n" " store i32 %0, i32* %arrayidx, align 4\n" " %indvars.iv.next = add nuw nsw i64 %indvars.iv, 1\n" " %arrayidx2 = getelementptr inbounds i32, i32* %A, i64 " "%indvars.iv.next\n" " %1 = load i32, i32* %arrayidx2, align 4\n" " %add3 = add nsw i32 %1, 1\n" " %arrayidx5 = getelementptr inbounds i32, i32* %B, i64 %indvars.iv\n" " store i32 %add3, i32* %arrayidx5, align 4\n" " %exitcond = icmp ne i64 %indvars.iv.next, %wide.trip.count\n" " br i1 %exitcond, label %for.body, label %for.end.loopexit\n" "\n" "for.end.loopexit:\n" " br label %for.end\n" "\n" "for.end:\n" " ret void\n" "}\n"; LLVMContext Context; std::unique_ptr<Module> M = makeLLVMModule(Context, ModuleStr); runTest( *M, "foo", [&](Function &F, LoopInfo &LI, DependenceInfo &DI, ScalarEvolution &SE) { Loop *L = *LI.begin(); assert(L && "expected the loop to be identified."); DataDependenceGraph DDG(*L, LI, DI); // Collect all the nodes that have an outgoing memory edge // while collecting all memory edges as well. There should // only be one node with an outgoing memory edge and there // should only be one memory edge in the entire graph. std::vector<DDGNode *> DependenceSourceNodes; std::vector<DDGEdge *> MemoryEdges; for (DDGNode *N : DDG) { for (DDGEdge *E : *N) { bool SourceAdded = false; if (E->isMemoryDependence()) { MemoryEdges.push_back(E); if (!SourceAdded) { DependenceSourceNodes.push_back(N); SourceAdded = true; } } } } EXPECT_EQ(DependenceSourceNodes.size(), 1ull); EXPECT_EQ(MemoryEdges.size(), 1ull); DataDependenceGraph::DependenceList DL; DDG.getDependencies(*DependenceSourceNodes.back(), MemoryEdges.back()->getTargetNode(), DL); EXPECT_EQ(DL.size(), 1ull); EXPECT_TRUE(DL.back()->isAnti()); EXPECT_EQ(DL.back()->getLevels(), 1u); EXPECT_NE(DL.back()->getDistance(1), nullptr); EXPECT_EQ(DL.back()->getDistance(1), SE.getOne(DL.back()->getDistance(1)->getType())); }); }
2,259
7,482
<filename>bsp/wch/arm/Libraries/CH32F10x_StdPeriph_Driver/StdPeriph_Driver/inc/ch32f10x_usb.h /***************COPYRIGHT(C) 2019 WCH. A11 rights reserved********************* * File Name : ch32f10x_usb.h * Author : WCH * Version : V1.0.0 * Date : 2019/10/15 * Description : This file contains all the functions prototypes for the USB * firmware library. *******************************************************************************/ #ifndef __CH32F10x_USB_H #define __CH32F10x_USB_H #include "stdio.h" #ifdef __cplusplus extern "C" { #endif #ifndef NULL #define NULL 0 #endif #ifndef VOID #define VOID (void) #endif #ifndef CONST #define CONST const #endif #ifndef BOOL typedef unsigned char BOOL; #endif #ifndef BOOLEAN typedef unsigned char BOOLEAN; #endif #ifndef CHAR typedef char CHAR; #endif #ifndef INT8 typedef char INT8; #endif #ifndef INT16 typedef short INT16; #endif #ifndef INT32 typedef long INT32; #endif #ifndef UINT8 typedef unsigned char UINT8; #endif #ifndef UINT16 typedef unsigned short UINT16; #endif #ifndef UINT32 typedef unsigned long UINT32; #endif #ifndef UINT8V typedef unsigned char volatile UINT8V; #endif #ifndef UINT16V typedef unsigned short volatile UINT16V; #endif #ifndef UINT32V typedef unsigned long volatile UINT32V; #endif #ifndef PVOID typedef void *PVOID; #endif #ifndef PCHAR typedef char *PCHAR; #endif #ifndef PCHAR typedef const char *PCCHAR; #endif #ifndef PINT8 typedef char *PINT8; #endif #ifndef PINT16 typedef short *PINT16; #endif #ifndef PINT32 typedef long *PINT32; #endif #ifndef PUINT8 typedef unsigned char *PUINT8; #endif #ifndef PUINT16 typedef unsigned short *PUINT16; #endif #ifndef PUINT32 typedef unsigned long *PUINT32; #endif #ifndef PUINT8V typedef volatile unsigned char *PUINT8V; #endif #ifndef PUINT16V typedef volatile unsigned short *PUINT16V; #endif #ifndef PUINT32V typedef volatile unsigned long *PUINT32V; #endif /******************************************************************************/ /* Peripheral memory map */ /******************************************************************************/ /* usb addresses // USB: +8000H - 83FFH */ #define USB_BASE_ADDR (0x40023400) #define EXTEN_CTRL (*((PUINT32V)(0x40023800))) #define USBD_LOWSPEED ((UINT32)0x0001) #define USBD_PU_EN ((UINT32)0x0002) #define USBHD_IO_EN ((UINT32)0x0004) #define USB_5V_SEL ((UINT32)0x0008) #define RCC_AHBPeriph_USBHD ((UINT32)0x00001000) /* USB */ #define R32_USB_CONTROL (*((PUINT32V)(0x40023400))) // USB control & interrupt enable & device address #define R8_USB_CTRL (*((PUINT8V)(0x40023400))) // USB base control #define RB_UC_HOST_MODE 0x80 // enable USB host mode: 0=device mode, 1=host mode #define RB_UC_LOW_SPEED 0x40 // enable USB low speed: 0=12Mbps, 1=1.5Mbps #define RB_UC_DEV_PU_EN 0x20 // USB device enable and internal pullup resistance enable #define RB_UC_SYS_CTRL1 0x20 // USB system control high bit #define RB_UC_SYS_CTRL0 0x10 // USB system control low bit #define MASK_UC_SYS_CTRL 0x30 // bit mask of USB system control // bUC_HOST_MODE & bUC_SYS_CTRL1 & bUC_SYS_CTRL0: USB system control // 0 00: disable USB device and disable internal pullup resistance // 0 01: enable USB device and disable internal pullup resistance, need external pullup resistance // 0 1x: enable USB device and enable internal pullup resistance // 1 00: enable USB host and normal status // 1 01: enable USB host and force UDP/UDM output SE0 state // 1 10: enable USB host and force UDP/UDM output J state // 1 11: enable USB host and force UDP/UDM output resume or K state #define RB_UC_INT_BUSY 0x08 // enable automatic responding busy for device mode or automatic pause for host mode during interrupt flag UIF_TRANSFER valid #define RB_UC_RESET_SIE 0x04 // force reset USB SIE, need software clear #define RB_UC_CLR_ALL 0x02 // force clear FIFO and count of USB #define RB_UC_DMA_EN 0x01 // DMA enable and DMA interrupt enable for USB #define R8_UDEV_CTRL (*((PUINT8V)(0x40023401))) // USB device physical prot control #define RB_UD_PD_DIS 0x80 // disable USB UDP/UDM pulldown resistance: 0=enable pulldown, 1=disable #define RB_UD_DP_PIN 0x20 // ReadOnly: indicate current UDP pin level #define RB_UD_DM_PIN 0x10 // ReadOnly: indicate current UDM pin level #define RB_UD_LOW_SPEED 0x04 // enable USB physical port low speed: 0=full speed, 1=low speed #define RB_UD_GP_BIT 0x02 // general purpose bit #define RB_UD_PORT_EN 0x01 // enable USB physical port I/O: 0=disable, 1=enable #define R8_UHOST_CTRL R8_UDEV_CTRL // USB host physical prot control #define RB_UH_PD_DIS 0x80 // disable USB UDP/UDM pulldown resistance: 0=enable pulldown, 1=disable #define RB_UH_DP_PIN 0x20 // ReadOnly: indicate current UDP pin level #define RB_UH_DM_PIN 0x10 // ReadOnly: indicate current UDM pin level #define RB_UH_LOW_SPEED 0x04 // enable USB port low speed: 0=full speed, 1=low speed #define RB_UH_BUS_RESET 0x02 // control USB bus reset: 0=normal, 1=force bus reset #define RB_UH_PORT_EN 0x01 // enable USB port: 0=disable, 1=enable port, automatic disabled if USB device detached #define R8_USB_INT_EN (*((PUINT8V)(0x40023402))) // USB interrupt enable #define RB_UIE_DEV_SOF 0x80 // enable interrupt for SOF received for USB device mode #define RB_UIE_DEV_NAK 0x40 // enable interrupt for NAK responded for USB device mode #define RB_UIE_FIFO_OV 0x10 // enable interrupt for FIFO overflow #define RB_UIE_HST_SOF 0x08 // enable interrupt for host SOF timer action for USB host mode #define RB_UIE_SUSPEND 0x04 // enable interrupt for USB suspend or resume event #define RB_UIE_TRANSFER 0x02 // enable interrupt for USB transfer completion #define RB_UIE_DETECT 0x01 // enable interrupt for USB device detected event for USB host mode #define RB_UIE_BUS_RST 0x01 // enable interrupt for USB bus reset event for USB device mode #define R8_USB_DEV_AD (*((PUINT8V)(0x40023403))) // USB device address #define RB_UDA_GP_BIT 0x80 // general purpose bit #define MASK_USB_ADDR 0x7F // bit mask for USB device address #define R32_USB_STATUS (*((PUINT32V)(0x40023404))) // USB miscellaneous status & interrupt flag & interrupt status #define R8_USB_MIS_ST (*((PUINT8V)(0x40023405))) // USB miscellaneous status #define RB_UMS_SOF_PRES 0x80 // RO, indicate host SOF timer presage status #define RB_UMS_SOF_ACT 0x40 // RO, indicate host SOF timer action status for USB host #define RB_UMS_SIE_FREE 0x20 // RO, indicate USB SIE free status #define RB_UMS_R_FIFO_RDY 0x10 // RO, indicate USB receiving FIFO ready status (not empty) #define RB_UMS_BUS_RESET 0x08 // RO, indicate USB bus reset status #define RB_UMS_SUSPEND 0x04 // RO, indicate USB suspend status #define RB_UMS_DM_LEVEL 0x02 // RO, indicate UDM level saved at device attached to USB host #define RB_UMS_DEV_ATTACH 0x01 // RO, indicate device attached status on USB host #define R8_USB_INT_FG (*((PUINT8V)(0x40023406))) // USB interrupt flag #define RB_U_IS_NAK 0x80 // RO, indicate current USB transfer is NAK received #define RB_U_TOG_OK 0x40 // RO, indicate current USB transfer toggle is OK #define RB_U_SIE_FREE 0x20 // RO, indicate USB SIE free status #define RB_UIF_FIFO_OV 0x10 // FIFO overflow interrupt flag for USB, direct bit address clear or write 1 to clear #define RB_UIF_HST_SOF 0x08 // host SOF timer interrupt flag for USB host, direct bit address clear or write 1 to clear #define RB_UIF_SUSPEND 0x04 // USB suspend or resume event interrupt flag, direct bit address clear or write 1 to clear #define RB_UIF_TRANSFER 0x02 // USB transfer completion interrupt flag, direct bit address clear or write 1 to clear #define RB_UIF_DETECT 0x01 // device detected event interrupt flag for USB host mode, direct bit address clear or write 1 to clear #define RB_UIF_BUS_RST 0x01 // bus reset event interrupt flag for USB device mode, direct bit address clear or write 1 to clear #define R8_USB_INT_ST (*((PUINT8V)(0x40023407))) // USB interrupt status #define RB_UIS_IS_NAK 0x80 // RO, indicate current USB transfer is NAK received for USB device mode #define RB_UIS_TOG_OK 0x40 // RO, indicate current USB transfer toggle is OK #define RB_UIS_TOKEN1 0x20 // RO, current token PID code bit 1 received for USB device mode #define RB_UIS_TOKEN0 0x10 // RO, current token PID code bit 0 received for USB device mode #define MASK_UIS_TOKEN 0x30 // RO, bit mask of current token PID code received for USB device mode #define UIS_TOKEN_OUT 0x00 #define UIS_TOKEN_SOF 0x10 #define UIS_TOKEN_IN 0x20 #define UIS_TOKEN_SETUP 0x30 // bUIS_TOKEN1 & bUIS_TOKEN0: current token PID code received for USB device mode // 00: OUT token PID received // 01: SOF token PID received // 10: IN token PID received // 11: SETUP token PID received #define MASK_UIS_ENDP 0x0F // RO, bit mask of current transfer endpoint number for USB device mode #define MASK_UIS_H_RES 0x0F // RO, bit mask of current transfer handshake response for USB host mode: 0000=no response, time out from device, others=handshake response PID received #define R8_USB_RX_LEN (*((PUINT8V)(0x40023408))) // USB receiving length #define R32_USB_BUF_MODE (*((PUINT32V)(0x4002340c))) // USB endpoint buffer mode #define R8_UEP4_1_MOD (*((PUINT8V)(0x4002340c))) // endpoint 4/1 mode #define RB_UEP1_RX_EN 0x80 // enable USB endpoint 1 receiving (OUT) #define RB_UEP1_TX_EN 0x40 // enable USB endpoint 1 transmittal (IN) #define RB_UEP1_BUF_MOD 0x10 // buffer mode of USB endpoint 1 // bUEPn_RX_EN & bUEPn_TX_EN & bUEPn_BUF_MOD: USB endpoint 1/2/3 buffer mode, buffer start address is UEPn_DMA // 0 0 x: disable endpoint and disable buffer // 1 0 0: 64 bytes buffer for receiving (OUT endpoint) // 1 0 1: dual 64 bytes buffer by toggle bit bUEP_R_TOG selection for receiving (OUT endpoint), total=128bytes // 0 1 0: 64 bytes buffer for transmittal (IN endpoint) // 0 1 1: dual 64 bytes buffer by toggle bit bUEP_T_TOG selection for transmittal (IN endpoint), total=128bytes // 1 1 0: 64 bytes buffer for receiving (OUT endpoint) + 64 bytes buffer for transmittal (IN endpoint), total=128bytes // 1 1 1: dual 64 bytes buffer by bUEP_R_TOG selection for receiving (OUT endpoint) + dual 64 bytes buffer by bUEP_T_TOG selection for transmittal (IN endpoint), total=256bytes #define RB_UEP4_RX_EN 0x08 // enable USB endpoint 4 receiving (OUT) #define RB_UEP4_TX_EN 0x04 // enable USB endpoint 4 transmittal (IN) // bUEP4_RX_EN & bUEP4_TX_EN: USB endpoint 4 buffer mode, buffer start address is UEP0_DMA // 0 0: single 64 bytes buffer for endpoint 0 receiving & transmittal (OUT & IN endpoint) // 1 0: single 64 bytes buffer for endpoint 0 receiving & transmittal (OUT & IN endpoint) + 64 bytes buffer for endpoint 4 receiving (OUT endpoint), total=128bytes // 0 1: single 64 bytes buffer for endpoint 0 receiving & transmittal (OUT & IN endpoint) + 64 bytes buffer for endpoint 4 transmittal (IN endpoint), total=128bytes // 1 1: single 64 bytes buffer for endpoint 0 receiving & transmittal (OUT & IN endpoint) // + 64 bytes buffer for endpoint 4 receiving (OUT endpoint) + 64 bytes buffer for endpoint 4 transmittal (IN endpoint), total=192bytes #define R8_UEP2_3_MOD (*((PUINT8V)(0x4002340d))) // endpoint 2/3 mode #define RB_UEP3_RX_EN 0x80 // enable USB endpoint 3 receiving (OUT) #define RB_UEP3_TX_EN 0x40 // enable USB endpoint 3 transmittal (IN) #define RB_UEP3_BUF_MOD 0x10 // buffer mode of USB endpoint 3 #define RB_UEP2_RX_EN 0x08 // enable USB endpoint 2 receiving (OUT) #define RB_UEP2_TX_EN 0x04 // enable USB endpoint 2 transmittal (IN) #define RB_UEP2_BUF_MOD 0x01 // buffer mode of USB endpoint 2 #define R8_UH_EP_MOD R8_UEP2_3_MOD //host endpoint mode #define RB_UH_EP_TX_EN 0x40 // enable USB host OUT endpoint transmittal #define RB_UH_EP_TBUF_MOD 0x10 // buffer mode of USB host OUT endpoint // bUH_EP_TX_EN & bUH_EP_TBUF_MOD: USB host OUT endpoint buffer mode, buffer start address is UH_TX_DMA // 0 x: disable endpoint and disable buffer // 1 0: 64 bytes buffer for transmittal (OUT endpoint) // 1 1: dual 64 bytes buffer by toggle bit bUH_T_TOG selection for transmittal (OUT endpoint), total=128bytes #define RB_UH_EP_RX_EN 0x08 // enable USB host IN endpoint receiving #define RB_UH_EP_RBUF_MOD 0x01 // buffer mode of USB host IN endpoint // bUH_EP_RX_EN & bUH_EP_RBUF_MOD: USB host IN endpoint buffer mode, buffer start address is UH_RX_DMA // 0 x: disable endpoint and disable buffer // 1 0: 64 bytes buffer for receiving (IN endpoint) // 1 1: dual 64 bytes buffer by toggle bit bUH_R_TOG selection for receiving (IN endpoint), total=128bytes #define R16_UEP0_DMA (*((PUINT16V)(0x40023410))) // endpoint 0 DMA buffer address #define R16_UEP1_DMA (*((PUINT16V)(0x40023414))) // endpoint 1 DMA buffer address #define R16_UEP2_DMA (*((PUINT16V)(0x40023418))) // endpoint 2 DMA buffer address #define R16_UH_RX_DMA R16_UEP2_DMA // host rx endpoint buffer high address #define R16_UEP3_DMA (*((PUINT16V)(0x4002341c))) // endpoint 3 DMA buffer address #define R16_UH_TX_DMA R16_UEP3_DMA // host tx endpoint buffer high address #define R32_USB_EP0_CTRL (*((PUINT32V)(0x40023420))) // endpoint 0 control & transmittal length #define R8_UEP0_T_LEN (*((PUINT8V)(0x40023420))) // endpoint 0 transmittal length #define R8_UEP0_CTRL (*((PUINT8V)(0x40023422))) // endpoint 0 control #define R32_USB_EP1_CTRL (*((PUINT32V)(0x40023424))) // endpoint 1 control & transmittal length #define R8_UEP1_T_LEN (*((PUINT8V)(0x40023424))) // endpoint 1 transmittal length #define R8_UEP1_CTRL (*((PUINT8V)(0x40023426))) // endpoint 1 control #define RB_UEP_R_TOG 0x80 // expected data toggle flag of USB endpoint X receiving (OUT): 0=DATA0, 1=DATA1 #define RB_UEP_T_TOG 0x40 // prepared data toggle flag of USB endpoint X transmittal (IN): 0=DATA0, 1=DATA1 #define RB_UEP_AUTO_TOG 0x10 // enable automatic toggle after successful transfer completion on endpoint 1/2/3: 0=manual toggle, 1=automatic toggle #define RB_UEP_R_RES1 0x08 // handshake response type high bit for USB endpoint X receiving (OUT) #define RB_UEP_R_RES0 0x04 // handshake response type low bit for USB endpoint X receiving (OUT) #define MASK_UEP_R_RES 0x0C // bit mask of handshake response type for USB endpoint X receiving (OUT) #define UEP_R_RES_ACK 0x00 #define UEP_R_RES_TOUT 0x04 #define UEP_R_RES_NAK 0x08 #define UEP_R_RES_STALL 0x0C // RB_UEP_R_RES1 & RB_UEP_R_RES0: handshake response type for USB endpoint X receiving (OUT) // 00: ACK (ready) // 01: no response, time out to host, for non-zero endpoint isochronous transactions // 10: NAK (busy) // 11: STALL (error) #define RB_UEP_T_RES1 0x02 // handshake response type high bit for USB endpoint X transmittal (IN) #define RB_UEP_T_RES0 0x01 // handshake response type low bit for USB endpoint X transmittal (IN) #define MASK_UEP_T_RES 0x03 // bit mask of handshake response type for USB endpoint X transmittal (IN) #define UEP_T_RES_ACK 0x00 #define UEP_T_RES_TOUT 0x01 #define UEP_T_RES_NAK 0x02 #define UEP_T_RES_STALL 0x03 // bUEP_T_RES1 & bUEP_T_RES0: handshake response type for USB endpoint X transmittal (IN) // 00: DATA0 or DATA1 then expecting ACK (ready) // 01: DATA0 or DATA1 then expecting no response, time out from host, for non-zero endpoint isochronous transactions // 10: NAK (busy) // 11: STALL (error) #define R8_UH_SETUP R8_UEP1_CTRL // host aux setup #define RB_UH_PRE_PID_EN 0x80 // USB host PRE PID enable for low speed device via hub #define RB_UH_SOF_EN 0x40 // USB host automatic SOF enable #define R32_USB_EP2_CTRL (*((PUINT32V)(0x40023428))) // endpoint 2 control & transmittal length #define R8_UEP2_T_LEN (*((PUINT8V)(0x40023428))) // endpoint 2 transmittal length #define R8_UEP2_CTRL (*((PUINT8V)(0x4002342a))) // endpoint 2 control #define R8_UH_EP_PID R8_UEP2_T_LEN // host endpoint and PID #define MASK_UH_TOKEN 0xF0 // bit mask of token PID for USB host transfer #define MASK_UH_ENDP 0x0F // bit mask of endpoint number for USB host transfer #define R8_UH_RX_CTRL R8_UEP2_CTRL // host receiver endpoint control #define RB_UH_R_TOG 0x80 // expected data toggle flag of host receiving (IN): 0=DATA0, 1=DATA1 #define RB_UH_R_AUTO_TOG 0x10 // enable automatic toggle after successful transfer completion: 0=manual toggle, 1=automatic toggle #define RB_UH_R_RES 0x04 // prepared handshake response type for host receiving (IN): 0=ACK (ready), 1=no response, time out to device, for isochronous transactions #define R32_USB_EP3_CTRL (*((PUINT32V)(0x4002342c))) // endpoint 3 control & transmittal length #define R8_UEP3_T_LEN (*((PUINT8V)(0x4002342c))) // endpoint 3 transmittal length #define R8_UEP3_CTRL (*((PUINT8V)(0x4002342e))) // endpoint 3 control #define R8_UH_TX_LEN R8_UEP3_T_LEN // host transmittal endpoint transmittal length #define R8_UH_TX_CTRL R8_UEP3_CTRL // host transmittal endpoint control #define RB_UH_T_TOG 0x40 // prepared data toggle flag of host transmittal (SETUP/OUT): 0=DATA0, 1=DATA1 #define RB_UH_T_AUTO_TOG 0x10 // enable automatic toggle after successful transfer completion: 0=manual toggle, 1=automatic toggle #define RB_UH_T_RES 0x01 // expected handshake response type for host transmittal (SETUP/OUT): 0=ACK (ready), 1=no response, time out from device, for isochronous transactions #define R32_USB_EP4_CTRL (*((PUINT32V)(0x40023430))) // endpoint 4 control & transmittal length #define R8_UEP4_T_LEN (*((PUINT8V)(0x40023430))) // endpoint 4 transmittal length #define R8_UEP4_CTRL (*((PUINT8V)(0x40023432))) // endpoint 4 control #define R8_USB_TYPE_C_CTRL (*((PUINT8V)(0x40023438))) // USB type-C control #define RB_UTCC_GP_BIT 0x80 // USB general purpose bit #define RB_UCC2_PD_EN 0x40 // USB CC2 5.1K pulldown resistance: 0=disable, 1=enable pulldown #define RB_UCC2_PU1_EN 0x20 // USB CC2 pullup resistance control high bit #define RB_UCC2_PU0_EN 0x10 // USB CC2 pullup resistance control low bit #define RB_VBUS_PD_EN 0x08 // USB VBUS 10K pulldown resistance: 0=disable, 1=enable pullup #define RB_UCC1_PD_EN 0x04 // USB CC1 5.1K pulldown resistance: 0=disable, 1=enable pulldown #define RB_UCC1_PU1_EN 0x02 // USB CC1 pullup resistance control high bit #define RB_UCC1_PU0_EN 0x01 // USB CC1 pullup resistance control low bit // RB_UCC?_PU1_EN & RB_UCC?_PU0_EN: USB CC pullup resistance selection // 00: disable pullup resistance // 01: enable 36K pullup resistance for default USB power // 10: enable 12K pullup resistance for 1.5A USB power // 11: enable 4.7K pullup resistance for 3A USB power #ifdef __cplusplus } #endif #endif //__CH32F10x_USB_H #ifndef __USB_TYPE__ #define __USB_TYPE__ #ifdef __cplusplus extern "C" { #endif /*----- USB constant and structure define --------------------------------*/ /* USB PID */ #ifndef USB_PID_SETUP #define USB_PID_NULL 0x00 /* reserved PID */ #define USB_PID_SOF 0x05 #define USB_PID_SETUP 0x0D #define USB_PID_IN 0x09 #define USB_PID_OUT 0x01 #define USB_PID_ACK 0x02 #define USB_PID_NAK 0x0A #define USB_PID_STALL 0x0E #define USB_PID_DATA0 0x03 #define USB_PID_DATA1 0x0B #define USB_PID_PRE 0x0C #endif /* USB standard device request code */ #ifndef USB_GET_DESCRIPTOR #define USB_GET_STATUS 0x00 #define USB_CLEAR_FEATURE 0x01 #define USB_SET_FEATURE 0x03 #define USB_SET_ADDRESS 0x05 #define USB_GET_DESCRIPTOR 0x06 #define USB_SET_DESCRIPTOR 0x07 #define USB_GET_CONFIGURATION 0x08 #define USB_SET_CONFIGURATION 0x09 #define USB_GET_INTERFACE 0x0A #define USB_SET_INTERFACE 0x0B #define USB_SYNCH_FRAME 0x0C #endif /* USB hub class request code */ #ifndef HUB_GET_DESCRIPTOR #define HUB_GET_STATUS 0x00 #define HUB_CLEAR_FEATURE 0x01 #define HUB_GET_STATE 0x02 #define HUB_SET_FEATURE 0x03 #define HUB_GET_DESCRIPTOR 0x06 #define HUB_SET_DESCRIPTOR 0x07 #endif /* USB HID class request code */ #ifndef HID_GET_REPORT #define HID_GET_REPORT 0x01 #define HID_GET_IDLE 0x02 #define HID_GET_PROTOCOL 0x03 #define HID_SET_REPORT 0x09 #define HID_SET_IDLE 0x0A #define HID_SET_PROTOCOL 0x0B #endif /* Bit define for USB request type */ #ifndef USB_REQ_TYP_MASK #define USB_REQ_TYP_IN 0x80 /* control IN, device to host */ #define USB_REQ_TYP_OUT 0x00 /* control OUT, host to device */ #define USB_REQ_TYP_READ 0x80 /* control read, device to host */ #define USB_REQ_TYP_WRITE 0x00 /* control write, host to device */ #define USB_REQ_TYP_MASK 0x60 /* bit mask of request type */ #define USB_REQ_TYP_STANDARD 0x00 #define USB_REQ_TYP_CLASS 0x20 #define USB_REQ_TYP_VENDOR 0x40 #define USB_REQ_TYP_RESERVED 0x60 #define USB_REQ_RECIP_MASK 0x1F /* bit mask of request recipient */ #define USB_REQ_RECIP_DEVICE 0x00 #define USB_REQ_RECIP_INTERF 0x01 #define USB_REQ_RECIP_ENDP 0x02 #define USB_REQ_RECIP_OTHER 0x03 #endif /* USB request type for hub class request */ #ifndef HUB_GET_HUB_DESCRIPTOR #define HUB_CLEAR_HUB_FEATURE 0x20 #define HUB_CLEAR_PORT_FEATURE 0x23 #define HUB_GET_BUS_STATE 0xA3 #define HUB_GET_HUB_DESCRIPTOR 0xA0 #define HUB_GET_HUB_STATUS 0xA0 #define HUB_GET_PORT_STATUS 0xA3 #define HUB_SET_HUB_DESCRIPTOR 0x20 #define HUB_SET_HUB_FEATURE 0x20 #define HUB_SET_PORT_FEATURE 0x23 #endif /* Hub class feature selectors */ #ifndef HUB_PORT_RESET #define HUB_C_HUB_LOCAL_POWER 0 #define HUB_C_HUB_OVER_CURRENT 1 #define HUB_PORT_CONNECTION 0 #define HUB_PORT_ENABLE 1 #define HUB_PORT_SUSPEND 2 #define HUB_PORT_OVER_CURRENT 3 #define HUB_PORT_RESET 4 #define HUB_PORT_POWER 8 #define HUB_PORT_LOW_SPEED 9 #define HUB_C_PORT_CONNECTION 16 #define HUB_C_PORT_ENABLE 17 #define HUB_C_PORT_SUSPEND 18 #define HUB_C_PORT_OVER_CURRENT 19 #define HUB_C_PORT_RESET 20 #endif /* USB descriptor type */ #ifndef USB_DESCR_TYP_DEVICE #define USB_DESCR_TYP_DEVICE 0x01 #define USB_DESCR_TYP_CONFIG 0x02 #define USB_DESCR_TYP_STRING 0x03 #define USB_DESCR_TYP_INTERF 0x04 #define USB_DESCR_TYP_ENDP 0x05 #define USB_DESCR_TYP_QUALIF 0x06 #define USB_DESCR_TYP_SPEED 0x07 #define USB_DESCR_TYP_OTG 0x09 #define USB_DESCR_TYP_HID 0x21 #define USB_DESCR_TYP_REPORT 0x22 #define USB_DESCR_TYP_PHYSIC 0x23 #define USB_DESCR_TYP_CS_INTF 0x24 #define USB_DESCR_TYP_CS_ENDP 0x25 #define USB_DESCR_TYP_HUB 0x29 #endif /* USB device class */ #ifndef USB_DEV_CLASS_HUB #define USB_DEV_CLASS_RESERVED 0x00 #define USB_DEV_CLASS_AUDIO 0x01 #define USB_DEV_CLASS_COMMUNIC 0x02 #define USB_DEV_CLASS_HID 0x03 #define USB_DEV_CLASS_MONITOR 0x04 #define USB_DEV_CLASS_PHYSIC_IF 0x05 #define USB_DEV_CLASS_POWER 0x06 #define USB_DEV_CLASS_PRINTER 0x07 #define USB_DEV_CLASS_STORAGE 0x08 #define USB_DEV_CLASS_HUB 0x09 #define USB_DEV_CLASS_VEN_SPEC 0xFF #endif /* USB endpoint type and attributes */ #ifndef USB_ENDP_TYPE_MASK #define USB_ENDP_DIR_MASK 0x80 #define USB_ENDP_ADDR_MASK 0x0F #define USB_ENDP_TYPE_MASK 0x03 #define USB_ENDP_TYPE_CTRL 0x00 #define USB_ENDP_TYPE_ISOCH 0x01 #define USB_ENDP_TYPE_BULK 0x02 #define USB_ENDP_TYPE_INTER 0x03 #endif #ifndef USB_DEVICE_ADDR #define USB_DEVICE_ADDR 0x02 #endif #ifndef DEFAULT_ENDP0_SIZE #define DEFAULT_ENDP0_SIZE 8 /* default maximum packet size for endpoint 0 */ #endif #ifndef MAX_PACKET_SIZE #define MAX_PACKET_SIZE 64 /* maximum packet size */ #endif #ifndef USB_BO_CBW_SIZE #define USB_BO_CBW_SIZE 0x1F #define USB_BO_CSW_SIZE 0x0D #endif #ifndef USB_BO_CBW_SIG0 #define USB_BO_CBW_SIG0 0x55 #define USB_BO_CBW_SIG1 0x53 #define USB_BO_CBW_SIG2 0x42 #define USB_BO_CBW_SIG3 0x43 #define USB_BO_CSW_SIG0 0x55 #define USB_BO_CSW_SIG1 0x53 #define USB_BO_CSW_SIG2 0x42 #define USB_BO_CSW_SIG3 0x53 #endif #ifndef __PACKED #define __PACKED __packed #endif __PACKED typedef struct _USB_SETUP_REQ { UINT8 bRequestType; UINT8 bRequest; UINT16 wValue; UINT16 wIndex; UINT16 wLength; } USB_SETUP_REQ, *PUSB_SETUP_REQ; __PACKED typedef struct _USB_DEVICE_DESCR { UINT8 bLength; UINT8 bDescriptorType; UINT16 bcdUSB; UINT8 bDeviceClass; UINT8 bDeviceSubClass; UINT8 bDeviceProtocol; UINT8 bMaxPacketSize0; UINT16 idVendor; UINT16 idProduct; UINT16 bcdDevice; UINT8 iManufacturer; UINT8 iProduct; UINT8 iSerialNumber; UINT8 bNumConfigurations; } USB_DEV_DESCR, *PUSB_DEV_DESCR; __PACKED typedef struct _USB_CONFIG_DESCR { UINT8 bLength; UINT8 bDescriptorType; UINT16 wTotalLength; UINT8 bNumInterfaces; UINT8 bConfigurationValue; UINT8 iConfiguration; UINT8 bmAttributes; UINT8 MaxPower; } USB_CFG_DESCR, *PUSB_CFG_DESCR; __PACKED typedef struct _USB_INTERF_DESCR { UINT8 bLength; UINT8 bDescriptorType; UINT8 bInterfaceNumber; UINT8 bAlternateSetting; UINT8 bNumEndpoints; UINT8 bInterfaceClass; UINT8 bInterfaceSubClass; UINT8 bInterfaceProtocol; UINT8 iInterface; } USB_ITF_DESCR, *PUSB_ITF_DESCR; __PACKED typedef struct _USB_ENDPOINT_DESCR { UINT8 bLength; UINT8 bDescriptorType; UINT8 bEndpointAddress; UINT8 bmAttributes; UINT16 wMaxPacketSize; UINT8 bInterval; } USB_ENDP_DESCR, *PUSB_ENDP_DESCR; __packed typedef struct _USB_CONFIG_DESCR_LONG { USB_CFG_DESCR cfg_descr; USB_ITF_DESCR itf_descr; USB_ENDP_DESCR endp_descr[1]; } USB_CFG_DESCR_LONG, *PUSB_CFG_DESCR_LONG; __PACKED typedef struct _USB_HUB_DESCR { UINT8 bDescLength; UINT8 bDescriptorType; UINT8 bNbrPorts; UINT8 wHubCharacteristicsL; UINT8 wHubCharacteristicsH; UINT8 bPwrOn2PwrGood; UINT8 bHubContrCurrent; UINT8 DeviceRemovable; UINT8 PortPwrCtrlMask; } USB_HUB_DESCR, *PUSB_HUB_DESCR; __PACKED typedef struct _USB_HID_DESCR { UINT8 bLength; UINT8 bDescriptorType; UINT16 bcdHID; UINT8 bCountryCode; UINT8 bNumDescriptors; UINT8 bDescriptorTypeX; UINT8 wDescriptorLengthL; UINT8 wDescriptorLengthH; } USB_HID_DESCR, *PUSB_HID_DESCR; __PACKED typedef struct _UDISK_BOC_CBW {/* command of BulkOnly USB-FlashDisk */ UINT32 mCBW_Sig; UINT32 mCBW_Tag; UINT32 mCBW_DataLen; /* uppest byte of data length, always is 0 */ UINT8 mCBW_Flag; /* transfer direction and etc. */ UINT8 mCBW_LUN; UINT8 mCBW_CB_Len; /* length of command block */ UINT8 mCBW_CB_Buf[16]; /* command block buffer */ } UDISK_BOC_CBW, *PUDISK_BOC_CBW; __PACKED typedef struct _UDISK_BOC_CSW {/* status of BulkOnly USB-FlashDisk */ UINT32 mCBW_Sig; UINT32 mCBW_Tag; UINT32 mCSW_Residue; /* return: remainder bytes */ /* uppest byte of remainder length, always is 0 */ UINT8 mCSW_Status; /* return: result status */ } UDISK_BOC_CSW, *PUDISK_BOC_CSW; extern PUINT8 pEP0_RAM_Addr; //ep0(64)+ep4_out(64)+ep4_in(64) extern PUINT8 pEP1_RAM_Addr; //ep1_out(64)+ep1_in(64) extern PUINT8 pEP2_RAM_Addr; //ep2_out(64)+ep2_in(64) extern PUINT8 pEP3_RAM_Addr; //ep3_out(64)+ep3_in(64) #define pSetupReqPak ((PUSB_SETUP_REQ)pEP0_RAM_Addr) #define pEP0_DataBuf (pEP0_RAM_Addr) #define pEP1_OUT_DataBuf (pEP1_RAM_Addr) #define pEP1_IN_DataBuf (pEP1_RAM_Addr+64) #define pEP2_OUT_DataBuf (pEP2_RAM_Addr) #define pEP2_IN_DataBuf (pEP2_RAM_Addr+64) #define pEP3_OUT_DataBuf (pEP3_RAM_Addr) #define pEP3_IN_DataBuf (pEP3_RAM_Addr+64) #define pEP4_OUT_DataBuf (pEP0_RAM_Addr+64) #define pEP4_IN_DataBuf (pEP0_RAM_Addr+128) void USB_DeviceInit( void ); void USB_DevTransProcess( void ); void DevEP1_OUT_Deal( UINT8 l ); void DevEP2_OUT_Deal( UINT8 l ); void DevEP3_OUT_Deal( UINT8 l ); void DevEP4_OUT_Deal( UINT8 l ); void DevEP1_IN_Deal( UINT8 l ); void DevEP2_IN_Deal( UINT8 l ); void DevEP3_IN_Deal( UINT8 l ); void DevEP4_IN_Deal( UINT8 l ); void Set_USBClock(void); #define EP1_GetINSta() (R8_UEP1_CTRL&UEP_T_RES_NAK) #define EP2_GetINSta() (R8_UEP2_CTRL&UEP_T_RES_NAK) #define EP3_GetINSta() (R8_UEP3_CTRL&UEP_T_RES_NAK) #define EP4_GetINSta() (R8_UEP4_CTRL&UEP_T_RES_NAK) #ifdef __cplusplus } #endif #endif // __USB_TYPE__ #ifndef __CH32F10x_USBHOST_H__ #define __CH32F10x_USBHOST_H__ #ifdef __cplusplus extern "C" { #endif #define ERR_SUCCESS 0x00 #define ERR_USB_CONNECT 0x15 #define ERR_USB_DISCON 0x16 #define ERR_USB_BUF_OVER 0x17 #define ERR_USB_DISK_ERR 0x1F #define ERR_USB_TRANSFER 0x20 #define ERR_USB_UNSUPPORT 0xFB #define ERR_USB_UNKNOWN 0xFE #define ERR_AOA_PROTOCOL 0x41 #define ROOT_DEV_DISCONNECT 0 #define ROOT_DEV_CONNECTED 1 #define ROOT_DEV_FAILED 2 #define ROOT_DEV_SUCCESS 3 #define DEV_TYPE_KEYBOARD ( USB_DEV_CLASS_HID | 0x20 ) #define DEV_TYPE_MOUSE ( USB_DEV_CLASS_HID | 0x30 ) #define DEF_AOA_DEVICE 0xF0 #define DEV_TYPE_UNKNOW 0xFF #define HUB_MAX_PORTS 4 #define WAIT_USB_TOUT_200US 800 typedef struct { UINT8 DeviceStatus; UINT8 DeviceAddress; UINT8 DeviceSpeed; UINT8 DeviceType; UINT16 DeviceVID; UINT16 DevicePID; UINT8 GpVar[4]; UINT8 GpHUBPortNum[4]; } _RootHubDev; extern _RootHubDev ThisUsbDev; extern UINT8 UsbDevEndp0Size; extern UINT8 FoundNewDev; extern PUINT8 pHOST_RX_RAM_Addr; extern PUINT8 pHOST_TX_RAM_Addr; #define pSetupReq ((PUSB_SETUP_REQ)pHOST_TX_RAM_Addr) extern const UINT8 SetupGetDevDescr[]; extern const UINT8 SetupGetCfgDescr[]; extern const UINT8 SetupSetUsbAddr[]; extern const UINT8 SetupSetUsbConfig[]; extern const UINT8 SetupSetUsbInterface[]; extern const UINT8 SetupClrEndpStall[]; void DisableRootHubPort(void) ; UINT8 AnalyzeRootHub( void ) ; void SetHostUsbAddr( UINT8 addr ); void SetUsbSpeed( UINT8 FullSpeed ); void ResetRootHubPort(void); UINT8 EnableRootHubPort(void); void SelectHubPort( UINT8 HubPortIndex ); UINT8 WaitUSB_Interrupt( void ); UINT8 USBHostTransact( UINT8 endp_pid, UINT8 tog, UINT16 timeout ); UINT8 HostCtrlTransfer( PUINT8 DataBuf, PUINT16 RetLen ); void CopySetupReqPkg( const UINT8 *pReqPkt ); UINT8 CtrlGetDeviceDescr( PUINT8 DataBuf ); UINT8 CtrlGetConfigDescr( PUINT8 DataBuf ); UINT8 CtrlSetUsbAddress( UINT8 addr ); UINT8 CtrlSetUsbConfig( UINT8 cfg ); UINT8 CtrlClearEndpStall( UINT8 endp ) ; UINT8 CtrlSetUsbIntercace( UINT8 cfg ); void DelsyMs( UINT16 t ); void USB_HostInit( void ); UINT8 InitRootDevice( PUINT8 DataBuf ); #ifdef DEBUG #define PRINT(X...) printf(X) #else #define PRINT(X...) #endif #define mDelaymS DelsyMs #define mDelayuS DelsyUs #ifdef __cplusplus } #endif #endif /* __CH32F10x_USBHOST_H */
15,261
1,417
import os import threading import time import typing from hydrus.core import HydrusConstants as HC from hydrus.core import HydrusData from hydrus.core import HydrusGlobals as HG from hydrus.core import HydrusThreading from hydrus.client.gui import QtPorting as QP class JobKey( object ): def __init__( self, pausable = False, cancellable = False, maintenance_mode = HC.MAINTENANCE_FORCED, only_start_if_unbusy = False, stop_time = None, cancel_on_shutdown = True ): self._key = HydrusData.GenerateKey() self._creation_time = HydrusData.GetNowFloat() self._pausable = pausable self._cancellable = cancellable self._maintenance_mode = maintenance_mode self._only_start_if_unbusy = only_start_if_unbusy self._stop_time = stop_time self._cancel_on_shutdown = cancel_on_shutdown self._start_time = HydrusData.GetNow() self._deleted = threading.Event() self._deletion_time = None self._done = threading.Event() self._cancelled = threading.Event() self._paused = threading.Event() self._ui_update_pause_period = 0.1 self._next_ui_update_pause = HydrusData.GetNowFloat() + self._ui_update_pause_period self._yield_pause_period = 10 self._next_yield_pause = HydrusData.GetNow() + self._yield_pause_period self._bigger_pause_period = 100 self._next_bigger_pause = HydrusData.GetNow() + self._bigger_pause_period self._longer_pause_period = 1000 self._next_longer_pause = HydrusData.GetNow() + self._longer_pause_period self._exception = None self._urls = [] self._variable_lock = threading.Lock() self._variables = dict() def __eq__( self, other ): if isinstance( other, JobKey ): return self.__hash__() == other.__hash__() return NotImplemented def __hash__( self ): return self._key.__hash__() def _CheckCancelTests( self ): if not self._cancelled.is_set(): should_cancel = False if self._cancel_on_shutdown and HydrusThreading.IsThreadShuttingDown(): should_cancel = True if HG.client_controller.ShouldStopThisWork( self._maintenance_mode, self._stop_time ): should_cancel = True if should_cancel: self.Cancel() if not self._deleted.is_set(): if self._deletion_time is not None: if HydrusData.TimeHasPassed( self._deletion_time ): self.Finish() self._deleted.set() def AddURL( self, url ): with self._variable_lock: self._urls.append( url ) def Cancel( self, seconds = None ): if seconds is None: self._cancelled.set() self.Finish() else: HG.client_controller.CallLater( seconds, self.Cancel ) def Delete( self, seconds = None ): if seconds is None: self._deletion_time = HydrusData.GetNow() else: self._deletion_time = HydrusData.GetNow() + seconds def DeleteNetworkJob( self ): self.DeleteVariable( 'network_job' ) def DeleteVariable( self, name ): with self._variable_lock: if name in self._variables: del self._variables[ name ] if HydrusData.TimeHasPassedFloat( self._next_ui_update_pause ): time.sleep( 0.00001 ) self._next_ui_update_pause = HydrusData.GetNowFloat() + self._ui_update_pause_period def Finish( self, seconds = None ): if seconds is None: self._done.set() else: HG.client_controller.CallLater( seconds, self.Finish ) def GetCreationTime( self ): return self._creation_time def GetErrorException( self ) -> Exception: if self._exception is None: raise Exception( 'No exception to return!' ) else: return self._exception def GetIfHasVariable( self, name ): with self._variable_lock: if name in self._variables: return self._variables[ name ] else: return None def GetKey( self ): return self._key def GetNetworkJob( self ): return self.GetIfHasVariable( 'network_job' ) def GetStatusTitle( self ) -> typing.Optional[ str ]: return self.GetIfHasVariable( 'status_title' ) def GetTraceback( self ): return self.GetIfHasVariable( 'traceback' ) def GetURLs( self ): with self._variable_lock: return list( self._urls ) def GetUserCallable( self ) -> typing.Optional[ HydrusData.Call ]: return self.GetIfHasVariable( 'user_callable' ) def HadError( self ): return self._exception is not None def HasVariable( self, name ): with self._variable_lock: return name in self._variables def IsCancellable( self ): self._CheckCancelTests() return self._cancellable and not self.IsDone() def IsCancelled( self ): self._CheckCancelTests() return self._cancelled.is_set() def IsDeleted( self ): self._CheckCancelTests() return self._deleted.is_set() def IsDone( self ): self._CheckCancelTests() return self._done.is_set() def IsPausable( self ): self._CheckCancelTests() return self._pausable and not self.IsDone() def IsPaused( self ): self._CheckCancelTests() return self._paused.is_set() and not self.IsDone() def IsWorking( self ): self._CheckCancelTests() return not self.IsDone() def PausePlay( self ): if self._paused.is_set(): self._paused.clear() else: self._paused.set() def SetCancellable( self, value ): self._cancellable = value def SetErrorException( self, e: Exception ): self._exception = e self.Cancel() def SetNetworkJob( self, network_job ): self.SetVariable( 'network_job', network_job ) def SetPausable( self, value ): self._pausable = value def SetStatusTitle( self, title: str ): self.SetVariable( 'status_title', title ) def SetTraceback( self, trace: str ): self.SetVariable( 'traceback', trace ) def SetUserCallable( self, call: HydrusData.Call ): self.SetVariable( 'user_callable', call ) def SetVariable( self, name, value ): with self._variable_lock: self._variables[ name ] = value if HydrusData.TimeHasPassed( self._next_ui_update_pause ): time.sleep( 0.00001 ) self._next_ui_update_pause = HydrusData.GetNow() + self._ui_update_pause_period def TimeRunning( self ): return HydrusData.GetNow() - self._start_time def ToString( self ): stuff_to_print = [] status_title = self.GetStatusTitle() if status_title is not None: stuff_to_print.append( status_title ) with self._variable_lock: if 'popup_text_1' in self._variables: stuff_to_print.append( self._variables[ 'popup_text_1' ] ) if 'popup_text_2' in self._variables: stuff_to_print.append( self._variables[ 'popup_text_2' ] ) trace = self.GetTraceback() if trace is not None: stuff_to_print.append( trace ) stuff_to_print = [ str( s ) for s in stuff_to_print ] try: return os.linesep.join( stuff_to_print ) except: return repr( stuff_to_print ) def WaitIfNeeded( self ): if HydrusData.TimeHasPassed( self._next_yield_pause ): time.sleep( 0.1 ) self._next_yield_pause = HydrusData.GetNow() + self._yield_pause_period if HydrusData.TimeHasPassed( self._next_bigger_pause ): time.sleep( 1 ) self._next_bigger_pause = HydrusData.GetNow() + self._bigger_pause_period if HydrusData.TimeHasPassed( self._longer_pause_period ): time.sleep( 10 ) self._next_longer_pause = HydrusData.GetNow() + self._longer_pause_period i_paused = False should_quit = False while self.IsPaused(): i_paused = True time.sleep( 0.1 ) if self.IsDone(): break if self.IsCancelled(): should_quit = True return ( i_paused, should_quit ) class FileRWLock( object ): class RLock( object ): def __init__( self, parent ): self.parent = parent def __enter__( self ): while not HydrusThreading.IsThreadShuttingDown(): with self.parent.lock: # if there are no writers, we can start reading if not self.parent.there_is_an_active_writer and self.parent.num_waiting_writers == 0: self.parent.num_readers += 1 return # otherwise wait a bit self.parent.read_available_event.wait( 1 ) self.parent.read_available_event.clear() def __exit__( self, exc_type, exc_val, exc_tb ): with self.parent.lock: self.parent.num_readers -= 1 do_write_notify = self.parent.num_readers == 0 and self.parent.num_waiting_writers > 0 if do_write_notify: self.parent.write_available_event.set() class WLock( object ): def __init__( self, parent ): self.parent = parent def __enter__( self ): # let all the readers know that we are bumping up to the front of the queue with self.parent.lock: self.parent.num_waiting_writers += 1 while not HydrusThreading.IsThreadShuttingDown(): with self.parent.lock: # if nothing reading or writing atm, sieze the opportunity if not self.parent.there_is_an_active_writer and self.parent.num_readers == 0: self.parent.num_waiting_writers -= 1 self.parent.there_is_an_active_writer = True return # otherwise wait a bit self.parent.write_available_event.wait( 1 ) self.parent.write_available_event.clear() def __exit__( self, exc_type, exc_val, exc_tb ): with self.parent.lock: self.parent.there_is_an_active_writer = False do_read_notify = self.parent.num_waiting_writers == 0 # reading is now available do_write_notify = self.parent.num_waiting_writers > 0 # another writer is waiting if do_read_notify: self.parent.read_available_event.set() if do_write_notify: self.parent.write_available_event.set() def __init__( self ): self.read = self.RLock( self ) self.write = self.WLock( self ) self.lock = threading.Lock() self.read_available_event = threading.Event() self.write_available_event = threading.Event() self.num_readers = 0 self.num_waiting_writers = 0 self.there_is_an_active_writer = False def IsLocked( self ): with self.lock: return self.num_waiting_writers > 0 or self.there_is_an_active_writer or self.num_readers > 0 def ReadersAreWorking( self ): with self.lock: return self.num_readers > 0 def WritersAreWaitingOrWorking( self ): with self.lock: return self.num_waiting_writers > 0 or self.there_is_an_active_writer class QtAwareJob( HydrusThreading.SingleJob ): PRETTY_CLASS_NAME = 'single UI job' def __init__( self, controller, scheduler, window, initial_delay, work_callable ): HydrusThreading.SingleJob.__init__( self, controller, scheduler, initial_delay, work_callable ) self._window = window def _BootWorker( self ): def qt_code(): if self._window is None or not QP.isValid( self._window ): return self.Work() QP.CallAfter( qt_code ) def _MyWindowDead( self ): return self._window is None or not QP.isValid( self._window ) def IsCancelled( self ): my_window_dead = self._MyWindowDead() if my_window_dead: self._is_cancelled.set() return HydrusThreading.SingleJob.IsCancelled( self ) def IsDead( self ): return self._MyWindowDead() class QtAwareRepeatingJob( HydrusThreading.RepeatingJob ): PRETTY_CLASS_NAME = 'repeating UI job' def __init__( self, controller, scheduler, window, initial_delay, period, work_callable ): HydrusThreading.RepeatingJob.__init__( self, controller, scheduler, initial_delay, period, work_callable ) self._window = window def _QTWork( self ): if self._window is None or not QP.isValid( self._window ): self._window = None return self.Work() def _BootWorker( self ): QP.CallAfter( self._QTWork ) def _MyWindowDead( self ): return self._window is None or not QP.isValid( self._window ) def IsCancelled( self ): my_window_dead = self._MyWindowDead() if my_window_dead: self._is_cancelled.set() return HydrusThreading.SingleJob.IsCancelled( self ) def IsDead( self ): return self._MyWindowDead()
10,155
347
<reponame>hbraha/ovirt-engine<filename>frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/view/ShowHideVfButtonView.java package org.ovirt.engine.ui.common.view; import org.ovirt.engine.ui.common.CommonApplicationConstants; import org.ovirt.engine.ui.common.gin.AssetProvider; import org.ovirt.engine.ui.common.presenter.ShowHideVfPresenterWidget; public class ShowHideVfButtonView extends ToggleActionButtonView implements ShowHideVfPresenterWidget.ViewDef { private static final CommonApplicationConstants constants = AssetProvider.getConstants(); public ShowHideVfButtonView() { super(constants.showVfLabel(), constants.hideVfLabel()); } }
225
721
<gh_stars>100-1000 { "api_id": "metastore:v1beta", "name_pretty": "Dataproc Metastore API", "distribution_name": "google-apis-metastore_v1beta", "language": "ruby", "library_type": "REST" }
96
854
<filename>Python3/696.py __________________________________________________________________________________________________ sample 108 ms submission class Solution: def countBinarySubstrings(self, s: str) -> int: s=list(map(len,s.replace('10','1 0').replace('01','0 1').split(' '))) #print(list(s)) return sum(min(a,b) for a,b in zip(s,s[1:])) __________________________________________________________________________________________________ sample 13132 kb submission class Solution: def countBinarySubstrings(self, s: str) -> int: ret, prev, cur = 0, 0, 1 for i in range(1, len(s)): if s[i-1] != s[i]: ret += min(prev, cur) prev, cur = cur, 1 else: cur += 1 return ret + min(prev, cur) __________________________________________________________________________________________________
323
3,266
package org.antlr.codegen; import java.util.*; public class JavaScriptTarget extends Target { /** Convert an int to a JavaScript Unicode character literal. * * The current JavaScript spec (ECMA-262) doesn't provide for octal * notation in String literals, although some implementations support it. * This method overrides the parent class so that characters will always * be encoded as Unicode literals (e.g. \u0011). */ public String encodeIntAsCharEscape(int v) { String hex = Integer.toHexString(v|0x10000).substring(1,5); return "\\u"+hex; } /** Convert long to two 32-bit numbers separted by a comma. * JavaScript does not support 64-bit numbers, so we need to break * the number into two 32-bit literals to give to the Bit. A number like * 0xHHHHHHHHLLLLLLLL is broken into the following string: * "0xLLLLLLLL, 0xHHHHHHHH" * Note that the low order bits are first, followed by the high order bits. * This is to match how the BitSet constructor works, where the bits are * passed in in 32-bit chunks with low-order bits coming first. * * Note: stole the following two methods from the ActionScript target. */ public String getTarget64BitStringFromValue(long word) { StringBuffer buf = new StringBuffer(22); // enough for the two "0x", "," and " " buf.append("0x"); writeHexWithPadding(buf, Integer.toHexString((int)(word & 0x00000000ffffffffL))); buf.append(", 0x"); writeHexWithPadding(buf, Integer.toHexString((int)(word >> 32))); return buf.toString(); } private void writeHexWithPadding(StringBuffer buf, String digits) { digits = digits.toUpperCase(); int padding = 8 - digits.length(); // pad left with zeros for (int i=1; i<=padding; i++) { buf.append('0'); } buf.append(digits); } }
722
480
/* Copyright (c) [2014 Baidu]. 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. * * File Name : * Author : * Version : $Revision:$ * Date : $Date:$ * Description : * * HISTORY: * Date | Modification | Author * 28/03/2014 | Initial Revision | */ #ifndef _INTERACTION_ #define _INTERACTION_ #include "stdint.h" #include "config.h" #define NOTIFICATION_DEBUG 0 #define NOTIFICATION_BONDING 1 #define NOTIFICATION_BONDED 2 #define NOTIFICATION_TEST 3 #define NOTIFICATION_CHARGING 4 #define NOTIFICATION_CALLING 5 #define NOTIFICATION_ALARM 6 #define NOTIFICATION_LOSE 7 #define NOTIFICATION_SWITCH 8 #define NOTIFICATION_TARGET 9 #define NOTIFICATION_STATE 10 #define NOTIFICATION_ANIMATE 11 // typedef enum { // Bonding = 0, // Charging, // Calling, // Alarm, // Counter, // Sleep, // Unknown // }Notification_Status; void notification_start( uint8_t type, uint16_t value ); void notification_stop( void ); #endif //_INTERACTION_
716
419
<filename>platform/compilation/fota/linux/fotasdk.h<gh_stars>100-1000 /* Copyright (C) 2017 RDA Technologies Limited and/or its affiliates("RDA"). * All rights reserved. * * This software is supplied "AS IS" without any warranties. * RDA assumes no responsibility or liability for the use of the software, * conveys no license or title under any patent, copyright, or mask work * right to the product. RDA reserves the right to make changes in the * software without notification. RDA also make no representation or * warranty that such application will be suitable for the specified use * without further testing or modification. */ #ifndef _FOTA_SDK_H_ #define _FOTA_SDK_H_ #ifdef _WIN32 #ifdef FOTASDK_EXPORTS #define FOTASDK_CAPI extern "C" __declspec(dllexport) #else #define FOTASDK_CAPI extern "C" __declspec(dllimport) #endif #else #ifdef FOTASDK_EXPORTS #define FOTASDK_CAPI extern "C" __attribute__((__visibility__("default"))) #else #define FOTASDK_CAPI extern "C" #endif #endif enum { ERR_INVALID_SECTOR_SIZE = 1, // must be 2^n ERR_CODE_BASE_UNALIGNED, ERR_CODE_SIZE_UNALIGNED, ERR_FOTA_END_UNAIGNED, // FOTA area end must be block aligned ERR_FOTA_START_UNALIGNED, // FOTA area start must be sector aligned ERR_FOTA_INVALID_AREA, // FOTA area not in FLASH range ERR_FAIL_READ_OLD, ERR_FAIL_READ_NEW, ERR_OLD_TOO_MANY_PACKET, // must be contiguous ERR_OLD_SIZE_UNALIGNED, // must be sector aligned ERR_OLD_BASE_MISMATCH, ERR_OLD_SIZE_OVERFLOW, ERR_NEW_TOO_MANY_PACKET, // must be contiguous ERR_NEW_SIZE_UNALIGNED, // must be sector aligned ERR_NEW_BASE_MISMATCH, ERR_NEW_SIZE_OVERFLOW, ERR_FAIL_WRITE_PACK, ERR_FAIL_READ_PACK, ERR_VERIFY_PACK_INVALID, ERR_VERIFY_UPGRADE_FAIL, ERR_VERIFY_UPGRADE_CLEAN_FAIL, ERR_VERIFY_CMP_FAIL }; struct FotaFlashParam { unsigned pysicalBase; // FLASH physical address, such as 0x08000000 unsigned codeFlashBase; // FLASH base for code (must be sector aligned) unsigned codeFlashSize; // FLASH size for code (must be sector aligned) }; // File name strings are encoded as UTF-8 FOTASDK_CAPI int FotaCreatePack(const char *olodfname, // input old LOD file name const char *nlodfname, // input new LOD file name const char *patchfname, // output patch file name unsigned *oldstart, // return old LOD start unsigned *oldsize, // return old LOD size unsigned *oldcrc, // return old data CRC struct FotaFlashParam flash); FOTASDK_CAPI const char *FotaErrorMsg(int result); #endif
1,192
1,374
<reponame>norzak/jsweet /* * TypeScript definitions to Java translator - http://www.jsweet.org * Copyright (C) 2015 CINCHEO SAS <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jsweet.input.typescriptdef.ast; /** * A parsing token. * * @author <NAME> */ public class Token { public int type; /** * Creates a new token * * @param type * the type as defined in the lexer * @param fileName * the name of the file from where the token was extracted * @param text * the text of the token * @param line * the line number where the token appears in the file * @param charBegin * the character where it begins in the file * @param charEnd * the character where it ends in the file */ public Token(int type, String fileName, String text, int line, int charBegin, int charEnd) { this.type = type; this.fileName = fileName; this.text = text; this.line = line; this.charBegin = charBegin; this.charEnd = charEnd; } public String getLocation() { return "" + fileName + ":" + line + "(" + charBegin + ")"; } String fileName; String text; int line; int charBegin; int charEnd; // public boolean equals(Object o) { // System.err.println("equals("+this+","+o+")"); // return text.equals(o.toString()); // } public String toString() { return text; } public int getCharBegin() { return charBegin; } public int getCharEnd() { return charEnd; } public int getLine() { return line; } public String getText() { return text; } public String getFileName() { return fileName; } public int getType() { return type; } }
798
6,717
<gh_stars>1000+ //****************************************************************************** // // Copyright (c) Microsoft. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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. // //****************************************************************************** // WindowsServicesMapsOfflineMaps.h // Generated from winmd2objc #pragma once #ifndef OBJCUWPWINDOWSSERVICESMAPSOFFLINEMAPSEXPORT #define OBJCUWPWINDOWSSERVICESMAPSOFFLINEMAPSEXPORT __declspec(dllimport) #ifndef IN_WinObjC_Frameworks_UWP_BUILD #pragma comment(lib, "ObjCUWPWindowsServicesMapsOfflineMaps.lib") #endif #endif #include <UWP/interopBase.h> @class WSMOOfflineMapPackage, WSMOOfflineMapPackageStartDownloadResult, WSMOOfflineMapPackageQueryResult; @protocol WSMOIOfflineMapPackageQueryResult, WSMOIOfflineMapPackageStartDownloadResult, WSMOIOfflineMapPackage, WSMOIOfflineMapPackageStatics; // Windows.Services.Maps.OfflineMaps.OfflineMapPackageQueryStatus enum _WSMOOfflineMapPackageQueryStatus { WSMOOfflineMapPackageQueryStatusSuccess = 0, WSMOOfflineMapPackageQueryStatusUnknownError = 1, WSMOOfflineMapPackageQueryStatusInvalidCredentials = 2, WSMOOfflineMapPackageQueryStatusNetworkFailure = 3, }; typedef unsigned WSMOOfflineMapPackageQueryStatus; // Windows.Services.Maps.OfflineMaps.OfflineMapPackageStatus enum _WSMOOfflineMapPackageStatus { WSMOOfflineMapPackageStatusNotDownloaded = 0, WSMOOfflineMapPackageStatusDownloading = 1, WSMOOfflineMapPackageStatusDownloaded = 2, WSMOOfflineMapPackageStatusDeleting = 3, }; typedef unsigned WSMOOfflineMapPackageStatus; // Windows.Services.Maps.OfflineMaps.OfflineMapPackageStartDownloadStatus enum _WSMOOfflineMapPackageStartDownloadStatus { WSMOOfflineMapPackageStartDownloadStatusSuccess = 0, WSMOOfflineMapPackageStartDownloadStatusUnknownError = 1, WSMOOfflineMapPackageStartDownloadStatusInvalidCredentials = 2, WSMOOfflineMapPackageStartDownloadStatusDeniedWithoutCapability = 3, }; typedef unsigned WSMOOfflineMapPackageStartDownloadStatus; #include "WindowsFoundation.h" #include "WindowsDevicesGeolocation.h" #import <Foundation/Foundation.h> // Windows.Services.Maps.OfflineMaps.OfflineMapPackage #ifndef __WSMOOfflineMapPackage_DEFINED__ #define __WSMOOfflineMapPackage_DEFINED__ OBJCUWPWINDOWSSERVICESMAPSOFFLINEMAPSEXPORT @interface WSMOOfflineMapPackage : RTObject + (void)findPackagesAsync:(WDGGeopoint*)queryPoint success:(void (^)(WSMOOfflineMapPackageQueryResult*))success failure:(void (^)(NSError*))failure; + (void)findPackagesInBoundingBoxAsync:(WDGGeoboundingBox*)queryBoundingBox success:(void (^)(WSMOOfflineMapPackageQueryResult*))success failure:(void (^)(NSError*))failure; + (void)findPackagesInGeocircleAsync:(WDGGeocircle*)queryCircle success:(void (^)(WSMOOfflineMapPackageQueryResult*))success failure:(void (^)(NSError*))failure; #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSString * displayName; @property (readonly) NSString * enclosingRegionName; @property (readonly) uint64_t estimatedSizeInBytes; @property (readonly) WSMOOfflineMapPackageStatus status; - (EventRegistrationToken)addStatusChangedEvent:(void(^)(WSMOOfflineMapPackage*, RTObject*))del; - (void)removeStatusChangedEvent:(EventRegistrationToken)tok; - (void)requestStartDownloadAsyncWithSuccess:(void (^)(WSMOOfflineMapPackageStartDownloadResult*))success failure:(void (^)(NSError*))failure; @end #endif // __WSMOOfflineMapPackage_DEFINED__ // Windows.Services.Maps.OfflineMaps.OfflineMapPackageStartDownloadResult #ifndef __WSMOOfflineMapPackageStartDownloadResult_DEFINED__ #define __WSMOOfflineMapPackageStartDownloadResult_DEFINED__ OBJCUWPWINDOWSSERVICESMAPSOFFLINEMAPSEXPORT @interface WSMOOfflineMapPackageStartDownloadResult : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) WSMOOfflineMapPackageStartDownloadStatus status; @end #endif // __WSMOOfflineMapPackageStartDownloadResult_DEFINED__ // Windows.Services.Maps.OfflineMaps.OfflineMapPackageQueryResult #ifndef __WSMOOfflineMapPackageQueryResult_DEFINED__ #define __WSMOOfflineMapPackageQueryResult_DEFINED__ OBJCUWPWINDOWSSERVICESMAPSOFFLINEMAPSEXPORT @interface WSMOOfflineMapPackageQueryResult : RTObject #if defined(__cplusplus) + (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased)); #endif @property (readonly) NSArray* /* WSMOOfflineMapPackage* */ packages; @property (readonly) WSMOOfflineMapPackageQueryStatus status; @end #endif // __WSMOOfflineMapPackageQueryResult_DEFINED__
1,657
1,325
#ifndef VOXEL_BLOCK_SERIALIZER_H #define VOXEL_BLOCK_SERIALIZER_H #include "../util/span.h" #include <core/io/file_access_memory.h> #include <core/reference.h> #include <vector> class StreamPeer; class VoxelBufferInternal; class VoxelBlockSerializerInternal { // Had to be named differently to not conflict with the wrapper for Godot script API public: struct SerializeResult { const std::vector<uint8_t> &data; bool success; inline SerializeResult(const std::vector<uint8_t> &p_data, bool p_success) : data(p_data), success(p_success) {} }; SerializeResult serialize(const VoxelBufferInternal &voxel_buffer); bool deserialize(Span<const uint8_t> p_data, VoxelBufferInternal &out_voxel_buffer); SerializeResult serialize_and_compress(const VoxelBufferInternal &voxel_buffer); bool decompress_and_deserialize(Span<const uint8_t> p_data, VoxelBufferInternal &out_voxel_buffer); bool decompress_and_deserialize(FileAccess *f, unsigned int size_to_read, VoxelBufferInternal &out_voxel_buffer); int serialize(Ref<StreamPeer> peer, VoxelBufferInternal &voxel_buffer, bool compress); void deserialize(Ref<StreamPeer> peer, VoxelBufferInternal &voxel_buffer, int size, bool decompress); private: // Make thread-locals? std::vector<uint8_t> _data; std::vector<uint8_t> _compressed_data; std::vector<uint8_t> _metadata_tmp; FileAccessMemory _file_access_memory; }; class VoxelBuffer; class VoxelBlockSerializer : public Reference { GDCLASS(VoxelBlockSerializer, Reference) public: int serialize(Ref<StreamPeer> peer, Ref<VoxelBuffer> voxel_buffer, bool compress); void deserialize(Ref<StreamPeer> peer, Ref<VoxelBuffer> voxel_buffer, int size, bool decompress); private: static void _bind_methods(); VoxelBlockSerializerInternal _serializer; }; #endif // VOXEL_BLOCK_SERIALIZER_H
641
319
/** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.demos; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.openimaj.feature.local.list.LocalFeatureList; import org.openimaj.feature.local.matcher.FastBasicKeypointMatcher; import org.openimaj.feature.local.matcher.MatchingUtilities; import org.openimaj.image.DisplayUtilities; import org.openimaj.image.FImage; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.colour.RGBColour; import org.openimaj.image.feature.local.engine.DoGSIFTEngine; import org.openimaj.image.feature.local.keypoints.Keypoint; import org.openimaj.math.geometry.line.Line2d; import org.openimaj.math.geometry.point.Point2d; import org.openimaj.math.geometry.shape.Shape; import org.openimaj.math.geometry.shape.Triangle; import org.openimaj.math.geometry.triangulation.DelaunayTriangulator; import org.openimaj.util.pair.Pair; public class DTConsistency { public static int computeDTScore(List<? extends Pair<? extends Point2d>> matches) { final int size = matches.size(); if (size <= 1) return 0; if (size == 2) return 1; if (size == 3) return 3; final List<Triangle> t1 = triangulateFirst(matches); final List<Triangle> t2 = triangulateSecond(matches); int commonEdges = 0; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { final boolean e1 = hasEdge(matches.get(i).firstObject(), matches.get(j).firstObject(), t1); final boolean e2 = hasEdge(matches.get(i).secondObject(), matches.get(j).secondObject(), t2); if (e1 && e2) commonEdges++; } } return commonEdges; } public static class DTConsistencyInfo { public List<Triangle> firstTrianglulation; public List<Triangle> secondTrianglulation; public List<Line2d> firstCommonEdges = new ArrayList<Line2d>(); public List<Line2d> secondCommonEdges = new ArrayList<Line2d>(); } public static DTConsistencyInfo computeTriangulationInfo(List<? extends Pair<? extends Point2d>> matches) { final int size = matches.size(); if (size <= 3) return null; final DTConsistencyInfo info = new DTConsistencyInfo(); info.firstTrianglulation = triangulateFirst(matches); info.secondTrianglulation = triangulateSecond(matches); for (int i = 0; i < size; i++) { final Point2d firsti = matches.get(i).firstObject(); final Point2d secondi = matches.get(i).secondObject(); for (int j = i + 1; j < size; j++) { final Point2d firstj = matches.get(j).firstObject(); final Point2d secondj = matches.get(j).secondObject(); final boolean e1 = hasEdge(firsti, firstj, info.firstTrianglulation); final boolean e2 = hasEdge(secondi, secondj, info.secondTrianglulation); if (e1 && e2) { info.firstCommonEdges.add(new Line2d(firsti, firstj)); info.secondCommonEdges.add(new Line2d(secondi, secondj)); } } } return info; } @SuppressWarnings("unchecked") public static List<Triangle> triangulateFirst(List<? extends Pair<? extends Point2d>> matches) { return DelaunayTriangulator.triangulate(Pair.getFirst((Iterable<Pair<Point2d>>) matches)); } @SuppressWarnings("unchecked") public static List<Triangle> triangulateSecond(List<? extends Pair<? extends Point2d>> matches) { return DelaunayTriangulator.triangulate(Pair.getSecond((Iterable<Pair<Point2d>>) matches)); } /** * Search for an edge between the given points in any of the triangles * * @param pt1 * @param pt2 * @param tris * @return */ private static boolean hasEdge(Point2d pt1, Point2d pt2, List<Triangle> tris) { for (final Triangle t : tris) { boolean foundP1 = false; boolean foundP2 = false; for (int i = 0; i < 3; i++) { if (t.vertices[i] == pt1) foundP1 = true; if (t.vertices[i] == pt2) foundP2 = true; } if (foundP1 && foundP2) return true; } return false; } public static List<Pair<Keypoint>> filterDuplicatePoints(List<Pair<Keypoint>> matches) { final List<Point2d> d1 = getDuplicatePoints(Pair.getFirst(matches)); final List<Point2d> d2 = getDuplicatePoints(Pair.getSecond(matches)); final List<Pair<Keypoint>> toRemove = new ArrayList<Pair<Keypoint>>(); for (final Pair<Keypoint> p : matches) { for (final Point2d d : d1) { if (p.firstObject() == d) toRemove.add(p); } } for (final Pair<Keypoint> p : matches) { for (final Point2d d : d2) { if (p.secondObject() == d) toRemove.add(p); } } matches.removeAll(toRemove); return matches; } public static List<Point2d> getDuplicatePoints(List<? extends Point2d> pts) { final List<Point2d> dups = new ArrayList<Point2d>(); for (int i = 0; i < pts.size(); i++) { final Point2d pti = pts.get(i); for (int j = 0; j < pts.size(); j++) { final Point2d ptj = pts.get(j); if (i != j) { if (pti.getX() == ptj.getX() && pti.getY() == ptj.getY()) { dups.add(pti); dups.add(ptj); } } } } return dups; } public static void main(String[] args) throws IOException { final FImage image1 = ImageUtilities.readF(new URL( "http://punch-records.co.uk/files/2013/01/Coca-cola-logo-eps-vector-nocturnar-com.jpg")); final FImage image2 = ImageUtilities .readF(new URL( "http://i133.photobucket.com/albums/q78/KylePix/Car%20Shows%20and%20Races/Los%20Angeles%2011/111124-4937CocaColaMotorcycle.jpg")); final DoGSIFTEngine engine = new DoGSIFTEngine(); engine.getOptions().setDoubleInitialImage(true); final LocalFeatureList<Keypoint> keys1 = engine.findFeatures(image1); final LocalFeatureList<Keypoint> keys2 = engine.findFeatures(image2); final FastBasicKeypointMatcher<Keypoint> matcher = new FastBasicKeypointMatcher<Keypoint>(6); matcher.setModelFeatures(keys1); matcher.findMatches(keys2); final List<Pair<Keypoint>> matches = filterDuplicatePoints(matcher.getMatches()); DisplayUtilities.display(MatchingUtilities.drawMatches(image1, image2, matches, 0F)); final DTConsistencyInfo info = DTConsistency.computeTriangulationInfo(matches); final MBFImage i1 = MBFImage.createRGB(image2); final MBFImage i2 = MBFImage.createRGB(image1); i1.drawLines(info.firstCommonEdges, 5, RGBColour.BLUE); i2.drawLines(info.secondCommonEdges, 5, RGBColour.BLUE); for (final Shape s : info.firstTrianglulation) i1.drawShape(s, RGBColour.RED); for (final Shape s : info.secondTrianglulation) i2.drawShape(s, RGBColour.RED); DisplayUtilities.display(i1); DisplayUtilities.display(i2); } }
3,010
420
<filename>src/ui/components/metrics_window.cpp #include "metrics_window.h" #include "ui.h" #include "libs/imgui/imgui.h" #include <inttypes.h> void metrics_window::update(PapayaMemory* mem) { if (!mem->misc.show_metrics) { return; } ImGui::Begin("Metrics"); // ======== // Profiler // ======== if (ImGui::CollapsingHeader("Profiler", 0, true, true)) { ImGui::Columns(3, "profilercolumns"); ImGui::Separator(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Cycles"); ImGui::NextColumn(); ImGui::Text("Millisecs"); ImGui::NextColumn(); ImGui::Separator(); for (i32 i = 0; i < Timer_COUNT; i++) { ImGui::Text("%s", get_timer_name(i)); ImGui::NextColumn(); ImGui::Text("%" PRIu64, timers[i].elapsed_cycles); ImGui::NextColumn(); ImGui::Text("%f", timers[i].elapsed_ms); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::Separator(); } // ===== // Input // ===== if (ImGui::CollapsingHeader("Input", 0, true, true)) { ImGui::Separator(); // Keyboard // -------- ImGui::Text("Keyboard"); ImGui::Columns(2, "inputcolumns"); ImGui::Separator(); ImGui::Text("Shift"); ImGui::NextColumn(); ImGui::Text("%d", mem->keyboard.shift); ImGui::NextColumn(); ImGui::Text("Ctrl"); ImGui::NextColumn(); ImGui::Text("%d", mem->keyboard.ctrl); ImGui::NextColumn(); ImGui::Text("Z"); ImGui::NextColumn(); ImGui::Text("%d", ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Z))); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); // Tablet // ------ ImGui::Text("Tablet"); ImGui::Columns(2, "inputcolumns"); ImGui::Separator(); ImGui::Text("PosX"); ImGui::NextColumn(); ImGui::Text("%d", mem->tablet.pos.x); ImGui::NextColumn(); ImGui::Text("PosY"); ImGui::NextColumn(); ImGui::Text("%d", mem->tablet.pos.y); ImGui::NextColumn(); ImGui::Text("Pressure"); ImGui::NextColumn(); ImGui::Text("%f", mem->tablet.pressure); ImGui::NextColumn(); ImGui::Text("Pen touch"); ImGui::NextColumn(); ImGui::Text((mem->tablet.buttons & EasyTab_Buttons_Pen_Touch) ? "1" : "0"); ImGui::NextColumn(); ImGui::Text("Pen lower"); ImGui::NextColumn(); ImGui::Text((mem->tablet.buttons & EasyTab_Buttons_Pen_Lower) ? "1" : "0"); ImGui::NextColumn(); ImGui::Text("Pen upper"); ImGui::NextColumn(); ImGui::Text((mem->tablet.buttons & EasyTab_Buttons_Pen_Upper) ? "1" : "0"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); // Mouse // ------ ImGui::Text("Mouse"); ImGui::Columns(2, "inputcolumns"); ImGui::Separator(); ImGui::Text("PosX"); ImGui::NextColumn(); ImGui::Text("%d", mem->mouse.pos.x); ImGui::NextColumn(); ImGui::Text("PosY"); ImGui::NextColumn(); ImGui::Text("%d", mem->mouse.pos.y); ImGui::NextColumn(); ImGui::Text("Buttons"); ImGui::NextColumn(); ImGui::Text("%d %d %d", mem->mouse.is_down[0], mem->mouse.is_down[1], mem->mouse.is_down[2]); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); } ImGui::End(); }
2,432
1,444
package mage.cards.i; import java.util.UUID; import mage.MageInt; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.combat.CantBlockAllEffect; import mage.abilities.keyword.DevoidAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Zone; import mage.filter.common.FilterCreaturePermanent; import mage.filter.predicate.Predicate; import mage.game.Game; /** * * @author LevelX2 */ public final class ImmobilizerEldrazi extends CardImpl { private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("Each creature with toughness greater than its power"); static { filter.add(new ImmobilizerEldraziPredicate()); } public ImmobilizerEldrazi(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{R}"); this.subtype.add(SubType.ELDRAZI); this.subtype.add(SubType.DRONE); this.power = new MageInt(2); this.toughness = new MageInt(1); // Devoid this.addAbility(new DevoidAbility(this.color)); // {2}{C}: Each creature with toughness greater than its power can't block this turn. Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new CantBlockAllEffect(filter, Duration.EndOfTurn), new ManaCostsImpl("{2}{C}")); this.addAbility(ability); } private ImmobilizerEldrazi(final ImmobilizerEldrazi card) { super(card); } @Override public ImmobilizerEldrazi copy() { return new ImmobilizerEldrazi(this); } } class ImmobilizerEldraziPredicate implements Predicate<MageObject> { @Override public boolean apply(MageObject input, Game game) { return input.getToughness().getValue() > input.getPower().getValue(); } @Override public String toString() { return "toughness greater than its power"; } }
766
475
<gh_stars>100-1000 /* * Copyright (C) 2020 The zfoo 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 com.zfoo.monitor.model; import com.zfoo.protocol.util.StringUtils; import com.zfoo.scheduler.util.TimeUtils; /** * @author jaysunxiao * @version 3.0 */ public class SarVO implements Comparable<SarVO> { private String name; private long rxpck; private long txpck; private long rxBytes; private long txBytes; private long inErrors; private long outErrors; private long inDrops; private long collisions; private long timestamp; public static SarVO valueOf(String name, long rxpck, long txpck, long rxBytes, long txBytes , long inErrors, long outErrors, long inDrops, long collisions, long timestamp) { var vo = new SarVO(); vo.name = name; vo.rxpck = rxpck; vo.txpck = txpck; vo.rxBytes = rxBytes; vo.txBytes = txBytes; vo.inErrors = inErrors; vo.outErrors = outErrors; vo.inDrops = inDrops; vo.collisions = collisions; vo.timestamp = timestamp; return vo; } public String pressure() { if (rxpck >= 5_0000) { return StringUtils.format("sar - 网卡流量[interface:{}] [rxpck:{}] [txpck:{}] [rxBytes:{}] [txBytes:{}] [inErrors:{}] [outErrors:{}] [inDrops:{}] [collisions:{}] [{}],性能影响:危险" , name, rxpck, txpck, rxBytes, txBytes, inErrors, outErrors, inDrops, collisions, TimeUtils.timeToString(timestamp)); } if (inErrors > 0 || outErrors > 0 || inDrops > 0 || collisions > 0) { return StringUtils.format("sar - 网卡流量[interface:{}] [rxpck:{}] [txpck:{}] [rxBytes:{}] [txBytes:{}] [inErrors:{}] [outErrors:{}] [inDrops:{}] [collisions:{}] [{}],性能影响:低" , name, rxpck, txpck, rxBytes, txBytes, inErrors, outErrors, inDrops, collisions, TimeUtils.timeToString(timestamp)); } return StringUtils.EMPTY; } @Override public int compareTo(SarVO target) { if (target == null) { return 1; } if (!this.name.equals(target.getName())) { return 0; } var a = this.rxpck + this.txpck; var b = target.getRxpck() + target.getTxpck(); return Long.compare(a, b); } @Override public String toString() { return StringUtils.format("[name:{}][rxpck:{}][txpck:{}][rxBytes:{}][txBytes:{}][inErrors:{}][outErrors:{}][inDrops:{}][collisions:{}][time:{}]" , name, rxpck, txpck, rxBytes, txBytes, inErrors, outErrors, inDrops, collisions, TimeUtils.timeToString(timestamp)); } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getRxpck() { return rxpck; } public void setRxpck(long rxpck) { this.rxpck = rxpck; } public long getTxpck() { return txpck; } public void setTxpck(long txpck) { this.txpck = txpck; } public long getRxBytes() { return rxBytes; } public void setRxBytes(long rxBytes) { this.rxBytes = rxBytes; } public long getTxBytes() { return txBytes; } public void setTxBytes(long txBytes) { this.txBytes = txBytes; } public long getInErrors() { return inErrors; } public void setInErrors(long inErrors) { this.inErrors = inErrors; } public long getOutErrors() { return outErrors; } public void setOutErrors(long outErrors) { this.outErrors = outErrors; } public long getInDrops() { return inDrops; } public void setInDrops(long inDrops) { this.inDrops = inDrops; } public long getCollisions() { return collisions; } public void setCollisions(long collisions) { this.collisions = collisions; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } }
2,040
1,600
#include "sum_integers.hpp" #include <vector> int main() { auto integers = {1, 2, 3, 4, 5}; if (sum_integers(integers) == 15) { return 0; } else { return 1; } }
81
317
<gh_stars>100-1000 __all__ = ( 'CLEError', 'CLEUnknownFormatError', 'CLEFileNotFoundError', 'CLEInvalidBinaryError', 'CLEOperationError', 'CLECompatibilityError', ) class CLEError(Exception): """ Base class for errors raised by CLE. """ pass class CLEUnknownFormatError(CLEError): """ Error raised when CLE encounters an unknown executable file format. """ pass class CLEFileNotFoundError(CLEError): """ Error raised when a file does not exist. """ pass class CLEInvalidBinaryError(CLEError): """ Error raised when an executable file is invalid or corrupted. """ pass class CLEOperationError(CLEError): """ Error raised when a problem is encountered in the process of loading an executable. """ pass class CLECompatibilityError(CLEError): """ Error raised when loading an executable that is not currently supported by CLE. """ pass class CLEMemoryError(CLEError): """ Error raised when performing memory operations on unmapped addresses """ pass
361
1,183
{ "name": "@adobe/leonardo-ui", "private": true, "version": "1.3.6", "description": "Demonstration UI for Leonardo", "repository": "<EMAIL>:adobe/leonardo.git", "author": "<NAME> <<EMAIL>>", "scripts": { "serve": "npx parcel src/index.html src/theme.html src/converter.html src/contrast-checker.html src/demo.html --no-hmr", "dev": "yarn copyIcons && yarn serve", "copyIcons": "mkdir -p dist && yarn copyWorkflowIcons && yarn copyUIIcons", "copyWorkflowIcons": "cp -r ../../node_modules/@adobe/spectrum-css-workflow-icons/dist/spectrum-icons.svg dist/", "copyUIIcons": "cp -r ../../node_modules/@spectrum-css/icon/dist/spectrum-css-icons.svg dist/", "copyCNAME": "cp -r src/CNAME dist/CNAME", "postPublish": "yarn deploySite", "buildSite": "npx parcel build --no-minify src/index.html src/theme.html src/converter.html src/contrast-checker.html src/demo.html --public-url ./ && yarn copyCNAME && yarn copyIcons", "deploySite": "yarn buildSite && npx ghpages -p dist" }, "keywords": [ "accessibility", "inclusive", "wcag", "contrast", "color", "contrast-ratio", "a11y", "luminance", "relative-luminance", "accessible", "a11ycolor", "colour", "adaptive", "adaptive-color", "color-generator", "contrast-generator", "color-contrast-generator" ], "license": "Apache-2.0", "devDependencies": { "ghpages": "^0.0.10", "parcel-bundler": "^1.12.4", "sass": "^1.23.6" }, "dependencies": { "@adobe/focus-ring-polyfill": "^0.1.5", "@adobe/leonardo-contrast-colors": "^1.0.0-alpha.12", "@adobe/spectrum-css-workflow-icons": "^1.0.0", "@spectrum-css/actionbutton": "^1.0.4", "@spectrum-css/alert": "^2.0.2", "@spectrum-css/button": "^2.0.2", "@spectrum-css/buttongroup": "^2.0.2", "@spectrum-css/checkbox": "^2.0.2", "@spectrum-css/colorhandle": "^1.0.0-beta.1", "@spectrum-css/colorloupe": "^1.0.0-beta.1", "@spectrum-css/colorslider": "^1.0.2", "@spectrum-css/dialog": "^2.0.2", "@spectrum-css/dropdown": "^2.1.1", "@spectrum-css/fieldgroup": "^2.0.2", "@spectrum-css/fieldlabel": "^2.0.2", "@spectrum-css/icon": "^3.0.4", "@spectrum-css/illustratedmessage": "2.0.0", "@spectrum-css/link": "^2.0.2", "@spectrum-css/menu": "^3.0.4", "@spectrum-css/page": "^2.0.2", "@spectrum-css/picker": "^1.0.4", "@spectrum-css/popover": "^3.0.4", "@spectrum-css/radio": "^2.0.2", "@spectrum-css/slider": "^2.0.2", "@spectrum-css/tabs": "^2.1.1", "@spectrum-css/textfield": "^2.0.2", "@spectrum-css/toast": "^2.0.4", "@spectrum-css/tooltip": "^2.0.2", "@spectrum-css/typography": "^2.0.2", "@spectrum-css/underlay": "^2.0.2", "@spectrum-css/vars": "^4.0.0", "clipboard": "^2.0.4", "color-blind": "^0.1.1", "d3": "^5.12.0", "d3-3d": "0.0.9", "d3-cam02": "^0.1.5", "d3-hsluv": "^0.1.2", "d3-hsv": "^0.1.0", "loadicons": "^1.0.0" } }
1,465
711
<filename>java110-bean/src/main/java/com/java110/vo/api/community/ApiCommunityDataVo.java package com.java110.vo.api.community; import com.java110.dto.community.CommunityAttrDto; import java.io.Serializable; import java.util.List; public class ApiCommunityDataVo implements Serializable { private String communityMemberId; private String communityId; private String name; private String address; private String nearbyLandmarks; private String cityCode; private String cityName; private String mapX; private String mapY; private String state; private String auditStatusCd; private String stateName; private String memberId; private String storeName; private String storeTypeCd; private String storeTypeName; private String tel; private List<CommunityAttrDto> communityAttrDtos; public String getCommunityId() { return communityId; } public void setCommunityId(String communityId) { this.communityId = communityId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getNearbyLandmarks() { return nearbyLandmarks; } public void setNearbyLandmarks(String nearbyLandmarks) { this.nearbyLandmarks = nearbyLandmarks; } public String getCityCode() { return cityCode; } public void setCityCode(String cityCode) { this.cityCode = cityCode; } public String getMapX() { return mapX; } public void setMapX(String mapX) { this.mapX = mapX; } public String getMapY() { return mapY; } public void setMapY(String mapY) { this.mapY = mapY; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getStateName() { return stateName; } public void setStateName(String stateName) { this.stateName = stateName; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getStoreTypeCd() { return storeTypeCd; } public void setStoreTypeCd(String storeTypeCd) { this.storeTypeCd = storeTypeCd; } public String getStoreTypeName() { return storeTypeName; } public void setStoreTypeName(String storeTypeName) { this.storeTypeName = storeTypeName; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getCommunityMemberId() { return communityMemberId; } public void setCommunityMemberId(String communityMemberId) { this.communityMemberId = communityMemberId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getAuditStatusCd() { return auditStatusCd; } public void setAuditStatusCd(String auditStatusCd) { this.auditStatusCd = auditStatusCd; } public List<CommunityAttrDto> getCommunityAttrDtos() { return communityAttrDtos; } public void setCommunityAttrDtos(List<CommunityAttrDto> communityAttrDtos) { this.communityAttrDtos = communityAttrDtos; } }
1,488
3,262
package com.tencent.angel.psagent.matrix.transport.router.range; import com.tencent.angel.psagent.matrix.transport.router.KeyValuePart; import com.tencent.angel.psagent.matrix.transport.router.RouterType; public abstract class RangeKeyValuePart extends KeyValuePart { /** * Start position for this partition in keys/values */ protected final transient int startPos; /** * End position for this partition in keys/values */ protected final transient int endPos; public RangeKeyValuePart(int rowId,int startPos, int endPos) { super(rowId); this.startPos = startPos; this.endPos = endPos; } public RouterType getRouterType() { return RouterType.RANGE; } }
231
341
/* -*- Mode: C; tab-width: 4 -*- * * Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(AFX_STDAFX_H__7F91E52B_CF39_429D_837D_599CE0B2B3D6__INCLUDED_) #define AFX_STDAFX_H__7F91E52B_CF39_429D_837D_599CE0B2B3D6__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #if defined(_AFXDLL) #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <winsock2.h> //#include <afxsock.h> // MFC socket extensions //{{AFX_INSERT_LOCATION}} // Microsoft eMbedded Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STDAFX_H__7F91E52B_CF39_429D_837D_599CE0B2B3D6__INCLUDED_)
579
32,544
<reponame>DBatOWL/tutorials package com.baeldung.quarkus; import com.baeldung.quarkus.utils.CustomTestProfile; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; import io.restassured.http.ContentType; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasItems; @QuarkusTest @TestProfile(CustomTestProfile.class) class CustomLibraryResourceManualTest { public static final String BOOKSTORE_ENDPOINT = "/custom/library/book"; @Test void whenGetBooksGivenNoQuery_thenAllBooksShouldBeReturned() { given().contentType(ContentType.JSON) .when().get(BOOKSTORE_ENDPOINT) .then().statusCode(200) .body("size()", is(2)) .body("title", hasItems("Foundation", "Dune")); } }
345
563
package com.gentics.mesh.example; import static com.gentics.mesh.core.rest.common.Permission.CREATE; import static com.gentics.mesh.core.rest.common.Permission.DELETE; import static com.gentics.mesh.core.rest.common.Permission.READ; import static com.gentics.mesh.example.ExampleUuids.PROJECT_DEMO2_UUID; import static com.gentics.mesh.example.ExampleUuids.PROJECT_DEMO_UUID; import static com.gentics.mesh.example.ExampleUuids.SCHEMA_FOLDER_UUID; import com.gentics.mesh.core.rest.project.ProjectCreateRequest; import com.gentics.mesh.core.rest.project.ProjectListResponse; import com.gentics.mesh.core.rest.project.ProjectResponse; import com.gentics.mesh.core.rest.project.ProjectUpdateRequest; import com.gentics.mesh.core.rest.schema.impl.SchemaReferenceImpl; public class ProjectExamples extends AbstractExamples { public ProjectResponse getProjectResponse(String name) { ProjectResponse project = new ProjectResponse(); project.setUuid(PROJECT_DEMO2_UUID); project.setName(name); project.setCreated(createOldTimestamp()); project.setCreator(createUserReference()); project.setEdited(createNewTimestamp()); project.setEditor(createUserReference()); project.setPermissions(READ, DELETE, CREATE); project.setRootNode(createNodeReference()); return project; } public ProjectResponse getProjectResponse2() { ProjectResponse project2 = new ProjectResponse(); project2.setUuid(PROJECT_DEMO_UUID); project2.setName("Dummy Project (Mobile)"); project2.setCreated(createOldTimestamp()); project2.setCreator(createUserReference()); project2.setEdited(createNewTimestamp()); project2.setEditor(createUserReference()); project2.setPermissions(READ, DELETE, CREATE); project2.setRootNode(createNodeReference()); return project2; } public ProjectListResponse getProjectListResponse() { ProjectListResponse projectList = new ProjectListResponse(); projectList.getData().add(getProjectResponse("Dummy project")); projectList.getData().add(getProjectResponse2()); setPaging(projectList, 1, 10, 2, 20); return projectList; } public ProjectUpdateRequest getProjectUpdateRequest(String name) { ProjectUpdateRequest projectUpdate = new ProjectUpdateRequest(); projectUpdate.setName(name); return projectUpdate; } public ProjectCreateRequest getProjectCreateRequest(String name) { ProjectCreateRequest projectCreate = new ProjectCreateRequest(); projectCreate.setName(name); projectCreate.setHostname("getmesh.io"); projectCreate.setSsl(true); projectCreate.setSchema(new SchemaReferenceImpl().setName("folder").setUuid(SCHEMA_FOLDER_UUID)); return projectCreate; } }
837
634
<reponame>halotroop2288/consulo /* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.openapi.editor; import com.intellij.openapi.vcs.ui.SpellCheckerCustomization; import com.intellij.ui.EditorCustomization; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author nik */ public class SpellCheckingEditorCustomizationProvider { private static final SpellCheckingEditorCustomizationProvider ourInstance = new SpellCheckingEditorCustomizationProvider(); @Nonnull public static SpellCheckingEditorCustomizationProvider getInstance() { return ourInstance; } @Nullable public final EditorCustomization getCustomization(boolean enabled) { return enabled ? getEnabledCustomization() : getDisabledCustomization(); } @Nullable public EditorCustomization getEnabledCustomization() { SpellCheckerCustomization spellCheckerCustomization = SpellCheckerCustomization.getInstance(); return spellCheckerCustomization.isEnabled() ? spellCheckerCustomization.getCustomization(true) : null; } @Nullable public EditorCustomization getDisabledCustomization() { SpellCheckerCustomization spellCheckerCustomization = SpellCheckerCustomization.getInstance(); return spellCheckerCustomization.isEnabled() ? spellCheckerCustomization.getCustomization(false) : null; } }
517
347
package org.ovirt.engine.core.common.businessentities; import java.util.Objects; import org.ovirt.engine.core.compat.Guid; /** * Status of kdump flow for specific host */ public class VdsKdumpStatus { /** * VDS UUID */ private Guid vdsId; /** * VDS kdump flow status */ private KdumpFlowStatus status; /** * Address and port the message came from */ private String address; public VdsKdumpStatus() { vdsId = Guid.Empty; status = null; address = null; } public Guid getVdsId() { return vdsId; } public void setVdsId(Guid vdsId) { this.vdsId = vdsId; } public KdumpFlowStatus getStatus() { return status; } public void setStatus(KdumpFlowStatus status) { this.status = status; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof VdsKdumpStatus)) { return false; } VdsKdumpStatus other = (VdsKdumpStatus) obj; return Objects.equals(vdsId, other.getVdsId()) && status == other.getStatus() && Objects.equals(address, other.getAddress()); } @Override public int hashCode() { return Objects.hash( vdsId, status, address ); } }
725
416
/* File: AVAudioUnitEQ.h Framework: AVFoundation Copyright 2016 Apple Inc. All rights reserved. */ #import <AVFAudio/AVAudioUnitEQ.h>
71
346
<filename>codecarbon/external/scheduler.py from threading import Lock, Timer class PeriodicScheduler(object): """ A periodic task running in threading.Timers From https://stackoverflow.com/a/18906292/14541668 """ def __init__(self, interval, function, *args, **kwargs): """ Init the scheduler. You have to call start() after initialization. ::interval:: interval in seconds to run the function. ::function:: function to run. ::args:: args to pass to the function. ::kwargs:: kwargs to pass to the function. """ self._lock = Lock() self._timer = None self.function = function self.interval = interval self.args = args self.kwargs = kwargs self._stopped = True def start(self, from_run=False): """ Start the scheduler. ::from_run:: For internal purposes to allow re-scheduling Please do not use from_run=True until you know what you do ! """ self._lock.acquire() if from_run or self._stopped: self._stopped = False self._timer = Timer(self.interval, self._run) self._timer.start() self._lock.release() def _run(self): self.start(from_run=True) self.function(*self.args, **self.kwargs) def stop(self): """ Stop the scheduler. """ self._lock.acquire() self._stopped = True self._timer.cancel() self._lock.release()
667
1,428
<filename>C/arraysum.c<gh_stars>1000+ #include <stdio.h> int main(){ // Sum and Average of elements of the array long arr[100],i,sum=0,size; float avg; printf("Enter size of array "); scanf("%ld",&size); printf("\nEnter %ld elements in the array \n",size); for(i=0;i<size;i++) { scanf("%ld",&arr[i]); sum += arr[i]; } avg=sum/size; printf("Sum of all the elements of the array is %ld\nAverage of all the elements of the array is %0.2f",sum,avg); printf("\n"); return 0; }
245
2,228
<filename>src/main/java/org/springframework/data/jpa/repository/query/PartTreeJpaQuery.java<gh_stars>1000+ /* * Copyright 2008-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.jpa.repository.query; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.query.JpaParameters.JpaParameter; import org.springframework.data.jpa.repository.query.JpaQueryExecution.DeleteExecution; import org.springframework.data.jpa.repository.query.JpaQueryExecution.ExistsExecution; import org.springframework.data.jpa.repository.query.ParameterMetadataProvider.ParameterMetadata; import org.springframework.data.repository.query.ResultProcessor; import org.springframework.data.repository.query.ReturnedType; import org.springframework.data.repository.query.parser.Part; import org.springframework.data.repository.query.parser.Part.Type; import org.springframework.data.repository.query.parser.PartTree; import org.springframework.data.util.Streamable; import org.springframework.lang.Nullable; /** * A {@link AbstractJpaQuery} implementation based on a {@link PartTree}. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class PartTreeJpaQuery extends AbstractJpaQuery { private final PartTree tree; private final JpaParameters parameters; private final QueryPreparer query; private final QueryPreparer countQuery; private final EntityManager em; private final EscapeCharacter escape; /** * Creates a new {@link PartTreeJpaQuery}. * * @param method must not be {@literal null}. * @param em must not be {@literal null}. */ PartTreeJpaQuery(JpaQueryMethod method, EntityManager em) { this(method, em, EscapeCharacter.DEFAULT); } /** * Creates a new {@link PartTreeJpaQuery}. * * @param method must not be {@literal null}. * @param em must not be {@literal null}. * @param escape character used for escaping characters used as patterns in LIKE-expressions. */ PartTreeJpaQuery(JpaQueryMethod method, EntityManager em, EscapeCharacter escape) { super(method, em); this.em = em; this.escape = escape; Class<?> domainClass = method.getEntityInformation().getJavaType(); this.parameters = method.getParameters(); boolean recreationRequired = parameters.hasDynamicProjection() || parameters.potentiallySortsDynamically(); try { this.tree = new PartTree(method.getName(), domainClass); validate(tree, parameters, method.toString()); this.countQuery = new CountQueryPreparer(recreationRequired); this.query = tree.isCountProjection() ? countQuery : new QueryPreparer(recreationRequired); } catch (Exception o_O) { throw new IllegalArgumentException( String.format("Failed to create query for method %s! %s", method, o_O.getMessage()), o_O); } } /* * (non-Javadoc) * @see org.springframework.data.jpa.repository.query.AbstractJpaQuery#doCreateQuery(JpaParametersParameterAccessor) */ @Override public Query doCreateQuery(JpaParametersParameterAccessor accessor) { return query.createQuery(accessor); } /* * (non-Javadoc) * @see org.springframework.data.jpa.repository.query.AbstractJpaQuery#doCreateCountQuery(JpaParametersParameterAccessor) */ @Override @SuppressWarnings("unchecked") public TypedQuery<Long> doCreateCountQuery(JpaParametersParameterAccessor accessor) { return (TypedQuery<Long>) countQuery.createQuery(accessor); } /* * (non-Javadoc) * @see org.springframework.data.jpa.repository.query.AbstractJpaQuery#getExecution() */ @Override protected JpaQueryExecution getExecution() { if (this.tree.isDelete()) { return new DeleteExecution(em); } else if (this.tree.isExistsProjection()) { return new ExistsExecution(); } return super.getExecution(); } private static void validate(PartTree tree, JpaParameters parameters, String methodName) { int argCount = 0; Iterable<Part> parts = () -> tree.stream().flatMap(Streamable::stream).iterator(); for (Part part : parts) { int numberOfArguments = part.getNumberOfArguments(); for (int i = 0; i < numberOfArguments; i++) { throwExceptionOnArgumentMismatch(methodName, part, parameters, argCount); argCount++; } } } private static void throwExceptionOnArgumentMismatch(String methodName, Part part, JpaParameters parameters, int index) { Type type = part.getType(); String property = part.getProperty().toDotPath(); if (!parameters.getBindableParameters().hasParameterAt(index)) { throw new IllegalStateException(String.format( "Method %s expects at least %d arguments but only found %d. This leaves an operator of type %s for property %s unbound.", methodName, index + 1, index, type.name(), property)); } JpaParameter parameter = parameters.getBindableParameter(index); if (expectsCollection(type) && !parameterIsCollectionLike(parameter)) { throw new IllegalStateException(wrongParameterTypeMessage(methodName, property, type, "Collection", parameter)); } else if (!expectsCollection(type) && !parameterIsScalarLike(parameter)) { throw new IllegalStateException(wrongParameterTypeMessage(methodName, property, type, "scalar", parameter)); } } private static String wrongParameterTypeMessage(String methodName, String property, Type operatorType, String expectedArgumentType, JpaParameter parameter) { return String.format("Operator %s on %s requires a %s argument, found %s in method %s.", operatorType.name(), property, expectedArgumentType, parameter.getType(), methodName); } private static boolean parameterIsCollectionLike(JpaParameter parameter) { return Iterable.class.isAssignableFrom(parameter.getType()) || parameter.getType().isArray(); } /** * Arrays are may be treated as collection like or in the case of binary data as scalar */ private static boolean parameterIsScalarLike(JpaParameter parameter) { return !Iterable.class.isAssignableFrom(parameter.getType()); } private static boolean expectsCollection(Type type) { return type == Type.IN || type == Type.NOT_IN; } /** * Query preparer to create {@link CriteriaQuery} instances and potentially cache them. * * @author <NAME> * @author <NAME> */ private class QueryPreparer { private final @Nullable CriteriaQuery<?> cachedCriteriaQuery; private final @Nullable ParameterBinder cachedParameterBinder; private final QueryParameterSetter.QueryMetadataCache metadataCache = new QueryParameterSetter.QueryMetadataCache(); QueryPreparer(boolean recreateQueries) { JpaQueryCreator creator = createCreator(null); if (recreateQueries) { this.cachedCriteriaQuery = null; this.cachedParameterBinder = null; } else { this.cachedCriteriaQuery = creator.createQuery(); this.cachedParameterBinder = getBinder(creator.getParameterExpressions()); } } /** * Creates a new {@link Query} for the given parameter values. */ public Query createQuery(JpaParametersParameterAccessor accessor) { CriteriaQuery<?> criteriaQuery = cachedCriteriaQuery; ParameterBinder parameterBinder = cachedParameterBinder; if (cachedCriteriaQuery == null || accessor.hasBindableNullValue()) { JpaQueryCreator creator = createCreator(accessor); criteriaQuery = creator.createQuery(getDynamicSort(accessor)); List<ParameterMetadata<?>> expressions = creator.getParameterExpressions(); parameterBinder = getBinder(expressions); } if (parameterBinder == null) { throw new IllegalStateException("ParameterBinder is null!"); } TypedQuery<?> query = createQuery(criteriaQuery); return restrictMaxResultsIfNecessary(invokeBinding(parameterBinder, query, accessor, this.metadataCache)); } /** * Restricts the max results of the given {@link Query} if the current {@code tree} marks this {@code query} as * limited. */ @SuppressWarnings("ConstantConditions") private Query restrictMaxResultsIfNecessary(Query query) { if (tree.isLimiting()) { if (query.getMaxResults() != Integer.MAX_VALUE) { /* * In order to return the correct results, we have to adjust the first result offset to be returned if: * - a Pageable parameter is present * - AND the requested page number > 0 * - AND the requested page size was bigger than the derived result limitation via the First/Top keyword. */ if (query.getMaxResults() > tree.getMaxResults() && query.getFirstResult() > 0) { query.setFirstResult(query.getFirstResult() - (query.getMaxResults() - tree.getMaxResults())); } } query.setMaxResults(tree.getMaxResults()); } if (tree.isExistsProjection()) { query.setMaxResults(1); } return query; } /** * Checks whether we are working with a cached {@link CriteriaQuery} and synchronizes the creation of a * {@link TypedQuery} instance from it. This is due to non-thread-safety in the {@link CriteriaQuery} implementation * of some persistence providers (i.e. Hibernate in this case), see DATAJPA-396. * * @param criteriaQuery must not be {@literal null}. */ private TypedQuery<?> createQuery(CriteriaQuery<?> criteriaQuery) { if (this.cachedCriteriaQuery != null) { synchronized (this.cachedCriteriaQuery) { return getEntityManager().createQuery(criteriaQuery); } } return getEntityManager().createQuery(criteriaQuery); } protected JpaQueryCreator createCreator(@Nullable JpaParametersParameterAccessor accessor) { EntityManager entityManager = getEntityManager(); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); ResultProcessor processor = getQueryMethod().getResultProcessor(); ParameterMetadataProvider provider; ReturnedType returnedType; if (accessor != null) { provider = new ParameterMetadataProvider(builder, accessor, escape); returnedType = processor.withDynamicProjection(accessor).getReturnedType(); } else { provider = new ParameterMetadataProvider(builder, parameters, escape); returnedType = processor.getReturnedType(); } return new JpaQueryCreator(tree, returnedType, builder, provider); } /** * Invokes parameter binding on the given {@link TypedQuery}. */ protected Query invokeBinding(ParameterBinder binder, TypedQuery<?> query, JpaParametersParameterAccessor accessor, QueryParameterSetter.QueryMetadataCache metadataCache) { QueryParameterSetter.QueryMetadata metadata = metadataCache.getMetadata("query", query); return binder.bindAndPrepare(query, metadata, accessor); } private ParameterBinder getBinder(List<ParameterMetadata<?>> expressions) { return ParameterBinderFactory.createCriteriaBinder(parameters, expressions); } private Sort getDynamicSort(JpaParametersParameterAccessor accessor) { return parameters.potentiallySortsDynamically() // ? accessor.getSort() // : Sort.unsorted(); } } /** * Special {@link QueryPreparer} to create count queries. * * @author <NAME> * @author <NAME> */ private class CountQueryPreparer extends QueryPreparer { CountQueryPreparer(boolean recreateQueries) { super(recreateQueries); } @Override protected JpaQueryCreator createCreator(@Nullable JpaParametersParameterAccessor accessor) { EntityManager entityManager = getEntityManager(); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); ParameterMetadataProvider provider; if (accessor != null) { provider = new ParameterMetadataProvider(builder, accessor, escape); } else { provider = new ParameterMetadataProvider(builder, parameters, escape); } return new JpaCountQueryCreator(tree, getQueryMethod().getResultProcessor().getReturnedType(), builder, provider); } /** * Customizes binding by skipping the pagination. */ @Override protected Query invokeBinding(ParameterBinder binder, TypedQuery<?> query, JpaParametersParameterAccessor accessor, QueryParameterSetter.QueryMetadataCache metadataCache) { QueryParameterSetter.QueryMetadata metadata = metadataCache.getMetadata("countquery", query); return binder.bind(query, metadata, accessor); } } }
4,095
2,038
<gh_stars>1000+ // Created by ProbablyInteractive. // Copyright 2009 Probably Interactive. All rights reserved. #import <Foundation/Foundation.h> #import "lua.h" #define WAX_VERSION 0.93 //just start wax with no script, and no extension. (can be used in swift) void wax_startWithNil(); //setup lua, and load wax stdlib void wax_start(char *initScript, lua_CFunction extensionFunctions, ...); //start with wax server void wax_startWithServer(); //setup lua void wax_setup(); void wax_end(); lua_State *wax_currentLuaState(); void luaopen_wax(lua_State *L); #pragma mark add by junzhan //you should call wax_start before these function. // run lua string. int wax_runLuaString(const char *script); //run lua byte code int wax_runLuaByteCode(NSData *data, NSString *name); //run lua file int wax_runLuaFile(const char *filePath); //lua runtime error callback typedef void (*WaxLuaRuntimeErrorHandler)(NSString *reason, BOOL willExit); void wax_setLuaRuntimeErrorHandler(WaxLuaRuntimeErrorHandler handler); WaxLuaRuntimeErrorHandler wax_getLuaRuntimeErrorHandler();
347
761
<reponame>EndevelCZ/umap import shutil import tempfile import pytest from django.core.signing import get_cookie_signer from .base import DataLayerFactory, MapFactory, UserFactory from umap.models import Licence, TileLayer TMP_ROOT = tempfile.mkdtemp() def pytest_configure(config): from django.conf import settings settings.MEDIA_ROOT = TMP_ROOT def pytest_unconfigure(config): shutil.rmtree(TMP_ROOT, ignore_errors=True) @pytest.fixture def user(): return UserFactory(password="<PASSWORD>") @pytest.fixture def licence(): # Should be created by the migrations. return Licence.objects.last() @pytest.fixture def map(licence, tilelayer): user = UserFactory(username="Gabriel", password="<PASSWORD>") return MapFactory(owner=user, licence=licence) @pytest.fixture def anonymap(map): map.owner = None map.save() return map @pytest.fixture def cookieclient(client, map): key, value = map.signed_cookie_elements client.cookies[key] = get_cookie_signer(salt=key).sign(value) return client @pytest.fixture def allow_anonymous(settings): settings.UMAP_ALLOW_ANONYMOUS = True @pytest.fixture def datalayer(map): return DataLayerFactory(map=map, name="Default Datalayer") @pytest.fixture def tilelayer(): return TileLayer.objects.last()
482
400
<reponame>tradeshift-zihe/ofdrw package org.ofdrw.core.pageDescription.clips; import org.junit.jupiter.api.Test; import org.ofdrw.TestTool; import org.ofdrw.core.basicType.ST_Array; import org.ofdrw.core.basicType.ST_Box; import org.ofdrw.core.basicType.ST_RefID; import org.ofdrw.core.graph.pathObj.AbbreviatedData; import org.ofdrw.core.graph.pathObj.AbbreviatedDataTest; import org.ofdrw.core.graph.pathObj.CT_Path; import org.ofdrw.core.graph.pathObj.CT_PathTest; import org.ofdrw.core.pageDescription.color.color.CT_Color; import static org.junit.jupiter.api.Assertions.*; public class ClipAreaTest { public static Area areaCase(){ return new Area() .setDrawParam(ST_RefID.getInstance("11")) .setCTM(ST_Array.unitCTM()) .setClipObj(CT_PathTest.pathCase()); } public static Area areaCase2(){ CT_Path path2 = CT_PathTest.pathCase() .setBoundary(new ST_Box(47, 97, 156, 206)) .setGraphicName("Second") .setAbbreviatedData( new AbbreviatedData() .M(150, 100) .L(300, 50) .L(300, 200) .C()); return new Area() .setDrawParam(ST_RefID.getInstance("75")) .setCTM(ST_Array.unitCTM()) .setClipObj(path2); } @Test public void gen() throws Exception { TestTool.genXml("ClipArea", areaCase()); } }
745
803
<gh_stars>100-1000 // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once class CFileFilter; class CFileFilterReference; static SIZE_T CFileFilterReferenceOffsetOfILE(); // A file path table entry. class CFilePathTableEntry // fpte { public: class COpenFile; public: CFilePathTableEntry( _Inout_z_ const WCHAR** const pwszKeyPath ); ~CFilePathTableEntry(); const WCHAR* WszKeyPath() const { return m_wszKeyPath; } COpenFile* Pof() const { return m_pof; } UINT UiHash() const { return CFilePathTableEntry::UiHash( m_wszKeyPath ); } void AddRef( _In_ int dref = 1 ) { m_cref += dref; } BOOL FRelease( _In_ int dref = 1 ) { m_cref -= dref; return m_cref == 0; } ERR ErrAddAsOwnerOrWaiter( _In_ CSemaphore* const psem ); void AddNextOwner(); void RemoveAsOwnerOrWaiter( _In_opt_ CSemaphore* const psem ); static UINT UiHash( _In_z_ const WCHAR* const wszKeyPath ); ERR ErrOpenFile( _Inout_ CFileFilter** const ppff, _In_ ICache* const pc, _Out_ COpenFile** const ppof ); void RemoveFile( _In_ COpenFile* const pof ); void DisconnectFile( _In_ COpenFile* const pof ); void TransferFiles( _In_ CFilePathTableEntry* const pfpteDest ); ERR ErrAccessCheck( _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCreate, _In_ const BOOL fCacheOpen ); ERR ErrDeleteCheck(); public: // Context for an open file. class COpenFile { public: COpenFile( _In_ CFilePathTableEntry* const pfpte, _Inout_ CFileFilter** const ppff, _In_ ICache* const pc ) : m_pfpte( pfpte ), m_pff( *ppff ), m_pc( pc ) { *ppff = NULL; } ~COpenFile() { delete m_pff; } CFilePathTableEntry* Pfpte() const { return m_pfpte; } CFileFilter* Pff() const { return m_pff; } ICache* Pc() const { return m_pc; } int CReference() const { return m_ilReferences.Count(); } void AddReference( _In_ CFileFilterReference* const pffr ) { m_ilReferences.InsertAsNextMost( pffr ); } BOOL FRemoveReference( _In_ CFileFilterReference* const pffr ) { m_ilReferences.Remove( pffr ); return m_ilReferences.FEmpty(); } void SetPfpte( _In_ CFilePathTableEntry* const pfpte ) { m_pfpte = pfpte; } ERR ErrAccessCheck( _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCreate, _In_ const BOOL fCacheOpen ); ERR ErrDeleteCheck(); static SIZE_T OffsetOfILE() { return OffsetOf( COpenFile, m_ile ); } private: typename CInvasiveList< COpenFile, OffsetOfILE >::CElement m_ile; CFilePathTableEntry* m_pfpte; CFileFilter* m_pff; ICache* m_pc; CCountedInvasiveList<CFileFilterReference, CFileFilterReferenceOffsetOfILE> m_ilReferences; }; private: // Wait context for cache miss collisions on the file path table. class CWaiter { public: CWaiter( _In_ CSemaphore* const psem ) : m_psem( psem ) { } CSemaphore* Psem() { return m_psem; } static SIZE_T OffsetOfILE() { return OffsetOf( CWaiter, m_ile ); } private: typename CInvasiveList< CWaiter, OffsetOfILE >::CElement m_ile; CSemaphore* const m_psem; }; private: const WCHAR* const m_wszKeyPath; int m_cref; CSemaphore* m_psemOwner; CInvasiveList<CWaiter, CWaiter::OffsetOfILE> m_ilWaiters; CInvasiveList<COpenFile, COpenFile::OffsetOfILE> m_ilOpenFiles; COpenFile* m_pof; }; INLINE CFilePathTableEntry::CFilePathTableEntry( _Inout_z_ const WCHAR** const pwszKeyPath ) : m_wszKeyPath( *pwszKeyPath ), m_cref( 0 ), m_psemOwner( NULL ), m_pof( NULL ) { *pwszKeyPath = NULL; } INLINE CFilePathTableEntry::~CFilePathTableEntry() { delete[] m_wszKeyPath; } INLINE ERR CFilePathTableEntry::ErrAddAsOwnerOrWaiter( _In_ CSemaphore* const psem ) { ERR err = JET_errSuccess; CWaiter* pwaiter = NULL; if ( !m_psemOwner ) { m_psemOwner = psem; m_psemOwner->Release(); } else { Alloc( pwaiter = new CWaiter( psem ) ); m_ilWaiters.InsertAsNextMost( pwaiter ); pwaiter = NULL; } HandleError: delete pwaiter; return err; } INLINE void CFilePathTableEntry::AddNextOwner() { CWaiter* pwaiter = m_ilWaiters.PrevMost(); if ( pwaiter != NULL ) { m_ilWaiters.Remove( pwaiter ); m_psemOwner = pwaiter->Psem(); m_psemOwner->Release(); delete pwaiter; } } INLINE void CFilePathTableEntry::RemoveAsOwnerOrWaiter( _In_opt_ CSemaphore* const psem ) { CWaiter* pwaiter = m_ilWaiters.PrevMost(); while ( pwaiter != NULL ) { CWaiter* const pwaiterNext = m_ilWaiters.Next( pwaiter ); if ( pwaiter->Psem() == psem ) { m_ilWaiters.Remove( pwaiter ); delete pwaiter; } pwaiter = pwaiterNext; } if ( m_psemOwner == psem ) { m_psemOwner = NULL; } } INLINE UINT CFilePathTableEntry::UiHash( _In_z_ const WCHAR* const wszKeyPath ) { const INT cbKeyPath = wszKeyPath ? LOSStrLengthW( wszKeyPath ) * sizeof( wszKeyPath[ 0 ] ) : 0; unsigned __int64 ui64Hash = Ui64FNVHash( wszKeyPath, cbKeyPath ); return (UINT)( ( ui64Hash >> 32 ) | ( ui64Hash & dwMax ) ); } INLINE ERR CFilePathTableEntry::ErrOpenFile( _Inout_ CFileFilter** const ppff, _In_ ICache* const pc, _Out_ COpenFile** const ppof ) { ERR err = JET_errSuccess; COpenFile* pof = NULL; *ppof = NULL; Alloc( pof = new COpenFile( this, ppff, pc ) ); m_ilOpenFiles.InsertAsPrevMost( pof ); *ppof = pof; m_pof = pof; pof = NULL; HandleError: delete pof; if ( err < JET_errSuccess ) { *ppof = NULL; } return err; } INLINE void CFilePathTableEntry::RemoveFile( _In_ COpenFile* const pof ) { if ( !pof ) { return; } DisconnectFile( pof ); m_ilOpenFiles.Remove( pof ); } INLINE void CFilePathTableEntry::DisconnectFile( _In_ COpenFile* const pof ) { m_pof = m_pof == pof ? NULL : m_pof; } INLINE void CFilePathTableEntry::TransferFiles( _In_ CFilePathTableEntry* const pfpteDest ) { while ( COpenFile* pof = m_ilOpenFiles.NextMost() ) { m_ilOpenFiles.Remove( pof ); BOOL fRelease = FRelease( pof->CReference() ); Assert( !fRelease ); pof->SetPfpte( pfpteDest ); pfpteDest->m_ilOpenFiles.InsertAsPrevMost( pof ); pfpteDest->m_pof = pof; pfpteDest->AddRef( pof->CReference() ); } m_pof = NULL; } INLINE ERR CFilePathTableEntry::ErrAccessCheck( _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCreate, _In_ const BOOL fCacheOpen ) { ERR err = JET_errSuccess; for ( COpenFile* pof = m_ilOpenFiles.PrevMost(); pof; pof = m_ilOpenFiles.Next( pof ) ) { Call( pof->ErrAccessCheck( fmf, fCreate, fCacheOpen ) ); } HandleError: return err; } INLINE ERR CFilePathTableEntry::ErrDeleteCheck() { ERR err = JET_errSuccess; for ( COpenFile* pof = m_ilOpenFiles.PrevMost(); pof; pof = m_ilOpenFiles.Next( pof ) ) { Call( pof->ErrDeleteCheck() ); } HandleError: return err; } // File path hash table key. class CFilePathHashKey { public: CFilePathHashKey() : m_wszKeyPath( NULL ), m_uiHash( 0 ) { } CFilePathHashKey( _In_z_ const WCHAR* const wszKeyPath ) : m_wszKeyPath( wszKeyPath ), m_uiHash( CFilePathTableEntry::UiHash( wszKeyPath ) ) { } CFilePathHashKey( _In_ CFilePathTableEntry* const pfpte ) : CFilePathHashKey( pfpte->WszKeyPath() ) { } CFilePathHashKey( _In_ const CFilePathHashKey& src ) { *this = src; } const CFilePathHashKey& operator=( _In_ const CFilePathHashKey& src ) { m_wszKeyPath = src.m_wszKeyPath; m_uiHash = src.m_uiHash; return *this; } const WCHAR* WszKeyPath() const { return m_wszKeyPath; } UINT UiHash() const { return m_uiHash; } private: const WCHAR* m_wszKeyPath; UINT m_uiHash; }; // File path hash table entry. class CFilePathHashEntry { public: CFilePathHashEntry() : m_pfpte( NULL ), m_uiHash( 0 ) { } CFilePathHashEntry( _In_ CFilePathTableEntry* const pfpte ) : m_pfpte( pfpte ), m_uiHash( pfpte->UiHash() ) { } CFilePathHashEntry( _In_ const CFilePathHashEntry& src ) { *this = src; } const CFilePathHashEntry& operator=( _In_ const CFilePathHashEntry& src ) { m_pfpte = src.m_pfpte; m_uiHash = src.m_uiHash; return *this; } CFilePathTableEntry* Pfpte() const { return m_pfpte; } UINT UiHash() const { return m_uiHash; } private: CFilePathTableEntry* m_pfpte; UINT m_uiHash; }; // File path hash table. typedef CDynamicHashTable<CFilePathHashKey, CFilePathHashEntry> CFilePathHash; // TFileSystemFilter: core implementation of IFileSystemFilter and its derivatives. // // This class provides the core of the file system filter used to implement the block cache. It is responsible for // intercepting relevant IFileSystemAPI calls, detecting files that are or should be cached, and managing the caches // for these files. This class also provides the ability for the cache to open cached files for write back such that // the engine can successfully access files without being aware of the cache. template< class I > class TFileSystemFilter // fsf : public TFileSystemWrapper<I> { public: // specialized API TFileSystemFilter( _In_ IFileSystemConfiguration* const pfsconfig, _Inout_ IFileSystemAPI** const ppfsapi, _In_ IFileIdentification* const pfident, _In_ ICacheTelemetry* const pctm, _In_ ICacheRepository * const pcrep ); virtual ~TFileSystemFilter(); void AddFileReference( _In_ CFileFilterReference* const pffr, _In_ CFilePathTableEntry::COpenFile* const pof ); void RemoveFileReference( _In_ CFileFilterReference* const pffr, _In_ CFilePathTableEntry::COpenFile* const pof ); public: // IFileSystemFilter // configuration ERR ErrFileOpenById( _In_ const VolumeId volumeid, _In_ const FileId fileid, _In_ const FileSerial fileserial, _In_ const IFileAPI::FileModeFlags fmf, _Out_ IFileAPI** const ppfapi ) override; ERR ErrFileRename( _In_ IFileAPI* const pfapi, _In_z_ const WCHAR* const wszPathDest, _In_ const BOOL fOverwriteExisting ) override; public: // IFileSystemAPI ERR ErrFileDelete( const WCHAR* const wszPath ); ERR ErrFileMove( const WCHAR* const wszPathSource, const WCHAR* const wszPathDest, const BOOL fOverwriteExisting = fFalse ) override; ERR ErrFileCopy( const WCHAR* const wszPathSource, const WCHAR* const wszPathDest, const BOOL fOverwriteExisting = fFalse ) override; ERR ErrFileCreate( _In_z_ const WCHAR* const wszPath, _In_ const IFileAPI::FileModeFlags fmf, _Out_ IFileAPI** const ppfapi ) override; ERR ErrFileOpen( _In_z_ const WCHAR* const wszPath, _In_ const IFileAPI::FileModeFlags fmf, _Out_ IFileAPI** const ppfapi ) override; public: // CFileSystemWrapper ERR ErrWrapFile( _Inout_ IFileAPI** const ppfapiInner, _Out_ IFileAPI** const ppfapi ) override; private: void ReleaseFile( _In_opt_ CFilePathTableEntry* const pfpte, _In_opt_ CSemaphore* const psem = NULL, _In_opt_ CFilePathTableEntry::COpenFile* const pof = NULL, _In_opt_ CFileFilterReference* const pffr = NULL ); ERR ErrLockFile( _In_z_ const WCHAR* const wszPath, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPath, _In_ CSemaphore* const psem, _Out_ CFilePathTableEntry** const ppfpte ); ERR ErrLockFiles( _In_z_ const WCHAR* const wszPathSrc, _In_z_ const WCHAR* const wszPathDest, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPathSrc, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPathDest, _In_ CSemaphore* const psem, _Out_ CFilePathTableEntry** const ppfpteSrc, _Out_ CFilePathTableEntry** const ppfpteDest ); ERR ErrLockFile( _In_z_ const WCHAR* const wszKeyPath, _In_ CSemaphore* const psem, _Out_ CFilePathTableEntry** const ppfpte ); ERR ErrGetFilePath( _In_z_ const WCHAR* const wszPath, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPath, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszKeyPath ); ERR ErrPrepareToDelete( _In_ CFilePathTableEntry* const pfpte ); ERR ErrFileCreateCacheMiss( _In_z_ const WCHAR* const wszAnyAbsPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ CFilePathTableEntry* const pfpte, _Out_ CFileFilterReference** const ppffr ); ERR ErrFileConfigure( _In_ CFileFilter* const pff, _In_z_ const WCHAR* const wszAnyAbsPath ); ERR ErrFileOpenInternal( _In_z_ const WCHAR* const wszAnyAbsPath, _In_z_ const WCHAR* const wszKeyPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCacheOpen, _Out_ CFileFilterReference** const ppffr ); ERR ErrFileOpenCacheMiss( _In_z_ const WCHAR* const wszAnyAbsPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCacheOpen, _In_ CFilePathTableEntry* const pfpte, _Out_ CFileFilterReference** const ppffr ); ERR ErrFileOpenAndConfigure( _In_z_ const WCHAR* const wszAnyAbsPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ CFilePathTableEntry* const pfpte, _Out_ CFileFilter** const ppff, _Out_ ICache** const ppc, _Out_ BOOL* const pfAttached ); ERR ErrFileOpenCacheHit( _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCreate, _In_ const BOOL fCacheOpen, _In_ CFilePathTableEntry::COpenFile* const pof, _Out_ CFileFilterReference** const ppffr ); void ReportCachedFileNotFoundById( _In_ const VolumeId volumeid, _In_ const FileId fileid, _In_ const FileSerial fileserial ); ERR ErrGetConfiguredCache( _In_ CFileFilter* const pff, _In_z_ const WCHAR* const wszKeyPath, _Out_ ICache** const ppc ); void ReportCacheOpenFailure( _In_ ICachedFileConfiguration* const pcfconfig, _In_ const ERR err ); ERR ErrGetCache( _In_ CFileFilter* const pff, _In_z_ const WCHAR* const wszKeyPath, _Out_ ICache** const ppc, _Out_ BOOL* const pfAttached ); ERR ErrGetConfiguration( _Out_ IBlockCacheConfiguration** const ppbcconfig ); ERR ErrGetConfiguration(); static ERR ErrGetConfiguration_( _In_ TFileSystemFilter<I>* const pfsf ) { return pfsf->ErrGetConfiguration(); } ERR ErrEnsureInitFilePathTable() { return m_initOnceFilePathTable.Init( ErrInitFilePathTable_, this ); }; ERR ErrInitFilePathTable(); static ERR ErrInitFilePathTable_( _In_ TFileSystemFilter<I>* const pfsf ) { return pfsf->ErrInitFilePathTable(); } void TermFilePathTable(); private: IFileSystemConfiguration* const m_pfsconfig; IFileIdentification* const m_pfident; ICacheTelemetry* const m_pctm; ICacheRepository* const m_pcrep; CInitOnce< ERR, decltype( &ErrInitFilePathTable_ ), TFileSystemFilter<I>* const > m_initOnceFilePathTable; CFilePathHash m_filePathHash; IBlockCacheConfiguration* m_pbcconfig; CInitOnce< ERR, decltype( &ErrGetConfiguration_ ), TFileSystemFilter<I>* const > m_initOnceAttach; }; template< class I > TFileSystemFilter<I>::TFileSystemFilter( _In_ IFileSystemConfiguration* const pfsconfig, _Inout_ IFileSystemAPI** const ppfsapi, _In_ IFileIdentification* const pfident, _In_ ICacheTelemetry* const pctm, _In_ ICacheRepository * const pcrep ) : TFileSystemWrapper<I>( (I** const)ppfsapi ), m_pfsconfig( pfsconfig ), m_pfident( pfident ), m_pctm( pctm ), m_pcrep( pcrep ), m_filePathHash( 0 ), m_pbcconfig( NULL ) { } template< class I > TFileSystemFilter<I>::~TFileSystemFilter() { delete m_pbcconfig; TermFilePathTable(); } template< class I > void TFileSystemFilter<I>::AddFileReference( _In_ CFileFilterReference* const pffr, _In_ CFilePathTableEntry::COpenFile* const pof ) { pof->Pfpte()->AddRef(); pof->AddReference( pffr ); } template< class I > void TFileSystemFilter<I>::RemoveFileReference( _In_ CFileFilterReference* const pffr, _In_ CFilePathTableEntry::COpenFile* const pof ) { // if this reference is not from the cache and the file is cached then ask the cache to close any references it // may have to this file. this will break any circular link that keeps the cache alive. if the cache still needs // to do write back to this file then it will open it again if ( !pffr->FCacheOpen() && pof->Pc() ) { VolumeId volumeid = volumeidInvalid; FileId fileid = fileidInvalid; FileSerial fileserial = fileserialInvalid; CallS( pof->Pff()->ErrGetPhysicalId( &volumeid, &fileid, &fileserial ) ); CallS( pof->Pc()->ErrClose( volumeid, fileid, fileserial ) ); } // release the reference on this open file and file path table entry ReleaseFile( pof->Pfpte(), NULL, pof, pffr ); } template< class I > ERR TFileSystemFilter<I>::ErrFileOpenById( _In_ const VolumeId volumeid, _In_ const FileId fileid, _In_ const FileSerial fileserial, _In_ const IFileAPI::FileModeFlags fmf, _Out_ IFileAPI** const ppfapi ) { ERR err = JET_errSuccess; const DWORD cwchAnyAbsPathMax = OSFSAPI_MAX_PATH; WCHAR wszAnyAbsPath[ cwchAnyAbsPathMax ] = { 0 }; const DWORD cwchKeyPathMax = OSFSAPI_MAX_PATH; WCHAR wszKeyPath[ cwchKeyPathMax ] = { 0 }; CFileFilterReference* pffr = NULL; VolumeId volumeidActual = volumeidInvalid; FileId fileidActual = fileidInvalid; FileSerial fileserialActual = fileserialInvalid; const int cAttemptMax = 10; int cAttempt = 0; *ppfapi = NULL; // defend against an invalid physical id if ( volumeid == volumeidInvalid ) { Error( ErrERRCheck( JET_errInvalidParameter ) ); } if ( fileid == fileidInvalid ) { Error( ErrERRCheck( JET_errInvalidParameter ) ); } if ( fileserial == fileserialInvalid ) { Error( ErrERRCheck( JET_errInvalidParameter ) ); } // retry until we have opened a file with the correct physical id while ( volumeidActual != volumeid || fileidActual != fileid ) { // if we have retried too many times then fail if ( ++cAttempt >= cAttemptMax ) { Call( ErrERRCheck( JET_errInternalError ) ); } // if we have a file open from a previous attempt then close it delete *ppfapi; *ppfapi = NULL; // translate the file id to a file path and the unambiguous file key path Call( m_pfident->ErrGetFilePathById( volumeid, fileid, wszAnyAbsPath, wszKeyPath ) ); // open the file // // NOTE: we presume any file opened by file id is for cache write back Call( ErrFileOpenInternal( wszAnyAbsPath, wszKeyPath, fmf, fTrue, &pffr ) ); // get the actual physical id for the file we opened Call( pffr->ErrGetPhysicalId( &volumeidActual, &fileidActual, &fileserialActual ) ); } // verify that the file we opened matches the requested file if ( fileserialActual != fileserial ) { Call( ErrERRCheck( JET_errFileNotFound ) ); } // return the opened file *ppfapi = pffr; pffr = NULL; HandleError: delete pffr; if ( err < JET_errSuccess ) { delete *ppfapi; *ppfapi = NULL; if ( err == JET_errFileNotFound || err == JET_errInvalidPath ) { ReportCachedFileNotFoundById( volumeid, fileid, fileserial ); err = ErrERRCheck( JET_errFileNotFound ); } } return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileRename( _In_ IFileAPI* const pfapi, _In_z_ const WCHAR* const wszPathDest, _In_ const BOOL fOverwriteExisting ) { ERR err = JET_errSuccess; const DWORD cwchPathSrcMax = OSFSAPI_MAX_PATH; WCHAR wszPathSrc[ cwchPathSrcMax ] = { 0 }; const DWORD cwchAbsPathSrcMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathSrc[ cwchAbsPathSrcMax ] = { 0 }; CSemaphore sem( CSyncBasicInfo( "TFileSystemFilter<I>::ErrFileRename" ) ); CFilePathTableEntry* pfpteSrc = NULL; const DWORD cwchAbsPathDestMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathDest[ cwchAbsPathDestMax ] = { 0 }; CFilePathTableEntry* pfpteDest = NULL; // do not accept relative destination paths if ( TFileSystemWrapper<I>::FPathIsRelative( wszPathDest ) ) { Call( ErrERRCheck( JET_errInvalidParameter ) ); } // wait to lock the entry for the source and destination files Call( pfapi->ErrPath( wszPathSrc ) ); Call( ErrLockFiles( wszPathSrc, wszPathDest, wszAbsPathSrc, wszAbsPathDest, &sem, &pfpteSrc, &pfpteDest ) ); // check if we can create the destination file Call( pfpteDest->ErrAccessCheck( fOverwriteExisting ? IFileAPI::fmfOverwriteExisting : IFileAPI::fmfNone, fTrue, fFalse ) ); // rename the file Call( pfapi->ErrRename( wszAbsPathDest, fOverwriteExisting ) ); // move any existing handles from the source to the target pfpteSrc->TransferFiles( pfpteDest ); HandleError: ReleaseFile( pfpteSrc, &sem ); ReleaseFile( pfpteDest, &sem ); return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileDelete( const WCHAR* const wszPath ) { ERR err = JET_errSuccess; const DWORD cwchAbsPathMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPath[ cwchAbsPathMax ] = { 0 }; CSemaphore sem( CSyncBasicInfo( "TFileSystemFilter<I>::ErrFileDelete" ) ); CFilePathTableEntry* pfpte = NULL; // wait to lock the entry for this file Call( ErrLockFile( wszPath, wszAbsPath, &sem, &pfpte ) ); // prepare to delete the file Call( ErrPrepareToDelete( pfpte ) ); // delete the file Call( TFileSystemWrapper<I>::ErrFileDelete( wszAbsPath ) ); // remove the open file from our file path table pfpte->DisconnectFile( pfpte->Pof() ); HandleError: ReleaseFile( pfpte, &sem ); return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileMove( const WCHAR* const wszPathSource, const WCHAR* const wszPathDest, const BOOL fOverwriteExisting ) { ERR err = JET_errSuccess; const DWORD cwchAbsPathSrcMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathSrc[ cwchAbsPathSrcMax ] = { 0 }; CSemaphore sem( CSyncBasicInfo( "TFileSystemFilter<I>::ErrFileMove" ) ); CFilePathTableEntry* pfpteSrc = NULL; const DWORD cwchAbsPathDestMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathDest[ cwchAbsPathDestMax ] = { 0 }; CFilePathTableEntry* pfpteDest = NULL; // wait to lock the entry for the source and destination files Call( ErrLockFiles( wszPathSource, wszPathDest, wszAbsPathSrc, wszAbsPathDest, &sem, &pfpteSrc, &pfpteDest ) ); // prepare to delete the source file Call( ErrPrepareToDelete( pfpteSrc ) ); // check if we can create the destination file Call( pfpteDest->ErrAccessCheck( fOverwriteExisting ? IFileAPI::fmfOverwriteExisting : IFileAPI::fmfNone, fTrue, fFalse ) ); // move the file Call( TFileSystemWrapper<I>::ErrFileMove( wszAbsPathSrc, wszAbsPathDest, fOverwriteExisting ) ); // move any existing handles from the source to the target pfpteSrc->TransferFiles( pfpteDest ); HandleError: ReleaseFile( pfpteSrc, &sem ); ReleaseFile( pfpteDest, &sem ); return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileCopy( const WCHAR* const wszPathSource, const WCHAR* const wszPathDest, const BOOL fOverwriteExisting ) { ERR err = JET_errSuccess; const DWORD cwchAbsPathSrcMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathSrc[ cwchAbsPathSrcMax ] = { 0 }; CSemaphore sem( CSyncBasicInfo( "TFileSystemFilter<I>::ErrFileCopy" ) ); CFilePathTableEntry* pfpteSrc = NULL; const DWORD cwchAbsPathDestMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathDest[ cwchAbsPathDestMax ] = { 0 }; CFilePathTableEntry* pfpteDest = NULL; // wait to lock the entry for the source and destination files Call( ErrLockFiles( wszPathSource, wszPathDest, wszAbsPathSrc, wszAbsPathDest, &sem, &pfpteSrc, &pfpteDest ) ); // check if we can access the source file Call( pfpteSrc->ErrAccessCheck( IFileAPI::fmfReadOnly, fFalse, fFalse ) ); // check if we can create the destination file Call( pfpteDest->ErrAccessCheck( fOverwriteExisting ? IFileAPI::fmfOverwriteExisting : IFileAPI::fmfNone, fTrue, fFalse ) ); // copy the file Call( TFileSystemWrapper<I>::ErrFileCopy( wszAbsPathSrc, wszAbsPathDest, fOverwriteExisting ) ); HandleError: ReleaseFile( pfpteSrc, &sem ); ReleaseFile( pfpteDest, &sem ); return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileCreate( _In_z_ const WCHAR* const wszPath, _In_ const IFileAPI::FileModeFlags fmf, _Out_ IFileAPI** const ppfapi ) { ERR err = JET_errSuccess; const DWORD cwchAbsPathMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPath[ cwchAbsPathMax ] = { 0 }; CSemaphore sem( CSyncBasicInfo( "TFileSystemFilter<I>::ErrFileCreate" ) ); CFilePathTableEntry* pfpte = NULL; CFileFilterReference* pffr = NULL; *ppfapi = NULL; // wait to lock the entry for this file Call( ErrLockFile( wszPath, wszAbsPath, &sem, &pfpte ) ); // if the file isn't open then open it if ( !pfpte->Pof() ) { Call( ErrFileCreateCacheMiss( wszAbsPath, fmf, pfpte, &pffr ) ); } // the file is already open else { // open the already open file // // NOTE: we presume any file opened by path is not for cache write back Call( ErrFileOpenCacheHit( fmf, fTrue, fFalse, pfpte->Pof(), &pffr ) ); // we are overwriting an existing file then truncate it. this also invalidates the cache for this file if ( DwCreationDispositionFromFileModeFlags( fTrue, fmf ) == CREATE_ALWAYS ) { TraceContextScope tcScope; Call( pfpte->Pof()->Pff()->ErrSetSize( *tcScope, 0, fFalse, qosIONormal ) ); } } // return the opened file *ppfapi = pffr; pffr = NULL; HandleError: ReleaseFile( pfpte, &sem ); delete pffr; if ( err < JET_errSuccess ) { delete *ppfapi; *ppfapi = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileOpen( _In_z_ const WCHAR* const wszPath, _In_ const IFileAPI::FileModeFlags fmf, _Out_ IFileAPI** const ppfapi ) { ERR err = JET_errSuccess; const DWORD cwchAbsPathMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPath[ cwchAbsPathMax ] = { 0 }; const DWORD cwchKeyPathMax = OSFSAPI_MAX_PATH; WCHAR wszKeyPath[ cwchKeyPathMax ] = { 0 }; CFileFilterReference* pffr = NULL; *ppfapi = NULL; // translate the relative file path into an absolute path and an unambiguous file key path Call( ErrGetFilePath( wszPath, wszAbsPath, wszKeyPath ) ); // open the file // // NOTE: we presume any file opened by path is not for cache write back Call( ErrFileOpenInternal( wszAbsPath, wszKeyPath, fmf, fFalse, &pffr ) ); // return the opened file *ppfapi = pffr; pffr = NULL; HandleError: delete pffr; if ( err < JET_errSuccess ) { delete *ppfapi; *ppfapi = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrWrapFile( _Inout_ IFileAPI** const ppfapiInner, _Out_ IFileAPI** const ppfapi ) { ERR err = JET_errSuccess; IFileAPI* pfapi = NULL; *ppfapi = NULL; if ( *ppfapiInner ) { Alloc( pfapi = new CFileFilter( ppfapiInner, (IFileSystemFilter*)this, m_pfsconfig, m_pctm, volumeidInvalid, fileidInvalid, NULL, NULL, NULL ) ); } *ppfapi = pfapi; pfapi = NULL; HandleError: delete pfapi; if ( err < JET_errSuccess ) { delete *ppfapi; *ppfapi = NULL; } return err; } template< class I > void TFileSystemFilter<I>::ReleaseFile( _In_opt_ CFilePathTableEntry* const pfpte, _In_opt_ CSemaphore* const psem, _In_opt_ CFilePathTableEntry::COpenFile* const pof, _In_opt_ CFileFilterReference* const pffr ) { BOOL fDeleteFilePathTableEntry = fFalse; BOOL fDeleteOpenFile = fFalse; if ( !pfpte ) { return; } CFilePathHashKey key( pfpte ); CFilePathHash::CLock lock; m_filePathHash.WriteLockKey( key, &lock ); if ( pof ) { if ( fDeleteOpenFile = pof->FRemoveReference( pffr ) ) { pfpte->RemoveFile( pof ); } } pfpte->RemoveAsOwnerOrWaiter( psem ); if ( fDeleteFilePathTableEntry = pfpte->FRelease() ) { CFilePathHash::ERR errFilePathHash = m_filePathHash.ErrDeleteEntry( &lock ); Assert( errFilePathHash == CFilePathHash::ERR::errSuccess ); } else { pfpte->AddNextOwner(); } m_filePathHash.WriteUnlockKey( &lock ); if ( fDeleteOpenFile ) { delete pof; } if ( fDeleteFilePathTableEntry ) { delete pfpte; } } template< class I > ERR TFileSystemFilter<I>::ErrLockFile( _In_z_ const WCHAR* const wszPath, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPath, _In_ CSemaphore* const psem, _Out_ CFilePathTableEntry** const ppfpte ) { ERR err = JET_errSuccess; const DWORD cwchKeyPathMax = OSFSAPI_MAX_PATH; WCHAR wszKeyPath[ cwchKeyPathMax ] = { 0 }; *ppfpte = NULL; Call( ErrGetFilePath( wszPath, wszAbsPath, wszKeyPath ) ); Call( ErrLockFile( wszKeyPath, psem, ppfpte ) ); HandleError: if ( err < JET_errSuccess ) { ReleaseFile( *ppfpte, psem ); *ppfpte = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrLockFiles( _In_z_ const WCHAR* const wszPathSrc, _In_z_ const WCHAR* const wszPathDest, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPathSrc, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPathDest, _In_ CSemaphore* const psem, _Out_ CFilePathTableEntry** const ppfpteSrc, _Out_ CFilePathTableEntry** const ppfpteDest ) { ERR err = JET_errSuccess; const DWORD cwchKeyPathSrcMax = OSFSAPI_MAX_PATH; WCHAR wszKeyPathSrc[ cwchKeyPathSrcMax ] = { 0 }; const DWORD cwchKeyPathDestMax = OSFSAPI_MAX_PATH; WCHAR wszKeyPathDest[ cwchKeyPathDestMax ] = { 0 }; WCHAR* pwszKeyPath1 = wszKeyPathSrc; CFilePathTableEntry** ppfpte1 = ppfpteSrc; WCHAR* pwszKeyPath2 = wszKeyPathDest; CFilePathTableEntry** ppfpte2 = ppfpteDest; Call( ErrGetFilePath( wszPathSrc, wszAbsPathSrc, wszKeyPathSrc ) ); Call( ErrGetFilePath( wszPathDest, wszAbsPathDest, wszKeyPathDest ) ); if ( LOSStrCompareW( wszKeyPathSrc, wszKeyPathDest ) > 0 ) { pwszKeyPath1 = wszKeyPathDest; ppfpte1 = ppfpteDest; pwszKeyPath2 = wszKeyPathSrc; ppfpte2 = ppfpteSrc; } Call( ErrLockFile( pwszKeyPath1, psem, ppfpte1 ) ); Call( ErrLockFile( pwszKeyPath2, psem, ppfpte2 ) ); HandleError: return err; } template< class I > ERR TFileSystemFilter<I>::ErrLockFile( _In_z_ const WCHAR* const wszKeyPath, _In_ CSemaphore* const psem, _Out_ CFilePathTableEntry** const ppfpte ) { ERR err = JET_errSuccess; CFilePathHashKey key( wszKeyPath ); CFilePathHashEntry entry; CFilePathHash::CLock lock; CFilePathHash::ERR errFilePathHash = CFilePathHash::ERR::errSuccess; BOOL fLocked = fFalse; CFilePathTableEntry* pfpteExisting = NULL; int cwchKeyPath = 0; WCHAR* wszKeyPathCopy = NULL; CFilePathTableEntry* pfpteNew = NULL; BOOL fRemove = fFalse; *ppfpte = NULL; Call( ErrEnsureInitFilePathTable() ); m_filePathHash.WriteLockKey( key, &lock ); fLocked = fTrue; errFilePathHash = m_filePathHash.ErrRetrieveEntry( &lock, &entry ); if ( errFilePathHash == CFilePathHash::ERR::errSuccess ) { pfpteExisting = entry.Pfpte(); } else { Assert( errFilePathHash == CFilePathHash::ERR::errEntryNotFound ); cwchKeyPath = LOSStrLengthW( wszKeyPath ) + 1; Alloc( wszKeyPathCopy = new WCHAR[ cwchKeyPath ] ); Call( ErrOSStrCbCopyW( wszKeyPathCopy, cwchKeyPath * sizeof( WCHAR ), wszKeyPath ) ); Alloc( pfpteExisting = pfpteNew = new CFilePathTableEntry( const_cast<const WCHAR** const>( &wszKeyPathCopy ) ) ); entry = CFilePathHashEntry( pfpteNew ); errFilePathHash = m_filePathHash.ErrInsertEntry( &lock, entry ); if ( errFilePathHash == CFilePathHash::ERR::errOutOfMemory ) { Call( ErrERRCheck( JET_errOutOfMemory ) ); } Assert( errFilePathHash == CFilePathHash::ERR::errSuccess ); fRemove = fTrue; } Call( pfpteExisting->ErrAddAsOwnerOrWaiter( psem ) ); pfpteExisting->AddRef(); fRemove = fFalse; m_filePathHash.WriteUnlockKey( &lock ); fLocked = fFalse; *ppfpte = pfpteExisting; psem->Wait(); HandleError: if ( fRemove ) { errFilePathHash = m_filePathHash.ErrDeleteEntry( &lock ); Assert( errFilePathHash == CFilePathHash::ERR::errSuccess ); delete pfpteNew; } if ( fLocked ) { m_filePathHash.WriteUnlockKey( &lock ); } delete[] wszKeyPathCopy; if ( err < JET_errSuccess ) { *ppfpte = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrGetFilePath( _In_z_ const WCHAR* const wszPath, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszAbsPath, _Out_bytecap_c_( cbOSFSAPI_MAX_PATHW ) WCHAR* const wszKeyPath ) { ERR err = JET_errSuccess; wszAbsPath[ 0 ] = 0; wszKeyPath[ 0 ] = 0; // compute the absolute path of the given path Call( TFileSystemWrapper<I>::ErrPathComplete( wszPath, wszAbsPath ) ); // translate the absolute path into an unambiguous file key path Call( m_pfident->ErrGetFileKeyPath( wszAbsPath, wszKeyPath ) ); HandleError: if ( err < JET_errSuccess ) { wszAbsPath[ 0 ] = 0; wszKeyPath[ 0 ] = 0; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrPrepareToDelete( _In_ CFilePathTableEntry* const pfpte ) { ERR err = JET_errSuccess; VolumeId volumeid = volumeidInvalid; FileId fileid = fileidInvalid; FileSerial fileserial = fileserialInvalid; // if the file is open then ask any cache that may have this file open to close it so we can delete it if ( pfpte->Pof() && pfpte->Pof()->Pc() ) { Call( pfpte->Pof()->Pff()->ErrGetPhysicalId( &volumeid, &fileid, &fileserial ) ); Call( pfpte->Pof()->Pc()->ErrClose( volumeid, fileid, fileserial ) ); } // check if we can delete the file Call( pfpte->ErrDeleteCheck() ); HandleError: return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileCreateCacheMiss( _In_z_ const WCHAR* const wszAnyAbsPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ CFilePathTableEntry* const pfpte, _Out_ CFileFilterReference** const ppffr ) { ERR err = JET_errSuccess; CFileFilter* pff = NULL; BOOL fCreated = fFalse; CFilePathTableEntry::COpenFile* pof = NULL; ICache* pc = NULL; *ppffr = NULL; // create the file Call( TFileSystemWrapper<I>::ErrFileCreate( wszAnyAbsPath, fmf, (IFileAPI**)&pff ) ); fCreated = fTrue; // configure the newly created file Call( ErrFileConfigure( pff, wszAnyAbsPath ) ); // get the file's configured cache Call( ErrGetConfiguredCache( pff, pfpte->WszKeyPath(), &pc ) ); // make the file available for other opens Call( pfpte->ErrOpenFile( &pff, pc, &pof ) ); // provide a wrapper for the cached file that will release it on the last close Alloc( *ppffr = new CFileFilterReference( this, pof, fmf, fFalse ) ); pof = NULL; HandleError: delete pof; delete pff; if ( err < JET_errSuccess ) { delete *ppffr; *ppffr = NULL; if ( fCreated ) { CallS( TFileSystemWrapper<I>::ErrFileDelete( wszAnyAbsPath ) ); } } return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileConfigure( _In_ CFileFilter* const pff, _In_z_ const WCHAR* const wszAnyAbsPath ) { ERR err = JET_errSuccess; VolumeId volumeid = volumeidInvalid; FileId fileid = fileidInvalid; Call( m_pfident->ErrGetFileId( wszAnyAbsPath, &volumeid, &fileid ) ); pff->SetFileId( volumeid, fileid ); HandleError: return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileOpenInternal( _In_z_ const WCHAR* const wszAnyAbsPath, _In_z_ const WCHAR* const wszKeyPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCacheOpen, _Out_ CFileFilterReference** const ppffr ) { ERR err = JET_errSuccess; CSemaphore sem( CSyncBasicInfo( "TFileSystemFilter<I>::ErrFileOpenInternal" ) ); CFilePathTableEntry* pfpte = NULL; *ppffr = NULL; // wait to lock the entry for this file Call( ErrLockFile( wszKeyPath, &sem, &pfpte ) ); // if the file isn't open then open it if ( !pfpte->Pof() ) { Call( ErrFileOpenCacheMiss( wszAnyAbsPath, fmf, fCacheOpen, pfpte, ppffr ) ); } // the file is already open else { // open the already open file Call( ErrFileOpenCacheHit( fmf, fFalse, fCacheOpen, pfpte->Pof(), ppffr ) ); // we are overwriting an existing file then truncate it. this also invalidates the cache for this file if ( DwCreationDispositionFromFileModeFlags( fFalse, fmf ) == TRUNCATE_EXISTING ) { TraceContextScope tcScope; Call( pfpte->Pof()->Pff()->ErrSetSize( *tcScope, 0, fFalse, qosIONormal ) ); } } HandleError: ReleaseFile( pfpte, &sem ); if ( err < JET_errSuccess ) { delete *ppffr; *ppffr = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileOpenCacheMiss( _In_z_ const WCHAR* const wszAnyAbsPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCacheOpen, _In_ CFilePathTableEntry* const pfpte, _Out_ CFileFilterReference** const ppffr ) { ERR err = JET_errSuccess; CFileFilter* pff = NULL; ICache* pc = NULL; BOOL fAttached = fFalse; const IFileAPI::FileModeFlags fmfReadOnlyMask = IFileAPI::fmfReadOnly | IFileAPI::fmfReadOnlyClient | IFileAPI::fmfReadOnlyPermissive; CFilePathTableEntry::COpenFile* pof = NULL; *ppffr = NULL; // open the file with the original flags Call( ErrFileOpenAndConfigure( wszAnyAbsPath, fmf, pfpte, &pff, &pc, &fAttached ) ); // if we opened this file read only and it is attached to the cache then open it read write so that the cache can // perform write back to the file due to cache pressure if ( fAttached && (fmf & fmfReadOnlyMask) != 0 ) { delete pff; pff = NULL; Call( ErrFileOpenAndConfigure( wszAnyAbsPath, fmf & ~fmfReadOnlyMask, pfpte, &pff, &pc, &fAttached )) } // make the file available for other opens Call( pfpte->ErrOpenFile( &pff, pc, &pof ) ); // provide a wrapper for the cached file that will release it on the last close Alloc( *ppffr = new CFileFilterReference( this, pof, fmf, fCacheOpen ) ); pof = NULL; HandleError: delete pof; delete pff; if ( err < JET_errSuccess ) { delete *ppffr; *ppffr = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileOpenAndConfigure( _In_z_ const WCHAR* const wszAnyAbsPath, _In_ const IFileAPI::FileModeFlags fmf, _In_ CFilePathTableEntry* const pfpte, _Out_ CFileFilter** const ppff, _Out_ ICache** const ppc, _Out_ BOOL* const pfAttached ) { ERR err = JET_errSuccess; CFileFilter* pff = NULL; ICache* pc = NULL; BOOL fAttached = fFalse; *ppff = NULL; *ppc = NULL; *pfAttached = fFalse; // open the file with the specified flags Call( TFileSystemWrapper<I>::ErrFileOpen( wszAnyAbsPath, fmf, (IFileAPI**)&pff ) ); // configure the newly opened file Call( ErrFileConfigure( pff, wszAnyAbsPath ) ); // get the file's cache Call( ErrGetCache( pff, pfpte->WszKeyPath(), &pc, &fAttached ) ); // return the opened file *ppff = pff; pff = NULL; *ppc = pc; *pfAttached = fAttached; HandleError: delete pff; if ( err < JET_errSuccess ) { delete *ppff; *ppff = NULL; *ppc = NULL; *pfAttached = fFalse; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrFileOpenCacheHit( _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCreate, _In_ const BOOL fCacheOpen, _In_ CFilePathTableEntry::COpenFile* const pof, _Out_ CFileFilterReference** const ppffr ) { ERR err = JET_errSuccess; *ppffr = NULL; // perform the access check against all currently open file handles for this file Call( pof->Pfpte()->ErrAccessCheck( fmf, fCreate, fCacheOpen ) ); // provide a wrapper for the cached file that will release it on the last close Alloc( *ppffr = new CFileFilterReference( this, pof, fmf, fCacheOpen ) ); HandleError: if ( err < JET_errSuccess ) { delete *ppffr; *ppffr = NULL; } return err; } template<class I> void TFileSystemFilter<I>::ReportCachedFileNotFoundById( _In_ const VolumeId volumeid, _In_ const FileId fileid, _In_ const FileSerial fileserial ) { const ULONG cwsz = 3; const WCHAR* rgpwsz[ cwsz ] = { 0 }; DWORD irgpwsz = 0; WCHAR wszVolumeId[ 64 ] = { 0 }; WCHAR wszFileId[ 64 ] = { 0 }; WCHAR wszFileSerial[ 64 ] = { 0 }; OSStrCbFormatW( wszVolumeId, sizeof( wszVolumeId ), L"0x%08x", volumeid ); OSStrCbFormatW( wszFileId, sizeof( wszFileId ), L"0x%016I64x", fileid ); OSStrCbFormatW( wszFileSerial, sizeof( wszFileSerial ), L"0x%08x", fileserial ); rgpwsz[ irgpwsz++ ] = wszVolumeId; rgpwsz[ irgpwsz++ ] = wszFileId; rgpwsz[ irgpwsz++ ] = wszFileSerial; m_pfsconfig->EmitEvent( eventError, BLOCK_CACHE_CATEGORY, BLOCK_CACHE_CACHED_FILE_ID_MISMATCH_ID, irgpwsz, rgpwsz, JET_EventLoggingLevelMin ); } template< class I > ERR TFileSystemFilter<I>::ErrGetConfiguredCache( _In_ CFileFilter* const pff, _In_z_ const WCHAR* const wszKeyPath, _Out_ ICache** const ppc ) { ERR err = JET_errSuccess; IBlockCacheConfiguration* pbcconfig = NULL; ICachedFileConfiguration* pcfconfig = NULL; const DWORD cwchAbsPathCachingFileMax = OSFSAPI_MAX_PATH; WCHAR wszAbsPathCachingFile[ cwchAbsPathCachingFileMax ] = { 0 }; const DWORD cwchKeyPathCachingFileMax = OSFSAPI_MAX_PATH; WCHAR wszKeyPathCachingFile[ cwchKeyPathCachingFileMax ] = { 0 }; ICacheConfiguration* pcconfig = NULL; ICache* pc = NULL; *ppc = NULL; // get the caching configuration for this file Call( ErrGetConfiguration( &pbcconfig ) ); Call( pbcconfig->ErrGetCachedFileConfiguration( wszKeyPath, &pcfconfig ) ); // if caching is enabled for this file then open its backing store if ( pcfconfig->FCachingEnabled() ) { // get the cache configuration for this file pcfconfig->CachingFilePath( wszAbsPathCachingFile ); Call( m_pfident->ErrGetFileKeyPath( wszAbsPathCachingFile, wszKeyPathCachingFile ) ); Call( pbcconfig->ErrGetCacheConfiguration( wszKeyPathCachingFile, &pcconfig ) ); // try to open the cache for this file. if we can't then we will use access the file without caching. this // is intentionally best effort only to allow continued operation if the caching storage is failed err = m_pcrep->ErrOpen( this, m_pfsconfig, &pcconfig, &pc ); if ( err < JET_errSuccess ) { ReportCacheOpenFailure( pcfconfig, err ); err = JET_errSuccess; } } // return the cache *ppc = pc; // save the caching state pff->SetCacheState( &pcfconfig, &pc, NULL ); HandleError: delete pc; delete pcconfig; delete pcfconfig; if ( err < JET_errSuccess ) { *ppc = NULL; } return err; } template<class I> void TFileSystemFilter<I>::ReportCacheOpenFailure( _In_ ICachedFileConfiguration* const pcfconfig, _In_ const ERR err ) { const ULONG cwsz = 2; const WCHAR* rgpwsz[ cwsz ] = { 0 }; DWORD irgpwsz = 0; WCHAR wszCachingFile[ OSFSAPI_MAX_PATH ] = { 0 }; WCHAR wszError[ 64 ] = { 0 }; pcfconfig->CachingFilePath( wszCachingFile ); OSStrCbFormatW( wszError, sizeof( wszError ), L"%i (0x%08x)", err, err ); rgpwsz[ irgpwsz++ ] = wszCachingFile; rgpwsz[ irgpwsz++ ] = wszError; m_pfsconfig->EmitEvent( eventWarning, BLOCK_CACHE_CATEGORY, BLOCK_CACHE_CACHING_FILE_OPEN_FAILURE_ID, irgpwsz, rgpwsz, JET_EventLoggingLevelMin ); } template< class I > ERR TFileSystemFilter<I>::ErrGetCache( _In_ CFileFilter* const pff, _In_z_ const WCHAR* const wszKeyPath, _Out_ ICache** const ppc, _Out_ BOOL* const pfAttached ) { ERR err = JET_errSuccess; CCachedFileHeader* pcfh = NULL; IBlockCacheConfiguration* pbcconfig = NULL; ICachedFileConfiguration* pcfconfig = NULL; ICache* pc = NULL; *ppc = NULL; *pfAttached = fFalse; // determine if this file has a cached file header err = CCachedFileHeader::ErrLoad( m_pfsconfig, pff, &pcfh ); // if the file has a valid cached file header then we need to open its backing store if ( err >= JET_errSuccess ) { Call( ErrGetConfiguration( &pbcconfig ) ); Call( pbcconfig->ErrGetCachedFileConfiguration( wszKeyPath, &pcfconfig ) ); Call( m_pcrep->ErrOpenById( this, m_pfsconfig, pbcconfig, pcfh->VolumeidCache(), pcfh->FileidCache(), pcfh->RgbUniqueIdCache(), &pc ) ); *ppc = pc; *pfAttached = fTrue; pff->SetCacheState( &pcfconfig, &pc, &pcfh ); } // if the file doesn't have a recognizable cached file header then open it as if it were not already cached else if ( err == JET_errReadVerifyFailure ) { // ignore any error we got trying to read the cached file header. if there is corrupt data there then it // will be discovered at a higher level later err = JET_errSuccess; // get the file's configured cache Call( ErrGetConfiguredCache( pff, wszKeyPath, ppc ) ); } HandleError: delete pc; delete pcfconfig; delete pcfh; if ( err < JET_errSuccess ) { *ppc = NULL; *pfAttached = fFalse; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrGetConfiguration( _Out_ IBlockCacheConfiguration** const ppbcconfig ) { ERR err = JET_errSuccess; *ppbcconfig = NULL; Call( m_initOnceAttach.Init( ErrGetConfiguration_, this ) ); *ppbcconfig = m_pbcconfig; HandleError: if ( err < JET_errSuccess ) { *ppbcconfig = NULL; } return err; } template< class I > ERR TFileSystemFilter<I>::ErrGetConfiguration() { return m_pfsconfig->ErrGetBlockCacheConfiguration( &m_pbcconfig ); } template< class I > ERR TFileSystemFilter<I>::ErrInitFilePathTable() { ERR err = JET_errSuccess; if ( m_filePathHash.ErrInit( 5.0, 1.0 ) == CFilePathHash::ERR::errOutOfMemory ) { Call( ErrERRCheck( JET_errOutOfMemory ) ); } HandleError: return err; } template< class I > void TFileSystemFilter<I>::TermFilePathTable() { if ( m_initOnceFilePathTable.FIsInit() ) { m_filePathHash.Term(); } } INLINE typename CFilePathHash::NativeCounter CFilePathHash::CKeyEntry::Hash( const CFilePathHashKey& key ) { return CFilePathHash::NativeCounter( key.UiHash() ); } INLINE typename CFilePathHash::NativeCounter CFilePathHash::CKeyEntry::Hash() const { return CFilePathHash::NativeCounter( m_entry.UiHash() ); } INLINE BOOL CFilePathHash::CKeyEntry::FEntryMatchesKey( const CFilePathHashKey& key ) const { if ( m_entry.UiHash() != key.UiHash() ) { return fFalse; } if ( LOSStrCompareW( m_entry.Pfpte()->WszKeyPath(), key.WszKeyPath() ) != 0 ) { return fFalse; } return fTrue; } INLINE void CFilePathHash::CKeyEntry::SetEntry( const CFilePathHashEntry& entry ) { m_entry = entry; } INLINE void CFilePathHash::CKeyEntry::GetEntry( CFilePathHashEntry * const pentry ) const { *pentry = m_entry; } // CFileSystemFilter: concrete TFileSystemFilter<IFileSystemFilter> class CFileSystemFilter : public TFileSystemFilter<IFileSystemFilter> { public: // specialized API CFileSystemFilter( _In_ IFileSystemConfiguration* const pfsconfig, _Inout_ IFileSystemAPI** const ppfsapi, _In_ IFileIdentification* const pfident, _In_ ICacheTelemetry* const pctm, _In_ ICacheRepository * const pcrep ) : TFileSystemFilter<IFileSystemFilter>( pfsconfig, ppfsapi, pfident, pctm, pcrep ) { } virtual ~CFileSystemFilter() {} }; // CFileFilterReference: a reference to an IFileFilter implementation. class CFileFilterReference : public CFileFilterWrapper { public: // specialized API CFileFilterReference( _In_ TFileSystemFilter<IFileSystemFilter>* const pfsf, _In_ CFilePathTableEntry::COpenFile* const pof, _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCacheOpen ) : CFileFilterWrapper( pof->Pff(), fCacheOpen ? IOMode::iomRaw : IOMode::iomEngine ), m_pfsf( pfsf ), m_pof( pof ), m_fmf( fmf ), m_fCacheOpen( fCacheOpen ) { m_pfsf->AddFileReference( this, m_pof ); } virtual ~CFileFilterReference() { m_pfsf->RemoveFileReference( this, m_pof ); } BOOL FCacheOpen() const { return m_fCacheOpen; } public: // IFileAPI FileModeFlags Fmf() const override { return m_fmf; } private: friend SIZE_T CFileFilterReferenceOffsetOfILE(); TFileSystemFilter<IFileSystemFilter>* const m_pfsf; CFilePathTableEntry::COpenFile* const m_pof; const IFileAPI::FileModeFlags m_fmf; const BOOL m_fCacheOpen; CInvasiveList< CFileFilterReference, CFileFilterReferenceOffsetOfILE >::CElement m_ile; }; static SIZE_T CFileFilterReferenceOffsetOfILE() { return OffsetOf( CFileFilterReference, m_ile ); } INLINE ERR CFilePathTableEntry::COpenFile::ErrAccessCheck( _In_ const IFileAPI::FileModeFlags fmf, _In_ const BOOL fCreate, _In_ const BOOL fCacheOpen ) { ERR err = JET_errSuccess; // perform the access check against all currently open file handles for this file for ( CFileFilterReference* ffr = m_ilReferences.PrevMost(); ffr != NULL && err >= JET_errSuccess; ffr = m_ilReferences.Next( ffr ) ) { // if the current open file is for the cache then do not access check against its share mode if ( ffr->FCacheOpen() ) { continue; } // if the proposed file is for the cache then it automatically gets access if ( fCacheOpen ) { continue; } // get the desired access for the proposed file DWORD dwDesiredAccess = DwDesiredAccessFromFileModeFlags( fmf ); // get the share mode for the current open file DWORD dwShareMode = DwShareModeFromFileModeFlags( ffr->Fmf() ); // do not grant access if the desired access doesn't match the share mode of the current open file if ( ( dwDesiredAccess & GENERIC_READ ) && !( dwShareMode & FILE_SHARE_READ ) ) { err = ErrERRCheck( JET_errFileAccessDenied ); } if ( ( dwDesiredAccess & GENERIC_WRITE ) && !( dwShareMode & FILE_SHARE_WRITE ) ) { err = ErrERRCheck( JET_errFileAccessDenied ); } if ( ( dwDesiredAccess & DELETE ) && !( dwShareMode & FILE_SHARE_DELETE ) ) { err = ErrERRCheck( JET_errFileAccessDenied ); } // get the creation disposition for the proposed file DWORD dwCreationDisposition = DwCreationDispositionFromFileModeFlags( fCreate, fmf ); // existing file check if ( dwCreationDisposition == CREATE_NEW ) { err = ErrERRCheck( JET_errFileAlreadyExists ); } } return err; } INLINE ERR CFilePathTableEntry::COpenFile::ErrDeleteCheck() { ERR err = JET_errSuccess; // perform the delete check against all currently open file handles for this file for ( CFileFilterReference* ffr = m_ilReferences.PrevMost(); ffr != NULL && err >= JET_errSuccess; ffr = m_ilReferences.Next( ffr ) ) { // get the share mode for the current open file DWORD dwShareMode = DwShareModeFromFileModeFlags( ffr->Fmf() ); // delete file check if ( !( dwShareMode & FILE_SHARE_DELETE ) ) { err = ErrERRCheck( JET_errFileAccessDenied ); } } return err; }
37,272
438
package info.bitrich.xchangestream.coinmate.dto.auth; import com.pusher.client.util.ConnectionFactory; import java.io.IOException; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import org.knowm.xchange.coinmate.CoinmateException; public class CoinmateUrlEncodedConnectionFactory extends ConnectionFactory { private final PusherAuthParamsObject pusherAuthParamsObject; public CoinmateUrlEncodedConnectionFactory(PusherAuthParamsObject pusherAuthParamsObject) { this.pusherAuthParamsObject = pusherAuthParamsObject; } public String getCharset() { return "UTF-8"; } public String getContentType() { return "application/x-www-form-urlencoded"; } public String getBody() { StringBuilder urlParameters = new StringBuilder(); try { Map<String, String> mQueryStringParameters = pusherAuthParamsObject.getParams(); urlParameters .append("channel_name=") .append(URLEncoder.encode(getChannelName(), getCharset())); urlParameters.append("&socket_id=").append(URLEncoder.encode(getSocketId(), getCharset())); Iterator var2 = mQueryStringParameters.keySet().iterator(); while (var2.hasNext()) { String parameterName = (String) var2.next(); urlParameters.append("&").append(parameterName).append("="); urlParameters.append( URLEncoder.encode((String) mQueryStringParameters.get(parameterName), getCharset())); } } catch (IOException e) { throw new CoinmateException(e.getMessage()); } return urlParameters.toString(); } }
561
2,144
<gh_stars>1000+ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.core.query.optimizer.filter; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.apache.pinot.common.request.Expression; import org.apache.pinot.common.request.Function; import org.apache.pinot.spi.data.Schema; import org.apache.pinot.sql.FilterKind; /** * The {@code FlattenAndOrFilterOptimizer} flattens the nested AND/OR filters. For example, AND(a, AND(b, c)) can * be flattened to AND(a, b, c). */ public class FlattenAndOrFilterOptimizer implements FilterOptimizer { @Override public Expression optimize(Expression filterExpression, @Nullable Schema schema) { return optimize(filterExpression); } private Expression optimize(Expression filterExpression) { Function function = filterExpression.getFunctionCall(); String operator = function.getOperator(); if (!operator.equals(FilterKind.AND.name()) && !operator.equals(FilterKind.OR.name())) { return filterExpression; } List<Expression> children = function.getOperands(); assert children != null; List<Expression> newChildren = new ArrayList<>(); for (Expression child : children) { Expression optimizedChild = optimize(child); Function childFunction = optimizedChild.getFunctionCall(); if (childFunction.getOperator().equals(operator)) { newChildren.addAll(childFunction.getOperands()); } else { newChildren.add(optimizedChild); } } function.setOperands(newChildren); return filterExpression; } }
711
1,194
<filename>hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/r4/OpenApiInterceptorJpaTest.java package ca.uhn.fhir.jpa.provider.r4; import ca.uhn.fhir.rest.openapi.OpenApiInterceptor; import org.apache.commons.io.IOUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; public class OpenApiInterceptorJpaTest extends BaseResourceProviderR4Test { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(OpenApiInterceptorJpaTest.class); @Override @AfterEach public void after() throws Exception { super.after(); ourRestServer.getInterceptorService().unregisterInterceptorsIf(t -> t instanceof OpenApiInterceptor); } @Test public void testFetchOpenApi() throws IOException { ourRestServer.registerInterceptor(new OpenApiInterceptor()); HttpGet get = new HttpGet(ourServerBase + "/metadata?_format=json&_pretty=true"); try (CloseableHttpResponse response = ourHttpClient.execute(get)) { String string = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(string); assertEquals(200, response.getStatusLine().getStatusCode()); } get = new HttpGet(ourServerBase + "/api-docs"); try (CloseableHttpResponse response = ourHttpClient.execute(get)) { String string = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); ourLog.info(string); assertEquals(200, response.getStatusLine().getStatusCode()); } } }
607
5,964
<filename>tests/VarAllocTest.cpp #include "Test.h" #include "SkVarAlloc.h" DEF_TEST(VarAlloc, r) { SkVarAlloc va(4/*start allocating at 16B*/); char* p = va.alloc(128, SK_MALLOC_THROW); sk_bzero(p, 128); // Just checking this is safe. #if !defined(SK_BUILD_FOR_ANDROID) && !defined(__UCLIBC__) // This method will always return 0 on Android and UCLIBC platforms. REPORTER_ASSERT(r, va.approxBytesAllocated() >= 128); #endif }
188
372
/* Copyright (C) 2000, 2004-2005 Free Software Foundation, Inc. This file is part of the GNU LIBICONV Library. The GNU LIBICONV Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU LIBICONV Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU LIBICONV Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Creates the UTF-8.TXT reference table. */ #include <stdio.h> #include <stdlib.h> #include "binary-io.h" int main () { int i1, i2, i3; #if O_BINARY SET_BINARY(fileno(stdout)); #endif /* Range 0x0000..0x007f */ for (i1 = 0; i1 < 0x80; i1++) printf("0x%02X\t0x%04X\n", i1, i1); /* Range 0x0080..0x07ff */ for (i1 = 2; i1 < 32; i1++) for (i2 = 0; i2 < 64; i2++) printf("0x%02X%02X\t0x%04X\n", 0xc0+i1,0x80+i2, (i1<<6)+i2); /* Range 0x0800..0xffff */ for (i1 = 0; i1 < 16; i1++) for (i2 = (i1==0 ? 32 : 0); i2 < 64; i2++) for (i3 = 0; i3 < 64; i3++) printf("0x%02X%02X%02X\t0x%04X\n", 0xe0+i1,0x80+i2,0x80+i3, (i1<<12)+(i2<<6)+i3); if (ferror(stdout) || fclose(stdout)) exit(1); exit(0); }
674
335
{ "word": "Literacy", "definitions": [ "The ability to read and write.", "Competence or knowledge in a specified area." ], "parts-of-speech": "Noun" }
78
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. * *************************************************************/ #include "precompiled_svx.hxx" #include "ParaLineSpacingControl.hxx" #include "ParaPropertyPanel.hrc" #include <sfx2/sidebar/ResourceDefinitions.hrc> #include <svx/dialogs.hrc> #include <svx/dialmgr.hxx> #include <unotools/viewoptions.hxx> #include <editeng/kernitem.hxx> #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include <sfx2/sidebar/Theme.hxx> #include <svtools/unitconv.hxx> #define _DEFAULT_LINE_SPACING 200 #define FIX_DIST_DEF 283 #define LINESPACE_1 100 #define LINESPACE_15 150 #define LINESPACE_2 200 #define LINESPACE_115 115 #define LLINESPACE_1 0 #define LLINESPACE_15 1 #define LLINESPACE_2 2 #define LLINESPACE_PROP 3 #define LLINESPACE_MIN 4 #define LLINESPACE_DURCH 5 #define LLINESPACE_FIX 6 #define DO_NOT_CUSTOM 0 #define USE_CUSTOM 1 namespace svx { namespace sidebar { ParaLineSpacingControl::ParaLineSpacingControl(Window* pParent, svx::sidebar::ParaPropertyPanel& rPanel) : PopupControl( pParent,SVX_RES(RID_POPUPPANEL_PARAPAGE_LINESPACING)), mbUseLineSPCustom (0), mbLineSPDisable (0), mrParaPropertyPanel (rPanel), mpBindings (NULL), nMinFixDist (BEGIN_VALUE), pActLineDistFld (&aLineDistAtPercentBox), maLineSpacing (ValueSetWithTextControl::IMAGE_TEXT,this, SVX_RES(LINE_SPACING)), maCustomFT (this, SVX_RES(FT_CUSTOM)), maLSpacingFT (this, SVX_RES(FT_LINE_SPACING)), aLineDist (this, SVX_RES(LB_LINE_SPACING)), maOfFT (this, SVX_RES(FT_OF)), aLineDistAtPercentBox (this, SVX_RES(ED_SBINDE_LINEDISTPERCENT)), aLineDistAtMetricBox (this, SVX_RES(ED_SBINDE_LINEDISTPOINT)), maSpacing1 (SVX_RES(IMG_SPACING1)), maSpacing115 (SVX_RES(IMG_SPACING115)), maSpacing15 (SVX_RES(IMG_SPACING15)), maSpacing2 (SVX_RES(IMG_SPACING2)), maSelSpacing1 (SVX_RES(IMG_SEL_SPACING1)), maSelSpacing115 (SVX_RES(IMG_SEL_SPACING115)), maSelSpacing15 (SVX_RES(IMG_SEL_SPACING15)), maSelSpacing2 (SVX_RES(IMG_SEL_SPACING2)), maImgCus (SVX_RES(IMG_CUSTOM)), maImgCusGrey (SVX_RES(IMG_CUSTOM_GRAY)), maStrCus (SVX_RES(STR_LCVALUE)), mpImg (NULL), mpImgSel (NULL), mpStr (NULL), mpStrTip (NULL), maLine (SVX_RES(STR_LSPACING)), maOf (SVX_RES(STR_LS_OF)), maValue (0), maPos (0) { initial(); FreeResource(); mpBindings = mrParaPropertyPanel.GetBindings(); // m_eLNSpaceUnit = mrParaPropertyPanel.maLNSpaceControl.GetCoreMetric(); m_eLNSpaceUnit = SFX_MAPUNIT_100TH_MM; } ParaLineSpacingControl::~ParaLineSpacingControl() { delete[] mpImg; delete[] mpImgSel; delete[] mpStr; delete[] mpStrTip; } void ParaLineSpacingControl::initial() { maLineSpacing.SetStyle( maLineSpacing.GetStyle()| WB_3DLOOK | WB_NO_DIRECTSELECT ); maLineSpacing.SetControlBackground( GetSettings().GetStyleSettings().GetHighContrastMode() ? GetSettings().GetStyleSettings().GetMenuColor() : sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); maLineSpacing.SetColor( GetSettings().GetStyleSettings().GetHighContrastMode() ? GetSettings().GetStyleSettings().GetMenuColor() : sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); maLineSpacing.SetBackground( GetSettings().GetStyleSettings().GetHighContrastMode() ? GetSettings().GetStyleSettings().GetMenuColor() : sfx2::sidebar::Theme::GetColor( sfx2::sidebar::Theme::Paint_PanelBackground )); mpImg = new Image[4]; mpImg[0] = maSpacing1; mpImg[1] = maSpacing115; mpImg[2] = maSpacing15; mpImg[3] = maSpacing2; mpImgSel = new Image[4]; mpImgSel[0] = maSelSpacing1; mpImgSel[1] = maSelSpacing115; mpImgSel[2] = maSelSpacing15; mpImgSel[3] = maSelSpacing2; mpStr = new XubString[4]; mpStr[0] = XubString(SVX_RES(STR_SPACING1)); mpStr[1] = XubString(SVX_RES(STR_SPACING115)); mpStr[2] = XubString(SVX_RES(STR_SPACING15)); mpStr[3] = XubString(SVX_RES(STR_SPACING2)); mpStrTip = new XubString[4]; mpStrTip[0] = XubString(SVX_RES(STR_LS_SINGLE)); mpStrTip[1] = XubString(SVX_RES(STR_LS_115)); mpStrTip[2] = XubString(SVX_RES(STR_LS_15)); mpStrTip[3] = XubString(SVX_RES(STR_LS_DOUBLE)); for (int i=0;i<4;i++) maLineSpacing.AddItem(mpImg[i], &mpImgSel[i],mpStr[i],&mpStrTip[i]); maLineSpacing.AddItem( maImgCus, 0, maStrCus, 0 ); SetAllNoSel(); Link aLink = LINK(this, ParaLineSpacingControl,VSSelHdl ); maLineSpacing.SetSelectHdl(aLink); maLineSpacing.StartSelection(); maLineSpacing.Show(); aLink = LINK( this, ParaLineSpacingControl, LineSPDistHdl_Impl ); aLineDist.SetSelectHdl(aLink); aLineDist.SelectEntryPos( LLINESPACE_1 ) ; aLink = LINK( this, ParaLineSpacingControl, LineSPDistAtHdl_Impl ); aLineDistAtPercentBox.SetModifyHdl( aLink ); aLineDistAtMetricBox.SetModifyHdl( aLink ); } void ParaLineSpacingControl::PopupModeEndCallback() { if( mbUseLineSPCustom ) { //maLinePos = mpLineSPPage->maPos; //maLineValue = mpLineSPPage->maValue; SvtViewOptions aWinOpt( E_WINDOW, LSP_POS_GLOBAL_VALUE ); ::com::sun::star::uno::Sequence < ::com::sun::star::beans::NamedValue > aSeq(1); aSeq[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("maLinePos") ); aSeq[0].Value <<= ::rtl::OUString( String::CreateFromInt64( maPos )); aWinOpt.SetUserData( aSeq ); SvtViewOptions aWinOpt2( E_WINDOW, LSP_LV_GLOBAL_VALUE ); aSeq[0].Name = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("maLineValue") ); aSeq[0].Value <<= ::rtl::OUString( String::CreateFromInt64( maValue )); aWinOpt2.SetUserData( aSeq ); } } void ParaLineSpacingControl::Rearrange(SfxItemState currSPState,FieldUnit currMetricUnit,SvxLineSpacingItem* currSPItem,const ::sfx2::sidebar::EnumContext currentContext) { SvtViewOptions aWinOpt( E_WINDOW, LSP_POS_GLOBAL_VALUE ); if ( aWinOpt.Exists() ) { ::com::sun::star::uno::Sequence < ::com::sun::star::beans::NamedValue > aSeq = aWinOpt.GetUserData(); ::rtl::OUString aTmp; if ( aSeq.getLength()) aSeq[0].Value >>= aTmp; String aWinData( aTmp ); maPos = (sal_uInt16)aWinData.ToInt32(); } SvtViewOptions aWinOpt2( E_WINDOW, LSP_LV_GLOBAL_VALUE ); if ( aWinOpt2.Exists() ) { ::com::sun::star::uno::Sequence < ::com::sun::star::beans::NamedValue > aSeq = aWinOpt2.GetUserData(); ::rtl::OUString aTmp; if ( aSeq.getLength()) aSeq[0].Value >>= aTmp; String aWinData( aTmp ); maValue = (sal_uInt16)aWinData.ToInt32(); } String sHelpText; switch(maPos) { case LLINESPACE_1: sHelpText += mpStrTip[0]; break; case LLINESPACE_15: sHelpText += mpStrTip[2]; break; case LLINESPACE_2: sHelpText += mpStrTip[3]; break; case LLINESPACE_PROP: sHelpText +=maLine; sHelpText.Append(String("Proportion: ", 12, RTL_TEXTENCODING_ASCII_US)); sHelpText += maOf; sHelpText.Append( String::CreateFromInt64( maValue )); break; case LLINESPACE_MIN: sHelpText += maLine; sHelpText.Append(String("At Least: ", 10, RTL_TEXTENCODING_ASCII_US)); sHelpText += maOf; sHelpText.Append( String::CreateFromInt64( maValue )); break; case LLINESPACE_DURCH: sHelpText += maLine; sHelpText.Append(String("Leading: ", 9, RTL_TEXTENCODING_ASCII_US)); sHelpText += maOf; sHelpText.Append( String::CreateFromInt64( maValue )); break; case LLINESPACE_FIX: sHelpText += maLine; sHelpText.Append(String("Fixed: ", 7, RTL_TEXTENCODING_ASCII_US)); sHelpText += maOf; sHelpText.Append( String::CreateFromInt64( maValue )); break; } if( !aWinOpt.Exists() && !aWinOpt2.Exists() ) mbLineSPDisable = sal_True; else mbLineSPDisable = sal_False; if( mbLineSPDisable ) maLineSpacing.ReplaceItemImages(5, maImgCusGrey,0); else { maLineSpacing.ReplaceItemImages(5, maImgCus,0); maLineSpacing.SetItemText(5,sHelpText); } SfxItemState eState = currSPState; SetFieldUnit( aLineDistAtMetricBox, currMetricUnit ); // mpLineSPPage->SetAllNoSel(); aLineDist.Enable(); pActLineDistFld->Enable(); pActLineDistFld->SetText( String() ); bool bValueSetFocus = sal_False; //wj if( eState >= SFX_ITEM_AVAILABLE ) { // SfxMapUnit eUnit = maLNSpaceControl.GetCoreMetric(); SfxMapUnit eUnit = SFX_MAPUNIT_100TH_MM; m_eLNSpaceUnit = eUnit; switch( currSPItem->GetLineSpaceRule() ) { case SVX_LINE_SPACE_AUTO: { SvxInterLineSpace eInter = currSPItem->GetInterLineSpaceRule(); switch( eInter ) { case SVX_INTER_LINE_SPACE_OFF: { aLineDist.SelectEntryPos( LLINESPACE_1 ); pActLineDistFld->Disable(); pActLineDistFld->SetText( String() ); mbUseLineSPCustom = DO_NOT_CUSTOM; if ( LINESPACE_1 == currSPItem->GetPropLineSpace() ) { maLineSpacing.SelectItem(1); bValueSetFocus = sal_True; //wj } } break; case SVX_INTER_LINE_SPACE_PROP: { if ( LINESPACE_1 == currSPItem->GetPropLineSpace() ) { aLineDist.SelectEntryPos( LLINESPACE_1 ); pActLineDistFld->Disable(); pActLineDistFld->SetText( String() ); mbUseLineSPCustom = DO_NOT_CUSTOM; maLineSpacing.SelectItem(1); bValueSetFocus = sal_True; //wj break; } if ( LINESPACE_15 == currSPItem->GetPropLineSpace() ) { aLineDist.SelectEntryPos( LLINESPACE_15 ); pActLineDistFld->Disable(); pActLineDistFld->SetText( String() ); mbUseLineSPCustom = DO_NOT_CUSTOM; maLineSpacing.SelectItem(3); bValueSetFocus = sal_True; //wj break; } if ( LINESPACE_2 == currSPItem->GetPropLineSpace() ) { aLineDist.SelectEntryPos( LLINESPACE_2 ); pActLineDistFld->Disable(); pActLineDistFld->SetText( String() ); mbUseLineSPCustom = DO_NOT_CUSTOM; maLineSpacing.SelectItem(4); bValueSetFocus = sal_True; //wj break; } aLineDist.SelectEntryPos( LLINESPACE_PROP ); if(pActLineDistFld != &(aLineDistAtPercentBox)) { pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtPercentBox); } else { pActLineDistFld = &(aLineDistAtMetricBox); pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtPercentBox); } pActLineDistFld->Enable(); pActLineDistFld->Show(); aLineDistAtPercentBox. SetValue( aLineDistAtPercentBox.Normalize( currSPItem->GetPropLineSpace() ) ); if( currSPItem->GetPropLineSpace() == LINESPACE_115 ) { mbUseLineSPCustom = DO_NOT_CUSTOM; maLineSpacing.SelectItem(2); bValueSetFocus = sal_True; //wj } else { mbUseLineSPCustom = USE_CUSTOM; maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); } } break; case SVX_INTER_LINE_SPACE_FIX: { if(pActLineDistFld != &(aLineDistAtMetricBox)) { pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtMetricBox); } else { pActLineDistFld = &(aLineDistAtPercentBox); pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtMetricBox); } pActLineDistFld->Enable(); pActLineDistFld->Show(); maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); SetMetricValue( aLineDistAtMetricBox, currSPItem->GetInterLineSpace(), eUnit ); aLineDist.SelectEntryPos( LLINESPACE_DURCH ); mbUseLineSPCustom = USE_CUSTOM; } break; default: break; } } break; case SVX_LINE_SPACE_FIX: { if(pActLineDistFld != &(aLineDistAtMetricBox)) { pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtMetricBox); } else { pActLineDistFld = &(aLineDistAtPercentBox); pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtMetricBox); } pActLineDistFld->Enable(); pActLineDistFld->Show(); maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); SetMetricValue(aLineDistAtMetricBox, currSPItem->GetLineHeight(), eUnit); aLineDist.SelectEntryPos( LLINESPACE_FIX ); mbUseLineSPCustom = USE_CUSTOM; } break; case SVX_LINE_SPACE_MIN: { if(pActLineDistFld != &(aLineDistAtMetricBox)) { pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtMetricBox); } else { pActLineDistFld = &(aLineDistAtPercentBox); pActLineDistFld->Disable(); pActLineDistFld->Hide(); pActLineDistFld = &(aLineDistAtMetricBox); } pActLineDistFld->Enable(); pActLineDistFld->Show(); maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); SetMetricValue(aLineDistAtMetricBox, currSPItem->GetLineHeight(), eUnit); aLineDist.SelectEntryPos( LLINESPACE_MIN ); mbUseLineSPCustom = USE_CUSTOM; } break; default: break; } } else if( eState == SFX_ITEM_DISABLED ) { aLineDist.Disable(); pActLineDistFld->Enable(sal_False); pActLineDistFld->SetText( String() ); maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); mbUseLineSPCustom = DO_NOT_CUSTOM; } else { pActLineDistFld->Enable(sal_False); pActLineDistFld->SetText( String() ); aLineDist.SetNoSelection(); maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); mbUseLineSPCustom = DO_NOT_CUSTOM; } aLineDist.SaveValue(); const sal_uInt16 uCount = aLineDist.GetEntryCount(); if( uCount == LLINESPACE_FIX + 1 ) { switch (currentContext.GetCombinedContext_DI()) { case CombinedEnumContext(Application_DrawImpress, Context_Table): case CombinedEnumContext(Application_DrawImpress, Context_DrawText): case CombinedEnumContext(Application_DrawImpress, Context_Draw): case CombinedEnumContext(Application_DrawImpress, Context_TextObject): case CombinedEnumContext(Application_DrawImpress, Context_Graphic): case CombinedEnumContext(Application_Calc, Context_DrawText): case CombinedEnumContext(Application_WriterVariants, Context_DrawText): case CombinedEnumContext(Application_WriterVariants, Context_Annotation): { aLineDist.RemoveEntry(LLINESPACE_FIX); } } } else if( uCount == LLINESPACE_FIX) { switch (currentContext.GetCombinedContext_DI()) { case CombinedEnumContext(Application_WriterVariants, Context_Default): case CombinedEnumContext(Application_WriterVariants, Context_Text): case CombinedEnumContext(Application_WriterVariants, Context_Table): { aLineDist.InsertEntry(String::CreateFromAscii("Fixed"), LLINESPACE_FIX); } } } maLineSpacing.Format(); maLineSpacing.StartSelection(); } void ParaLineSpacingControl::SetAllNoSel() { maLineSpacing.SelectItem(1); maLineSpacing.SetNoSelection(); } IMPL_LINK( ParaLineSpacingControl, LineSPDistHdl_Impl, ListBox*, pBox ) { maLineSpacing.SetNoSelection(); maLineSpacing.SelectItem(0); maLineSpacing.Format(); maLineSpacing.StartSelection(); switch( pBox->GetSelectEntryPos() ) { case LLINESPACE_1: case LLINESPACE_15: case LLINESPACE_2: pActLineDistFld->Enable(sal_False); pActLineDistFld->SetText( String() ); break; case LLINESPACE_DURCH: aLineDistAtPercentBox.Hide(); pActLineDistFld = &aLineDistAtMetricBox; aLineDistAtMetricBox.SetMin(0); if ( !aLineDistAtMetricBox.GetText().Len() ) aLineDistAtMetricBox.SetValue( aLineDistAtMetricBox.Normalize( 0 ) ); aLineDistAtPercentBox.Hide(); pActLineDistFld->Show(); pActLineDistFld->Enable(); break; case LLINESPACE_MIN: aLineDistAtPercentBox.Hide(); pActLineDistFld = &aLineDistAtMetricBox; aLineDistAtMetricBox.SetMin(0); if ( !aLineDistAtMetricBox.GetText().Len() ) aLineDistAtMetricBox.SetValue( aLineDistAtMetricBox.Normalize( 0 ), FUNIT_TWIP ); aLineDistAtPercentBox.Hide(); pActLineDistFld->Show(); pActLineDistFld->Enable(); break; case LLINESPACE_PROP: aLineDistAtMetricBox.Hide(); pActLineDistFld = &aLineDistAtPercentBox; if ( !aLineDistAtPercentBox.GetText().Len() ) aLineDistAtPercentBox.SetValue( aLineDistAtPercentBox.Normalize( 100 ), FUNIT_TWIP ); aLineDistAtMetricBox.Hide(); pActLineDistFld->Show(); pActLineDistFld->Enable(); break; case LLINESPACE_FIX: { aLineDistAtPercentBox.Hide(); pActLineDistFld = &aLineDistAtMetricBox; sal_Int64 nTemp = aLineDistAtMetricBox.GetValue(); aLineDistAtMetricBox.SetMin(aLineDistAtMetricBox.Normalize(nMinFixDist), FUNIT_TWIP); if ( aLineDistAtMetricBox.GetValue() != nTemp ) SetMetricValue( aLineDistAtMetricBox, FIX_DIST_DEF, SFX_MAPUNIT_TWIP ); aLineDistAtPercentBox.Hide(); pActLineDistFld->Show(); pActLineDistFld->Enable(); } break; } ExecuteLineSpace(); return 0; } IMPL_LINK( ParaLineSpacingControl, LineSPDistAtHdl_Impl, MetricField*, /* pBox */ ) { ExecuteLineSpace(); return (0L); } void ParaLineSpacingControl::ExecuteLineSpace() { aLineDist.SaveValue(); maLineSpacing.SetNoSelection(); SvxLineSpacingItem aSpacing(_DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE); sal_uInt16 nPos = aLineDist.GetSelectEntryPos(); switch ( nPos ) { case LLINESPACE_1: case LLINESPACE_15: case LLINESPACE_2: { SetLineSpace( aSpacing, nPos ); maPos = nPos; } break; case LLINESPACE_PROP: { SetLineSpace( aSpacing, nPos, aLineDistAtPercentBox.Denormalize( (long)aLineDistAtPercentBox.GetValue() ) ); maPos = nPos; maValue =aLineDistAtPercentBox.GetValue(); } break; case LLINESPACE_MIN: case LLINESPACE_DURCH: case LLINESPACE_FIX: { SetLineSpace( aSpacing, nPos, GetCoreValue( aLineDistAtMetricBox, m_eLNSpaceUnit ) ); maPos = nPos; maValue = GetCoreValue( aLineDistAtMetricBox, m_eLNSpaceUnit ); } break; default: DBG_ERROR( "error!!" ); break; } mpBindings->GetDispatcher()->Execute( SID_ATTR_PARA_LINESPACE, SFX_CALLMODE_RECORD, &aSpacing, 0L); mbUseLineSPCustom = USE_CUSTOM; } void ParaLineSpacingControl::SetLineSpace( SvxLineSpacingItem& rLineSpace, int eSpace, long lValue ) { switch ( eSpace ) { case LLINESPACE_1: rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO; rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF; break; case LLINESPACE_15: rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO; rLineSpace.SetPropLineSpace( LINESPACE_15 ); break; case LLINESPACE_2: rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO; rLineSpace.SetPropLineSpace( LINESPACE_2 ); break; case LLINESPACE_PROP: rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO; rLineSpace.SetPropLineSpace( (sal_uInt8)lValue ); break; case LLINESPACE_MIN: rLineSpace.SetLineHeight( (sal_uInt16)lValue ); rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF; break; case LLINESPACE_DURCH: rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO; rLineSpace.SetInterLineSpace( (sal_uInt16)lValue ); break; case LLINESPACE_FIX: rLineSpace.SetLineHeight((sal_uInt16)lValue); rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_FIX; rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF; break; } } IMPL_LINK(ParaLineSpacingControl, VSSelHdl, void *, pControl) { maLineSpacing.SetNoSelection(); bool bClosePop = true; if(pControl == &maLineSpacing) { sal_uInt16 iPos = maLineSpacing.GetSelectItemId(); switch ( iPos ) { case 1: ExecuteLineSpacing( 0, 0 ); break; case 2: ExecuteLineSpacing( 0, 3 ); break; case 3: ExecuteLineSpacing( 0, 1 ); break; case 4: ExecuteLineSpacing( 0, 2 ); break; case 5: { if(!(mbLineSPDisable)) { //maPos = mrParaPropertyPanel.maLinePos; aLineDist.SelectEntryPos( maPos ) ; aLineDist.SaveValue(); //maValue = mrParaPropertyPanel.maLineValue; SvxLineSpacingItem aSpacing(_DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE); switch(maPos) { case LLINESPACE_1: case LLINESPACE_15: case LLINESPACE_2: SetLineSpace( aSpacing, maPos ); break; case LLINESPACE_PROP: SetLineSpace( aSpacing, maPos, aLineDistAtPercentBox.Denormalize( (long)maValue ) ); break; case LLINESPACE_MIN: case LLINESPACE_DURCH: case LLINESPACE_FIX: SetLineSpace( aSpacing, maPos, (long)maValue ); break; } mpBindings->GetDispatcher()->Execute( SID_ATTR_PARA_LINESPACE, SFX_CALLMODE_RECORD, &aSpacing, 0L); ExecuteLineSpacing( USE_CUSTOM, 0 ); } else bClosePop = sal_False; } break; } } if(bClosePop) mrParaPropertyPanel.EndSpacingPopupMode(); return 0; } void ParaLineSpacingControl::ExecuteLineSpacing( sal_uInt16 aIsCustom, sal_uInt16 aEntry ) { if( !aIsCustom ) { aLineDist.SelectEntryPos( aEntry ) ; aLineDist.SaveValue(); SvxLineSpacingItem aSpacing(_DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE); sal_uInt16 nPos = aEntry; if( aEntry == LLINESPACE_PROP ) SetLineSpace( aSpacing, nPos, aLineDistAtPercentBox.Denormalize( (long)115 ) ); else SetLineSpace( aSpacing, nPos ); mpBindings->GetDispatcher()->Execute( SID_ATTR_PARA_LINESPACE, SFX_CALLMODE_RECORD, &aSpacing, 0L); } if( !aIsCustom ) { mbUseLineSPCustom = DO_NOT_CUSTOM; mrParaPropertyPanel.EndSpacingPopupMode(); } maLineSpacing.SetNoSelection(); } }} // end of namespace sidebar
10,702
9,959
<gh_stars>1000+ /* * These are stub versions of various bits of javac-internal API (for various different versions of javac). Lombok is compiled against these. */ package com.sun.tools.javac.util; public class Context { public static class Key<T> { } public interface Factory<T> { T make(Context c); T make(); } public <T> void put(Key<T> key, Factory<T> fac) { } public <T> void put(Key<T> key, T data) { } public <T> void put(Class<T> clazz, T data) { } public <T> T get(Key<T> key) { return null; } public <T> T get(Class<T> clazz) { return null; } }
240
552
<reponame>dodoproptit99/Multilingual_Text_to_Speech<gh_stars>100-1000 import torch from torch.nn import functional as F from torch.nn import Sequential, ModuleList, Linear, ReLU, Sigmoid, MaxPool1d, ConstantPad1d, MaxPool1d, GRU from modules.layers import ConvBlock class PostnetCBHG(torch.nn.Module): """ CBHG block with a linear output layer. Arguments: input_dim -- number of channels of the input (probably should match the number of mels) output_dim -- number of channels of the output bank_size -- number of convolutions with kernel 1..bank_size in the convolutional bank bank_channels -- output channels of convolutions in the bank projection_channels -- channels of the convolutional projection layers (these layers are two) projection_kernel_size -- kernel size of the convolutional projection layers highway_dim -- output dimension of the highway layers gru_dim -- dim of the GRU layer dropout -- dropout of the convolution layers """ def __init__(self, input_dim, output_dim, bank_size, bank_channels, projection_channels, projection_kernel_size, highway_dim, gru_dim, dropout): super(PostnetCBHG, self).__init__() assert gru_dim % 2 == 0, ('Bidirectional GRU dimension must be divisible by 2.') self._bank = ModuleList([ ConvBlock(input_dim, bank_channels, k, dropout, 'relu') for k in range(1, bank_size + 1) ]) self._pool_and_project = Sequential( ConstantPad1d((0, 1), 0.0), MaxPool1d(2, stride=1), ConvBlock(bank_channels * bank_size, projection_channels, projection_kernel_size, dropout, 'relu'), ConvBlock(projection_channels, input_dim, projection_kernel_size, dropout, 'identity') ) highways = [HighwayLayer(highway_dim) for _ in range(4)] self._highway_layers = Sequential( Linear(input_dim, highway_dim), ReLU(), *highways ) self._gru = GRU(highway_dim, gru_dim // 2, batch_first=True, bidirectional=True) self._output_layer = Linear(gru_dim, output_dim) def forward(self, x, x_lengths): residual = x bx = [layer(x) for layer in self._bank] x = torch.cat(bx, dim=1) x = self._pool_and_project(x) x = x + residual x = x.transpose(1, 2) x = self._highway_layers(x) ml = x.size(1) sorted_lengths, sorted_idxs = torch.sort(x_lengths, descending=True) x = x[sorted_idxs] x = torch.nn.utils.rnn.pack_padded_sequence(x, sorted_lengths, batch_first=True) self._gru.flatten_parameters() x, _ = self._gru(x) bx, _ = torch.nn.utils.rnn.pad_packed_sequence(x, batch_first=True, total_length=ml) x = torch.zeros_like(bx) x[sorted_idxs] = bx x = self._output_layer(x) x = x.transpose(1, 2) return x class HighwayLayer(torch.nn.Module): """Gated layer.""" def __init__(self, dimension): super(HighwayLayer, self).__init__() self._linear = Sequential( Linear(dimension, dimension), ReLU() ) self._gate = Sequential( Linear(dimension, dimension), Sigmoid() ) def forward(self, x): p = self._gate(x) return self._linear(x) * p + x * (1.0 - p)
1,521
14,668
<filename>components/metrics/metrics_data_validation.h // 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. #ifndef COMPONENTS_METRICS_METRICS_DATA_VALIDATION_H_ #define COMPONENTS_METRICS_METRICS_DATA_VALIDATION_H_ #include "base/base_export.h" #include "base/feature_list.h" #include "base/time/time.h" // Features and functions in this file are necessary to set up artificial A / B // experiments that help us better assess the accuracy and power of our field // trial data. All code in this file should not have any impact on client's // experience. namespace metrics { // Only used for testing. namespace internal { extern const base::Feature kPseudoMetricsEffectFeature; } // namespace internal // Used to assess the reliability of field trial data by sending artificial // non-uniform data drawn from a log normal distribution. extern const base::Feature kNonUniformityValidationFeature; // The parameters for the log normal distribution. They refer to the default // mean, the delta that would be applied to the default mean (the actual mean // equals mean + log(1 + delta)) and the standard deviation of the distribution // that's being generated. These parameters are carefully calculated so that // ~0.01% of data drawn from the distribution would fall in the underflow bucket // and ~0.01% of data in the overflow bucket. And they also leave us enough // wiggle room to shift mean using delta in experiments without losing precision // badly because of data in the overflow bucket. // // The way we get these numbers are based on the following calculation: // u := the lower threshold for the overflow bucket (in this case, 10000). // l := the upper threshold for the smallest bucket (in this case, 1). // p := the probability that an observation will fall in the highest bucket (in // this case, 0.01%) and also the probability that an observation will fall in // the lowest bucket. // // mean = (log(u) + log(l)) / 2 // sd = (log(u) - log(l)) / (2 * qnorm(1-p)) // // At this point, experiments should only control the delta but not mean and // stdDev. Putting them in feature params so that we can configure them from the // server side if we want. extern const base::FeatureParam<double> kLogNormalMean; extern const base::FeatureParam<double> kLogNormalDelta; extern const base::FeatureParam<double> kLogNormalStdDev; // In order to assess if we're able to accurately detect a statistically // significant difference in our field trial data, we set up pseudo metrics for // some of our key metrics. Values of these pseudo metrics are the linear // transformation (ax + b) of real values (x). The multiplicative factor (a) and // additive factor (b) are controlled by field trial experiments. // // Returns the sample value for a pseudo metric given the |sample| from the real // metric and the assigned field trial group. The input type is double because // we don't want to lose precision before applying transformation. The output // type is int because things logged to histograms are ints. int GetPseudoMetricsSample(double sample); // Returns the TimeDelta for a pseudo metric given the |sample| from the real // metric and the assigned field trial group. The unit of the additive factor // (b) is milliseconds. base::TimeDelta GetPseudoMetricsSample(base::TimeDelta sample); } // namespace metrics #endif // COMPONENTS_METRICS_METRICS_DATA_VALIDATION_H_
913
1,103
<reponame>termux-one/EasY_HaCk """ Parser for an obscure FMV file format: bin files from the game "The Amazing Spider-Man vs. The Kingpin" (Sega CD) Author: <NAME> Creation date: 2006-09-30 File samples: http://samples.mplayerhq.hu/game-formats/spiderman-segacd-bin/ """ from hachoir_parser import Parser from hachoir_core.field import FieldSet, UInt32, String, RawBytes from hachoir_core.endian import BIG_ENDIAN from hachoir_core.text_handler import textHandler, hexadecimal class Chunk(FieldSet): tag_info = { "CONF" : ("conf[]", None, "Configuration header"), "AUDI" : ("audio[]", None, "Audio chunk"), "SYNC" : ("sync[]", None, "Start of video frame data"), "IVRA" : ("ivra[]", None, "Vector codebook (?)"), "VRAM" : ("video[]", None, "Video RAM tile pattern"), "CRAM" : ("color[]", None, "Color RAM (palette)"), "CEND" : ("video_end[]", None, "End of video data"), "MEND" : ("end_file", None, "End of file"), } def __init__(self, *args): FieldSet.__init__(self, *args) self._size = self["length"].value * 8 fourcc = self["fourcc"].value if fourcc in self.tag_info: self._name, self._parser, self._description = self.tag_info[fourcc] else: self._parser = None self._description = "Unknown chunk: fourcc %s" % self["fourcc"].display def createFields(self): yield String(self, "fourcc", 4, "FourCC", charset="ASCII") yield textHandler(UInt32(self, "length", "length"), hexadecimal) size = self["length"].value - 8 if 0 < size: if self._parser: for field in self._parser(self, size): yield field else: yield RawBytes(self, "data", size) class SpiderManVideoFile(Parser): PARSER_TAGS = { "id": "spiderman_video", "category": "game", "file_ext": ("bin",), "min_size": 8*8, "description": "The Amazing Spider-Man vs. The Kingpin (Sega CD) FMV video" } endian = BIG_ENDIAN def validate(self): return (self.stream.readBytes(0, 4) == 'CONF') def createFields(self): while not self.eof: yield Chunk(self, "chunk[]")
1,005
3,301
<reponame>okjay/Alink package com.alibaba.alink.operator.batch.nlp; import org.apache.flink.ml.api.misc.param.Params; import com.alibaba.alink.operator.batch.utils.ModelMapBatchOp; import com.alibaba.alink.operator.common.nlp.DocHashCountVectorizerModelMapper; import com.alibaba.alink.params.nlp.DocHashCountVectorizerPredictParams; /** * Transform a document to a sparse vector based on the statistics provided by DocHashCountVectorizerTrainBatchOp. * It uses MurmurHash 3 to get the hash value of a word as the index. */ public class DocHashCountVectorizerPredictBatchOp extends ModelMapBatchOp <DocHashCountVectorizerPredictBatchOp> implements DocHashCountVectorizerPredictParams <DocHashCountVectorizerPredictBatchOp> { private static final long serialVersionUID = -6029385456358959482L; public DocHashCountVectorizerPredictBatchOp() { this(new Params()); } public DocHashCountVectorizerPredictBatchOp(Params params) { super(DocHashCountVectorizerModelMapper::new, params); } }
321
632
<reponame>qiniu/android-sdk<filename>library/src/main/java/com/qiniu/android/storage/UploadSource.java package com.qiniu.android.storage; import java.io.IOException; abstract class UploadSource { /** * 未知大小 */ static final long UnknownSourceSize = -1; /** * 获取资源唯一标识 * 作为断点续传时判断是否为同一资源的依据之一; * 如果两个资源的 record key 和 资源唯一标识均相同则认为资源为同一资源,断点续传才会生效 * 注: * 同一资源的数据必须完全相同,否则上传可能会出现异常 * * @return 资源修改时间 */ abstract String getId(); /** * 是否可以重新加载文件信息,也即是否可以重新读取信息 * @return return */ abstract boolean couldReloadSource(); /** * 重新加载文件信息,以便于重新读取 * * @return 重新加载是否成功 */ abstract boolean reloadSource(); /** * 获取资源文件名 * @return 资源文件名 */ abstract String getFileName(); /** * 获取资源大小 * 无法获取大小时返回 -1 * 作用: * 1. 验证资源是否为同一资源 * 2. 计算上传进度 * * @return 资源大小 */ abstract long getSize(); /** * 读取数据 * 1. 返回 byte[] 可能为空,但不会为 null; * 2. 当 byte[] 大小和 dataSize 不同时,则源数据已经读取结束 * 3. 读取异常时抛出 IOException * 4. 仅支持串行调用,且 dataOffset 依次递增 * * @param dataSize 数据大小 * @param dataOffset 数据偏移量 * @return 数据 * @throws IOException 异常 */ abstract byte[] readData(int dataSize, long dataOffset) throws IOException; /** * 关闭流 */ abstract void close(); /** * 资源类型 */ abstract String getSourceType(); }
1,170
587
<gh_stars>100-1000 #include "../hedley.h" #if HEDLEY_IAR_VERSION_CHECK(8,0,0) # pragma diag_suppress=Pe381 #elif defined(HEDLEY_SUNPRO_VERSION) && !defined(__cplusplus) # pragma error_messages(off,E_EMPTY_DECLARATION) #elif defined(HEDLEY_TI_VERSION) # pragma diag_suppress 383 #endif HEDLEY_STATIC_ASSERT(sizeof(char) == 1, "char must be one byte"); int main(void) { return 0; }
170
1,109
/******************************************************************************* * Copyright 2016 Intuit * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.intuit.wasabi.analyticsobjects.statistics; import com.intuit.wasabi.analyticsobjects.Event; import com.intuit.wasabi.experimentobjects.Bucket; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * Test for the {@link BucketComparison} */ public class BucketComparisonTest { BucketComparison bucketComparison; @Before public void setup() { Bucket.Label label = Bucket.Label.valueOf("TestLabel"); Map<Event.Name, ActionComparisonStatistics> map = new HashMap<Event.Name, ActionComparisonStatistics>(); ComparisonStatistics comparisonStatistics = new ComparisonStatistics(); bucketComparison = new BucketComparison.Builder().withOtherLabel(label) .withJointActionComparison(comparisonStatistics).withActionComparisons(map).build(); } @Test public void gettersAndSetters() { Bucket.Label label = Bucket.Label.valueOf("NewTestLabel"); Map<Event.Name, ActionComparisonStatistics> map = new HashMap<Event.Name, ActionComparisonStatistics>(); ComparisonStatistics comparisonStatistics = new ComparisonStatistics(); bucketComparison.setActionComparisons(map); bucketComparison.setJointActionComparison(comparisonStatistics); bucketComparison.setOtherLabel(label); assertThat(bucketComparison.getActionComparisons(), is(map)); assertThat(bucketComparison.getJointActionComparison(), is(comparisonStatistics)); assertThat(bucketComparison.getOtherLabel(), is(label)); } @Test public void addToActionComparisonsTest() { Bucket.Label label = Bucket.Label.valueOf("TestLabel"); ComparisonStatistics comparisonStatistics = new ComparisonStatistics(); BucketComparison bucketComparison = new BucketComparison.Builder().withOtherLabel(label) .withJointActionComparison(comparisonStatistics).withActionComparisons(null).build(); bucketComparison.addToActionComparisons(Event.Name.valueOf("TestName"), new ActionComparisonStatistics()); assertThat(bucketComparison.getActionComparisons().size(), is(1)); } @Test public void toStringTest() { assertThat(bucketComparison.toString(), is("BucketComparison" + "[otherLabel=TestLabel,jointActionComparison=" + "ComparisonStatistics[sufficientData=false,fractionDataCollected=<null>," + "clearComparisonWinner=<null>,actionRateDifference=<null>," + "smallestDistinguishableEffectSize=<null>],actionComparisons={}]")); } @Test public void hashcodeTest() { assertThat(bucketComparison.hashCode(), is(-214943778)); } @Test public void cloneAndEqual() { BucketComparison bucketComparison1 = bucketComparison.clone(); assertThat(bucketComparison1, is(bucketComparison1)); } }
1,225
575
<filename>components/translate/content/renderer/per_frame_translate_agent.h // Copyright (c) 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. #ifndef COMPONENTS_TRANSLATE_CONTENT_RENDERER_PER_FRAME_TRANSLATE_AGENT_H_ #define COMPONENTS_TRANSLATE_CONTENT_RENDERER_PER_FRAME_TRANSLATE_AGENT_H_ #include "components/translate/content/common/translate.mojom.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_frame_observer.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/pending_associated_receiver.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" namespace translate { // This class deals with page translation. It is a RenderFrame's // IPC client for translation requests from the browser process. // // This class supports translating sub frames as well as the main // frame. It is intended to replace TranslateAgent (which only // translates the main frame. Both classes will exist for a transition // period in order to control an experiment for proving out sub frame // translation. class PerFrameTranslateAgent : public content::RenderFrameObserver, public mojom::TranslateAgent { public: PerFrameTranslateAgent(content::RenderFrame* render_frame, int world_id, blink::AssociatedInterfaceRegistry* registry); ~PerFrameTranslateAgent() override; // mojom::TranslateAgent implementation. void GetWebLanguageDetectionDetails( GetWebLanguageDetectionDetailsCallback callback) override; void TranslateFrame(const std::string& translate_script, const std::string& source_lang, const std::string& target_lang, TranslateFrameCallback callback) override; void RevertTranslation() override; protected: // Returns true if the translate library is available, meaning the JavaScript // has already been injected in that page. virtual bool IsTranslateLibAvailable(); // Returns true if the translate library has been initialized successfully. virtual bool IsTranslateLibReady(); // Returns true if the translation script has finished translating the page. virtual bool HasTranslationFinished(); // Returns true if the translation script has reported an error performing the // translation. virtual bool HasTranslationFailed(); // Returns the error code generated in translate library. virtual int64_t GetErrorCode(); // Starts the translation by calling the translate library. This method // should only be called when the translate script has been injected in the // page. Returns false if the call failed immediately. virtual bool StartTranslation(); // Asks the Translate element in the page what the language of the page is. // Can only be called if a translation has happened and was successful. // Returns the language code on success, an empty string on failure. virtual std::string GetOriginalPageLanguage(); // Adjusts a delay time for a posted task. This is overridden in tests to do // tasks immediately by returning 0. virtual base::TimeDelta AdjustDelay(int delay_in_milliseconds); // Executes the JavaScript code in |script| in the main frame of RenderView. virtual void ExecuteScript(const std::string& script); // Executes the JavaScript code in |script| in the main frame of RenderView, // and returns the boolean returned by the script evaluation if the script was // run successfully. Otherwise, returns |fallback| value. virtual bool ExecuteScriptAndGetBoolResult(const std::string& script, bool fallback); // Executes the JavaScript code in |script| in the main frame of RenderView, // and returns the string returned by the script evaluation if the script was // run successfully. Otherwise, returns empty string. virtual std::string ExecuteScriptAndGetStringResult( const std::string& script); // Executes the JavaScript code in |script| in the main frame of RenderView. // and returns the number returned by the script evaluation if the script was // run successfully. Otherwise, returns 0.0. virtual double ExecuteScriptAndGetDoubleResult(const std::string& script); // Executes the JavaScript code in |script| in the main frame of RenderView. // and returns the integer value returned by the script evaluation if the // script was run successfully. Otherwise, returns 0. virtual int64_t ExecuteScriptAndGetIntegerResult(const std::string& script); private: FRIEND_TEST_ALL_PREFIXES(PerFrameTranslateAgentTest, TestBuildTranslationScript); // Converts language code to the one used in server supporting list. static void ConvertLanguageCodeSynonym(std::string* code); // Sets receiver for translate messages from browser process. void BindReceiver( mojo::PendingAssociatedReceiver<mojom::TranslateAgent> receiver); // Builds the translation JS used to translate from source_lang to // target_lang. static std::string BuildTranslationScript(const std::string& source_lang, const std::string& target_lang); // RenderFrameObserver implementation. void OnDestruct() override; // Cancels any translation that is currently being performed. This does not // revert existing translations. void CancelPendingTranslation(); // Checks if the current running page translation is finished or errored and // notifies the browser accordingly. If the translation has not terminated, // posts a task to check again later. |check_count| is used to limit the // number of retries. void CheckTranslateStatus(int check_count); // Called by TranslateFrame to do the actual translation. |count| is used to // limit the number of retries. void TranslateFrameImpl(int count); // Sends a message to the browser to notify it that the translation failed // with |error|. void NotifyBrowserTranslationFailed(TranslateErrors::Type error); // Convenience method to access the main frame. Can return nullptr, typically // if the page is being closed. blink::WebLocalFrame* GetMainFrame(); // The states associated with the current translation. TranslateFrameCallback translate_callback_pending_; std::string source_lang_; std::string target_lang_; // The world ID to use for script execution. int world_id_; mojo::AssociatedReceiver<mojom::TranslateAgent> receiver_{this}; // Method factory used to make calls to TranslateFrameImpl. base::WeakPtrFactory<PerFrameTranslateAgent> weak_method_factory_{this}; DISALLOW_COPY_AND_ASSIGN(PerFrameTranslateAgent); }; } // namespace translate #endif // COMPONENTS_TRANSLATE_CONTENT_RENDERER_PER_FRAME_TRANSLATE_AGENT_H_
2,025
601
<gh_stars>100-1000 """ Utilities for manipulating bokeh models. """ from __future__ import annotations import textwrap from contextlib import contextmanager from typing import ( TYPE_CHECKING, Any, Iterable, List, Optional, ) import numpy as np from bokeh.document import Document from bokeh.document.events import ( ColumnDataChangedEvent, DocumentPatchedEvent, ModelChangedEvent, ) from bokeh.model import DataModel from bokeh.models import Box, ColumnDataSource, Model from bokeh.protocol import Protocol from typing_extensions import Literal from .state import state if TYPE_CHECKING: from bokeh.core.enums import HoldPolicyType from bokeh.document.events import DocumentChangedEvent from bokeh.protocol.message import Message from pyviz_comms import Comm #--------------------------------------------------------------------- # Private API #--------------------------------------------------------------------- class comparable_array(np.ndarray): """ Array subclass that allows comparisons. """ def __eq__(self, other: Any) -> bool: return super().__eq__(other).all().item() def __ne__(self, other: Any) -> bool: return super().__ne__(other).all().item() def monkeypatch_events(events: List['DocumentChangedEvent']) -> None: """ Patch events applies patches to events that are to be dispatched avoiding various issues in Bokeh. """ for e in events: # Patch ColumnDataChangedEvents which reference non-existing columns if isinstance(getattr(e, 'hint', None), ColumnDataChangedEvent): e.hint.cols = None # type: ignore # Patch ModelChangedEvents which change an array property (see https://github.com/bokeh/bokeh/issues/11735) elif (isinstance(e, ModelChangedEvent) and isinstance(e.model, DataModel) and isinstance(e.new, np.ndarray)): new_array = comparable_array(e.new.shape, e.new.dtype, e.new) e.new = new_array e.serializable_new = new_array #--------------------------------------------------------------------- # Public API #--------------------------------------------------------------------- def diff( doc: 'Document', binary: bool = True, events: Optional[List['DocumentChangedEvent']] = None ) -> Message[Any] | None: """ Returns a json diff required to update an existing plot with the latest plot data. """ if events is None: events = list(doc.callbacks._held_events) if not events or state._hold: return None patch_events = [event for event in events if isinstance(event, DocumentPatchedEvent)] monkeypatch_events(events) msg_type: Literal["PATCH-DOC"] = "PATCH-DOC" msg = Protocol().create(msg_type, patch_events, use_buffers=binary) doc.callbacks._held_events = [e for e in doc.callbacks._held_events if e not in events] return msg def remove_root(obj: 'Model', replace: Optional['Document'] = None) -> None: """ Removes the document from any previously displayed bokeh object """ for model in obj.select({'type': Model}): prev_doc = model.document model._document = None if prev_doc: prev_doc.remove_root(model) if replace: model._document = replace def add_to_doc(obj: 'Model', doc: 'Document', hold: bool = False): """ Adds a model to the supplied Document removing it from any existing Documents. """ # Add new root remove_root(obj) doc.add_root(obj) if doc.callbacks.hold_value is None and hold: doc.hold() @contextmanager def hold(doc: 'Document', policy: 'HoldPolicyType' = 'combine', comm: Optional['Comm'] = None): held = doc.callbacks.hold_value try: if policy is None: doc.unhold() else: doc.hold(policy) yield finally: if held: doc.callbacks._hold = held else: if comm is not None: from .notebook import push push(doc, comm) doc.unhold() def patch_cds_msg(model, msg): """ Required for handling messages containing JSON serialized typed array from the frontend. """ for event in msg.get('content', {}).get('events', []): if event.get('kind') != 'ModelChanged' or event.get('attr') != 'data': continue cds = model.select_one({'id': event.get('model').get('id')}) if not isinstance(cds, ColumnDataSource): continue for col, values in event.get('new', {}).items(): if isinstance(values, dict): event['new'][col] = [v for _, v in sorted(values.items())] _DEFAULT_IGNORED_REPR = frozenset(['children', 'text', 'name', 'toolbar', 'renderers', 'below', 'center', 'left', 'right']) def bokeh_repr(obj: 'Model', depth: int = 0, ignored: Optional[Iterable[str]] = None) -> str: """ Returns a string repr for a bokeh model, useful for recreating panel objects using pure bokeh. """ if ignored is None: ignored = _DEFAULT_IGNORED_REPR from ..viewable import Viewable if isinstance(obj, Viewable): obj = obj.get_root(Document()) r = "" cls = type(obj).__name__ properties = sorted(obj.properties_with_values(include_defaults=False).items()) props = [] for k, v in properties: if k in ignored: continue if isinstance(v, Model): v = '%s()' % type(v).__name__ else: v = repr(v) if len(v) > 30: v = v[:30] + '...' props.append('%s=%s' % (k, v)) props_repr = ', '.join(props) if isinstance(obj, Box): r += '{cls}(children=[\n'.format(cls=cls) for obj in obj.children: # type: ignore r += textwrap.indent(bokeh_repr(obj, depth=depth+1) + ',\n', ' ') r += '], %s)' % props_repr else: r += '{cls}({props})'.format(cls=cls, props=props_repr) return r
2,331
335
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file portfolio/builders/equityoption.hpp \brief Engine builder for equity options \ingroup builders */ #pragma once #include <ored/portfolio/builders/vanillaoption.hpp> namespace ore { namespace data { //! Engine Builder for European Equity Option Options /*! Pricing engines are cached by asset/currency \ingroup builders */ class EquityEuropeanOptionEngineBuilder : public EuropeanOptionEngineBuilder { public: EquityEuropeanOptionEngineBuilder() : EuropeanOptionEngineBuilder("BlackScholesMerton", {"EquityOption"}, AssetClass::EQ) {} }; /*! Engine builder for European cash-settled equity options. \ingroup builders */ class EquityEuropeanCSOptionEngineBuilder : public EuropeanCSOptionEngineBuilder { public: EquityEuropeanCSOptionEngineBuilder() : EuropeanCSOptionEngineBuilder("BlackScholesMerton", {"EquityOptionEuropeanCS"}, AssetClass::EQ) {} }; //! Engine Builder for American Equity Options using Finite Difference Method /*! Pricing engines are cached by asset/currency \ingroup builders */ class EquityAmericanOptionFDEngineBuilder : public AmericanOptionFDEngineBuilder { public: EquityAmericanOptionFDEngineBuilder() : AmericanOptionFDEngineBuilder("BlackScholesMerton", {"EquityOptionAmerican"}, AssetClass::EQ, expiryDate_) {} }; //! Engine Builder for American Equity Options using Barone Adesi Whaley Approximation /*! Pricing engines are cached by asset/currency \ingroup builders */ class EquityAmericanOptionBAWEngineBuilder : public AmericanOptionBAWEngineBuilder { public: EquityAmericanOptionBAWEngineBuilder() : AmericanOptionBAWEngineBuilder("BlackScholesMerton", {"EquityOptionAmerican"}, AssetClass::EQ) {} }; } // namespace data } // namespace ore
675
683
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.testing.common; import java.lang.reflect.Field; public final class AgentClassLoaderAccess { private static final ClassLoader agentClassLoader; static { try { Class<?> agentInitializerClass = ClassLoader.getSystemClassLoader() .loadClass("io.opentelemetry.javaagent.bootstrap.AgentInitializer"); Field agentClassLoaderField = agentInitializerClass.getDeclaredField("agentClassLoader"); agentClassLoaderField.setAccessible(true); agentClassLoader = (ClassLoader) agentClassLoaderField.get(null); } catch (Throwable t) { throw new AssertionError("Could not access agent classLoader", t); } } public static ClassLoader getAgentClassLoader() { return agentClassLoader; } static Class<?> loadClass(String name) { try { return agentClassLoader.loadClass(name); } catch (ClassNotFoundException e) { throw new AssertionError("Could not load class from agent classloader", e); } } private AgentClassLoaderAccess() {} }
377
378
<filename>container/openejb-core/src/test/java/org/apache/openejb/timer/TransactionRegistryInTimeoutTest.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.apache.openejb.timer; import org.apache.openejb.jee.EnterpriseBean; import org.apache.openejb.jee.SingletonBean; import org.apache.openejb.junit.ApplicationComposer; import org.apache.openejb.testing.Module; import org.junit.Test; import org.junit.runner.RunWith; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.ScheduleExpression; import javax.ejb.SessionContext; import javax.ejb.Singleton; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.Synchronization; import javax.transaction.TransactionSynchronizationRegistry; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @RunWith(ApplicationComposer.class) public class TransactionRegistryInTimeoutTest { @EJB private EjbTimerTx ejb; @Test public void run() { ejb.setTimerNow(); try { ejb.latch().await(1, TimeUnit.MINUTES); } catch (final InterruptedException e) { Thread.interrupted(); fail(e.getMessage()); } final TxListener sync = ejb.sync(); assertNotNull(sync); assertTrue(sync.done > 0); } @Module public EnterpriseBean bean() { return new SingletonBean(EjbTimerTx.class).localBean(); } @Singleton @Lock(LockType.READ) public static class EjbTimerTx { @Resource private TimerService timerService; @Resource private TransactionSynchronizationRegistry registry; @Resource private SessionContext context; private final CountDownLatch latch = new CountDownLatch(1); private final TxListener sync = new TxListener(latch); @Timeout @Lock(LockType.WRITE) public void timerFired() { try { final String jndi = "java:comp/TransactionSynchronizationRegistry"; final TransactionSynchronizationRegistry txRegistry = (TransactionSynchronizationRegistry) new InitialContext().lookup(jndi); assertNotNull(txRegistry); assertNotNull(context.lookup(jndi)); assertNotNull(registry); txRegistry.registerInterposedSynchronization(sync); } catch (final NamingException e) { throw new IllegalStateException(e); } } public TxListener sync() { return sync; } public CountDownLatch latch() { return latch; } public Timer setTimerNow() { final ScheduleExpression schedule = new ScheduleExpression().second("*/3").minute("*").hour("*"); final TimerConfig timerConfig = new TimerConfig(); timerConfig.setPersistent(false); return timerService.createCalendarTimer(schedule, timerConfig); } } public static class TxListener implements Synchronization { public volatile int done = 0; private final CountDownLatch latch; public TxListener(final CountDownLatch latch) { this.latch = latch; } @Override public void beforeCompletion() { // no-op } @Override public void afterCompletion(final int i) { try { final TransactionSynchronizationRegistry txRegistry = (TransactionSynchronizationRegistry) new InitialContext().lookup("java:comp/TransactionSynchronizationRegistry"); assertNotNull(txRegistry); done++; latch.countDown(); } catch (final NamingException e) { throw new IllegalStateException(e); } } } }
1,941
713
package org.infinispan.remoting.inboundhandler.action; import org.infinispan.remoting.inboundhandler.BasePerCacheInboundInvocationHandler; /** * An {@link Action} implementation that checks if the command topology id is valid. * <p/> * The command topology id is valid when it is higher or equal thant the first topology as member for this node. * * @author <NAME> * @since 8.0 */ public class CheckTopologyAction implements Action { private final BasePerCacheInboundInvocationHandler handler; public CheckTopologyAction(BasePerCacheInboundInvocationHandler handler) { this.handler = handler; } @Override public ActionStatus check(ActionState state) { return handler.isCommandSentBeforeFirstTopology(state.getCommandTopologyId()) ? ActionStatus.CANCELED : ActionStatus.READY; } }
264
605
/*===-------------------------------------------------------------------------- * ROCm Device Libraries * * This file is distributed under the University of Illinois Open Source * License. See LICENSE.TXT for details. *===------------------------------------------------------------------------*/ DECLARE_TABLE(float, M32_J0, 8*9) 1.0f, 0.44869526e-7f, -0.250000678f, 0.394978156e-5f, 0.0156135085f, 0.186404843e-4f, -0.000451465494f, 0.906744475e-5f, 0.462022483e-5f, 0.0f, -0.519147497f, 0.107938702f, 0.0566017522f, -0.00865766565f, -0.00219399941f, 0.000264347633f, 0.431469054e-4f, -0.427168323e-5f, -0.402759396f, -0.133988793e-8f, 0.201379688f, -0.0175186868f, -0.0133525141f, 0.00103577016f, 0.000371882642f, -0.245406847e-4f, -0.544857844e-5f, 0.0f, 0.340264805f, -0.0308206513f, -0.0529884948f, 0.00463103756f, 0.00225704943f, -0.00017515902f, -0.45676898e-4f, 0.314800819e-5f, 0.300115752f, 0.142140419e-8f, -0.150057871f, 0.00712970835f, 0.0117425671f, -0.00062589107f, -0.00035076219f, 0.175677152e-4f, 0.542756342e-5f, 0.0f, -0.271452299f, 0.0156841249f, 0.0440337286f, -0.00250929967f, -0.0020600007f, 0.000112417278f, 0.440465451e-4f, -0.224955545e-5f, -0.249704877f, -0.114020252e-8f, 0.124852435f, -0.00409076252f, -0.0101027605f, 0.000385232178f, 0.000318490142f, -0.120950437e-4f, -0.516322204e-5f, 0.0f, 0.232459831f, -0.00985706448f, -0.0381859695f, 0.00160739566f, 0.00184174666f, -0.758016756e-4f, -0.408780042e-4f, 0.162275495e-5f, END_TABLE() DECLARE_TABLE(float, M32_J1, 8*9) 0.0f, 0.5f, 0.462571126e-8f, -0.0625000886f, 0.646901306e-6f, 0.00260184106f, 0.455472757e-5f, -0.592206849e-4f, 0.284771796e-5f, 0.581865224f, -0.432727717e-10f, -0.205110698f, 0.00605894703f, 0.0138016513f, -0.000372288399f, -0.000394630783f, 0.908655709e-5f, 0.594411649e-5f, 0.0f, -0.402759391f, 0.0525561452f, 0.0534102785f, -0.00517971268f, -0.00223227521f, 0.000174696729f, 0.448728749e-4f, -0.312619124e-5f, -0.346126202f, -0.135982554e-8f, 0.166974529f, -0.00967824094f, -0.0120991661f, 0.000665244429f, 0.000353951297f, -0.170900235e-4f, -0.544345571e-5f, 0.0f, 0.300115751f, -0.0213892127f, -0.0469704276f, 0.00313028838f, 0.00210522941f, -0.000125486758f, -0.441893462e-4f, 0.235877085e-5f, 0.273299942f, 0.123871464e-8f, -0.134774676f, 0.00511631544f, 0.0106318216f, -0.000448605206f, -0.000326670201f, 0.130923618e-4f, 0.520545213e-5f, 0.0f, -0.249704872f, 0.0122723573f, 0.04041102f, -0.00192680868f, -0.00191084766f, 0.865574383e-4f, 0.412630035e-4f, -0.171042992e-5f, -0.233304417f, -0.101355681e-8f, 0.11580092f, -0.00324897742f, -0.00937250256f, 0.000303501923f, 0.000297960941f, -0.958268173e-5f, -0.490863176e-5f, END_TABLE() DECLARE_TABLE(float, M32_Y0, 18*9) -0.0738042951f, 0.177606017f, -0.016073968f, 0.000538602667f, -0.949500521e-5f, 0.10358476e-6f, -0.769307974e-9f, 0.414351772e-11f, -0.168538199e-13f, -0.779129354f, 2.21109539f, -3.14817837f, 6.76234763f, -16.5245871f, 41.721874f, -101.297948f, 197.994167f, -213.204578f, -0.541790797f, 1.64879305f, -1.61343882f, 2.39011447f, -4.27463147f, 7.8283496f, -14.2356687f, 22.309494f, -20.7850723f, -0.35708307f, 1.3315403f, -1.00504975f, 1.07504147f, -1.54659225f, 2.2281907f, -3.21955386f, 4.18656836f, -3.43559538f, -0.204564821f, 1.12081681f, -0.712857069f, 0.554042423f, -0.680799155f, 0.814950073f, -0.973649903f, 1.07700623f, -0.787302821f, 0.0f, 0.879420802f, -0.492078934f, 0.220553062f, -0.226122006f, 0.218871042f, -0.204734177f, 0.205007038f, -0.209851389f, 0.0882569642f, 0.781212821f, -0.434734855f, 0.144909902f, -0.137517504f, 0.124034055f, -0.100221697f, 0.072159059f, -0.0322405804f, 0.258216852f, 0.584364035f, -0.362853954f, 0.0616967017f, -0.0457019916f, 0.0403914876f, -0.0257050488f, 0.0138811594f, -0.00448857991f, 0.428917561f, 0.331694423f, -0.316518592f, 0.0305795132f, -0.00474255594f, 0.0105095903f, -0.00569634195f, 0.0023888513f, -0.000671151428f, 0.520786412f, 0.316257491e-10f, -0.260393207f, 0.0395048433f, 0.00821442047f, 0.000959730625f, -0.00123958131f, 0.00037168397f, -0.000105767765f, 0.493297245f, -0.159512126f, -0.215140053f, 0.050767252f, 0.00813790411f, -0.000862432027f, -0.000649450987f, 0.000150259461f, -0.184581358e-4f, 0.37685001f, -0.324674425f, -0.134312601f, 0.0630235318f, 0.00445562302f, -0.00210112822f, -0.000263972937f, 0.876453474e-4f, -0.546484929e-5f, 0.0f, -0.40254267f, 0.0508559094f, 0.058523724f, -0.00685252463f, -0.002182572f, 0.000194599211f, 0.485251783e-4f, -0.269518635e-5f, -0.340318045f, -0.176035638e-8f, 0.170159015f, -0.0104461902f, -0.0127369142f, 0.000831821655f, 0.000360781298f, -0.205125477e-4f, -0.556989234e-5f, 0.0f, 0.300097614f, -0.0211752365f, -0.0480240177f, 0.00331834481f, 0.00217561974f, -0.000140580184f, -0.451359559e-4f, 0.265455576e-5f, 0.271459877f, 0.139172743e-8f, -0.135729934f, 0.00526326684f, 0.0108515634f, -0.000483436056f, -0.000335109802f, 0.145606732e-4f, 0.530954251e-5f, 0.0f, -0.249701237f, 0.0122135007f, 0.0408203043f, -0.00197714145f, -0.00194569725f, 0.914230753e-4f, 0.425102172e-4f, -0.190386676e-5f, -0.232461766f, -0.985286365e-9f, 0.11623088f, -0.00329754703f, -0.00947537951f, 0.000315310068f, 0.000302731128f, -0.101595111e-4f, -0.49823498e-5f, END_TABLE() DECLARE_TABLE(float, M32_Y1, 18*9) -0.196057091f, 0.0543486882f, -0.00295530534f, 0.716426875e-4f, -0.992674062e-6f, 0.893187962e-8f, -0.564802451e-10f, 0.264946691e-12f, -0.956040552e-15f, -1.47147239f, 2.49842603f, -4.705631f, 9.97554229f, -20.1713128f, 40.1878477f, -76.6812412f, 123.027773f, -115.903802f, -1.2171501f, 1.6698932f, -2.28529116f, 4.02725834f, -6.58555591f, 10.5423814f, -16.4151681f, 22.3415253f, -18.8343596f, -1.03759455f, 1.24628662f, -1.23436566f, 1.89920078f, -2.63550437f, 3.50388357f, -4.46415376f, 4.77962593f, -3.00258761f, -0.837397335f, 0.930919184f, -0.554175938f, 0.733648813f, -0.859400875f, 0.908155864f, -0.904818857f, 0.731425234f, -0.332223767f, -0.607228956f, 0.737838338f, -0.203493924f, 0.210066093f, -0.230917988f, 0.188616636f, -0.14625808f, 0.0958024404f, -0.0364996384f, -0.391867956f, 0.650927429f, -0.100177392f, 0.0422373453f, -0.07235139f, 0.0493095772f, -0.0299278561f, 0.0165691516f, -0.00564529733f, -0.197513707f, 0.593769812f, -0.0913166067f, -0.013725346f, -0.0252004653f, 0.0176426751f, -0.00832470911f, 0.00410178601f, -0.00142662074f, 0.0f, 0.520786412f, -0.118514546f, -0.0328573972f, -0.00479781174f, 0.00742247989f, -0.00259521656f, 0.00107430961f, -0.000512579875f, 0.0584489381f, 0.492108098f, -0.130161305f, -0.0341572041f, -0.000981824109f, 0.00587622283f, -0.00185575707f, 0.000582281731f, -0.000148343917f, 0.240364643f, 0.364553919f, -0.170769591f, -0.0276077249f, 0.00766230439f, 0.00273966927f, -0.000828295737f, 0.000137588785f, -0.305187593e-4f, 0.416729928f, -0.258296385e-9f, -0.193004092f, 0.0146874353f, 0.0120957914f, -0.000525144004f, -0.000426716299f, 0.352388331e-4f, 0.877397631e-6f, 0.367444533f, -0.182322102f, -0.151633779f, 0.0373228744f, 0.00917855673f, -0.00164468944f, -0.000284979934f, 0.451783718e-4f, 0.198340769e-5f, 0.0f, -0.340318045f, 0.0313386774f, 0.0509479111f, -0.00416011363f, -0.00216575933f, 0.000146604317f, 0.458142122e-4f, -0.282657316e-5f, -0.30317374f, -0.139307478e-8f, 0.148440893f, -0.00682601599f, -0.0113866644f, 0.000555890828f, 0.000340287228f, -0.150871178e-4f, -0.536125411e-5f, 0.0f, 0.271459876f, -0.0157898843f, -0.0434063812f, 0.00241795425f, 0.00201116367f, -0.000104184764f, -0.430443521e-4f, 0.204582146e-5f, 0.250912536f, 0.109595535e-8f, -0.124232101f, 0.00400995233f, 0.009956529f, -0.000365777587f, -0.000312125102f, 0.111983746e-4f, 0.504825687e-5f, 0.0f, -0.232461765f, 0.00989270158f, 0.037901591f, -0.0015771177f, -0.00181666561f, 0.72793478e-4f, 0.40167952e-4f, -0.153180005e-5f, END_TABLE()
6,285
539
# Copyright 2018-2021 Xanadu Quantum Technologies 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. """ Tests for the CommutingEvolution template. """ import pytest from pennylane import numpy as np import pennylane as qml from scipy.linalg import expm def test_adjoint(): """Tests the CommutingEvolution.adjoint method provides the correct adjoint operation.""" n_wires = 2 dev1 = qml.device("default.qubit", wires=n_wires) dev2 = qml.device("default.qubit", wires=n_wires) obs = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliY(0) @ qml.PauliX(1)] coeffs = [1, -1] hamiltonian = qml.Hamiltonian(coeffs, obs) frequencies = (2,) @qml.qnode(dev1) def adjoint_evolution_circuit(time): for i in range(n_wires): qml.Hadamard(i) qml.adjoint(qml.CommutingEvolution)(hamiltonian, time, frequencies) return qml.expval(qml.PauliZ(1)) @qml.qnode(dev2) def evolution_circuit(time): for i in range(n_wires): qml.Hadamard(i) qml.CommutingEvolution(hamiltonian, time, frequencies) return qml.expval(qml.PauliZ(1)) evolution_circuit(0.13) adjoint_evolution_circuit(-0.13) assert all(np.isclose(dev1.state, dev2.state)) def test_decomposition_expand(): """Test that the decomposition of CommutingEvolution is an ApproxTimeEvolution with one step.""" hamiltonian = 0.5 * qml.PauliX(0) @ qml.PauliY(1) time = 2.345 op = qml.CommutingEvolution(hamiltonian, time) decomp = op.decomposition() assert isinstance(decomp, qml.ApproxTimeEvolution) assert all(decomp.hyperparameters["hamiltonian"].coeffs == hamiltonian.coeffs) assert decomp.hyperparameters["n"] == 1 tape = op.expand() assert len(tape) == 1 assert isinstance(tape[0], qml.ApproxTimeEvolution) def test_matrix(): """Test that the matrix of commuting evolution is the same as exponentiating -1j * t the hamiltonian.""" h = 2.34 * qml.PauliX(0) time = 0.234 op = qml.CommutingEvolution(h, time) mat = qml.matrix(op) expected = expm(-1j * time * qml.matrix(h)) assert qml.math.allclose(mat, expected) def test_forward_execution(): """Compare the foward execution to an exactly known result.""" dev = qml.device("default.qubit", wires=2) H = qml.PauliX(0) @ qml.PauliY(1) - 1.0 * qml.PauliY(0) @ qml.PauliX(1) freq = (2, 4) @qml.qnode(dev, diff_method=None) def circuit(time): qml.PauliX(0) qml.CommutingEvolution(H, time, freq) return qml.expval(qml.PauliZ(0)) t = 1.0 res = circuit(t) expected = -np.cos(4) assert np.allclose(res, expected) class TestInputs: """Tests for input validation of `CommutingEvolution`.""" def test_invalid_hamiltonian(self): """Tests TypeError is raised if `hamiltonian` is not type `qml.Hamiltonian`.""" invalid_operator = qml.PauliX(0) assert pytest.raises(TypeError, qml.CommutingEvolution, invalid_operator, 1) class TestGradients: """Tests that correct gradients are obtained for `CommutingEvolution` when frequencies are specified.""" def test_two_term_case(self): """Tests the parameter shift rules for `CommutingEvolution` equal the finite difference result for a two term shift rule case.""" n_wires = 1 dev = qml.device("default.qubit", wires=n_wires) hamiltonian = qml.Hamiltonian([1], [qml.PauliX(0)]) frequencies = (2,) @qml.qnode(dev) def circuit(time): qml.PauliX(0) qml.CommutingEvolution(hamiltonian, time, frequencies) return qml.expval(qml.PauliZ(0)) x_vals = np.linspace(-np.pi, np.pi, num=10) grads_finite_diff = [qml.gradients.finite_diff(circuit)(x) for x in x_vals] grads_param_shift = [qml.gradients.param_shift(circuit)(x) for x in x_vals] assert all(np.isclose(grads_finite_diff, grads_param_shift, atol=1e-4)) def test_four_term_case(self): """Tests the parameter shift rules for `CommutingEvolution` equal the finite difference result for a four term shift rule case.""" n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) coeffs = [1, -1] obs = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliY(0) @ qml.PauliX(1)] hamiltonian = qml.Hamiltonian(coeffs, obs) frequencies = (2, 4) @qml.qnode(dev) def circuit(time): qml.PauliX(0) qml.CommutingEvolution(hamiltonian, time, frequencies) return qml.expval(qml.PauliZ(0)) x_vals = [np.array(x, requires_grad=True) for x in np.linspace(-np.pi, np.pi, num=10)] grads_finite_diff = [qml.gradients.finite_diff(circuit)(x) for x in x_vals] grads_param_shift = [qml.gradients.param_shift(circuit)(x) for x in x_vals] assert all(np.isclose(grads_finite_diff, grads_param_shift, atol=1e-4)) def test_differentiable_hamiltonian(self): """Tests correct gradients are produced when the Hamiltonian is differentiable.""" n_wires = 2 dev = qml.device("default.qubit", wires=n_wires) obs = [qml.PauliX(0) @ qml.PauliY(1), qml.PauliY(0) @ qml.PauliX(1)] diff_coeffs = np.array([1.0, -1.0], requires_grad=True) frequencies = (2, 4) def parameterized_hamiltonian(coeffs): return qml.Hamiltonian(coeffs, obs) @qml.qnode(dev) def circuit(time, coeffs): qml.PauliX(0) qml.CommutingEvolution(parameterized_hamiltonian(coeffs), time, frequencies) return qml.expval(qml.PauliZ(0)) x_vals = [np.array(x, requires_grad=True) for x in np.linspace(-np.pi, np.pi, num=10)] grads_finite_diff = [ np.hstack(qml.gradients.finite_diff(circuit)(x, diff_coeffs)) for x in x_vals ] grads_param_shift = [ np.hstack(qml.gradients.param_shift(circuit)(x, diff_coeffs)) for x in x_vals ] assert np.isclose(grads_finite_diff, grads_param_shift, atol=1e-6).all()
3,123
8,851
<filename>wagtail/tests/testapp/migrations/0006_sectionedrichtextpage_sectionedrichtextpagesection.py # -*- coding: utf-8 -*- from django.db import migrations, models import modelcluster.fields import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0028_merge'), ('tests', '0005_customrichblockfieldpage_customrichtextfieldpage_defaultrichblockfieldpage_defaultrichtextfieldpage'), ] operations = [ migrations.CreateModel( name='SectionedRichTextPage', fields=[ ('page_ptr', models.OneToOneField(parent_link=True, to='wagtailcore.Page', serialize=False, auto_created=True, primary_key=True, on_delete=models.CASCADE)), ], options={ 'abstract': False, }, bases=('wagtailcore.page',), ), migrations.CreateModel( name='SectionedRichTextPageSection', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('sort_order', models.IntegerField(editable=False, null=True, blank=True)), ('body', wagtail.core.fields.RichTextField()), ('page', modelcluster.fields.ParentalKey(related_name='sections', to='tests.SectionedRichTextPage', on_delete=models.CASCADE)), ], options={ 'ordering': ['sort_order'], 'abstract': False, }, ), ]
702
403
package com.camunda.bpm.demo.uel_variable_evaluator.nonarquillian; import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat; import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.init; import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.runtimeService; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.engine.test.mock.Mocks; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.camunda.bpm.demo.uel_variable_evaluator.LoggerDelegate; import com.camunda.bpm.demo.uel_variable_evaluator.UEL; /** * Test case starting an in-memory database-backed Process Engine. */ public class InMemoryH2Test { @Rule public ProcessEngineRule rule = new ProcessEngineRule(); private static final String PROCESS_DEFINITION_KEY = "uel-variable-evaluator"; // enable more detailed logging static { // LogUtil.readJavaUtilLoggingConfigFromClasspath(); // process engine // LogFactory.useJdkLogging(); // MyBatis } @Before public void setup() { init(rule.getProcessEngine()); } /** * Just tests if the process definition is deployable. */ @Test @Deployment(resources = "process.bpmn") public void testParsingAndDeployment() { // nothing is done here, as we just want to check for exceptions during deployment } @Test @Deployment(resources = "process.bpmn") public void testExecution() { LoggerDelegate logger = new LoggerDelegate(); Mocks.register("logger", logger); Mocks.register("uel", new UEL()); Map <String, Object> variables = new HashMap<String, Object>(); variables.put("expression", "${logger.execute(execution)}"); ProcessInstance processInstance = runtimeService().startProcessInstanceByKey(PROCESS_DEFINITION_KEY, variables); assertThat(processInstance) .hasVariables("loggerInvoked"); } }
700
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "weblayer/browser/android/resource_mapper.h" #include <map> #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/check_op.h" #include "base/no_destructor.h" #include "base/notreached.h" #include "components/resources/android/theme_resources.h" #include "weblayer/browser/java/jni/ResourceMapper_jni.h" namespace weblayer { namespace { using ResourceMap = std::map<int, int>; ResourceMap* GetIdMap() { static base::NoDestructor<ResourceMap> id_map; return id_map.get(); } // Create the mapping. IDs start at 0 to correspond to the array that gets // built in the corresponding ResourceID Java class. void ConstructMap() { DCHECK(GetIdMap()->empty()); JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef<jintArray> java_id_array = Java_ResourceMapper_getResourceIdList(env); std::vector<int> resource_id_list; base::android::JavaIntArrayToIntVector(env, java_id_array, &resource_id_list); size_t next_id = 0; #define LINK_RESOURCE_ID(c_id, java_id) \ (*GetIdMap())[c_id] = resource_id_list[next_id++]; #define DECLARE_RESOURCE_ID(c_id, java_id) \ (*GetIdMap())[c_id] = resource_id_list[next_id++]; #include "components/resources/android/blocked_content_resource_id.h" #include "components/resources/android/page_info_resource_id.h" #include "components/resources/android/permissions_resource_id.h" #include "components/resources/android/sms_resource_id.h" #include "components/resources/android/webxr_resource_id.h" #undef LINK_RESOURCE_ID #undef DECLARE_RESOURCE_ID // Make sure ID list sizes match up. DCHECK_EQ(next_id, resource_id_list.size()); } } // namespace int MapToJavaDrawableId(int resource_id) { if (GetIdMap()->empty()) { ConstructMap(); } ResourceMap::iterator iterator = GetIdMap()->find(resource_id); if (iterator != GetIdMap()->end()) { return iterator->second; } // The resource couldn't be found. // If you've landed here, please ensure that the header that declares the // mapping of your native resource to Java resource is listed both in // ResourceId.tempalate and in this file, next to other *resource_id.h // headers. NOTREACHED(); return 0; } } // namespace weblayer
829
1,155
// Copyright 2010 <NAME> // henry UNDERSCORE christophe AT hotmail DOT com // This is an extended version of the state machine available in the boost::mpl library // Distributed under the same license as the original. // Copyright for the original version: // Copyright 2005 <NAME> and <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) // same as iPodSearch.cpp but using eUML // requires boost >= v1.40 because using mpl::string #include <vector> #include <iostream> #include <boost/msm/back/state_machine.hpp> #include <boost/msm/front/euml/euml.hpp> #include <boost/msm/front/euml/stl.hpp> using namespace std; using namespace boost::msm::front::euml; namespace msm = boost::msm; namespace mpl = boost::mpl; // how long the timer will ring when countdown elapsed. #define RINGING_TIME 5 namespace // Concrete FSM implementation { // events BOOST_MSM_EUML_DECLARE_ATTRIBUTE(std::string,m_song) BOOST_MSM_EUML_ATTRIBUTES((attributes_ << m_song ), OneSongDef) struct OneSong_impl : euml_event<OneSong_impl>,OneSongDef { OneSong_impl(){} OneSong_impl(const string& asong) { get_attribute(m_song)=asong; } OneSong_impl(const char* asong) { get_attribute(m_song)=asong; } OneSong_impl(const OneSong_impl& asong) { get_attribute(m_song)=asong.get_attribute(m_song); } const string& get_data() const {return get_attribute(m_song);} }; OneSong_impl const OneSong; // attribute definitions BOOST_MSM_EUML_DECLARE_ATTRIBUTE(vector<OneSong_impl>,m_src_container) BOOST_MSM_EUML_DECLARE_ATTRIBUTE(vector<OneSong_impl>,m_tgt_container) BOOST_MSM_EUML_DECLARE_ATTRIBUTE(std::string,m_letters) BOOST_MSM_EUML_DECLARE_ATTRIBUTE(vector<OneSong_impl>::iterator,m_src_it) // the same attribute name can be reused BOOST_MSM_EUML_ATTRIBUTES((attributes_ << m_song ), NotFoundDef) BOOST_MSM_EUML_EVENT_WITH_ATTRIBUTES(NotFound,NotFoundDef) BOOST_MSM_EUML_ATTRIBUTES((attributes_ << m_song ), FoundDef) BOOST_MSM_EUML_EVENT_WITH_ATTRIBUTES(Found,FoundDef) BOOST_MSM_EUML_EVENT(Done) // Concrete FSM implementation // The list of FSM states BOOST_MSM_EUML_STATE(( (push_back_(fsm_(m_tgt_container),event_(m_song)) ,process_(Done)), no_action ),Insert) BOOST_MSM_EUML_STATE(( if_then_else_( string_find_(event_(m_song),state_(m_letters)) != Npos_<string>() , process2_(Found,event_(m_song)), process2_(NotFound,event_(m_song)) ) , no_action, attributes_ << m_letters ),StringFind) BOOST_MSM_EUML_STATE(( if_then_( state_(m_src_it) != end_(fsm_(m_src_container)), process2_(OneSong,*(state_(m_src_it)++)) ), no_action, attributes_ << m_src_it ),Foreach) // replaces the old transition table BOOST_MSM_EUML_TRANSITION_TABLE(( StringFind == Foreach + OneSong , Insert == StringFind + Found , Foreach == StringFind + NotFound , Foreach == Insert + Done // +------------------------------------------------------------------------------+ ),transition_table ) BOOST_MSM_EUML_ACTION(Log_No_Transition) { template <class FSM,class Event> void operator()(Event const& e,FSM&,int state) { std::cout << "no transition from state " << state << " on event " << typeid(e).name() << std::endl; } }; // create a state machine "on the fly" BOOST_MSM_EUML_DECLARE_STATE_MACHINE(( transition_table, //STT init_ << Foreach, // Init ( clear_(fsm_(m_src_container)), //clear source clear_(fsm_(m_tgt_container)), //clear results push_back_(fsm_(m_src_container), String_<mpl::string<'Let ','it ','be'> >()),//add a song push_back_(fsm_(m_src_container), String_<mpl::string<'Yell','ow s','ubma','rine'> >()),//add a song push_back_(fsm_(m_src_container), String_<mpl::string<'Twis','t an','d Sh','out'> >()),//add a song push_back_(fsm_(m_src_container), String_<mpl::string<'She ','love','s yo','u'> >()),//add a song attribute_(substate_(Foreach()),m_src_it) = begin_(fsm_(m_src_container)) //set the search begin ), // Entry no_action, // Exit attributes_ << m_src_container // song list << m_tgt_container, // result configure_<< no_configure_, Log_No_Transition ), iPodSearch_) //fsm name // choice of back-end typedef msm::back::state_machine<iPodSearch_> iPodSearch; void test() { iPodSearch search; // look for "She Loves You" using the first letters search.get_state<BOOST_MSM_EUML_STATE_NAME(StringFind)&>().get_attribute(m_letters)="Sh";// will find 2 songs // needed to start the highest-level SM. This will call on_entry and mark the start of the SM search.start(); // display all the songs for (vector<OneSong_impl>::const_iterator it = search.get_attribute(m_tgt_container).begin(); it != search.get_attribute(m_tgt_container).end();++it) { cout << "candidate song:" << (*it).get_attribute(m_song) << endl; } cout << "search using more letters" << endl; // look for "She Loves You" using more letters search.get_state<BOOST_MSM_EUML_STATE_NAME(StringFind)&>().get_attribute(m_letters)="She";// will find 1 song search.start(); // display all the songs for (vector<OneSong_impl>::const_iterator it = search.get_attribute(m_tgt_container).begin(); it != search.get_attribute(m_tgt_container).end();++it) { cout << "candidate song:" << (*it).get_attribute(m_song) << endl; } } } int main() { test(); return 0; }
3,730
1,345
<reponame>FreddyZeng/nlp-lang package org.nlpcn.commons.lang.util; import org.junit.Assert; import org.junit.Test; import java.io.File; public class FileFinderTest { @Test public void test() { File find = (FileFinder.findByFile(new File("./"), "FileFinder.java",10)); Assert.assertNotNull(find); find = (FileFinder.findByFile(new File("./"), "FileFinder.java",9)); Assert.assertNull(find); } }
202
521
/* $Id: Intel_Atom_330_1_60GHz.h $ */ /** @file * CPU database entry "Intel Atom 330 1.60GHz". * Generated at 2015-11-04T12:58:59Z by VBoxCpuReport v5.0.51r103818 on linux.amd64. */ /* * Copyright (C) 2013-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifndef VBOX_CPUDB_Intel_Atom_330_1_60GHz #define VBOX_CPUDB_Intel_Atom_330_1_60GHz #ifndef CPUM_DB_STANDALONE /** * CPUID leaves for Intel(R) Atom(TM) CPU 330 @ 1.60GHz. */ static CPUMCPUIDLEAF const g_aCpuIdLeaves_Intel_Atom_330_1_60GHz[] = { { 0x00000000, 0x00000000, 0x00000000, 0x0000000a, 0x756e6547, 0x6c65746e, 0x49656e69, 0 }, { 0x00000001, 0x00000000, 0x00000000, 0x000106c2, 0x01040800, 0x0040e31d, 0xbfe9fbff, 0 | CPUMCPUIDLEAF_F_CONTAINS_APIC_ID | CPUMCPUIDLEAF_F_CONTAINS_APIC }, { 0x00000002, 0x00000000, 0x00000000, 0x4fba5901, 0x0e3080c0, 0x00000000, 0x00000000, 0 }, { 0x00000003, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x00000004, 0x00000000, UINT32_MAX, 0x04004121, 0x0140003f, 0x0000003f, 0x00000001, 0 }, { 0x00000004, 0x00000001, UINT32_MAX, 0x04004122, 0x01c0003f, 0x0000003f, 0x00000001, 0 }, { 0x00000004, 0x00000002, UINT32_MAX, 0x04004143, 0x01c0003f, 0x000003ff, 0x00000001, 0 }, { 0x00000004, 0x00000003, UINT32_MAX, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x00000005, 0x00000000, 0x00000000, 0x00000040, 0x00000040, 0x00000003, 0x00000010, 0 }, { 0x00000006, 0x00000000, 0x00000000, 0x00000001, 0x00000002, 0x00000001, 0x00000000, 0 }, { 0x00000007, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x00000008, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x00000009, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x0000000a, 0x00000000, 0x00000000, 0x07280203, 0x00000000, 0x00000000, 0x00002501, 0 }, { 0x80000000, 0x00000000, 0x00000000, 0x80000008, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x80000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x20100800, 0 }, { 0x80000002, 0x00000000, 0x00000000, 0x20202020, 0x20202020, 0x746e4920, 0x52286c65, 0 }, { 0x80000003, 0x00000000, 0x00000000, 0x74412029, 0x54286d6f, 0x4320294d, 0x20205550, 0 }, { 0x80000004, 0x00000000, 0x00000000, 0x20303333, 0x20402020, 0x30362e31, 0x007a4847, 0 }, { 0x80000005, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x80000006, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x02008040, 0x00000000, 0 }, { 0x80000007, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0 }, { 0x80000008, 0x00000000, 0x00000000, 0x00003020, 0x00000000, 0x00000000, 0x00000000, 0 }, }; #endif /* !CPUM_DB_STANDALONE */ #ifndef CPUM_DB_STANDALONE /** * MSR ranges for Intel(R) Atom(TM) CPU 330 @ 1.60GHz. */ static CPUMMSRRANGE const g_aMsrRanges_Intel_Atom_330_1_60GHz[] = { MFI(0x00000000, "IA32_P5_MC_ADDR", Ia32P5McAddr), /* value=0x0 */ MFX(0x00000001, "IA32_P5_MC_TYPE", Ia32P5McType, Ia32P5McType, 0, 0, UINT64_MAX), /* value=0x0 */ MFX(0x00000006, "IA32_MONITOR_FILTER_LINE_SIZE", Ia32MonitorFilterLineSize, Ia32MonitorFilterLineSize, 0, 0, UINT64_C(0xffffffffffff0000)), /* value=0x40 */ MFN(0x00000010, "IA32_TIME_STAMP_COUNTER", Ia32TimestampCounter, Ia32TimestampCounter), /* value=0x5a7`e94bd2c0 */ MFX(0x00000017, "IA32_PLATFORM_ID", Ia32PlatformId, ReadOnly, UINT64_C(0xc00008836ac1b), 0, 0), /* value=0xc0000`8836ac1b */ MFX(0x0000001b, "IA32_APIC_BASE", Ia32ApicBase, Ia32ApicBase, UINT32_C(0xfee00800), 0, UINT64_C(0xffffffff000006ff)), MVX(0x00000033, "TEST_CTL", 0, 0, UINT64_C(0xffffffff7fffffff)), MVO(0x00000039, "C2_UNK_0000_0039", 0x1), MFO(0x0000003a, "IA32_FEATURE_CONTROL", Ia32FeatureControl), /* value=0x1 */ MVO(0x0000003f, "P6_UNK_0000_003f", 0), RFN(0x00000040, 0x00000047, "MSR_LASTBRANCH_n_FROM_IP", IntelLastBranchToN, IntelLastBranchToN), RFN(0x00000060, 0x00000067, "MSR_LASTBRANCH_n_TO_IP", IntelLastBranchFromN, IntelLastBranchFromN), MFN(0x00000079, "IA32_BIOS_UPDT_TRIG", WriteOnly, IgnoreWrite), MFX(0x0000008b, "BBL_CR_D3|BIOS_SIGN", Ia32BiosSignId, Ia32BiosSignId, 0, 0, UINT32_MAX), /* value=0x20d`00000000 */ RSN(0x000000c1, 0x000000c2, "IA32_PMCn", Ia32PmcN, Ia32PmcN, 0x0, ~(uint64_t)UINT32_MAX, 0), MFX(0x000000c7, "IA32_PMC6", Ia32PmcN, Ia32PmcN, 0, UINT64_C(0xfff7bdefff7df7df), 0), /* value=0x16101c00`00000000 */ MFX(0x000000cd, "MSR_FSB_FREQ", IntelP6FsbFrequency, ReadOnly, 0x101, 0, 0), /* value=0x101 */ MVO(0x000000ce, "IA32_PLATFORM_INFO", UINT64_C(0x1b1b0c004e4e0000)), MVO(0x000000cf, "C2_UNK_0000_00cf", 0x1f), MVO(0x000000e0, "C2_UNK_0000_00e0", 0x6800f0), MVO(0x000000e1, "C2_UNK_0000_00e1", UINT32_C(0xf0f00000)), MFX(0x000000e2, "MSR_PKG_CST_CONFIG_CONTROL", IntelPkgCStConfigControl, IntelPkgCStConfigControl, 0, 0xbfff, UINT64_C(0xfffffffffc804000)), /* value=0x26b001 */ MFX(0x000000e3, "C2_SMM_CST_MISC_INFO", IntelCore2SmmCStMiscInfo, IntelCore2SmmCStMiscInfo, 0, 0, ~(uint64_t)UINT32_MAX), /* value=0x0 */ MFX(0x000000e4, "MSR_PMG_IO_CAPTURE_BASE", IntelPmgIoCaptureBase, IntelPmgIoCaptureBase, 0, 0, UINT64_C(0xffffffffff800000)), /* value=0x0 */ MVO(0x000000e5, "C2_UNK_0000_00e5", UINT32_C(0xd00a00f8)), MFN(0x000000e7, "IA32_MPERF", Ia32MPerf, Ia32MPerf), /* value=0x63`19743600 */ MFN(0x000000e8, "IA32_APERF", Ia32APerf, Ia32APerf), /* value=0x63`199424b8 */ MFX(0x000000ee, "C1_EXT_CONFIG", IntelCore1ExtConfig, IntelCore1ExtConfig, 0, UINT64_C(0xff7bdeffffc5ffff), 0), /* value=0x3384103 */ MFX(0x000000fe, "IA32_MTRRCAP", Ia32MtrrCap, ReadOnly, 0x508, 0, 0), /* value=0x508 */ MVX(0x00000116, "BBL_CR_ADDR", 0x3fc0, UINT64_C(0xfffffff00000001f), 0), MVX(0x00000118, "BBL_CR_DECC", 0, UINT64_C(0xfffc0000fffc0000), 0), MFX(0x00000119, "BBL_CR_CTL", IntelBblCrCtl, IntelBblCrCtl, 0x938008, 0x4080017f, ~(uint64_t)UINT32_MAX), /* value=0x938008 */ MFN(0x0000011a, "BBL_CR_TRIG", WriteOnly, IgnoreWrite), MVX(0x0000011b, "P6_UNK_0000_011b", 0, 0x1, UINT64_C(0xfffffffffffffffe)), MVX(0x0000011c, "C2_UNK_0000_011c", 0xd96000, 0, UINT64_C(0xfffffffff0000000)), MFX(0x0000011e, "BBL_CR_CTL3", IntelBblCrCtl3, IntelBblCrCtl3, 0x7f00011f, UINT32_C(0xff83f81f), UINT64_C(0xffffffff007c06e0)), /* value=0x7f00011f */ MFX(0x00000174, "IA32_SYSENTER_CS", Ia32SysEnterCs, Ia32SysEnterCs, 0, ~(uint64_t)UINT32_MAX, 0), /* value=0x10 */ MFN(0x00000175, "IA32_SYSENTER_ESP", Ia32SysEnterEsp, Ia32SysEnterEsp), /* value=0x0 */ MFN(0x00000176, "IA32_SYSENTER_EIP", Ia32SysEnterEip, Ia32SysEnterEip), /* value=0xffffffff`81573970 */ MFX(0x00000179, "IA32_MCG_CAP", Ia32McgCap, ReadOnly, 0x805, 0, 0), /* value=0x805 */ MFX(0x0000017a, "IA32_MCG_STATUS", Ia32McgStatus, Ia32McgStatus, 0, 0, UINT64_MAX), /* value=0x0 */ RSN(0x00000186, 0x00000187, "IA32_PERFEVTSELn", Ia32PerfEvtSelN, Ia32PerfEvtSelN, 0x0, 0, ~(uint64_t)UINT32_MAX), MFX(0x00000194, "CLOCK_FLEX_MAX", IntelFlexRatio, IntelFlexRatio, 0, UINT32_C(0xfffee0c0), ~(uint64_t)UINT32_MAX), /* value=0x0 */ MFX(0x00000198, "IA32_PERF_STATUS", Ia32PerfStatus, ReadOnly, UINT64_C(0xc1b0c1b06000c1b), 0, 0), /* value=0xc1b0c1b`06000c1b */ MFX(0x00000199, "IA32_PERF_CTL", Ia32PerfCtl, Ia32PerfCtl, 0xc1b, 0, 0), /* Might bite. value=0xc1b */ MFX(0x0000019a, "IA32_CLOCK_MODULATION", Ia32ClockModulation, Ia32ClockModulation, 0x2, 0, UINT64_C(0xffffffffffffffe1)), /* value=0x2 */ MFX(0x0000019b, "IA32_THERM_INTERRUPT", Ia32ThermInterrupt, Ia32ThermInterrupt, 0x3, 0, UINT64_C(0xffffffffff0000e0)), /* value=0x3 */ MFX(0x0000019c, "IA32_THERM_STATUS", Ia32ThermStatus, Ia32ThermStatus, UINT32_C(0x884c0000), UINT32_C(0xf87f03ff), UINT64_C(0xffffffff0780fc00)), /* value=0x884c0000 */ MFX(0x0000019d, "IA32_THERM2_CTL", Ia32Therm2Ctl, ReadOnly, 0x61b, 0, 0), /* value=0x61b */ MVX(0x0000019e, "P6_UNK_0000_019e", 0, UINT32_C(0xffff0000), ~(uint64_t)UINT32_MAX), MFX(0x000001a0, "IA32_MISC_ENABLE", Ia32MiscEnable, Ia32MiscEnable, 0x60940488, UINT64_C(0x366131884), UINT64_C(0xfffffff89908c372)), /* value=0x60940488 */ MVX(0x000001aa, "P6_PIC_SENS_CFG", UINT32_C(0x800f0421), UINT64_C(0xffffffffff80000e), 0), MFX(0x000001c9, "MSR_LASTBRANCH_TOS", IntelLastBranchTos, IntelLastBranchTos, 0, 0, UINT64_C(0xfffffffffffffff8)), /* value=0x0 */ MFX(0x000001d9, "IA32_DEBUGCTL", Ia32DebugCtl, Ia32DebugCtl, 0, 0, UINT64_C(0xffffffffffffe03c)), /* value=0x0 */ MFO(0x000001db, "P6_LAST_BRANCH_FROM_IP", P6LastBranchFromIp), /* value=0xffffffff`a07ac16e */ MFO(0x000001dc, "P6_LAST_BRANCH_TO_IP", P6LastBranchToIp), /* value=0xffffffff`8105c4f0 */ MFN(0x000001dd, "P6_LAST_INT_FROM_IP", P6LastIntFromIp, P6LastIntFromIp), /* value=0x0 */ MFN(0x000001de, "P6_LAST_INT_TO_IP", P6LastIntToIp, P6LastIntToIp), /* value=0x0 */ MFX(0x00000200, "IA32_MTRR_PHYS_BASE0", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x0, 0, UINT64_C(0xffffffff00000ff8)), /* value=0xe0000000 */ MFX(0x00000201, "IA32_MTRR_PHYS_MASK0", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x0, 0, UINT64_C(0xfffffff0000007ff)), /* value=0xe0000800 */ MFX(0x00000202, "IA32_MTRR_PHYS_BASE1", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x1, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x6 */ MFX(0x00000203, "IA32_MTRR_PHYS_MASK1", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x1, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x800 */ MFX(0x00000204, "IA32_MTRR_PHYS_BASE2", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x2, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x0 */ MFX(0x00000205, "IA32_MTRR_PHYS_MASK2", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x2, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x0 */ MFX(0x00000206, "IA32_MTRR_PHYS_BASE3", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x3, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x0 */ MFX(0x00000207, "IA32_MTRR_PHYS_MASK3", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x3, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x0 */ MFX(0x00000208, "IA32_MTRR_PHYS_BASE4", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x4, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x0 */ MFX(0x00000209, "IA32_MTRR_PHYS_MASK4", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x4, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x0 */ MFX(0x0000020a, "IA32_MTRR_PHYS_BASE5", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x5, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x0 */ MFX(0x0000020b, "IA32_MTRR_PHYS_MASK5", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x5, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x0 */ MFX(0x0000020c, "IA32_MTRR_PHYS_BASE6", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x6, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x0 */ MFX(0x0000020d, "IA32_MTRR_PHYS_MASK6", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x6, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x0 */ MFX(0x0000020e, "IA32_MTRR_PHYS_BASE7", Ia32MtrrPhysBaseN, Ia32MtrrPhysBaseN, 0x7, 0, UINT64_C(0xffffffff00000ff8)), /* value=0x0 */ MFX(0x0000020f, "IA32_MTRR_PHYS_MASK7", Ia32MtrrPhysMaskN, Ia32MtrrPhysMaskN, 0x7, 0, UINT64_C(0xfffffff0000007ff)), /* value=0x0 */ MFS(0x00000250, "IA32_MTRR_FIX64K_00000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix64K_00000), MFS(0x00000258, "IA32_MTRR_FIX16K_80000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix16K_80000), MFS(0x00000259, "IA32_MTRR_FIX16K_A0000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix16K_A0000), MFS(0x00000268, "IA32_MTRR_FIX4K_C0000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_C0000), MFS(0x00000269, "IA32_MTRR_FIX4K_C8000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_C8000), MFS(0x0000026a, "IA32_MTRR_FIX4K_D0000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_D0000), MFS(0x0000026b, "IA32_MTRR_FIX4K_D8000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_D8000), MFS(0x0000026c, "IA32_MTRR_FIX4K_E0000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_E0000), MFS(0x0000026d, "IA32_MTRR_FIX4K_E8000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_E8000), MFS(0x0000026e, "IA32_MTRR_FIX4K_F0000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_F0000), MFS(0x0000026f, "IA32_MTRR_FIX4K_F8000", Ia32MtrrFixed, Ia32MtrrFixed, GuestMsrs.msr.MtrrFix4K_F8000), MVX(0x000002e0, "I7_SB_NO_EVICT_MODE", 0, 0, UINT64_C(0xffffffff7ffffffc)), MFZ(0x000002ff, "IA32_MTRR_DEF_TYPE", Ia32MtrrDefType, Ia32MtrrDefType, GuestMsrs.msr.MtrrDefType, 0, UINT64_C(0xfffffffffffff3f8)), MFX(0x00000309, "IA32_FIXED_CTR0", Ia32FixedCtrN, Ia32FixedCtrN, 0x0, 0, UINT64_C(0xffffff0000000000)), /* value=0x8c */ MFX(0x0000030a, "IA32_FIXED_CTR1", Ia32FixedCtrN, Ia32FixedCtrN, 0x1, 0x81201, UINT64_C(0xffffff0000000000)), /* value=0xff`ad893763 */ MFX(0x0000030b, "IA32_FIXED_CTR2", Ia32FixedCtrN, Ia32FixedCtrN, 0x2, 0, UINT64_C(0xffffff0000000000)), /* value=0x8f4 */ MFX(0x00000345, "IA32_PERF_CAPABILITIES", Ia32PerfCapabilities, ReadOnly, 0xc1, 0, 0), /* value=0xc1 */ MFX(0x0000038d, "IA32_FIXED_CTR_CTRL", Ia32FixedCtrCtrl, Ia32FixedCtrCtrl, 0, 0, UINT64_C(0xfffffffffffff000)), /* value=0xb0 */ MFX(0x0000038e, "IA32_PERF_GLOBAL_STATUS", Ia32PerfGlobalStatus, ReadOnly, 0, 0, 0), /* value=0x0 */ MFX(0x0000038f, "IA32_PERF_GLOBAL_CTRL", Ia32PerfGlobalCtrl, Ia32PerfGlobalCtrl, 0, 0, UINT64_C(0xfffffff8fffffffc)), /* value=0x7`00000003 */ MFX(0x00000390, "IA32_PERF_GLOBAL_OVF_CTRL", Ia32PerfGlobalOvfCtrl, Ia32PerfGlobalOvfCtrl, 0, UINT64_C(0xc000000700000003), UINT64_C(0x3ffffff8fffffffc)), /* value=0x0 */ MVX(0x000003ca, "TODO_0000_03ca", 0x10510, 0, UINT64_C(0xffffffffffe00000)), MFX(0x000003f1, "IA32_PEBS_ENABLE", Ia32PebsEnable, Ia32PebsEnable, 0, 0, UINT64_C(0xfffffffffffffffe)), /* value=0x0 */ RFN(0x00000400, 0x00000417, "IA32_MCi_CTL_STATUS_ADDR_MISC", Ia32McCtlStatusAddrMiscN, Ia32McCtlStatusAddrMiscN), MVX(0x000004f8, "C2_UNK_0000_04f8", 0, 0, 0), MVX(0x000004f9, "C2_UNK_0000_04f9", 0, 0, 0), MVX(0x000004fa, "C2_UNK_0000_04fa", 0, 0, 0), MVX(0x000004fb, "C2_UNK_0000_04fb", 0, 0, 0), MVX(0x000004fc, "C2_UNK_0000_04fc", 0, 0, 0), MVX(0x000004fd, "C2_UNK_0000_04fd", 0, 0, 0), MVX(0x000004fe, "C2_UNK_0000_04fe", 0, 0, 0), MVX(0x000004ff, "C2_UNK_0000_04ff", 0, 0, 0), MFN(0x00000600, "IA32_DS_AREA", Ia32DsArea, Ia32DsArea), /* value=0xffff8800`d6ee1c00 */ MFX(0xc0000080, "AMD64_EFER", Amd64Efer, Amd64Efer, 0xd01, 0x400, UINT64_C(0xfffffffffffff2fe)), MFN(0xc0000081, "AMD64_STAR", Amd64SyscallTarget, Amd64SyscallTarget), /* value=0x230010`00000000 */ MFN(0xc0000082, "AMD64_STAR64", Amd64LongSyscallTarget, Amd64LongSyscallTarget), /* value=0xffffffff`815715d0 */ MFN(0xc0000083, "AMD64_STARCOMPAT", Amd64CompSyscallTarget, Amd64CompSyscallTarget), /* value=0xffffffff`81573ad0 */ MFX(0xc0000084, "AMD64_SYSCALL_FLAG_MASK", Amd64SyscallFlagMask, Amd64SyscallFlagMask, 0, ~(uint64_t)UINT32_MAX, 0), /* value=0x47700 */ MFN(0xc0000100, "AMD64_FS_BASE", Amd64FsBase, Amd64FsBase), /* value=0x7fe4`93136740 */ MFN(0xc0000101, "AMD64_GS_BASE", Amd64GsBase, Amd64GsBase), /* value=0xffff8800`db500000 */ MFN(0xc0000102, "AMD64_KERNEL_GS_BASE", Amd64KernelGsBase, Amd64KernelGsBase), /* value=0x0 */ }; #endif /* !CPUM_DB_STANDALONE */ /** * Database entry for Intel(R) Atom(TM) CPU 330 @ 1.60GHz. */ static CPUMDBENTRY const g_Entry_Intel_Atom_330_1_60GHz = { /*.pszName = */ "Intel Atom 330 1.60GHz", /*.pszFullName = */ "Intel(R) Atom(TM) CPU 330 @ 1.60GHz", /*.enmVendor = */ CPUMCPUVENDOR_INTEL, /*.uFamily = */ 6, /*.uModel = */ 28, /*.uStepping = */ 2, /*.enmMicroarch = */ kCpumMicroarch_Intel_Atom_Bonnell, /*.uScalableBusFreq = */ CPUM_SBUSFREQ_133MHZ, /*.fFlags = */ 0, /*.cMaxPhysAddrWidth= */ 32, /*.fMxCsrMask = */ 0xffff, /*.paCpuIdLeaves = */ NULL_ALONE(g_aCpuIdLeaves_Intel_Atom_330_1_60GHz), /*.cCpuIdLeaves = */ ZERO_ALONE(RT_ELEMENTS(g_aCpuIdLeaves_Intel_Atom_330_1_60GHz)), /*.enmUnknownCpuId = */ CPUMUNKNOWNCPUID_LAST_STD_LEAF, /*.DefUnknownCpuId = */ { 0x07280203, 0x00000000, 0x00000000, 0x00002501 }, /*.fMsrMask = */ UINT32_MAX, /*.cMsrRanges = */ ZERO_ALONE(RT_ELEMENTS(g_aMsrRanges_Intel_Atom_330_1_60GHz)), /*.paMsrRanges = */ NULL_ALONE(g_aMsrRanges_Intel_Atom_330_1_60GHz), }; #endif /* !VBOX_DB_Intel_Atom_330_1_60GHz */
8,593
326
/************************************************ Copyright (c) 2016, Xilinx, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************/ //______________________________________________________________________________ // crec_tb.cpp: // - carrier/phase recovery testbench // // // // <NAME>, may 2012 //______________________________________________________________________________ #include "crec.h" int main () { cdata_t din; // crec input cdata_t dout_mix; // mixer output cphase_t ph_xy; // phase offset input cphase_t t_ph_xy; // phase offset output from phase recovery blk ctl_crec_t control; // crec control setting hd_t hd_out; cdata_t sd_out; error_t err; qam_t qam = control.qam; loop_int_t loop_integ; loop_out_t loop_out; // control setting control.qam = 0; //control.lf_p = 4; // 2^-4 control.lf_p = 6; // 2^-6 control.lf_i = 5; // 2^-14 control.lf_out_gain = 1; // 2^-1 control.reg_clr = 0; control.reg_init = 0; // file IO ifstream fp_cin ("cin.txt"); //ifstream fp_cin ("lf_cin.txt"); //ifstream fp_phin ("lf_phin.txt"); ofstream fp_dout ("hw_dout.txt"); ofstream fp_debug ("debug.txt"); float f_din; for (int i = 0; i<13000; ++i) { //for (int i = 0; i<6560; ++i) { //for (int i = 0; i<1100; ++i) { fp_cin >> f_din; din.i = f_din; fp_cin >> f_din; din.q = f_din; //fp_phin >> f_din; ph_xy.i = f_din; //fp_phin >> f_din; ph_xy.q = f_din; // to make it a close loop ph_xy.i = t_ph_xy.i; ph_xy.q = t_ph_xy.q; //#define SEPARATE #ifndef SEPARATE crec ( din, &dout_mix, ph_xy, &t_ph_xy, &loop_integ, control ); fp_dout << dout_mix.i << "\t " << dout_mix.q << "\t " << " " << endl; fp_debug << loop_integ << "\t " << endl; #else //cout << din.i << " "<< din.q; mix( din, &dout_mix, ph_xy ); fp_dout << dout_mix.i << "\t " << dout_mix.q << "\t " << " " << endl; slicer ( qam, dout_mix, &hd_out, &sd_out, &err); //fp_debug << err.i << "\t " << err.q << "\t " << " " << endl; phase_recovery ( hd_out, sd_out, &loop_integ, &loop_out, &t_ph_xy, control); fp_debug << loop_integ << "\t " << endl; //fp_debug << t_ph_xy.i << "\t " << loop_out << endl; //fp_cout << dout_mix.i << "\t " << dout_mix.q << "\t " << loop_integ << endl; #endif }; fp_dout.close(); fp_debug.close(); fp_cin.close(); //fp_phin.close(); return 0; } #ifdef EACH //______________________________________________________________________________ // apply phase correction cphase_t ph_xy; din = {1.1, 2.1}; ph_xy = {0.45, 0.44}; mix( din, &dout_mix, ph_xy ); //cout << endl << dout_mix.i << " " << dout_mix.q << endl; //______________________________________________________________________________ // slicer hd_t hd_out; cdata_t sd_out; error_t err; qam_t qam = control.qam; slicer ( qam, dout_mix, &hd_out, &sd_out, &err); //---- sanity check //cdata_t tmp = { -1.4, 3.4}; //slicer ( qam, tmp, &hd_out, &sd_out, &err); //cout << endl << "hd: " << hd_out.i << " " << hd_out.q << endl; //cout << "sd: " << sd_out.i << " " << sd_out.q << endl; //cout << "err: " << err.i << " " << err.q << endl; //______________________________________________________________________________ // determine phase offset phase_t ph_est; compute_phase ( hd_out, sd_out, &ph_est ); //---- sanity check //hd_t t_hd = { -0.9375, 0.875}; //cdata_t t_sd = { -1.1, 0.4}; //compute_phase ( t_hd, t_sd, &ph_est ); //cout << "ph_est: " << ph_est << endl; //______________________________________________________________________________ // loop filter loop_int_t loop_int; loop_out_t loop_out; //loop_filter( ph_est, &loop_out, &loop_int, control ); //phase_t tin = -1.125; //loop_filter( tin, &loop_out, &loop_int, control ); //---- stand alone testbench //ifstream fp_lf_in; fp_lf_in.open("lf_in.txt", ios::in); //ofstream fp_lf_out; fp_lf_out.open("lf_out.txt", ios::out); ifstream fp_lf_in("lf_in.txt"); //ifstream fp_lf_in("yyy.txt"); //ofstream fp_din("din.txt"); ofstream fp_lf_out("lf_out.txt"); phase_t tin; float f_tin; float f_loop_out, f_loop_int; for (int i = 0; i<118000; ++i) { //for (int i = 0; i<5; ++i) { fp_lf_in >> f_tin; tin = f_tin; //cout << tin << endl; //fp_din << tin << endl; loop_filter( tin, &loop_out, &loop_int, control ); f_loop_out = loop_out; f_loop_int = loop_int; fp_lf_out << f_loop_out << " " << f_loop_int << endl; //fp_lf_out << f_loop_out << endl; } fp_lf_in.close(); //fp_din.close(); fp_lf_out.close(); cout << "done............."; //______________________________________________________________________________ // VCO //---- stand alone testbench loop_out_t loop_out; cphase_t ph_offset; ofstream fp_vco_out; fp_vco_out.open("vco_out.txt", ios::out); float f_i, f_q; ap_fixed<16,1> tphase; //for (int i = 0; i<118000; ++i) { for (int i = 0; i<200; ++i) { loop_out = .01; vco ( loop_out, &tphase, &ph_offset ); f_i = ph_offset.i; //f_i = tphase; f_q = ph_offset.q; fp_vco_out << f_i << " " << f_q << endl; } fp_vco_out.close(); cout << "done............."; } #endif
2,860
742
package org.support.project.knowledge.deploy.v1_8_0; import org.support.project.common.util.FileUtil; import org.support.project.knowledge.config.AppConfig; import org.support.project.knowledge.dao.ServiceConfigsDao; import org.support.project.knowledge.dao.ServiceLocaleConfigsDao; import org.support.project.knowledge.deploy.Migrate; import org.support.project.knowledge.entity.ServiceConfigsEntity; import org.support.project.knowledge.entity.ServiceLocaleConfigsEntity; import org.support.project.ormapping.tool.dao.InitializeDao; public class Migrate_1_8_1 implements Migrate { public static Migrate_1_8_1 get() { return org.support.project.di.Container.getComp(Migrate_1_8_1.class); } @Override public boolean doMigrate() throws Exception { InitializeDao initializeDao = InitializeDao.get(); String[] sqlpaths = { "/org/support/project/knowledge/deploy/v1_8_0/migrate2.sql", }; initializeDao.initializeDatabase(sqlpaths); ServiceConfigsEntity serviceConfigsEntity = new ServiceConfigsEntity(AppConfig.get().getSystemName()); serviceConfigsEntity.setServiceLabel(AppConfig.get().getSystemName()); serviceConfigsEntity.setServiceIcon("fa-book"); ServiceConfigsDao.get().insert(serviceConfigsEntity); ServiceLocaleConfigsEntity en = new ServiceLocaleConfigsEntity("en", AppConfig.get().getSystemName()); en.setPageHtml(FileUtil.read(getClass().getResourceAsStream("/org/support/project/knowledge/deploy/v1_8_0/top_info.html"))); ServiceLocaleConfigsDao.get().insert(en); ServiceLocaleConfigsEntity ja = new ServiceLocaleConfigsEntity("ja", AppConfig.get().getSystemName()); ja.setPageHtml(FileUtil.read(getClass().getResourceAsStream("/org/support/project/knowledge/deploy/v1_8_0/top_info_ja.html"))); ServiceLocaleConfigsDao.get().insert(ja); return true; } }
731
1,561
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Description: This controller gives to its node the following behavior: * Listen the keyboard. According to the pressed key, send a * message through an emitter or handle the position of Robot1 */ import com.cyberbotics.webots.controller.Supervisor; import com.cyberbotics.webots.controller.Emitter; import com.cyberbotics.webots.controller.Field; import com.cyberbotics.webots.controller.Keyboard; import com.cyberbotics.webots.controller.Node; public class Driver extends Supervisor { private final int timeStep = 128; private Emitter emitter; private Field translationField; private Keyboard keyboard; private double x = -0.3; private double y = -0.1; private double[] translation = {x, y, 0}; public Driver() { emitter = getEmitter("emitter"); Node robot = getFromDef("ROBOT1"); if (robot == null) // robot might be null if the controller is about to quit System.exit(1); translationField = robot.getField("translation"); keyboard = getKeyboard(); keyboard.enable(timeStep); } public void run() { String previous_message=""; String message=""; displayHelp(); // main loop // quit the loop when the simulation is ended while (step(timeStep) != -1) { // Read sensors; update message according to the pressed keyboard key int k=keyboard.getKey(); switch (k){ case 'A': message = "avoid obstacles"; break; case 'F': message = "move forward"; break; case 'S': message = "stop"; break; case 'T': message = "turn"; break; case ('I'): displayHelp(); break; case 'G':{ double[] translationValues = translationField.getSFVec3f(); System.out.println("ROBOT1 is located at ("+translationValues[0]+","+translationValues[1]+")"); break;} case 'R': System.out.println("Teleport ROBOT1 at ("+x+","+y+")"); translationField.setSFVec3f(translation); break; default: message = ""; } // send actuators commands; send a new message through the emitter device if (!message.equals("") && !message.equals(previous_message)) { previous_message=message; System.out.println("Please, "+message); byte[] formated = message.getBytes(); emitter.send(formated); } } } private void displayHelp(){ System.out.println("Commands:\n"+ " I for displaying the commands\n"+ " A for avoid obstacles\n"+ " F for move forward\n"+ " S for stop\n"+ " T for turn\n" + " R for positioning ROBOT1 at (-0.3,-0.1)\n"+ " G for knowing the (x,y) position of ROBOT1"); } public static void main(String[] args) { Driver controller = new Driver(); controller.run(); } }
1,413
521
<reponame>Fimbure/icebox-1 /* Copyright (c) 2001, Stanford University * All rights reserved * * See the file LICENSE.txt for information on redistributing this software. */ #include "cr_packfunctions.h" #include "packspu.h" #include "packspu_proto.h" #include "cr_mem.h" void PACKSPU_APIENTRY packspu_ChromiumParametervCR(GLenum target, GLenum type, GLsizei count, const GLvoid *values) { CRMessage msg; int len; GLint ai32ServerValues[2]; GLboolean fFlush = GL_FALSE; GET_THREAD(thread); switch(target) { case GL_GATHER_PACK_CR: /* flush the current pack buffer */ packspuFlush( (void *) thread ); /* the connection is thread->server.conn */ msg.header.type = CR_MESSAGE_GATHER; msg.gather.offset = 69; len = sizeof(CRMessageGather); crNetSend(thread->netServer.conn, NULL, &msg, len); return; case GL_SHARE_LISTS_CR: { ContextInfo *pCtx[2]; GLint *ai32Values; int i; if (count != 2) { WARN(("GL_SHARE_LISTS_CR invalid cound %d", count)); return; } if (type != GL_UNSIGNED_INT && type != GL_INT) { WARN(("GL_SHARE_LISTS_CR invalid type %d", type)); return; } ai32Values = (GLint*)values; for (i = 0; i < 2; ++i) { const int slot = ai32Values[i] - MAGIC_OFFSET; if (slot < 0 || slot >= pack_spu.numContexts) { WARN(("GL_SHARE_LISTS_CR invalid value[%d] %d", i, ai32Values[i])); return; } pCtx[i] = &pack_spu.context[slot]; if (!pCtx[i]->clientState) { WARN(("GL_SHARE_LISTS_CR invalid pCtx1 for value[%d] %d", i, ai32Values[i])); return; } ai32ServerValues[i] = pCtx[i]->serverCtx; } crStateShareLists(pCtx[0]->clientState, pCtx[1]->clientState); values = ai32ServerValues; fFlush = GL_TRUE; break; } default: break; } crPackChromiumParametervCR(target, type, count, values); if (fFlush) packspuFlush( (void *) thread ); } GLboolean packspuSyncOnFlushes(void) { #if 1 /*Seems to still cause issues, always sync for now*/ return 1; #else GLint buffer; crStateGetIntegerv(&pack_spu.StateTracker, GL_DRAW_BUFFER, &buffer); /*Usually buffer==GL_BACK, so put this extra check to simplify boolean eval on runtime*/ return (buffer != GL_BACK) && (buffer == GL_FRONT_LEFT || buffer == GL_FRONT_RIGHT || buffer == GL_FRONT || buffer == GL_FRONT_AND_BACK || buffer == GL_LEFT || buffer == GL_RIGHT); #endif } void PACKSPU_APIENTRY packspu_DrawBuffer(GLenum mode) { GLboolean hadtoflush; hadtoflush = packspuSyncOnFlushes(); crStateDrawBuffer(&pack_spu.StateTracker, mode); crPackDrawBuffer(mode); if (hadtoflush && !packspuSyncOnFlushes()) packspu_Flush(); } void PACKSPU_APIENTRY packspu_Finish( void ) { GET_THREAD(thread); GLint writeback = CRPACKSPU_IS_WDDM_CRHGSMI() ? 1 : pack_spu.thread[pack_spu.idxThreadInUse].netServer.conn->actual_network; crPackFinish(); if (packspuSyncOnFlushes()) { if (writeback) { crPackWriteback(&writeback); packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); } } } void PACKSPU_APIENTRY packspu_Flush( void ) { GET_THREAD(thread); int writeback=1; int found=0; if (!thread->bInjectThread) { crPackFlush(); if (packspuSyncOnFlushes()) { crPackWriteback(&writeback); packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); } } else { int i; crLockMutex(&_PackMutex); /*Make sure we process commands in order they should appear, so flush other threads first*/ for (i=0; i<MAX_THREADS; ++i) { if (pack_spu.thread[i].inUse && (thread != &pack_spu.thread[i]) && pack_spu.thread[i].netServer.conn && pack_spu.thread[i].packer && pack_spu.thread[i].packer->currentBuffer) { packspuFlush((void *) &pack_spu.thread[i]); if (pack_spu.thread[i].netServer.conn->u32ClientID == thread->netServer.conn->u32InjectClientID) { found=1; } } } if (!found) { /*Thread we're supposed to inject commands for has been detached, so there's nothing to sync with and we should just pass commands through our own connection. */ thread->netServer.conn->u32InjectClientID=0; } packspuFlush((void *) thread); crUnlockMutex(&_PackMutex); } } void PACKSPU_APIENTRY packspu_NewList(GLuint list, GLenum mode) { crStateNewList(&pack_spu.StateTracker, list, mode); crPackNewList(list, mode); } void PACKSPU_APIENTRY packspu_EndList() { crStateEndList(&pack_spu.StateTracker); crPackEndList(); } void PACKSPU_APIENTRY packspu_VBoxWindowDestroy( GLint con, GLint window ) { if (CRPACKSPU_IS_WDDM_CRHGSMI()) { GET_THREAD(thread); if (con) { CRPackContext * curPacker = crPackGetContext(); CRASSERT(!thread || !thread->bInjectThread); thread = GET_THREAD_VAL_ID(con); crPackSetContext(thread->packer); crPackWindowDestroy(window); if (curPacker != thread->packer) crPackSetContext(curPacker); return; } CRASSERT(thread); CRASSERT(thread->bInjectThread); } crPackWindowDestroy(window); } GLint PACKSPU_APIENTRY packspu_VBoxWindowCreate( GLint con, const char *dpyName, GLint visBits ) { GET_THREAD(thread); static int num_calls = 0; int writeback = CRPACKSPU_IS_WDDM_CRHGSMI() ? 1 : pack_spu.thread[pack_spu.idxThreadInUse].netServer.conn->actual_network; GLint return_val = (GLint) 0; ThreadInfo *curThread = thread; GLint retVal; if (CRPACKSPU_IS_WDDM_CRHGSMI()) { if (!con) { crError("connection expected!"); return 0; } thread = GET_THREAD_VAL_ID(con); } else { CRASSERT(!con); if (!thread) { thread = packspuNewThread( #if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST) NULL #endif ); } } CRASSERT(thread); CRASSERT(thread->packer); CRASSERT(crPackGetContext() == (curThread ? curThread->packer : NULL)); crPackSetContext(thread->packer); crPackWindowCreate( dpyName, visBits, &return_val, &writeback ); packspuFlush(thread); if (!(thread->netServer.conn->actual_network)) { retVal = num_calls++; } else { CRPACKSPU_WRITEBACK_WAIT(thread, writeback); retVal = return_val; } if (CRPACKSPU_IS_WDDM_CRHGSMI()) { if (thread != curThread) { if (curThread) crPackSetContext(curThread->packer); else crPackSetContext(NULL); } } return retVal; } GLint PACKSPU_APIENTRY packspu_WindowCreate( const char *dpyName, GLint visBits ) { return packspu_VBoxWindowCreate( 0, dpyName, visBits ); } GLboolean PACKSPU_APIENTRY packspu_AreTexturesResident( GLsizei n, const GLuint * textures, GLboolean * residences ) { GET_THREAD(thread); int writeback = 1; GLboolean return_val = GL_TRUE; GLsizei i; if (!CRPACKSPU_IS_WDDM_CRHGSMI() && !(pack_spu.thread[pack_spu.idxThreadInUse].netServer.conn->actual_network)) { crError( "packspu_AreTexturesResident doesn't work when there's no actual network involved!\nTry using the simplequery SPU in your chain!" ); } crPackAreTexturesResident( n, textures, residences, &return_val, &writeback ); packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); /* Since the Chromium packer/unpacker can't return both 'residences' * and the function's return value, compute the return value here. */ for (i = 0; i < n; i++) { if (!residences[i]) { return_val = GL_FALSE; break; } } return return_val; } GLboolean PACKSPU_APIENTRY packspu_AreProgramsResidentNV( GLsizei n, const GLuint * ids, GLboolean * residences ) { GET_THREAD(thread); int writeback = 1; GLboolean return_val = GL_TRUE; GLsizei i; if (!CRPACKSPU_IS_WDDM_CRHGSMI() && !(pack_spu.thread[pack_spu.idxThreadInUse].netServer.conn->actual_network)) { crError( "packspu_AreProgramsResidentNV doesn't work when there's no actual network involved!\nTry using the simplequery SPU in your chain!" ); } crPackAreProgramsResidentNV( n, ids, residences, &return_val, &writeback ); packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); /* Since the Chromium packer/unpacker can't return both 'residences' * and the function's return value, compute the return value here. */ for (i = 0; i < n; i++) { if (!residences[i]) { return_val = GL_FALSE; break; } } return return_val; } void PACKSPU_APIENTRY packspu_GetPolygonStipple( GLubyte * mask ) { GET_THREAD(thread); int writeback = 1; crPackGetPolygonStipple( mask, &writeback ); #ifdef CR_ARB_pixel_buffer_object if (!crStateIsBufferBound(&pack_spu.StateTracker, GL_PIXEL_PACK_BUFFER_ARB)) #endif { packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); } } void PACKSPU_APIENTRY packspu_GetPixelMapfv( GLenum map, GLfloat * values ) { GET_THREAD(thread); int writeback = 1; crPackGetPixelMapfv( map, values, &writeback ); #ifdef CR_ARB_pixel_buffer_object if (!crStateIsBufferBound(&pack_spu.StateTracker, GL_PIXEL_PACK_BUFFER_ARB)) #endif { packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); } } void PACKSPU_APIENTRY packspu_GetPixelMapuiv( GLenum map, GLuint * values ) { GET_THREAD(thread); int writeback = 1; crPackGetPixelMapuiv( map, values, &writeback ); #ifdef CR_ARB_pixel_buffer_object if (!crStateIsBufferBound(&pack_spu.StateTracker, GL_PIXEL_PACK_BUFFER_ARB)) #endif { packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); } } void PACKSPU_APIENTRY packspu_GetPixelMapusv( GLenum map, GLushort * values ) { GET_THREAD(thread); int writeback = 1; crPackGetPixelMapusv( map, values, &writeback ); #ifdef CR_ARB_pixel_buffer_object if (!crStateIsBufferBound(&pack_spu.StateTracker, GL_PIXEL_PACK_BUFFER_ARB)) #endif { packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); } } static void packspuFluchOnThreadSwitch(GLboolean fEnable) { GET_THREAD(thread); if (thread->currentContext->fAutoFlush == fEnable) return; thread->currentContext->fAutoFlush = fEnable; thread->currentContext->currentThread = fEnable ? thread : NULL; } static void packspuCheckZerroVertAttr(GLboolean fEnable) { GET_THREAD(thread); thread->currentContext->fCheckZerroVertAttr = fEnable; } void PACKSPU_APIENTRY packspu_ChromiumParameteriCR(GLenum target, GLint value) { switch (target) { case GL_FLUSH_ON_THREAD_SWITCH_CR: /* this is a pure packspu state, don't propagate it any further */ packspuFluchOnThreadSwitch(value); return; case GL_CHECK_ZERO_VERT_ARRT: packspuCheckZerroVertAttr(value); return; case GL_SHARE_CONTEXT_RESOURCES_CR: crStateShareContext(&pack_spu.StateTracker, value); break; case GL_RCUSAGE_TEXTURE_SET_CR: { Assert(value); crStateSetTextureUsed(&pack_spu.StateTracker, value, GL_TRUE); break; } case GL_RCUSAGE_TEXTURE_CLEAR_CR: { Assert(value); #ifdef DEBUG { CRContext *pCurState = crStateGetCurrent(&pack_spu.StateTracker); CRTextureObj *tobj = (CRTextureObj*)crHashtableSearch(pCurState->shared->textureTable, value); Assert(tobj); } #endif crStateSetTextureUsed(&pack_spu.StateTracker, value, GL_FALSE); break; } default: break; } crPackChromiumParameteriCR(target, value); } GLenum PACKSPU_APIENTRY packspu_GetError( void ) { GET_THREAD(thread); int writeback = 1; GLenum return_val = (GLenum) 0; CRContext *pCurState = crStateGetCurrent(&pack_spu.StateTracker); NOREF(pCurState); /* it's unused, but I don't know about side effects.. */ if (!CRPACKSPU_IS_WDDM_CRHGSMI() && !(pack_spu.thread[pack_spu.idxThreadInUse].netServer.conn->actual_network)) { crError( "packspu_GetError doesn't work when there's no actual network involved!\nTry using the simplequery SPU in your chain!" ); } crPackGetError( &return_val, &writeback ); packspuFlush( (void *) thread ); CRPACKSPU_WRITEBACK_WAIT(thread, writeback); return return_val; } GLint PACKSPU_APIENTRY packspu_VBoxPackSetInjectThread(struct VBOXUHGSMI *pHgsmi) { GLint con = 0; int i; GET_THREAD(thread); CRASSERT(!thread); RT_NOREF(pHgsmi); crLockMutex(&_PackMutex); { CRASSERT(CRPACKSPU_IS_WDDM_CRHGSMI() || (pack_spu.numThreads>0)); CRASSERT(pack_spu.numThreads<MAX_THREADS); for (i=0; i<MAX_THREADS; ++i) { if (!pack_spu.thread[i].inUse) { thread = &pack_spu.thread[i]; break; } } CRASSERT(thread); thread->inUse = GL_TRUE; if (!CRPACKSPU_IS_WDDM_CRHGSMI()) thread->id = crThreadID(); else thread->id = THREAD_OFFSET_MAGIC + i; thread->currentContext = NULL; thread->bInjectThread = GL_TRUE; thread->netServer.name = crStrdup(pack_spu.name); thread->netServer.buffer_size = 64 * 1024; packspuConnectToServer(&(thread->netServer) #if defined(VBOX_WITH_CRHGSMI) && defined(IN_GUEST) , pHgsmi #endif ); CRASSERT(thread->netServer.conn); CRASSERT(thread->packer == NULL); thread->packer = crPackNewContext(); CRASSERT(thread->packer); crPackInitBuffer(&(thread->buffer), crNetAlloc(thread->netServer.conn), thread->netServer.conn->buffer_size, thread->netServer.conn->mtu); thread->buffer.canBarf = thread->netServer.conn->Barf ? GL_TRUE : GL_FALSE; crPackSetBuffer( thread->packer, &thread->buffer ); crPackFlushFunc( thread->packer, packspuFlush ); crPackFlushArg( thread->packer, (void *) thread ); crPackSendHugeFunc( thread->packer, packspuHuge ); crPackSetContext( thread->packer ); crSetTSD(&_PackTSD, thread); pack_spu.numThreads++; } crUnlockMutex(&_PackMutex); if (CRPACKSPU_IS_WDDM_CRHGSMI()) { CRASSERT(thread->id - THREAD_OFFSET_MAGIC < RT_ELEMENTS(pack_spu.thread) && GET_THREAD_VAL_ID(thread->id) == thread); con = thread->id; } return con; } GLuint PACKSPU_APIENTRY packspu_VBoxPackGetInjectID(GLint con) { GLuint ret; crLockMutex(&_PackMutex); { ThreadInfo *thread = NULL; if (CRPACKSPU_IS_WDDM_CRHGSMI()) { if (!con) { crError("connection expected!"); return 0; } thread = GET_THREAD_VAL_ID(con); } else { CRASSERT(!con); thread = GET_THREAD_VAL(); } CRASSERT(thread && thread->netServer.conn && thread->netServer.conn->type==CR_VBOXHGCM); ret = thread->netServer.conn->u32ClientID; } crUnlockMutex(&_PackMutex); return ret; } void PACKSPU_APIENTRY packspu_VBoxPackSetInjectID(GLuint id) { crLockMutex(&_PackMutex); { GET_THREAD(thread); CRASSERT(thread && thread->netServer.conn && thread->netServer.conn->type==CR_VBOXHGCM && thread->bInjectThread); thread->netServer.conn->u32InjectClientID = id; } crUnlockMutex(&_PackMutex); } void PACKSPU_APIENTRY packspu_VBoxAttachThread() { #if 0 int i; GET_THREAD(thread); for (i=0; i<MAX_THREADS; ++i) { if (pack_spu.thread[i].inUse && thread==&pack_spu.thread[i] && thread->id==crThreadID()) { crError("2nd attach to same thread"); } } #endif crSetTSD(&_PackTSD, NULL); crStateVBoxAttachThread(&pack_spu.StateTracker); } void PACKSPU_APIENTRY packspu_VBoxDetachThread() { if (CRPACKSPU_IS_WDDM_CRHGSMI()) { crPackSetContext(NULL); crSetTSD(&_PackTSD, NULL); } else { int i; GET_THREAD(thread); if (thread) { crLockMutex(&_PackMutex); for (i=0; i<MAX_THREADS; ++i) { if (pack_spu.thread[i].inUse && thread==&pack_spu.thread[i] && thread->id==crThreadID() && thread->netServer.conn) { CRASSERT(pack_spu.numThreads>0); packspuFlush((void *) thread); if (pack_spu.thread[i].packer) { CR_LOCK_PACKER_CONTEXT(thread->packer); crPackSetContext(NULL); CR_UNLOCK_PACKER_CONTEXT(thread->packer); crPackDeleteContext(pack_spu.thread[i].packer); if (pack_spu.thread[i].buffer.pack) { crNetFree(pack_spu.thread[i].netServer.conn, pack_spu.thread[i].buffer.pack); pack_spu.thread[i].buffer.pack = NULL; } } crNetFreeConnection(pack_spu.thread[i].netServer.conn); if (pack_spu.thread[i].netServer.name) crFree(pack_spu.thread[i].netServer.name); pack_spu.numThreads--; /*note can't shift the array here, because other threads have TLS references to array elements*/ crMemZero(&pack_spu.thread[i], sizeof(ThreadInfo)); crSetTSD(&_PackTSD, NULL); if (i==pack_spu.idxThreadInUse) { for (i=0; i<MAX_THREADS; ++i) { if (pack_spu.thread[i].inUse) { pack_spu.idxThreadInUse=i; break; } } } break; } } for (i=0; i<CR_MAX_CONTEXTS; ++i) { ContextInfo *ctx = &pack_spu.context[i]; if (ctx->currentThread == thread) { CRASSERT(ctx->fAutoFlush); ctx->currentThread = NULL; } } crUnlockMutex(&_PackMutex); } } crStateVBoxDetachThread(&pack_spu.StateTracker); } void PACKSPU_APIENTRY packspu_VBoxPresentComposition(GLint win, const struct VBOXVR_SCR_COMPOSITOR * pCompositor, const struct VBOXVR_SCR_COMPOSITOR_ENTRY *pChangedEntry) { RT_NOREF(win, pCompositor, pChangedEntry); } void PACKSPU_APIENTRY packspu_StringMarkerGREMEDY(GLsizei len, const GLvoid *string) { RT_NOREF(len, string); }
10,417
852
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 // // Select the partons status 2 and 3 for MC Jet Flavour // Author: Attilio // Date: 10.10.2007 // //======================================================================= // user include files #include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Common/interface/Ref.h" //#include "DataFormats/Candidate/interface/CandidateFwd.h" //#include "DataFormats/HepMCCandidate/interface/GenParticleCandidate.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" #include "DataFormats/HepMCCandidate/interface/GenParticleFwd.h" #include <memory> #include <string> #include <iostream> #include <vector> using namespace std; using namespace reco; using namespace edm; class PartonSelector : public edm::global::EDProducer<> { public: PartonSelector(const edm::ParameterSet&); ~PartonSelector() override; private: void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; bool withLeptons; // Optionally specify leptons bool withTop; // Optionally include top quarks in the list bool acceptNoDaughters; // Parton with zero daugthers are not considered by default, make it configurable unsigned int skipFirstN; // Default skips first 6 particles, make it configurable edm::EDGetTokenT<reco::GenParticleCollection> tokenGenParticles_; // input collection }; //========================================================================= PartonSelector::PartonSelector(const edm::ParameterSet& iConfig) { produces<reco::GenParticleRefVector>(); withLeptons = iConfig.getParameter<bool>("withLeptons"); tokenGenParticles_ = consumes<reco::GenParticleCollection>(iConfig.getParameter<edm::InputTag>("src")); if (iConfig.exists("acceptNoDaughters")) { acceptNoDaughters = iConfig.getParameter<bool>("acceptNoDaughters"); } else { acceptNoDaughters = false; } if (iConfig.exists("skipFirstN")) { skipFirstN = iConfig.getParameter<unsigned int>("skipFirstN"); } else { skipFirstN = 6; } if (iConfig.exists("withTop")) { withTop = iConfig.getParameter<bool>("withTop"); } else { withTop = false; } } //========================================================================= PartonSelector::~PartonSelector() {} // ------------ method called to produce the data ------------ void PartonSelector::produce(StreamID, Event& iEvent, const EventSetup& iEs) const { //edm::Handle <reco::CandidateView> particles; edm::Handle<reco::GenParticleCollection> particles; iEvent.getByToken(tokenGenParticles_, particles); edm::LogVerbatim("PartonSelector") << "=== GenParticle size:" << particles->size(); int nPart = 0; auto thePartons = std::make_unique<GenParticleRefVector>(); for (size_t m = 0; m < particles->size(); m++) { // Don't take into account first 6 particles in generator list if (m < skipFirstN) continue; const GenParticle& aParticle = (*particles)[m]; bool isAParton = false; bool isALepton = false; int flavour = abs(aParticle.pdgId()); if (flavour == 1 || flavour == 2 || flavour == 3 || flavour == 4 || flavour == 5 || (flavour == 6 && withTop) || flavour == 21) isAParton = true; if (flavour == 11 || flavour == 12 || flavour == 13 || flavour == 14 || flavour == 15 || flavour == 16) isALepton = true; //Add Partons status 3 if (aParticle.status() == 3 && isAParton) { thePartons->push_back(GenParticleRef(particles, m)); nPart++; } //Add Partons status 2 int nparton_daughters = 0; if ((aParticle.numberOfDaughters() > 0 || acceptNoDaughters) && isAParton) { for (unsigned int i = 0; i < aParticle.numberOfDaughters(); i++) { int daughterFlavour = abs(aParticle.daughter(i)->pdgId()); if ((daughterFlavour == 1 || daughterFlavour == 2 || daughterFlavour == 3 || daughterFlavour == 4 || daughterFlavour == 5 || daughterFlavour == 6 || daughterFlavour == 21)) { nparton_daughters++; } } if (nparton_daughters == 0) { nPart++; thePartons->push_back(GenParticleRef(particles, m)); } } //Add Leptons // Here you have to decide what to do with taus.... // Now all leptons, including e and mu from leptonic tau decays, are added if (withLeptons && aParticle.status() == 3 && isALepton) { thePartons->push_back(GenParticleRef(particles, m)); nPart++; } } edm::LogVerbatim("PartonSelector") << "=== GenParticle selected:" << nPart; iEvent.put(std::move(thePartons)); } DEFINE_FWK_MODULE(PartonSelector);
1,769
3,301
<reponame>queyuexzy/Alink<filename>core/src/main/java/com/alibaba/alink/params/huge/HasNumCheckpoint.java package com.alibaba.alink.params.huge; import org.apache.flink.ml.api.misc.param.ParamInfo; import org.apache.flink.ml.api.misc.param.ParamInfoFactory; import org.apache.flink.ml.api.misc.param.WithParams; public interface HasNumCheckpoint<T> extends WithParams <T> { ParamInfo <Integer> NUM_CHECKPOINT = ParamInfoFactory .createParamInfo("numCheckpoint", Integer.class) .setDescription("The number of checkpoint") .setHasDefaultValue(1) .setAlias(new String[] {"checkPointSize"}) .build(); default Integer getNumCheckpoint() { return get(NUM_CHECKPOINT); } default T setNumCheckpoint(Integer value) { return set(NUM_CHECKPOINT, value); } }
273
769
#ifndef __SDCARD_SDIO_H #define __SDCARD_SDIO_H #include "stm32l4xx.h" #include "gpio.h" // Enable usage of SDIO 4-bit bus // 0 - use 1-bit bus // 1 - use 4-bit bus #define SDIO_USE_4BIT 1 // Enable usage of DMA transfers // 0 - no DMA-related code // 1 - use DMA-related code #define SDIO_USE_DMA 1 #if (SDIO_USE_DMA) #include "dma.h" // Handle for SDIO DMA channel DMA_HandleTypeDef SDIO_DMA_CH; // SDIO DMA channel parameters #define SDIO_DMA_CHANNEL DMA2_Channel4 // 4 or 5 #define SDIO_DMA_REQUEST DMA_REQUEST_7 // SDIO DMA channel direction #define SDIO_DMA_DIR_TX DMA_DIR_M2P // SDIO write #define SDIO_DMA_DIR_RX DMA_DIR_P2M // SDIO read #endif // SDIO_USE_DMA // SDIO HAL #define SDIO_GPIO_PERIPH (RCC_AHB2ENR_GPIOCEN | RCC_AHB2ENR_GPIODEN) #define SDIO_GPIO_AF GPIO_AF12 // SDIO CMD pin (PD2) #define SDIO_GPIO_CMD_PORT GPIOD #define SDIO_GPIO_CMD_PIN GPIO_PIN_2 #define SDIO_GPIO_CMD_SRC GPIO_PinSource2 // SDIO CK pin (PC12) #define SDIO_GPIO_CK_PORT GPIOC #define SDIO_GPIO_CK_PIN GPIO_PIN_12 #define SDIO_GPIO_CK_SRC GPIO_PinSource12 // SDIO D0 pin (PC8) #define SDIO_GPIO_D0_PORT GPIOC #define SDIO_GPIO_D0_PIN GPIO_PIN_8 #define SDIO_GPIO_D0_SRC GPIO_PinSource8 #if (SDIO_USE_4BIT) // SDIO D1 pin (PC9) #define SDIO_GPIO_D1_PORT GPIOC #define SDIO_GPIO_D1_PIN GPIO_PIN_9 #define SDIO_GPIO_D1_SRC GPIO_PinSource9 // SDIO D2 pin (PC10) #define SDIO_GPIO_D2_PORT GPIOC #define SDIO_GPIO_D2_PIN GPIO_PIN_10 #define SDIO_GPIO_D2_SRC GPIO_PinSource10 // SDIO D3 pin (PC11) #define SDIO_GPIO_D3_PORT GPIOC #define SDIO_GPIO_D3_PIN GPIO_PIN_11 #define SDIO_GPIO_D3_SRC GPIO_PinSource11 #endif // SDIO_USE_4BIT #ifdef STM32L1XX_HD // Alias word address of bits of the SDIO DCTRL register #define SDIO_DCTRL_OFFSET ((uint32_t)(&(SDMMC1->DCTRL)) - PERIPH_BASE) #define SDIO_DCTRL_DTEN_BN 0U // DTEN #define SDIO_DCTRL_DTEN_BB *(__IO uint32_t *)(PERIPH_BB_BASE + (SDMMC_DCTRL_OFFSET << 5) + (SDMMC_DCTRL_DTEN_BN << 2)) // Alias word address of bits of the SDIO CLKCR register #define SDIO_CLKCR_OFFSET ((uint32_t)(&(SDMMC1->CLKCR)) - PERIPH_BASE) #define SDIO_CLKCR_CLKEN_BN 8U // CLKEN #define SDIO_CLKCR_CLKEN_BB *(__IO uint32_t *)(PERIPH_BB_BASE + (SDMMC_CLKCR_OFFSET << 5) + (SDMMC_CLKCR_CLKEN_BN << 2)) #endif // STM32L1XX_HD // SDIO power supply control bits #define SD_PWR_OFF ((uint32_t)0x00000000U) // Power off: the clock to card is stopped #define SD_PWR_ON (SDMMC_POWER_PWRCTRL) // Power on: the card is clocked // SDIO clock divider #define SD_CLK_DIV_400K ((uint32_t)0x00000076U) // SDIO clock 400kHz (48MHz / (0x76 + 2) = 400kHz) #define SD_CLK_DIV_1M ((uint32_t)0x0000002EU) // SDIO clock 1MHz (48MHz / (0x2e + 2) = 1MHz) #define SD_CLK_DIV_2M ((uint32_t)0x00000016U) // SDIO clock 2MHz (48MHz / (0x16 + 2) = 2MHz) #define SD_CLK_DIV_4M ((uint32_t)0x0000000AU) // SDIO clock 4MHz (48MHz / (0x0a + 2) = 4MHz) #define SD_CLK_DIV_6M85 ((uint32_t)0x00000005U) // SDIO clock 6.85MHz (48MHz / (0x05 + 2) = 6.85MHz) #define SD_CLK_DIV_8M ((uint32_t)0x00000004U) // SDIO clock 8MHz (48MHz / (0x04 + 2) = 8MHz) #define SD_CLK_DIV_9M6 ((uint32_t)0x00000003U) // SDIO clock 9.6MHz (48MHz / (0x03 + 2) = 9.6MHz) #define SD_CLK_DIV_12M ((uint32_t)0x00000002U) // SDIO clock 12MHz (48MHz / (0x02 + 2) = 12MHz) #define SD_CLK_DIV_16M ((uint32_t)0x00000001U) // SDIO clock 16MHz (48MHz / (0x01 + 2) = 16MHz) #define SD_CLK_DIV_24M ((uint32_t)0x00000000U) // SDIO clock 24MHz (48MHz / (0x00 + 2) = 24MHz) // SDIO clocks for initialization and data transfer #define SD_CLK_DIV_INIT (SD_CLK_DIV_400K) // SDIO initialization frequency (400kHz) //#define SD_CLK_DIV_TRAN (SD_CLK_DIV_400K) // SDIO data transfer 400kHz //#define SD_CLK_DIV_TRAN (SD_CLK_DIV_1M) // SDIO data transfer 1MHz //#define SD_CLK_DIV_TRAN (SD_CLK_DIV_8M) // SDIO data transfer 8MHz //#define SD_CLK_DIV_TRAN (SD_CLK_DIV_9M6) // SDIO data transfer 9.6MHz //#define SD_CLK_DIV_TRAN (SD_CLK_DIV_12M) // SDIO data transfer 12MHz //#define SD_CLK_DIV_TRAN (SD_CLK_DIV_16M) // SDIO data transfer 16MHz #define SD_CLK_DIV_TRAN (SD_CLK_DIV_24M) // SDIO data transfer frequency // SDIO CMD response type #define SD_RESP_NONE ((uint32_t)0x00000000U) // No response #define SD_RESP_SHORT (SDMMC_CMD_WAITRESP_0) // Short response #define SD_RESP_LONG (SDMMC_CMD_WAITRESP) // Long response // SD commands index #define SD_CMD_GO_IDLE_STATE ((uint8_t)0U) #define SD_CMD_SEND_OP_COND ((uint8_t)1U) // MMC only #define SD_CMD_ALL_SEND_CID ((uint8_t)2U) // Not supported in SPI mode #define SD_CMD_SEND_REL_ADDR ((uint8_t)3U) // Not supported in SPI mode #define SD_CMD_SWITCH_FUNC ((uint8_t)6U) #define SD_CMD_SEL_DESEL_CARD ((uint8_t)7U) // Not supported in SPI mode #define SD_CMD_HS_SEND_EXT_CSD ((uint8_t)8U) #define SD_CMD_SEND_CSD ((uint8_t)9U) #define SD_CMD_SEND_CID ((uint8_t)10U) #define SD_CMD_READ_DAT_UNTIL_STOP ((uint8_t)11U) // Not supported in SPI mode #define SD_CMD_STOP_TRANSMISSION ((uint8_t)12U) #define SD_CMD_SEND_STATUS ((uint8_t)13U) #define SD_CMD_GO_INACTIVE_STATE ((uint8_t)15U) // Not supported in SPI mode #define SD_CMD_SET_BLOCKLEN ((uint8_t)16U) #define SD_CMD_READ_SINGLE_BLOCK ((uint8_t)17U) #define SD_CMD_READ_MULT_BLOCK ((uint8_t)18U) #define SD_CMD_WRITE_DAT_UNTIL_STOP ((uint8_t)20U) // Not supported in SPI mode #define SD_CMD_WRITE_BLOCK ((uint8_t)24U) #define SD_CMD_WRITE_MULTIPLE_BLOCK ((uint8_t)25U) #define SD_CMD_PROG_CSD ((uint8_t)27U) #define SD_CMD_SET_WRITE_PROT ((uint8_t)28U) // Not supported in SPI mode #define SD_CMD_CLR_WRITE_PROT ((uint8_t)29U) // Not supported in SPI mode #define SD_CMD_SEND_WRITE_PROT ((uint8_t)30U) // Not supported in SPI mode #define SD_CMD_ERASE ((uint8_t)38U) #define SD_CMD_LOCK_UNLOCK ((uint8_t)42U) #define SD_CMD_APP_CMD ((uint8_t)55U) #define SD_CMD_READ_OCR ((uint8_t)58U) // Read OCR register #define SD_CMD_CRC_ON_OFF ((uint8_t)59U) // On/Off CRC check by SD Card (in SPI mode) // Following commands are SD Card Specific commands. // SD_CMD_APP_CMD should be sent before sending these commands. #define SD_CMD_SET_BUS_WIDTH ((uint8_t)6U) // ACMD6 #define SD_CMD_SD_SEND_OP_COND ((uint8_t)41U) // ACMD41 #define SD_CMD_SET_CLR_CARD_DETECT ((uint8_t)42U) // ACMD42 #define SD_CMD_SEND_SCR ((uint8_t)51U) // ACMD51 // Pattern for R6 response #define SD_CHECK_PATTERN ((uint32_t)0x000001AAU) // R6 response error bits #define SD_R6_GENERAL_UNKNOWN_ERROR ((uint32_t)0x00002000U) #define SD_R6_ILLEGAL_CMD ((uint32_t)0x00004000U) #define SD_R6_COM_CRC_FAILED ((uint32_t)0x00008000U) // Argument for ACMD41 to select voltage window #define SD_OCR_VOLTAGE ((uint32_t)0x80100000U) // Mask for errors in card status value #define SD_OCR_ALL_ERRORS ((uint32_t)0xFDFFE008U) // All possible error bits #define SD_OCR_OUT_OF_RANGE ((uint32_t)0x80000000U) // The command's argument was out of allowed range #define SD_OCR_ADDRESS_ERROR ((uint32_t)0x40000000U) // A misaligned address used in the command #define SD_OCR_BLOCK_LEN_ERROR ((uint32_t)0x20000000U) // The transfer block length is not allowed for this card #define SD_OCR_ERASE_SEQ_ERROR ((uint32_t)0x10000000U) // An error in the sequence of erase commands occurred #define SD_OCR_ERASE_PARAM ((uint32_t)0x08000000U) // An invalid selection of write-blocks for erase occurred #define SD_OCR_WP_VIOLATION ((uint32_t)0x04000000U) // Attempt to write to a protected block or to the write protected card #define SD_OCR_LOCK_UNLOCK_FAILED ((uint32_t)0x01000000U) // Sequence or password error in lock/unlock card command #define SD_OCR_COM_CRC_ERROR ((uint32_t)0x00800000U) // The CRC check of the previous command failed #define SD_OCR_ILLEGAL_COMMAND ((uint32_t)0x00400000U) // Command not legal for the card state #define SD_OCR_CARD_ECC_FAILED ((uint32_t)0x00200000U) // Card internal ECC was applied but failed to correct the data #define SD_OCR_CC_ERROR ((uint32_t)0x00100000U) // Internal card controller error #define SD_OCR_ERROR ((uint32_t)0x00080000U) // A general or an unknown error occurred during the operation #define SD_OCR_STREAM_R_UNDERRUN ((uint32_t)0x00040000U) // The card could not sustain data transfer in stream read operation #define SD_OCR_STREAM_W_OVERRUN ((uint32_t)0x00020000U) // The card could not sustain data programming in stream mode #define SD_OCR_CSD_OVERWRITE ((uint32_t)0x00010000U) // CSD overwrite error #define SD_OCR_WP_ERASE_SKIP ((uint32_t)0x00008000U) // Only partial address space was erased #define SD_OCR_CARD_ECC_DISABLED ((uint32_t)0x00004000U) // The command has been executed without using the internal ECC #define SD_OCR_ERASE_RESET ((uint32_t)0x00002000U) // An erase sequence was cleared before executing #define SD_OCR_AKE_SEQ_ERROR ((uint32_t)0x00000008U) // Error in the sequence of the authentication process // Card state (OCR[12:9] bits CURRENT_STATE) #define SD_STATE_IDLE ((uint8_t)0x00U) // Idle #define SD_STATE_READY ((uint8_t)0x01U) // Ready #define SD_STATE_IDENT ((uint8_t)0x02U) // Identification #define SD_STATE_STBY ((uint8_t)0x03U) // Stand-by #define SD_STATE_TRAN ((uint8_t)0x04U) // Transfer #define SD_STATE_DATA ((uint8_t)0x05U) // Sending data #define SD_STATE_RCV ((uint8_t)0x06U) // Receive data #define SD_STATE_PRG ((uint8_t)0x07U) // Programming #define SD_STATE_DIS ((uint8_t)0x08U) // Disconnect #define SD_STATE_ERROR ((uint8_t)0xFFU) // Error or unknown state // Mask for ACMD41 #define SD_STD_CAPACITY ((uint32_t)0x00000000U) #define SD_HIGH_CAPACITY ((uint32_t)0x40000000U) // Timeout for CMD0 or CMD8 #define SD_CMD_TIMEOUT ((uint32_t)0x00010000U) // SDIO timeout for data transfer ((48MHz / CLKDIV / 1000) * timeout_ms) #define SD_DATA_R_TIMEOUT ((uint32_t)((48000000U / (SD_CLK_DIV_TRAN + 2U) / 1000U) * 100U)) // Data read timeout is 100ms #define SD_DATA_W_TIMEOUT ((uint32_t)((48000000U / (SD_CLK_DIV_TRAN + 2U) / 1000U) * 250U)) // Date write timeout is 250ms // Trials count for ACMD41 #define SD_ACMD41_TRIALS ((uint32_t)0x0000FFFFU) // Bitmap to clear the SDIO command flags #define SDIO_ICR_CMD ((uint32_t)(SDMMC_ICR_CCRCFAILC | SDMMC_ICR_CTIMEOUTC | \ SDMMC_ICR_CMDRENDC | SDMMC_ICR_CMDSENTC)) // Bitmap to clear the SDIO data flags #define SDIO_ICR_DATA ((uint32_t)(SDMMC_ICR_RXOVERRC | SDMMC_ICR_DCRCFAILC | \ SDMMC_ICR_DTIMEOUTC | SDMMC_ICR_DBCKENDC | \ SDMMC_ICR_STBITERRC)) // Bitmap to clear the SDIO static flags (command and data) #define SDIO_ICR_STATIC ((uint32_t)(SDMMC_ICR_CCRCFAILC | SDMMC_ICR_DCRCFAILC | SDMMC_ICR_CTIMEOUTC | \ SDMMC_ICR_DTIMEOUTC | SDMMC_ICR_TXUNDERRC | SDMMC_ICR_RXOVERRC | \ SDMMC_ICR_CMDRENDC | SDMMC_ICR_CMDSENTC | SDMMC_ICR_DATAENDC | \ SDMMC_ICR_DBCKENDC)) // SDIO bus width #define SD_BUS_1BIT ((uint32_t)0x00000000U) // 1-bit wide bus (SDIO_D0 used) #define SD_BUS_4BIT (SDMMC_CLKCR_WIDBUS_0) // 4-bit wide bus (SDIO_D[3:0] used) #define SD_BUS_8BIT (SDMMC_CLKCR_WIDBUS_1) // 8-bit wide bus (SDIO_D[7:0] used) // SDIO transfer flags #define SDIO_XFER_COMMON_FLAGS (SDMMC_STA_DTIMEOUT | SDMMC_STA_DCRCFAIL | SDMMC_STA_STBITERR) // SDIO flags for single block receive #define SDIO_RX_SB_FLAGS (SDIO_XFER_COMMON_FLAGS | SDMMC_STA_DBCKEND | SDMMC_STA_RXOVERR) // SDIO flags for multiple block receive #define SDIO_RX_MB_FLAGS (SDIO_XFER_COMMON_FLAGS | SDMMC_STA_DATAEND | SDMMC_STA_RXOVERR) // SDIO flags for single block transmit #define SDIO_TX_SB_FLAGS (SDIO_XFER_COMMON_FLAGS | SDMMC_STA_DBCKEND | SDMMC_STA_TXUNDERR) // SDIO flags for multiple block transmit #define SDIO_TX_MB_FLAGS (SDIO_XFER_COMMON_FLAGS | SDMMC_STA_DATAEND | SDMMC_STA_TXUNDERR) // SDIO transfer error flags #define SDIO_XFER_ERROR_FLAGS (SDIO_XFER_COMMON_FLAGS | SDMMC_STA_TXUNDERR | SDMMC_STA_RXOVERR) // RCA for the MMC card #define SDIO_MMC_RCA ((uint16_t)0x0001U) // SD card response type enum { SD_R1 = 0x01, // R1 SD_R1b = 0x02, // R1b SD_R2 = 0x03, // R2 SD_R3 = 0x04, // R3 SD_R6 = 0x05, // R6 (SDIO only) SD_R7 = 0x06 // R7 }; // Card type enum { SDCT_UNKNOWN = 0x00, SDCT_SDSC_V1 = 0x01, // Standard capacity SD card v1.0 SDCT_SDSC_V2 = 0x02, // Standard capacity SD card v2.0 SDCT_MMC = 0x03, // MMC SDCT_SDHC = 0x04 // High capacity SD card (SDHC or SDXC) }; // SD functions result typedef enum { SDR_Success = 0x00, SDR_Timeout = 0x01, // Timeout SDR_CRCError = 0x02, // Response for command received but CRC check failed SDR_ReadError = 0x03, // Read block error (response for CMD17) SDR_WriteError = 0x04, // Write block error (response for CMD24) SDR_WriteErrorInternal = 0x05, // Write block error due to internal card error SDR_Unsupported = 0x06, // Unsupported card found SDR_BadResponse = 0x07, SDR_SetBlockSizeFailed = 0x08, // Set block size command failed (response for CMD16) SDR_UnknownCard = 0x09, SDR_NoResponse = 0x0A, SDR_AddrOutOfRange = 0x0B, // Address out of range SDR_WriteCRCError = 0x0C, // Data write rejected due to a CRC error SDR_InvalidVoltage = 0x0D, // Unsupported voltage range SDR_DataTimeout = 0x0E, // Data block transfer timeout SDR_DataCRCFail = 0x0F, // Data block transfer CRC failed SDR_RXOverrun = 0x10, // Receive FIFO overrun SDR_TXUnderrun = 0x11, // Transmit FIFO underrun SDR_StartBitError = 0x12, // Start bit not detected on all data signals SDR_AddrMisaligned = 0x13, // A misaligned address which did not match the block length was used in the command SDR_BlockLenError = 0x14, // The transfer block length is not allowed for this card SDR_EraseSeqError = 0x15, // An error in the sequence of erase commands occurred SDR_EraseParam = 0x16, // An invalid selection of write-blocks for erase occurred SDR_WPViolation = 0x17, // Attempt to write to a protected block or to the write protected card SDR_LockUnlockFailed = 0x18, // Error in lock/unlock command SDR_ComCRCError = 0x19, // The CRC check of the previous command failed SDR_IllegalCommand = 0x1A, // Command is not legal for the the current card state SDR_CardECCFailed = 0x1B, // Card internal ECC was applied but failed to correct the data SDR_CCError = 0x1C, // Internal card controller error SDR_GeneralError = 0x1D, // A general or an unknown error occurred during the operation SDR_StreamUnderrun = 0x1E, // The card could not sustain data transfer in stream read operation SDR_StreamOverrun = 0x1F, // The card could not sustain data programming in stream mode SDR_CSDOverwrite = 0x20, // CSD overwrite error SDR_WPEraseSkip = 0x21, // Only partial address space was erased SDR_ECCDisabled = 0x22, // The command has been executed without using the internal ECC SDR_EraseReset = 0x23, // An erase sequence was cleared before executing SDR_AKESeqError = 0x24, // Error in the sequence of the authentication process SDR_UnknownError = 0xFF // Unknown error } SDResult; // SD card description typedef struct { uint8_t Type; // Card type (detected by SD_Init()) uint32_t Capacity; // Card capacity (MBytes for SDHC/SDXC, bytes otherwise) uint32_t BlockCount; // SD card blocks count uint32_t BlockSize; // SD card block size (bytes), determined in SD_ReadCSD() uint32_t MaxBusClkFreq; // Maximum card bus frequency (MHz) uint8_t CSDVer; // SD card CSD register version uint16_t RCA; // SD card RCA address (only for SDIO) uint8_t MID; // SD card manufacturer ID uint16_t OID; // SD card OEM/Application ID uint8_t PNM[5]; // SD card product name (5-character ASCII string) uint8_t PRV; // SD card product revision (two BCD digits: '6.2' will be 01100010b) uint32_t PSN; // SD card serial number uint16_t MDT; // SD card manufacturing date uint8_t CSD[16]; // SD card CSD register (card structure data) uint8_t CID[16]; // SD card CID register (card identification number) uint8_t SCR[8]; // SD card SCR register (SD card configuration) } SDCard_TypeDef; // Exported variables // SD card parameters extern SDCard_TypeDef SDCard; // Public functions and macros #ifndef __GNUC__ // Change an endianess of unsigned long integer (uint32_t) #define SWAP_UINT32(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | ((x) << 24)) #endif // Function prototypes void SD_GPIO_Init(void); void SD_GPIO_DeInit(void); void SD_SDIO_Init(void); void SD_SDIO_DeInit(void); SDResult SD_SetBlockSize(uint32_t block_size); SDResult SD_Init(void); SDResult SD_SetBusWidth(uint32_t BW); void SD_SetBusClock(uint32_t clk_div); void SD_GetCardInfo(void); SDResult SD_HighSpeed(void); SDResult SD_StopTransfer(void); SDResult SD_GetCardStatus(uint8_t *pStatus); SDResult SD_ReadBlock(uint32_t addr, uint32_t *pBuf, uint32_t len); SDResult SD_WriteBlock(uint32_t addr, uint32_t *pBuf, uint32_t length); #if (SDIO_USE_DMA) void SD_Configure_DMA(uint32_t *pBuf, uint32_t length, uint8_t direction); SDResult SD_ReadBlock_DMA(uint32_t addr, uint32_t *pBuf, uint32_t length); SDResult SD_WriteBlock_DMA(uint32_t addr, uint32_t *pBuf, uint32_t length); SDResult SD_CheckRead(uint32_t length); SDResult SD_CheckWrite(uint32_t length); #endif // SDIO_USE_DMA #endif // __SDCARD_SDIO_H
9,326
852
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms from L1Trigger.L1THGCal.hgcalTriggerGeometryESProducer_cfi import * from Validation.HGCalValidation.hgcalValidationTPG_cfi import * runHGCALValidationTPG = cms.Sequence(hgcalTrigPrimValidation)
97
835
/* * Copyright (C) 2015 Twitter, 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 com.twitter.sdk.android.mopub; import android.graphics.Color; final class ColorUtils { private static final int RGB_TOTAL_COLORS = 256; private static final float DEFAULT_LIGHTNESS_THRESHOLD = .6f; private static final float ON_TAP_LIGHTNESS_THRESHOLD = .3f; private static final float CTA_ON_TAP_DARKNESS_FACTOR = 0.1f; private static final float CTA_ON_TAP_LIGHTNESS_FACTOR = 0.2f; private static final float CTA_TEXT_LIGHTNESS_FACTOR = .6f; private static final int OPAQUE_ALPHA = Math.round(255 * 1.0f); private static final int TRANSPARENT_ALPHA = Math.round(255 * 0.9f); private static final int COLOR_FULLY_WHITE = Math.round(255 * 1.0f); private static final int COLOR_PARTIALLY_BLACK = Math.round(255 * 0.4f); private ColorUtils() {} public static int calculateCtaTextColor(final int ctaBackgroundColor) { if (isLightColor(ctaBackgroundColor)) { return calculateDarkerColor(ctaBackgroundColor, CTA_TEXT_LIGHTNESS_FACTOR); } else { return Color.WHITE; } } public static int calculateCtaOnTapColor(final int ctaBackgroundColor) { if (isLightColor(ctaBackgroundColor, ON_TAP_LIGHTNESS_THRESHOLD)) { return calculateDarkerColor(ctaBackgroundColor, CTA_ON_TAP_DARKNESS_FACTOR); } else { return calculateLighterColor(ctaBackgroundColor, CTA_ON_TAP_LIGHTNESS_FACTOR); } } public static boolean isLightColor(final int color) { return isLightColor(color, DEFAULT_LIGHTNESS_THRESHOLD); } /** * This method calculates a darker color provided a factor of reduction in lightness. * * @param color The original color value * @param factor Factor of lightness reduction, range can be between 0 - 1.0 * @return The calculated darker color */ public static int calculateDarkerColor(final int color, final float factor) { final int a = Color.alpha(color); final int r = Color.red(color); final int g = Color.green(color); final int b = Color.blue(color); final int lightnessLevel = Math.round(RGB_TOTAL_COLORS * factor); return Color.argb(a, Math.max(r - lightnessLevel, 0), Math.max(g - lightnessLevel, 0), Math.max(b - lightnessLevel, 0)); } /** * This method calculates a lighter color provided a factor of increase in lightness. * * @param color A color value * @param factor Factor of increase in lightness, range can be between 0 - 1.0 * @return The calculated darker color */ public static int calculateLighterColor(final int color, final float factor) { final int a = Color.alpha(color); final int r = Color.red(color); final int g = Color.green(color); final int b = Color.blue(color); final int lightnessLevel = Math.round(RGB_TOTAL_COLORS * factor); return Color.argb(a, Math.min(r + lightnessLevel, 255), Math.min(g + lightnessLevel, 255), Math.min(b + lightnessLevel, 255)); } /** * This method calculates the suitable contrasting color that is viewable. * * @param color A color value. * @return The calculated contrasting color that is viewable. */ public static int calculateContrastingColor(final int color) { final boolean isLightColor = isLightColor(color); final int alpha = isLightColor ? OPAQUE_ALPHA : TRANSPARENT_ALPHA; final int rgbColor = isLightColor ? COLOR_PARTIALLY_BLACK : COLOR_FULLY_WHITE; return Color.argb(alpha, rgbColor, rgbColor, rgbColor); } /** * This method uses HSL to determine in a human eyesight terms if a color is light or not. * See: http://en.wikipedia.org/wiki/HSL_and_HSV. The threshold values are from ITU Rec. 709 * http://en.wikipedia.org/wiki/Rec._709#Luma_coefficients * * * @param color A color value * @param factor A factor of lightness measured between 0-1.0 * @return Whether or not the color is considered light */ public static boolean isLightColor(final int color, final float factor) { final int r = Color.red(color); final int g = Color.green(color); final int b = Color.blue(color); final double threshold = 0.21 * r + 0.72 * g + 0.07 * b; return threshold > (RGB_TOTAL_COLORS * factor); } }
1,923
856
// // Copyright © 2021 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <backendsCommon/Workload.hpp> #include <arm_compute/runtime/CL/functions/CLReductionOperation.h> namespace armnn { arm_compute::Status ClReduceWorkloadValidate(const TensorInfo& input, const TensorInfo& output, const ReduceDescriptor& descriptor); class ClReduceWorkload : public BaseWorkload<ReduceQueueDescriptor> { public: ClReduceWorkload(const ReduceQueueDescriptor& descriptor, const WorkloadInfo& info); void Execute() const override; private: mutable arm_compute::CLReductionOperation m_Layer; }; } //namespace armnn
308
601
<filename>datasets/phrasecut_eval.py # Copyright (c) <NAME> & <NAME>. Licensed under the Apache License 2.0. All Rights Reserved import os from collections import defaultdict from typing import Dict, List import util.dist as dist from .phrasecut_utils.evaluator import Evaluator from .phrasecut_utils.refvg_loader import RefVGLoader from .phrasecut_utils.subset import PhraseCutSubsets class PhrasecutEvaluator(object): def __init__(self, split, ann_folder, output_dir="phrasecut_eval", eval_mask=False): subset = PhraseCutSubsets(ann_folder) loader = RefVGLoader(ann_folder, subset, split=split) if dist.is_main_process(): if not os.path.exists(output_dir): os.mkdir(output_dir) self.output_dir = output_dir self.evaluator = Evaluator(loader, summary_path=output_dir) self.eval_mask = eval_mask self.predictions = [] def update(self, predictions): self.predictions += predictions def synchronize_between_processes(self): all_predictions = dist.all_gather(self.predictions) merged_predictions = [] for p in all_predictions: merged_predictions += p self.predictions = merged_predictions def summarize(self): if dist.is_main_process(): imgid2pred: Dict[str, List] = defaultdict(list) for p in self.predictions: imgid2pred[p["original_id"]].append(p) for img_id, pred in imgid2pred.items(): im_pred_dict = {p["task_id"]: p for p in pred} self.evaluator.eval_single_img( img_id, im_pred_dict, pred_mask_tag="masks" if self.eval_mask else None, pred_boxes_tag="boxes", verbose=False, ) mask_box = ["box"] if self.eval_mask: mask_box.append("mask") results = self.evaluator.analyze_stats(mask_box, exp_name_in_summary=None, save_result_to_path=None) results = results["all"]["pred_box_acc"] return {f"Precision@{k}": v for k, v in results.items()} return None
1,015
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Courtefontaine","circ":"3ème circonscription","dpt":"Doubs","inscrits":195,"abs":89,"votants":106,"blancs":14,"nuls":6,"exp":86,"res":[{"nuance":"LR","nom":"<NAME>","voix":61},{"nuance":"REM","nom":"M. <NAME>","voix":25}]}
110
564
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.toolkit.oasv.diffvalidation.skeleton.schema; import org.apache.servicecomb.toolkit.oasv.diffvalidation.api.*; import org.apache.servicecomb.toolkit.oasv.common.OasObjectPropertyLocation; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ComposedSchema; import io.swagger.v3.oas.models.media.Schema; import java.util.ArrayList; import java.util.List; import static org.apache.servicecomb.toolkit.oasv.diffvalidation.util.OasObjectDiffValidatorUtils.*; import static org.apache.servicecomb.toolkit.oasv.common.OasObjectType.SCHEMA; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; /** * Schema object difference validator engine. * It does validation recursively */ public class SchemaDiffValidatorEngine extends OasObjectDiffValidatorTemplate<Schema> implements SchemaDiffValidator { private final List<SchemaAddValidator> schemaAddValidators; private final List<SchemaDelValidator> schemaDelValidators; private final List<SchemaCompareValidator> schemaCompareValidators; public SchemaDiffValidatorEngine( List<SchemaAddValidator> schemaAddValidators, List<SchemaDelValidator> schemaDelValidators, List<SchemaCompareValidator> schemaCompareValidators) { this.schemaAddValidators = new ArrayList<>(schemaAddValidators); this.schemaDelValidators = new ArrayList<>(schemaDelValidators); this.schemaCompareValidators = new ArrayList<>(schemaCompareValidators); } @Override protected List<OasDiffViolation> validateAdd(OasDiffValidationContext context, OasObjectPropertyLocation rightLocation, Schema rightOasObject) { return schemaAddValidators .stream() .map(v -> v.validate(context, rightLocation, rightOasObject)) .flatMap(list -> list.stream()) .collect(toList()); } @Override protected List<OasDiffViolation> validateDel(OasDiffValidationContext context, OasObjectPropertyLocation leftLocation, Schema leftOasObject) { return schemaDelValidators .stream() .map(v -> v.validate(context, leftLocation, leftOasObject)) .flatMap(list -> list.stream()) .collect(toList()); } @Override protected List<OasDiffViolation> validateCompare(OasDiffValidationContext context, OasObjectPropertyLocation leftLocation, Schema leftOasObject, OasObjectPropertyLocation rightLocation, Schema rightOasObject) { List<OasDiffViolation> violations = new ArrayList<>(); violations.addAll( schemaCompareValidators .stream() .map(v -> v.validate(context, leftLocation, leftOasObject, rightLocation, rightOasObject)) .flatMap(list -> list.stream()) .collect(toList()) ); violations.addAll( validateCompareOrdinary(context, leftLocation, leftOasObject, rightLocation, rightOasObject) ); violations.addAll( validateCompareArray(context, leftLocation, leftOasObject, rightLocation, rightOasObject) ); violations.addAll( validateCompareComposed(context, leftLocation, leftOasObject, rightLocation, rightOasObject) ); return violations; } private List<OasDiffViolation> validateCompareOrdinary(OasDiffValidationContext context, OasObjectPropertyLocation leftLocation, Schema leftOasObject, OasObjectPropertyLocation rightLocation, Schema rightOasObject) { return doDiffValidateMapProperty( context, "properties", leftLocation, leftOasObject.getProperties(), rightLocation, rightOasObject.getProperties(), SCHEMA, singletonList(this) ); } private List<OasDiffViolation> validateCompareArray(OasDiffValidationContext context, OasObjectPropertyLocation leftLocation, Schema leftOasObject, OasObjectPropertyLocation rightLocation, Schema rightOasObject) { Schema leftItems = null; OasObjectPropertyLocation leftItemsLocation = null; if (leftOasObject instanceof ArraySchema) { leftItems = ((ArraySchema) leftOasObject).getItems(); leftItemsLocation = leftLocation.property("items", SCHEMA); } Schema<?> rightItems = null; OasObjectPropertyLocation rightItemsLocation = null; if (rightOasObject instanceof ArraySchema) { rightItems = ((ArraySchema) rightOasObject).getItems(); rightItemsLocation = rightLocation.property("items", SCHEMA); } return doDiffValidateProperty( context, leftItemsLocation, leftItems, rightItemsLocation, rightItems, singletonList(this) ); } private List<OasDiffViolation> validateCompareComposed(OasDiffValidationContext context, OasObjectPropertyLocation leftLocation, Schema leftOasObject, OasObjectPropertyLocation rightLocation, Schema rightOasObject) { List<OasDiffViolation> violations = new ArrayList<>(); List<Schema> leftAllOf = null; List<Schema> leftOneOf = null; List<Schema> leftAnyOf = null; if (leftOasObject instanceof ComposedSchema) { leftAllOf = ((ComposedSchema) leftOasObject).getAllOf(); leftOneOf = ((ComposedSchema) leftOasObject).getOneOf(); leftAnyOf = ((ComposedSchema) leftOasObject).getAnyOf(); } List<Schema> rightAllOf = null; List<Schema> rightOneOf = null; List<Schema> rightAnyOf = null; if (rightOasObject instanceof ComposedSchema) { rightAllOf = ((ComposedSchema) rightOasObject).getAllOf(); rightOneOf = ((ComposedSchema) rightOasObject).getOneOf(); rightAnyOf = ((ComposedSchema) rightOasObject).getAnyOf(); } violations.addAll( doDiffValidateListProperty( context, "allOf", leftLocation, leftAllOf, rightLocation, rightAllOf, SCHEMA, schema -> System.identityHashCode(schema), singletonList(this) ) ); violations.addAll( doDiffValidateListProperty( context, "oneOf", leftLocation, leftOneOf, rightLocation, rightOneOf, SCHEMA, schema -> System.identityHashCode(schema), singletonList(this) ) ); violations.addAll( doDiffValidateListProperty( context, "anyOf", leftLocation, leftAnyOf, rightLocation, rightAnyOf, SCHEMA, schema -> System.identityHashCode(schema), singletonList(this) ) ); return violations; } }
2,559
3,084
<filename>biometrics/adapters/storage_adapter/StorageAdapter.cpp /*++ THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Copyright (c) Microsoft Corporation. All rights reserved Module Name: Storage.cpp Abstract: This module contains a stub implementation of a Storage Adapter plug-in for the Windows Biometric service. Author: - Environment: Win32, user mode only. Revision History: NOTES: (None) --*/ /////////////////////////////////////////////////////////////////////////////// // // Header files... // /////////////////////////////////////////////////////////////////////////////// #include "precomp.h" #include "winbio_adapter.h" #include "StorageAdapter.h" /////////////////////////////////////////////////////////////////////////////// // // Forward declarations for the Storage Adapter's interface routines... // /////////////////////////////////////////////////////////////////////////////// static HRESULT WINAPI StorageAdapterAttach( _Inout_ PWINBIO_PIPELINE Pipeline ); static HRESULT WINAPI StorageAdapterDetach( _Inout_ PWINBIO_PIPELINE Pipeline ); static HRESULT WINAPI StorageAdapterClearContext( _Inout_ PWINBIO_PIPELINE Pipeline ); static HRESULT WINAPI StorageAdapterCreateDatabase( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_UUID DatabaseId, _In_ WINBIO_BIOMETRIC_TYPE Factor, _In_ PWINBIO_UUID Format, _In_ LPCWSTR FilePath, _In_ LPCWSTR ConnectString, _In_ SIZE_T IndexElementCount, _In_ SIZE_T InitialSize ); static HRESULT WINAPI StorageAdapterEraseDatabase( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_UUID DatabaseId, _In_ LPCWSTR FilePath, _In_ LPCWSTR ConnectString ); static HRESULT WINAPI StorageAdapterOpenDatabase( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_UUID DatabaseId, _In_ LPCWSTR FilePath, _In_ LPCWSTR ConnectString ); static HRESULT WINAPI StorageAdapterCloseDatabase( _Inout_ PWINBIO_PIPELINE Pipeline ); static HRESULT WINAPI StorageAdapterGetDataFormat( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PWINBIO_UUID Format, _Out_ PWINBIO_VERSION Version ); static HRESULT WINAPI StorageAdapterGetDatabaseSize( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PSIZE_T AvailableRecordCount, _Out_ PSIZE_T TotalRecordCount ); static HRESULT WINAPI StorageAdapterAddRecord( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_STORAGE_RECORD RecordContents ); static HRESULT WINAPI StorageAdapterDeleteRecord( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_IDENTITY Identity, _In_ WINBIO_BIOMETRIC_SUBTYPE SubFactor ); static HRESULT WINAPI StorageAdapterQueryBySubject( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_IDENTITY Identity, _In_ WINBIO_BIOMETRIC_SUBTYPE SubFactor ); static HRESULT WINAPI StorageAdapterQueryByContent( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ WINBIO_BIOMETRIC_SUBTYPE SubFactor, _In_ ULONG IndexVector[], _In_ SIZE_T IndexElementCount ); static HRESULT WINAPI StorageAdapterGetRecordCount( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PSIZE_T RecordCount ); static HRESULT WINAPI StorageAdapterFirstRecord( _Inout_ PWINBIO_PIPELINE Pipeline ); static HRESULT WINAPI StorageAdapterNextRecord( _Inout_ PWINBIO_PIPELINE Pipeline ); static HRESULT WINAPI StorageAdapterGetCurrentRecord( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PWINBIO_STORAGE_RECORD RecordContents ); static HRESULT WINAPI StorageAdapterControlUnit( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ ULONG ControlCode, _In_ PUCHAR SendBuffer, _In_ SIZE_T SendBufferSize, _In_ PUCHAR ReceiveBuffer, _In_ SIZE_T ReceiveBufferSize, _Out_ PSIZE_T ReceiveDataSize, _Out_ PULONG OperationStatus ); static HRESULT WINAPI StorageAdapterControlUnitPrivileged( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ ULONG ControlCode, _In_ PUCHAR SendBuffer, _In_ SIZE_T SendBufferSize, _In_ PUCHAR ReceiveBuffer, _In_ SIZE_T ReceiveBufferSize, _Out_ PSIZE_T ReceiveDataSize, _Out_ PULONG OperationStatus ); //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // // Interface dispatch table // /////////////////////////////////////////////////////////////////////////////// static WINBIO_STORAGE_INTERFACE g_StorageInterface = { WINBIO_STORAGE_INTERFACE_VERSION_1, WINBIO_ADAPTER_TYPE_STORAGE, sizeof(WINBIO_STORAGE_INTERFACE), {0x7f6c2610, 0xfdba, 0x41a3, {0xae, 0x1c, 0x8f, 0xd5, 0x84, 0x59, 0x8d, 0x13}}, StorageAdapterAttach, StorageAdapterDetach, StorageAdapterClearContext, StorageAdapterCreateDatabase, StorageAdapterEraseDatabase, StorageAdapterOpenDatabase, StorageAdapterCloseDatabase, StorageAdapterGetDataFormat, StorageAdapterGetDatabaseSize, StorageAdapterAddRecord, StorageAdapterDeleteRecord, StorageAdapterQueryBySubject, StorageAdapterQueryByContent, StorageAdapterGetRecordCount, StorageAdapterFirstRecord, StorageAdapterNextRecord, StorageAdapterGetCurrentRecord, StorageAdapterControlUnit, StorageAdapterControlUnitPrivileged }; //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // // Mandatory DLL entrypoint function. // /////////////////////////////////////////////////////////////////////////////// BOOL APIENTRY DllMain( HANDLE ModuleHandle, DWORD ReasonForCall, LPVOID Reserved ) { UNREFERENCED_PARAMETER(ModuleHandle); UNREFERENCED_PARAMETER(ReasonForCall); UNREFERENCED_PARAMETER(Reserved); return TRUE; } //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // // Well-known interface-discovery function exported by the Storage Adapter // /////////////////////////////////////////////////////////////////////////////// HRESULT WINAPI WbioQueryStorageInterface( _Out_ PWINBIO_STORAGE_INTERFACE *StorageInterface ) { *StorageInterface = &g_StorageInterface; return S_OK; } //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // // Storage Adapter action routines // /////////////////////////////////////////////////////////////////////////////// static HRESULT WINAPI StorageAdapterAttach( _Inout_ PWINBIO_PIPELINE Pipeline ) { UNREFERENCED_PARAMETER(Pipeline); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterDetach( _Inout_ PWINBIO_PIPELINE Pipeline ) { UNREFERENCED_PARAMETER(Pipeline); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterClearContext( _Inout_ PWINBIO_PIPELINE Pipeline ) { UNREFERENCED_PARAMETER(Pipeline); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterCreateDatabase( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_UUID DatabaseId, _In_ WINBIO_BIOMETRIC_TYPE Factor, _In_ PWINBIO_UUID Format, _In_ LPCWSTR FilePath, _In_ LPCWSTR ConnectString, _In_ SIZE_T IndexElementCount, _In_ SIZE_T InitialSize ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(DatabaseId); UNREFERENCED_PARAMETER(Factor); UNREFERENCED_PARAMETER(Format); UNREFERENCED_PARAMETER(FilePath); UNREFERENCED_PARAMETER(ConnectString); UNREFERENCED_PARAMETER(IndexElementCount); UNREFERENCED_PARAMETER(InitialSize); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterEraseDatabase( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_UUID DatabaseId, _In_ LPCWSTR FilePath, _In_ LPCWSTR ConnectString ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(DatabaseId); UNREFERENCED_PARAMETER(FilePath); UNREFERENCED_PARAMETER(ConnectString); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterOpenDatabase( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_UUID DatabaseId, _In_ LPCWSTR FilePath, _In_ LPCWSTR ConnectString ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(DatabaseId); UNREFERENCED_PARAMETER(FilePath); UNREFERENCED_PARAMETER(ConnectString); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterCloseDatabase( _Inout_ PWINBIO_PIPELINE Pipeline ) { UNREFERENCED_PARAMETER(Pipeline); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterGetDataFormat( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PWINBIO_UUID Format, _Out_ PWINBIO_VERSION Version ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(Format); UNREFERENCED_PARAMETER(Version); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterGetDatabaseSize( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PSIZE_T AvailableRecordCount, _Out_ PSIZE_T TotalRecordCount ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(AvailableRecordCount); UNREFERENCED_PARAMETER(TotalRecordCount); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterAddRecord( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_STORAGE_RECORD RecordContents ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(RecordContents); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterDeleteRecord( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_IDENTITY Identity, _In_ WINBIO_BIOMETRIC_SUBTYPE SubFactor ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(Identity); UNREFERENCED_PARAMETER(SubFactor); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterQueryBySubject( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ PWINBIO_IDENTITY Identity, _In_ WINBIO_BIOMETRIC_SUBTYPE SubFactor ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(Identity); UNREFERENCED_PARAMETER(SubFactor); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterQueryByContent( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ WINBIO_BIOMETRIC_SUBTYPE SubFactor, _In_ ULONG IndexVector[], _In_ SIZE_T IndexElementCount ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(SubFactor); UNREFERENCED_PARAMETER(IndexVector); UNREFERENCED_PARAMETER(IndexElementCount); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterGetRecordCount( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PSIZE_T RecordCount ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(RecordCount); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterFirstRecord( _Inout_ PWINBIO_PIPELINE Pipeline ) { UNREFERENCED_PARAMETER(Pipeline); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterNextRecord( _Inout_ PWINBIO_PIPELINE Pipeline ) { UNREFERENCED_PARAMETER(Pipeline); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterGetCurrentRecord( _Inout_ PWINBIO_PIPELINE Pipeline, _Out_ PWINBIO_STORAGE_RECORD RecordContents ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(RecordContents); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterControlUnit( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ ULONG ControlCode, _In_ PUCHAR SendBuffer, _In_ SIZE_T SendBufferSize, _In_ PUCHAR ReceiveBuffer, _In_ SIZE_T ReceiveBufferSize, _Out_ PSIZE_T ReceiveDataSize, _Out_ PULONG OperationStatus ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(ControlCode); UNREFERENCED_PARAMETER(SendBuffer); UNREFERENCED_PARAMETER(SendBufferSize); UNREFERENCED_PARAMETER(ReceiveBuffer); UNREFERENCED_PARAMETER(ReceiveBufferSize); UNREFERENCED_PARAMETER(ReceiveDataSize); UNREFERENCED_PARAMETER(OperationStatus); return E_NOTIMPL; } //----------------------------------------------------------------------------- static HRESULT WINAPI StorageAdapterControlUnitPrivileged( _Inout_ PWINBIO_PIPELINE Pipeline, _In_ ULONG ControlCode, _In_ PUCHAR SendBuffer, _In_ SIZE_T SendBufferSize, _In_ PUCHAR ReceiveBuffer, _In_ SIZE_T ReceiveBufferSize, _Out_ PSIZE_T ReceiveDataSize, _Out_ PULONG OperationStatus ) { UNREFERENCED_PARAMETER(Pipeline); UNREFERENCED_PARAMETER(ControlCode); UNREFERENCED_PARAMETER(SendBuffer); UNREFERENCED_PARAMETER(SendBufferSize); UNREFERENCED_PARAMETER(ReceiveBuffer); UNREFERENCED_PARAMETER(ReceiveBufferSize); UNREFERENCED_PARAMETER(ReceiveDataSize); UNREFERENCED_PARAMETER(OperationStatus); return E_NOTIMPL; } //-----------------------------------------------------------------------------
5,728
1,008
/* * 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 org.springframework.web.reactive.result.method.annotation; import im.turms.server.common.util.ReflectionUtil; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.http.codec.HttpMessageReader; import org.springframework.web.method.HandlerMethod; import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver; import org.springframework.web.reactive.result.method.TurmsHandlerMethod; import java.lang.invoke.MethodHandle; import java.util.List; /** * @author <NAME> */ public class TurmsControllerMethodResolver extends ControllerMethodResolver { private final List<HandlerMethodArgumentResolver> requestMappingResolvers; public TurmsControllerMethodResolver(ArgumentResolverConfigurer customResolvers, ReactiveAdapterRegistry adapterRegistry, ConfigurableApplicationContext context, List<HttpMessageReader<?>> readers) { super(customResolvers, adapterRegistry, context, readers); try { MethodHandle requestMappingResolvers = ReflectionUtil .getGetter(ControllerMethodResolver.class.getDeclaredField("requestMappingResolvers")); this.requestMappingResolvers = (List<HandlerMethodArgumentResolver>) requestMappingResolvers.invoke(this); } catch (Throwable e) { throw new RuntimeException(e); } } @Override public TurmsHandlerMethod getRequestMappingMethod(HandlerMethod handlerMethod) { TurmsHandlerMethod method = (TurmsHandlerMethod) handlerMethod; method.setArgumentResolvers(requestMappingResolvers); return method; } }
841
5,169
{ "name": "Wombat", "version": "0.1.1", "summary": "Word-Of-Mouth as a service.", "description": "At its core, Wombat is about people, and its strength lies in its ability to see the people behind both the app and the device.\n\nWe help you delight your users by optimizing your interactions with them, earning their trust and respect.\n\nAn equally important value is keeping you delighted in using Wombat.\n\nThis is why we’ve made Wombat ridiculously simple to integrate, and just as easy to use.\n\nIt’s not just another unified dashboard with infinite options. By changing the way we treat our users (that’s you!), Wombat is changing the way users think about apps, and apps think about users.", "homepage": "http://www.getwombat.com", "license": "Copyright 2015 Wombat", "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/ldkop", "platforms": { "ios": "8.0" }, "ios": { "vendored_frameworks": "Wombat.framework" }, "source": { "git": "https://bitbucket.org/getwombat/ios_releases.git", "tag": "V_0.1.1" }, "source_files": "Wombat.framework/Headers/*.h", "frameworks": [ "UIKit", "Foundation", "CoreFoundation" ], "dependencies": { "Bolts": [ ], "KeenClient": [ ], "GVUserDefaults": [ ], "SSKeychain": [ ], "Reachability": [ ], "PureLayout": [ ], "AGWindowView": [ ], "AFNetworking": [ ], "CocoaLumberjack": [ ], "NSDate-Extensions": [ ], "UIColor-HexString": [ ] } }
599
1,071
<gh_stars>1000+ #------------------------------------------------------------------------------ # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # bind_insert.py # # Demonstrate how to insert a row into a table using bind variables. #------------------------------------------------------------------------------ import cx_Oracle as oracledb import sample_env connection = oracledb.connect(sample_env.get_main_connect_string()) #------------------------------------------------------------------------------ # "Bind by position" #------------------------------------------------------------------------------ rows = [ (1, "First"), (2, "Second"), (3, "Third"), (4, "Fourth"), (5, None), # Insert a NULL value (6, "Sixth"), (7, "Seventh") ] cursor = connection.cursor() # predefine maximum string size to avoid data scans and memory reallocations; # the None value indicates that the default processing can take place cursor.setinputsizes(None, 20) cursor.executemany("insert into mytab(id, data) values (:1, :2)", rows) #------------------------------------------------------------------------------ # "Bind by name" #------------------------------------------------------------------------------ rows = [ {"d": "Eighth", "i": 8}, {"d": "Ninth", "i": 9}, {"d": "Tenth", "i": 10} ] cursor = connection.cursor() # Predefine maximum string size to avoid data scans and memory reallocations cursor.setinputsizes(d=20) cursor.executemany("insert into mytab(id, data) values (:i, :d)", rows) #------------------------------------------------------------------------------ # Inserting a single bind still needs tuples #------------------------------------------------------------------------------ rows = [ ("Eleventh",), ("Twelth",) ] cursor = connection.cursor() cursor.executemany("insert into mytab(id, data) values (11, :1)", rows) #------------------------------------------------------------------------------ # Now query the results back #------------------------------------------------------------------------------ # Don't commit - this lets the demo be run multiple times #connection.commit() for row in cursor.execute('select * from mytab'): print(row)
584