max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,442
<reponame>VersiraSec/epsilon-cfw<filename>ion/src/device/shared/regs/cortex.h #ifndef REGS_CORTEX_H #define REGS_CORTEX_H #include "register.h" #include <regs/config/cortex.h> namespace Ion { namespace Device { namespace Regs { class CORTEX { public: class SYST_CSR : public Register32 { public: enum class CLKSOURCE : uint8_t { AHB_DIV8 = 0, AHB = 1 }; REGS_BOOL_FIELD(COUNTFLAG, 16); REGS_TYPE_FIELD(CLKSOURCE, 2, 2); REGS_BOOL_FIELD(TICKINT, 1); REGS_BOOL_FIELD(ENABLE, 0); }; class SYST_RVR : public Register32 { public: REGS_FIELD(RELOAD, uint32_t, 23, 0); }; class SYST_CVR : public Register32 { public: REGS_FIELD(CURRENT, uint32_t, 23, 0); }; class ICSR : Register32 { public: REGS_BOOL_FIELD(PENDSVSET, 28); REGS_BOOL_FIELD(PENDSVCLR, 27); }; // Vector table offset register // http://www.st.com/content/ccc/resource/technical/document/programming_manual/6c/3a/cb/e7/e4/ea/44/9b/DM00046982.pdf/files/DM00046982.pdf/jcr:content/translations/en.DM00046982.pdf class VTOR : Register32 { public: void setVTOR(void *address) volatile { assert(((uint32_t)address & 0xC00001FF) == 0); setBitRange(29, 9, (uint32_t)address >> 9); } }; // Application Interrupt and Reset Control Register // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0552a/Cihehdge.html class AIRCR : public Register32 { public: void requestReset() volatile { set(0x5FA<<16 |(1<<2)); } }; // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/Cihhjgdh.html class SCR : public Register32 { public: REGS_BOOL_FIELD(SLEEPDEEP, 2); }; class CCR : public Register32 { public: REGS_BOOL_FIELD(IC, 17); REGS_BOOL_FIELD(DC, 16); }; class SHPR1 : public Register32 { public: REGS_FIELD(USAGE_FAULT_PRI, uint8_t, 23, 16); REGS_FIELD(BUS_FAULT_PRI, uint8_t, 15, 8); REGS_FIELD(MEM_MANAGE_PRI, uint8_t, 7, 0); }; class SHPR2 : public Register32 { public: REGS_FIELD(SVCALL_PRI, uint8_t, 31, 24); }; class SHPR3 : public Register32 { public: REGS_FIELD(SYSTICK_PRI, uint8_t, 31, 24); REGS_FIELD(PENDSV_PRI, uint8_t, 23, 16); }; class SHCRS : public Register32 { public: REGS_BOOL_FIELD(USGFAULTENA, 18); REGS_BOOL_FIELD(BUSFAULTENA, 17); REGS_BOOL_FIELD(MEMFAULTENA, 16); }; #if REGS_CORTEX_CONFIG_CACHE class CCSIDR : public Register32 { public: using Register32::Register32; REGS_FIELD(ASSOCIATIVITY, uint16_t, 12, 3); REGS_FIELD(NUMSETS, uint16_t, 27, 13); }; class CSSELR : public Register32 { public: REGS_BOOL_FIELD(IND, 0); }; #endif // Coprocessor Access Control Register // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0553a/BEHBJHIG.html class CPACR : public Register32 { public: enum class Access { Denied = 0, PrivilegedOnly = 1, Full = 3 }; void setAccess(int index, Access a) volatile { setBitRange(2*index+1, 2*index, (uint32_t)a); } }; #if REGS_CORTEX_CONFIG_CACHE class ICIALLU : public Register32 { public: using Register32::Register32; }; class DCSW : public Register32 { public: DCSW() : Register32(0) {} REGS_FIELD(SET, uint16_t, 13, 5); REGS_FIELD(WAY, uint8_t, 31, 30); }; class DCISW : public DCSW { }; class DCCSW : public DCSW { }; class DCCISW : public DCSW { }; #endif constexpr CORTEX() {}; REGS_REGISTER_AT(SYST_CSR, 0x10); REGS_REGISTER_AT(SYST_RVR, 0x14); REGS_REGISTER_AT(SYST_CVR, 0x18); REGS_REGISTER_AT(ICSR, 0xD04); REGS_REGISTER_AT(VTOR, 0xD08); REGS_REGISTER_AT(AIRCR, 0xD0C); REGS_REGISTER_AT(SCR, 0xD10); REGS_REGISTER_AT(CCR, 0xD14); REGS_REGISTER_AT(SHPR1, 0xD18); REGS_REGISTER_AT(SHPR2, 0xD1C); REGS_REGISTER_AT(SHPR3, 0xD20); REGS_REGISTER_AT(SHCRS, 0xD24); #if REGS_CORTEX_CONFIG_CACHE REGS_REGISTER_AT(CCSIDR, 0xD80); REGS_REGISTER_AT(CSSELR, 0xD84); #endif REGS_REGISTER_AT(CPACR, 0xD88); #if REGS_CORTEX_CONFIG_CACHE REGS_REGISTER_AT(ICIALLU, 0xF50); REGS_REGISTER_AT(DCISW, 0xF60); REGS_REGISTER_AT(DCCSW, 0xF6C); REGS_REGISTER_AT(DCCISW, 0xF74); #endif private: constexpr uint32_t Base() const { return 0xE000E000; } }; constexpr CORTEX CORTEX; } } } #endif
1,984
3,200
# Copyright 2020-2021 Huawei Technologies Co., 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. # ============================================================================ import numpy as np import pytest import mindspore.context as context import mindspore.nn as nn from mindspore import Tensor, Parameter from mindspore.ops import operations as P from mindspore.ops.operations import _inner_ops as inner context.set_context(mode=context.GRAPH_MODE, device_target="GPU") # all cases tested against dchip func_map = { "update": P.ScatterUpdate, "add": P.ScatterAdd, "sub": P.ScatterSub, } class TestScatterFuncNet(nn.Cell): def __init__(self, func, lock, inputx, indices, updates): super(TestScatterFuncNet, self).__init__() self.scatter_func = func_map[func](use_locking=lock) self.inputx = Parameter(inputx, name="inputx") self.indices = Parameter(indices, name="indices") self.updates = Parameter(updates, name="updates") def construct(self): out = self.scatter_func(self.inputx, self.indices, self.updates) return out def scatter_func_net(func, inputx, indices, updates): lock = True net = TestScatterFuncNet(func, lock, inputx, indices, updates) return net() def scatter_func_use_locking_false_net(func, inputx, indices, updates): lock = False net = TestScatterFuncNet(func, lock, inputx, indices, updates) return net() class TestScatterFuncDynamicNet(nn.Cell): def __init__(self, func, inputx, indices, updates): super(TestScatterFuncDynamicNet, self).__init__() self.scatter_func = func_map[func]() self.test_dynamic = inner.GpuConvertToDynamicShape() self.inputx = Parameter(inputx, name="inputx") self.indices = Parameter(indices, name="indices") self.updates = Parameter(updates, name="updates") def construct(self): indices = self.test_dynamic(self.indices) updates = self.test_dynamic(self.updates) out = self.scatter_func(self.inputx, indices, updates) return out def scatter_func_d_net(func, inputx, indices, updates): context.set_context(mode=context.GRAPH_MODE, device_target="GPU") net = TestScatterFuncDynamicNet(func, inputx, indices, updates) return net() class TestScatterFuncDynamicNet2(nn.Cell): def __init__(self, func, inputx): super(TestScatterFuncDynamicNet2, self).__init__() self.scatter_func = func_map[func]() self.test_dynamic = inner.GpuConvertToDynamicShape() self.inputx = Parameter(inputx, name="inputx") def construct(self, indices, updates): indices = self.test_dynamic(indices) updates = self.test_dynamic(updates) out = self.scatter_func(self.inputx, indices, updates) return out def scatter_func_d2_net(func, inputx, indices_1, updates_1, indices_2, updates_2): context.set_context(mode=context.GRAPH_MODE, device_target="GPU") net = TestScatterFuncDynamicNet2(func, inputx) out1 = net(indices_1, updates_1) out2 = net(indices_2, updates_2) return (out1, out2) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_small_float32(): inputx = Tensor(np.zeros((2, 3)).astype(np.float32)) indices = Tensor(np.array([[0, 1], [0, 1]]).astype(np.int32)) updates = Tensor(np.arange(12).reshape((2, 2, 3)).astype(np.float32)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array([[6.0, 8.0, 10.0], [12.0, 14.0, 16.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array([[-6.0, -8.0, -10.0], [-12.0, -14.0, -16.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_input_updated(): inputx = Tensor(np.zeros((2, 3)).astype(np.float32)) indices = Tensor(np.array([[0, 1], [0, 1]]).astype(np.int32)) updates = Tensor(np.arange(12).reshape((2, 2, 3)).astype(np.float32)) lock = True # update net = TestScatterFuncNet("update", lock, inputx, indices, updates) net() expected = np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]) np.testing.assert_array_almost_equal(net.inputx.asnumpy(), expected) # add net = TestScatterFuncNet("add", lock, inputx, indices, updates) net() expected = np.array([[6.0, 8.0, 10.0], [12.0, 14.0, 16.0]]) np.testing.assert_array_almost_equal(net.inputx.asnumpy(), expected) # sub net = TestScatterFuncNet("sub", lock, inputx, indices, updates) net() expected = np.array([[-6.0, -8.0, -10.0], [-12.0, -14.0, -16.0]]) np.testing.assert_array_almost_equal(net.inputx.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_large_shape_float32(): inputx = Tensor(np.ones((4, 2, 3, 4)).astype(np.float32)) indices = Tensor(np.array([[0, 2], [3, 1]]).astype(np.int32)) updates = Tensor(np.arange(96).reshape((2, 2, 2, 3, 4)).astype(np.float32)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array( [ [ [[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 10.0, 11.0]], [[12.0, 13.0, 14.0, 15.0], [16.0, 17.0, 18.0, 19.0], [20.0, 21.0, 22.0, 23.0]], ], [ [[72.0, 73.0, 74.0, 75.0], [76.0, 77.0, 78.0, 79.0], [80.0, 81.0, 82.0, 83.0]], [[84.0, 85.0, 86.0, 87.0], [88.0, 89.0, 90.0, 91.0], [92.0, 93.0, 94.0, 95.0]], ], [ [[24.0, 25.0, 26.0, 27.0], [28.0, 29.0, 30.0, 31.0], [32.0, 33.0, 34.0, 35.0]], [[36.0, 37.0, 38.0, 39.0], [40.0, 41.0, 42.0, 43.0], [44.0, 45.0, 46.0, 47.0]], ], [ [[48.0, 49.0, 50.0, 51.0], [52.0, 53.0, 54.0, 55.0], [56.0, 57.0, 58.0, 59.0]], [[60.0, 61.0, 62.0, 63.0], [64.0, 65.0, 66.0, 67.0], [68.0, 69.0, 70.0, 71.0]], ], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array( [ [ [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]], [[13.0, 14.0, 15.0, 16.0], [17.0, 18.0, 19.0, 20.0], [21.0, 22.0, 23.0, 24.0]], ], [ [[73.0, 74.0, 75.0, 76.0], [77.0, 78.0, 79.0, 80.0], [81.0, 82.0, 83.0, 84.0]], [[85.0, 86.0, 87.0, 88.0], [89.0, 90.0, 91.0, 92.0], [93.0, 94.0, 95.0, 96.0]], ], [ [[25.0, 26.0, 27.0, 28.0], [29.0, 30.0, 31.0, 32.0], [33.0, 34.0, 35.0, 36.0]], [[37.0, 38.0, 39.0, 40.0], [41.0, 42.0, 43.0, 44.0], [45.0, 46.0, 47.0, 48.0]], ], [ [[49.0, 50.0, 51.0, 52.0], [53.0, 54.0, 55.0, 56.0], [57.0, 58.0, 59.0, 60.0]], [[61.0, 62.0, 63.0, 64.0], [65.0, 66.0, 67.0, 68.0], [69.0, 70.0, 71.0, 72.0]], ], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array( [ [ [[1.0, 0.0, -1.0, -2.0], [-3.0, -4.0, -5.0, -6.0], [-7.0, -8.0, -9.0, -10.0]], [ [-11.0, -12.0, -13.0, -14.0], [-15.0, -16.0, -17.0, -18.0], [-19.0, -20.0, -21.0, -22.0], ], ], [ [ [-71.0, -72.0, -73.0, -74.0], [-75.0, -76.0, -77.0, -78.0], [-79.0, -80.0, -81.0, -82.0], ], [ [-83.0, -84.0, -85.0, -86.0], [-87.0, -88.0, -89.0, -90.0], [-91.0, -92.0, -93.0, -94.0], ], ], [ [ [-23.0, -24.0, -25.0, -26.0], [-27.0, -28.0, -29.0, -30.0], [-31.0, -32.0, -33.0, -34.0], ], [ [-35.0, -36.0, -37.0, -38.0], [-39.0, -40.0, -41.0, -42.0], [-43.0, -44.0, -45.0, -46.0], ], ], [ [ [-47.0, -48.0, -49.0, -50.0], [-51.0, -52.0, -53.0, -54.0], [-55.0, -56.0, -57.0, -58.0], ], [ [-59.0, -60.0, -61.0, -62.0], [-63.0, -64.0, -65.0, -66.0], [-67.0, -68.0, -69.0, -70.0], ], ], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_small_float32_use_locking_false(): inputx = Tensor(np.zeros((2, 3)).astype(np.float32)) indices = Tensor(np.array([1, 0]).astype(np.int32)) updates = Tensor(np.arange(6).reshape((2, 3)).astype(np.float32)) # update output = scatter_func_use_locking_false_net("update", inputx, indices, updates) expected = np.array([[3.0, 4.0, 5.0], [0.0, 1.0, 2.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_use_locking_false_net("add", inputx, indices, updates) expected = np.array([[3.0, 4.0, 5.0], [0.0, 1.0, 2.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_use_locking_false_net("sub", inputx, indices, updates) expected = np.array([[-3.0, -4.0, -5.0], [0.0, -1.0, -2.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_input_less_than_1_float32(): inputx = Tensor( np.array( [ [0.214141, 0.415151, 0.51516], [0.876542, 0.451611, 0.55112], [0.111244, 0.633333, 0.34444], ] ).astype(np.float32) ) indices = Tensor(np.array([[[1, 0, 2], [2, 2, 0]], [[1, 0, 1], [2, 1, 2]]]).astype(np.int32)) updates = Tensor(np.arange(34, 70).reshape((2, 2, 3, 3)).astype(np.float32)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array( [[37.0, 38.0, 39.0], [34.0, 35.0, 66.0], [67.0, 68.0, 69.0],], dtype=np.float32, ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array( [ [141.21414, 144.41515, 147.51517], [208.87654, 212.45161, 216.55112], [257.11124, 262.63333, 267.34442], ], dtype=np.float32, ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array( [ [-140.78586, -143.58485, -146.48483], [-207.12346, -211.54839, -215.44888], [-256.88876, -261.36667, -266.65558], ], dtype=np.float32, ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_float16(): inputx = Tensor(np.zeros((2, 3)).astype(np.float16)) indices = Tensor(np.array([[0, 1], [0, 1]]).astype(np.int32)) updates = Tensor(np.arange(12).reshape((2, 2, 3)).astype(np.float16)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array([[6.0, 8.0, 10.0], [12.0, 14.0, 16.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array([[-6.0, -8.0, -10.0], [-12.0, -14.0, -16.0]]) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_large_float16(): inputx = Tensor(np.zeros((2, 3, 4)).astype(np.float16)) indices = Tensor(np.array([[0, 0], [1, 1]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.float16)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array( [ [[63.0, 64.0, 65.0, 66.0], [67.0, 68.0, 69.0, 70.0], [71.0, 72.0, 73.0, 74.0],], [[99.0, 100.0, 101.0, 102.0], [103.0, 104.0, 105.0, 106.0], [95.0, 96.0, 97.0, 98.0],], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array( [ [ [138.0, 140.0, 142.0, 144.0], [146.0, 148.0, 150.0, 152.0], [154.0, 156.0, 158.0, 160.0], ], [ [186.0, 188.0, 190.0, 192.0], [194.0, 196.0, 198.0, 200.0], [202.0, 204.0, 206.0, 208.0], ], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array( [ [ [-138.0, -140.0, -142.0, -144.0], [-146.0, -148.0, -150.0, -152.0], [-154.0, -156.0, -158.0, -160.0], ], [ [-186.0, -188.0, -190.0, -192.0], [-194.0, -196.0, -198.0, -200.0], [-202.0, -204.0, -206.0, -208.0], ], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_disordered_float16(): inputx = Tensor(np.flip(np.arange(34, 46).reshape(3, 4).astype(np.float16))) indices = Tensor(np.array([[[0, 1, 2], [2, 1, 0]], [[0, 0, 0], [2, 2, 2]]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.float16)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array( [[95.0, 96.0, 97.0, 98.0], [67.0, 68.0, 69.0, 70.0], [99.0, 100.0, 101.0, 102.0]] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array( [[464.0, 468.0, 472.0, 476.0], [187.0, 188.0, 189.0, 190.0], [492.0, 496.0, 500.0, 504.0]] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array( [ [-374.0, -380.0, -386.0, -392.0], [-105.0, -108.0, -111.0, -114.0], [-418.0, -424.0, -430.0, -436.0], ] ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_large_int32(): inputx = Tensor(np.zeros((2, 3, 4)).astype(np.int32)) indices = Tensor(np.array([[0, 0], [1, 1]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.int32)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array( [ [[63.0, 64.0, 65.0, 66.0], [67.0, 68.0, 69.0, 70.0], [71.0, 72.0, 73.0, 74.0],], [[99.0, 100.0, 101.0, 102.0], [103.0, 104.0, 105.0, 106.0], [95.0, 96.0, 97.0, 98.0],], ] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array( [ [ [138.0, 140.0, 142.0, 144.0], [146.0, 148.0, 150.0, 152.0], [154.0, 156.0, 158.0, 160.0], ], [ [186.0, 188.0, 190.0, 192.0], [194.0, 196.0, 198.0, 200.0], [202.0, 204.0, 206.0, 208.0], ], ] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array( [ [ [-138.0, -140.0, -142.0, -144.0], [-146.0, -148.0, -150.0, -152.0], [-154.0, -156.0, -158.0, -160.0], ], [ [-186.0, -188.0, -190.0, -192.0], [-194.0, -196.0, -198.0, -200.0], [-202.0, -204.0, -206.0, -208.0], ], ] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_disordered_int32(): inputx = Tensor(np.flip(np.arange(34, 46).reshape(3, 4).astype(np.int32))) indices = Tensor(np.array([[[0, 1, 2], [2, 1, 0]], [[0, 0, 0], [2, 2, 2]]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.int32)) # update output = scatter_func_net("update", inputx, indices, updates) expected = np.array( [[95.0, 96.0, 97.0, 98.0], [67.0, 68.0, 69.0, 70.0], [99.0, 100.0, 101.0, 102.0]] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_net("add", inputx, indices, updates) expected = np.array( [[464.0, 468.0, 472.0, 476.0], [187.0, 188.0, 189.0, 190.0], [492.0, 496.0, 500.0, 504.0]] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_net("sub", inputx, indices, updates) expected = np.array( [ [-374.0, -380.0, -386.0, -392.0], [-105.0, -108.0, -111.0, -114.0], [-418.0, -424.0, -430.0, -436.0], ] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_disordered_dynamic_int32(): inputx = Tensor(np.flip(np.arange(34, 46).reshape(3, 4).astype(np.int32))) indices = Tensor(np.array([[[0, 1, 2], [2, 1, 0]], [[0, 0, 0], [2, 2, 2]]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.int32)) # update output = scatter_func_d_net("update", inputx, indices, updates) expected = np.array( [[95.0, 96.0, 97.0, 98.0], [67.0, 68.0, 69.0, 70.0], [99.0, 100.0, 101.0, 102.0]] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_d_net("add", inputx, indices, updates) expected = np.array( [[464.0, 468.0, 472.0, 476.0], [187.0, 188.0, 189.0, 190.0], [492.0, 496.0, 500.0, 504.0]] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_d_net("sub", inputx, indices, updates) expected = np.array( [ [-374.0, -380.0, -386.0, -392.0], [-105.0, -108.0, -111.0, -114.0], [-418.0, -424.0, -430.0, -436.0], ] ).astype(np.int32) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_disordered_dynamic_int8(): inputx = Tensor(np.flip(np.arange(34, 46).reshape(3, 4).astype(np.int8))) indices = Tensor(np.array([[[0, 1, 2], [2, 1, 0]], [[0, 0, 0], [2, 2, 2]]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.int8)) # update output = scatter_func_d_net("update", inputx, indices, updates) expected = np.array( [[95.0, 96.0, 97.0, 98.0], [67.0, 68.0, 69.0, 70.0], [99.0, 100.0, 101.0, 102.0]] ).astype(np.int8) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_d_net("add", inputx, indices, updates) expected = np.array( [[464.0, 468.0, 472.0, 476.0], [187.0, 188.0, 189.0, 190.0], [492.0, 496.0, 500.0, 504.0]] ).astype(np.int8) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_d_net("sub", inputx, indices, updates) expected = np.array( [ [-118.0, -124.0, 126.0, 120.0], [-105.0, -108.0, -111.0, -114.0], [94.0, 88.0, 82.0, 76.0], ] ).astype(np.int8) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_disordered_dynamic_uint8(): inputx = Tensor(np.flip(np.arange(34, 46).reshape(3, 4).astype(np.uint8))) indices = Tensor(np.array([[[0, 1, 2], [2, 1, 0]], [[0, 0, 0], [2, 2, 2]]]).astype(np.int32)) updates = Tensor(np.arange(63, 111).reshape((2, 2, 3, 4)).astype(np.uint8)) # update output = scatter_func_d_net("update", inputx, indices, updates) expected = np.array( [[95.0, 96.0, 97.0, 98.0], [67.0, 68.0, 69.0, 70.0], [99.0, 100.0, 101.0, 102.0]] ).astype(np.uint8) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_d_net("add", inputx, indices, updates) expected = np.array( [[464.0, 468.0, 472.0, 476.0], [187.0, 188.0, 189.0, 190.0], [492.0, 496.0, 500.0, 504.0]] ).astype(np.uint8) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_d_net("sub", inputx, indices, updates) expected = np.array( [[138.0, 132.0, 126.0, 120.0], [151.0, 148.0, 145.0, 142.0], [94.0, 88.0, 82.0, 76.0]] ).astype(np.uint8) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_input_less_than_1_dynamic_float32(): inputx = Tensor( np.array( [ [0.214141, 0.415151, 0.51516], [0.876542, 0.451611, 0.55112], [0.111244, 0.633333, 0.34444], ] ).astype(np.float32) ) indices = Tensor(np.array([[[1, 0, 2], [2, 2, 0]], [[1, 0, 1], [2, 1, 2]]]).astype(np.int32)) updates = Tensor(np.arange(34, 70).reshape((2, 2, 3, 3)).astype(np.float32)) # update output = scatter_func_d_net("update", inputx, indices, updates) expected = np.array( [[37.0, 38.0, 39.0], [34.0, 35.0, 66.0], [67.0, 68.0, 69.0],], dtype=np.float32, ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # add output = scatter_func_d_net("add", inputx, indices, updates) expected = np.array( [ [141.21414, 144.41515, 147.51517], [208.87654, 212.45161, 216.55112], [257.11124, 262.63333, 267.34442], ], dtype=np.float32, ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) # sub output = scatter_func_d_net("sub", inputx, indices, updates) expected = np.array( [ [-140.78586, -143.58485, -146.48483], [-207.12346, -211.54839, -215.44888], [-256.88876, -261.36667, -266.65558], ], dtype=np.float32, ) np.testing.assert_array_almost_equal(output.asnumpy(), expected) @pytest.mark.level0 @pytest.mark.platform_x86_gpu_training @pytest.mark.env_onecard def test_scatter_func_dynamic_two_inputs(): inputx = Tensor(np.zeros((2, 3)).astype(np.float32)) indices_1 = Tensor(np.array([[0, 1], [0, 1]]).astype(np.int32)) updates_1 = Tensor(np.arange(12).reshape((2, 2, 3)).astype(np.float32)) indices_2 = Tensor(np.array([[0, 0], [1, 1], [1, 0]]).astype(np.int32)) updates_2 = Tensor(np.flip(np.arange(18).reshape((3, 2, 3)).astype(np.float32))) # update output_1, output_2 = scatter_func_d2_net( "update", inputx, indices_1, updates_1, indices_2, updates_2 ) expected_1 = np.array([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]) expected_2 = np.array([[17.0, 16.0, 15.0], [11.0, 10.0, 9.0]]) np.testing.assert_array_almost_equal(output_1.asnumpy(), expected_1) np.testing.assert_array_almost_equal(output_2.asnumpy(), expected_2) # add output_1, output_2 = scatter_func_d2_net( "add", inputx, indices_1, updates_1, indices_2, updates_2 ) expected_1 = np.array([[6.0, 8.0, 10.0], [12.0, 14.0, 16.0]]) expected_2 = np.array([[39.0, 38.0, 37.0], [36.0, 35.0, 34.0]]) np.testing.assert_array_almost_equal(output_1.asnumpy(), expected_1) np.testing.assert_array_almost_equal(output_2.asnumpy(), expected_2) # sub output_1, output_2 = scatter_func_d2_net( "sub", inputx, indices_1, updates_1, indices_2, updates_2 ) expected_1 = np.array([[-6.0, -8.0, -10.0], [-12.0, -14.0, -16.0]]) expected_2 = np.array([[-39.0, -38.0, -37.0], [-36.0, -35.0, -34.0]]) np.testing.assert_array_almost_equal(output_1.asnumpy(), expected_1) np.testing.assert_array_almost_equal(output_2.asnumpy(), expected_2)
13,662
575
// 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. #include "third_party/blink/renderer/modules/indexeddb/web_idb_cursor_impl.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <utility> #include "base/bind.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/associated_receiver.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_associated_receiver.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/renderer/modules/indexeddb/idb_key_range.h" #include "third_party/blink/renderer/modules/indexeddb/mock_web_idb_callbacks.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" namespace blink { namespace { class MockCursorImpl : public mojom::blink::IDBCursor { public: explicit MockCursorImpl( mojo::PendingAssociatedReceiver<mojom::blink::IDBCursor> receiver) : receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(base::BindOnce( &MockCursorImpl::CursorDestroyed, base::Unretained(this))); } void Prefetch(int32_t count, mojom::blink::IDBCursor::PrefetchCallback callback) override { ++prefetch_calls_; last_prefetch_count_ = count; std::move(callback).Run(mojom::blink::IDBCursorResult::NewEmpty(true)); } void PrefetchReset(int32_t used_prefetches, int32_t unused_prefetches) override { ++reset_calls_; last_used_count_ = used_prefetches; } void Advance(uint32_t count, mojom::blink::IDBCursor::AdvanceCallback callback) override { ++advance_calls_; std::move(callback).Run(mojom::blink::IDBCursorResult::NewEmpty(true)); } void CursorContinue( std::unique_ptr<IDBKey> key, std::unique_ptr<IDBKey> primary_key, mojom::blink::IDBCursor::CursorContinueCallback callback) override { ++continue_calls_; std::move(callback).Run(mojom::blink::IDBCursorResult::NewEmpty(true)); } void CursorDestroyed() { destroyed_ = true; } int prefetch_calls() { return prefetch_calls_; } int last_prefetch_count() { return last_prefetch_count_; } int reset_calls() { return reset_calls_; } int last_used_count() { return last_used_count_; } int advance_calls() { return advance_calls_; } int continue_calls() { return continue_calls_; } bool destroyed() { return destroyed_; } private: int prefetch_calls_ = 0; int last_prefetch_count_ = 0; int reset_calls_ = 0; int last_used_count_ = 0; int advance_calls_ = 0; int continue_calls_ = 0; bool destroyed_ = false; mojo::AssociatedReceiver<IDBCursor> receiver_; }; class MockContinueCallbacks : public testing::StrictMock<MockWebIDBCallbacks> { public: MockContinueCallbacks(std::unique_ptr<IDBKey>* key = nullptr, Vector<WebBlobInfo>* blobs = nullptr) : key_(key), blobs_(blobs) {} void SetState(base::WeakPtr<WebIDBCursorImpl> cursor, int64_t transaction_id) override {} void SuccessValue(mojom::blink::IDBReturnValuePtr return_value) override {} void SuccessCursorContinue( std::unique_ptr<IDBKey> key, std::unique_ptr<IDBKey> primaryKey, base::Optional<std::unique_ptr<IDBValue>> value) override { if (key_) *key_ = IDBKey::Clone(key); if (blobs_ && value.has_value()) *blobs_ = value.value()->BlobInfo(); } private: std::unique_ptr<IDBKey>* key_; Vector<WebBlobInfo>* blobs_; }; } // namespace class WebIDBCursorImplTest : public testing::Test { public: WebIDBCursorImplTest() : null_key_(IDBKey::CreateNone()) { mojo::AssociatedRemote<mojom::blink::IDBCursor> remote; mock_cursor_ = std::make_unique<MockCursorImpl>( remote.BindNewEndpointAndPassDedicatedReceiver()); cursor_ = std::make_unique<WebIDBCursorImpl>( remote.Unbind(), 1, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); } // Disallow copy and assign. WebIDBCursorImplTest(const WebIDBCursorImplTest&) = delete; WebIDBCursorImplTest& operator=(const WebIDBCursorImplTest&) = delete; protected: ScopedTestingPlatformSupport<TestingPlatformSupport> platform_; std::unique_ptr<IDBKey> null_key_; std::unique_ptr<WebIDBCursorImpl> cursor_; std::unique_ptr<MockCursorImpl> mock_cursor_; }; TEST_F(WebIDBCursorImplTest, PrefetchTest) { // Call continue() until prefetching should kick in. int continue_calls = 0; EXPECT_EQ(mock_cursor_->continue_calls(), 0); for (int i = 0; i < WebIDBCursorImpl::kPrefetchContinueThreshold; ++i) { cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks()); platform_->RunUntilIdle(); EXPECT_EQ(++continue_calls, mock_cursor_->continue_calls()); EXPECT_EQ(0, mock_cursor_->prefetch_calls()); } // Do enough repetitions to verify that the count grows each time, // but not so many that the maximum limit is hit. const int kPrefetchRepetitions = 5; int expected_key = 0; int last_prefetch_count = 0; for (int repetitions = 0; repetitions < kPrefetchRepetitions; ++repetitions) { // Initiate the prefetch cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks()); platform_->RunUntilIdle(); EXPECT_EQ(continue_calls, mock_cursor_->continue_calls()); EXPECT_EQ(repetitions + 1, mock_cursor_->prefetch_calls()); // Verify that the requested count has increased since last time. int prefetch_count = mock_cursor_->last_prefetch_count(); EXPECT_GT(prefetch_count, last_prefetch_count); last_prefetch_count = prefetch_count; // Fill the prefetch cache as requested. Vector<std::unique_ptr<IDBKey>> keys; Vector<std::unique_ptr<IDBKey>> primary_keys; Vector<std::unique_ptr<IDBValue>> values; size_t expected_size = 0; for (int i = 0; i < prefetch_count; ++i) { std::unique_ptr<IDBKey> key = IDBKey::CreateNumber(expected_key + i); keys.emplace_back(std::move(key)); primary_keys.emplace_back(); expected_size++; EXPECT_EQ(expected_size, keys.size()); EXPECT_EQ(expected_size, primary_keys.size()); Vector<WebBlobInfo> blob_info; blob_info.ReserveInitialCapacity(expected_key + i); for (int j = 0; j < expected_key + i; ++j) { blob_info.emplace_back(WebBlobInfo::BlobForTesting( WebString("blobuuid"), "text/plain", 123)); } values.emplace_back(std::make_unique<IDBValue>( scoped_refptr<SharedBuffer>(), std::move(blob_info))); } cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys), std::move(values)); // Note that the real dispatcher would call cursor->CachedContinue() // immediately after cursor->SetPrefetchData() to service the request // that initiated the prefetch. // Verify that the cache is used for subsequent continue() calls. for (int i = 0; i < prefetch_count; ++i) { std::unique_ptr<IDBKey> key; Vector<WebBlobInfo> blobs; cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks(&key, &blobs)); platform_->RunUntilIdle(); EXPECT_EQ(continue_calls, mock_cursor_->continue_calls()); EXPECT_EQ(repetitions + 1, mock_cursor_->prefetch_calls()); EXPECT_EQ(mojom::IDBKeyType::Number, key->GetType()); EXPECT_EQ(expected_key, static_cast<int>(blobs.size())); EXPECT_EQ(expected_key++, key->Number()); } } cursor_.reset(); platform_->RunUntilIdle(); EXPECT_TRUE(mock_cursor_->destroyed()); } TEST_F(WebIDBCursorImplTest, AdvancePrefetchTest) { // Call continue() until prefetching should kick in. EXPECT_EQ(0, mock_cursor_->continue_calls()); for (int i = 0; i < WebIDBCursorImpl::kPrefetchContinueThreshold; ++i) { cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks()); } platform_->RunUntilIdle(); EXPECT_EQ(0, mock_cursor_->prefetch_calls()); // Initiate the prefetch cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks()); platform_->RunUntilIdle(); EXPECT_EQ(1, mock_cursor_->prefetch_calls()); EXPECT_EQ(static_cast<int>(WebIDBCursorImpl::kPrefetchContinueThreshold), mock_cursor_->continue_calls()); EXPECT_EQ(0, mock_cursor_->advance_calls()); const int prefetch_count = mock_cursor_->last_prefetch_count(); // Fill the prefetch cache as requested. int expected_key = 0; Vector<std::unique_ptr<IDBKey>> keys; Vector<std::unique_ptr<IDBKey>> primary_keys; Vector<std::unique_ptr<IDBValue>> values; size_t expected_size = 0; for (int i = 0; i < prefetch_count; ++i) { std::unique_ptr<IDBKey> key = IDBKey::CreateNumber(expected_key + i); keys.emplace_back(std::move(key)); primary_keys.emplace_back(); expected_size++; EXPECT_EQ(expected_size, keys.size()); EXPECT_EQ(expected_size, primary_keys.size()); Vector<WebBlobInfo> blob_info; blob_info.ReserveInitialCapacity(expected_key + i); for (int j = 0; j < expected_key + i; ++j) { blob_info.emplace_back(WebBlobInfo::BlobForTesting(WebString("blobuuid"), "text/plain", 123)); } values.emplace_back(std::make_unique<IDBValue>( scoped_refptr<SharedBuffer>(), std::move(blob_info))); } cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys), std::move(values)); // Note that the real dispatcher would call cursor->CachedContinue() // immediately after cursor->SetPrefetchData() to service the request // that initiated the prefetch. // Need at least this many in the cache for the test steps. ASSERT_GE(prefetch_count, 5); // IDBCursor.continue() std::unique_ptr<IDBKey> key; cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks(&key)); platform_->RunUntilIdle(); EXPECT_EQ(0, key->Number()); // IDBCursor.advance(1) cursor_->Advance(1, new MockContinueCallbacks(&key)); platform_->RunUntilIdle(); EXPECT_EQ(1, key->Number()); // IDBCursor.continue() cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks(&key)); platform_->RunUntilIdle(); EXPECT_EQ(2, key->Number()); // IDBCursor.advance(2) cursor_->Advance(2, new MockContinueCallbacks(&key)); platform_->RunUntilIdle(); EXPECT_EQ(4, key->Number()); EXPECT_EQ(0, mock_cursor_->advance_calls()); // IDBCursor.advance(lots) - beyond the fetched amount cursor_->Advance(WebIDBCursorImpl::kMaxPrefetchAmount, new MockContinueCallbacks(&key)); platform_->RunUntilIdle(); EXPECT_EQ(1, mock_cursor_->advance_calls()); EXPECT_EQ(1, mock_cursor_->prefetch_calls()); EXPECT_EQ(static_cast<int>(WebIDBCursorImpl::kPrefetchContinueThreshold), mock_cursor_->continue_calls()); cursor_.reset(); platform_->RunUntilIdle(); EXPECT_TRUE(mock_cursor_->destroyed()); } TEST_F(WebIDBCursorImplTest, PrefetchReset) { // Call continue() until prefetching should kick in. int continue_calls = 0; EXPECT_EQ(mock_cursor_->continue_calls(), 0); for (int i = 0; i < WebIDBCursorImpl::kPrefetchContinueThreshold; ++i) { cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks()); platform_->RunUntilIdle(); EXPECT_EQ(++continue_calls, mock_cursor_->continue_calls()); EXPECT_EQ(0, mock_cursor_->prefetch_calls()); } // Initiate the prefetch cursor_->CursorContinue(null_key_.get(), null_key_.get(), new MockContinueCallbacks()); platform_->RunUntilIdle(); EXPECT_EQ(continue_calls, mock_cursor_->continue_calls()); EXPECT_EQ(1, mock_cursor_->prefetch_calls()); EXPECT_EQ(0, mock_cursor_->reset_calls()); // Now invalidate it cursor_->ResetPrefetchCache(); // No reset should have been sent since nothing has been received yet. platform_->RunUntilIdle(); EXPECT_EQ(0, mock_cursor_->reset_calls()); // Fill the prefetch cache as requested. int prefetch_count = mock_cursor_->last_prefetch_count(); Vector<std::unique_ptr<IDBKey>> keys(prefetch_count); Vector<std::unique_ptr<IDBKey>> primary_keys(prefetch_count); Vector<std::unique_ptr<IDBValue>> values; for (int i = 0; i < prefetch_count; ++i) { values.emplace_back(std::make_unique<IDBValue>( scoped_refptr<SharedBuffer>(), Vector<WebBlobInfo>())); } cursor_->SetPrefetchData(std::move(keys), std::move(primary_keys), std::move(values)); // No reset should have been sent since prefetch data hasn't been used. platform_->RunUntilIdle(); EXPECT_EQ(0, mock_cursor_->reset_calls()); // The real dispatcher would call cursor->CachedContinue(), so do that: MockContinueCallbacks callbacks; cursor_->CachedContinue(&callbacks); // Now the cursor should have reset the rest of the cache. platform_->RunUntilIdle(); EXPECT_EQ(1, mock_cursor_->reset_calls()); EXPECT_EQ(1, mock_cursor_->last_used_count()); cursor_.reset(); platform_->RunUntilIdle(); EXPECT_TRUE(mock_cursor_->destroyed()); } } // namespace blink
5,429
713
EmbeddedCacheManager cacheManager = ...; Configuration cacheConfig = new ConfigurationBuilder().persistence() .addStore(JpaStoreConfigurationBuilder.class) .persistenceUnitName("org.infinispan.loaders.jpa.configurationTest") .entityClass(User.class) .build(); cacheManager.defineCache("usersCache", cacheConfig); Cache<String, User> usersCache = cacheManager.getCache("usersCache"); usersCache.put("raytsang", new User(...));
164
451
<filename>CodeGenere/photogram/cEqAppui_NoDist__PProjInc_M2CPolyn0.cpp // File Automatically generated by eLiSe #include "StdAfx.h" #include "cEqAppui_NoDist__PProjInc_M2CPolyn0.h" cEqAppui_NoDist__PProjInc_M2CPolyn0::cEqAppui_NoDist__PProjInc_M2CPolyn0(): cElCompiledFonc(2) { AddIntRef (cIncIntervale("Intr",0,3)); AddIntRef (cIncIntervale("Orient",3,9)); AddIntRef (cIncIntervale("Tmp_PTer",9,12)); Close(false); } void cEqAppui_NoDist__PProjInc_M2CPolyn0::ComputeVal() { double tmp0_ = mCompCoord[3]; double tmp1_ = mCompCoord[4]; double tmp2_ = cos(tmp1_); double tmp3_ = mCompCoord[9]; double tmp4_ = mCompCoord[10]; double tmp5_ = mCompCoord[11]; double tmp6_ = sin(tmp0_); double tmp7_ = cos(tmp0_); double tmp8_ = sin(tmp1_); double tmp9_ = mCompCoord[5]; double tmp10_ = mLocProjI_x * tmp3_; double tmp11_ = mLocProjP0_x + tmp10_; double tmp12_ = mLocProjJ_x * tmp4_; double tmp13_ = tmp11_ + tmp12_; double tmp14_ = mLocProjK_x * tmp5_; double tmp15_ = tmp13_ + tmp14_; double tmp16_ = mCompCoord[6]; double tmp17_ = (tmp15_) - tmp16_; double tmp18_ = sin(tmp9_); double tmp19_ = -(tmp18_); double tmp20_ = -(tmp8_); double tmp21_ = cos(tmp9_); double tmp22_ = mLocProjI_y * tmp3_; double tmp23_ = mLocProjP0_y + tmp22_; double tmp24_ = mLocProjJ_y * tmp4_; double tmp25_ = tmp23_ + tmp24_; double tmp26_ = mLocProjK_y * tmp5_; double tmp27_ = tmp25_ + tmp26_; double tmp28_ = mCompCoord[7]; double tmp29_ = (tmp27_) - tmp28_; double tmp30_ = mLocProjI_z * tmp3_; double tmp31_ = mLocProjP0_z + tmp30_; double tmp32_ = mLocProjJ_z * tmp4_; double tmp33_ = tmp31_ + tmp32_; double tmp34_ = mLocProjK_z * tmp5_; double tmp35_ = tmp33_ + tmp34_; double tmp36_ = mCompCoord[8]; double tmp37_ = (tmp35_) - tmp36_; double tmp38_ = -(tmp6_); double tmp39_ = tmp7_ * tmp20_; double tmp40_ = tmp6_ * tmp20_; double tmp41_ = tmp38_ * tmp19_; double tmp42_ = tmp39_ * tmp21_; double tmp43_ = tmp41_ + tmp42_; double tmp44_ = (tmp43_) * (tmp17_); double tmp45_ = tmp7_ * tmp19_; double tmp46_ = tmp40_ * tmp21_; double tmp47_ = tmp45_ + tmp46_; double tmp48_ = (tmp47_) * (tmp29_); double tmp49_ = tmp44_ + tmp48_; double tmp50_ = tmp2_ * tmp21_; double tmp51_ = tmp50_ * (tmp37_); double tmp52_ = tmp49_ + tmp51_; double tmp53_ = tmp7_ * tmp2_; double tmp54_ = tmp53_ * (tmp17_); double tmp55_ = tmp6_ * tmp2_; double tmp56_ = tmp55_ * (tmp29_); double tmp57_ = tmp54_ + tmp56_; double tmp58_ = tmp8_ * (tmp37_); double tmp59_ = tmp57_ + tmp58_; double tmp60_ = (tmp59_) / (tmp52_); double tmp61_ = tmp38_ * tmp21_; double tmp62_ = tmp39_ * tmp18_; double tmp63_ = tmp61_ + tmp62_; double tmp64_ = (tmp63_) * (tmp17_); double tmp65_ = tmp7_ * tmp21_; double tmp66_ = tmp40_ * tmp18_; double tmp67_ = tmp65_ + tmp66_; double tmp68_ = (tmp67_) * (tmp29_); double tmp69_ = tmp64_ + tmp68_; double tmp70_ = tmp2_ * tmp18_; double tmp71_ = tmp70_ * (tmp37_); double tmp72_ = tmp69_ + tmp71_; double tmp73_ = (tmp72_) / (tmp52_); mVal[0] = ((mLocNDP0_x + mLocNDdx_x * (tmp60_) + mLocNDdy_x * (tmp73_)) - mLocXIm) * mLocScNorm; mVal[1] = ((mLocNDP0_y + mLocNDdx_y * (tmp60_) + mLocNDdy_y * (tmp73_)) - mLocYIm) * mLocScNorm; } void cEqAppui_NoDist__PProjInc_M2CPolyn0::ComputeValDeriv() { double tmp0_ = mCompCoord[3]; double tmp1_ = mCompCoord[4]; double tmp2_ = cos(tmp1_); double tmp3_ = mCompCoord[9]; double tmp4_ = mCompCoord[10]; double tmp5_ = mCompCoord[11]; double tmp6_ = sin(tmp0_); double tmp7_ = cos(tmp0_); double tmp8_ = sin(tmp1_); double tmp9_ = mCompCoord[5]; double tmp10_ = mLocProjI_x * tmp3_; double tmp11_ = mLocProjP0_x + tmp10_; double tmp12_ = mLocProjJ_x * tmp4_; double tmp13_ = tmp11_ + tmp12_; double tmp14_ = mLocProjK_x * tmp5_; double tmp15_ = tmp13_ + tmp14_; double tmp16_ = mCompCoord[6]; double tmp17_ = (tmp15_) - tmp16_; double tmp18_ = sin(tmp9_); double tmp19_ = -(tmp18_); double tmp20_ = -(tmp8_); double tmp21_ = cos(tmp9_); double tmp22_ = mLocProjI_y * tmp3_; double tmp23_ = mLocProjP0_y + tmp22_; double tmp24_ = mLocProjJ_y * tmp4_; double tmp25_ = tmp23_ + tmp24_; double tmp26_ = mLocProjK_y * tmp5_; double tmp27_ = tmp25_ + tmp26_; double tmp28_ = mCompCoord[7]; double tmp29_ = (tmp27_) - tmp28_; double tmp30_ = mLocProjI_z * tmp3_; double tmp31_ = mLocProjP0_z + tmp30_; double tmp32_ = mLocProjJ_z * tmp4_; double tmp33_ = tmp31_ + tmp32_; double tmp34_ = mLocProjK_z * tmp5_; double tmp35_ = tmp33_ + tmp34_; double tmp36_ = mCompCoord[8]; double tmp37_ = (tmp35_) - tmp36_; double tmp38_ = -(tmp6_); double tmp39_ = tmp7_ * tmp20_; double tmp40_ = tmp6_ * tmp20_; double tmp41_ = tmp38_ * tmp19_; double tmp42_ = tmp39_ * tmp21_; double tmp43_ = tmp41_ + tmp42_; double tmp44_ = (tmp43_) * (tmp17_); double tmp45_ = tmp7_ * tmp19_; double tmp46_ = tmp40_ * tmp21_; double tmp47_ = tmp45_ + tmp46_; double tmp48_ = (tmp47_) * (tmp29_); double tmp49_ = tmp44_ + tmp48_; double tmp50_ = tmp2_ * tmp21_; double tmp51_ = tmp50_ * (tmp37_); double tmp52_ = tmp49_ + tmp51_; double tmp53_ = tmp7_ * tmp2_; double tmp54_ = tmp53_ * (tmp17_); double tmp55_ = tmp6_ * tmp2_; double tmp56_ = tmp55_ * (tmp29_); double tmp57_ = tmp54_ + tmp56_; double tmp58_ = tmp8_ * (tmp37_); double tmp59_ = tmp57_ + tmp58_; double tmp60_ = -(1); double tmp61_ = tmp60_ * tmp6_; double tmp62_ = -(tmp7_); double tmp63_ = tmp61_ * tmp20_; double tmp64_ = tmp39_ * tmp18_; double tmp65_ = tmp38_ * tmp21_; double tmp66_ = tmp65_ + tmp64_; double tmp67_ = (tmp66_) * (tmp17_); double tmp68_ = tmp7_ * tmp21_; double tmp69_ = tmp40_ * tmp18_; double tmp70_ = tmp68_ + tmp69_; double tmp71_ = (tmp70_) * (tmp29_); double tmp72_ = tmp67_ + tmp71_; double tmp73_ = tmp2_ * tmp18_; double tmp74_ = tmp73_ * (tmp37_); double tmp75_ = tmp72_ + tmp74_; double tmp76_ = tmp62_ * tmp19_; double tmp77_ = tmp63_ * tmp21_; double tmp78_ = tmp76_ + tmp77_; double tmp79_ = (tmp78_) * (tmp17_); double tmp80_ = tmp61_ * tmp19_; double tmp81_ = tmp80_ + tmp42_; double tmp82_ = (tmp81_) * (tmp29_); double tmp83_ = tmp79_ + tmp82_; double tmp84_ = ElSquare(tmp52_); double tmp85_ = tmp60_ * tmp8_; double tmp86_ = -(tmp2_); double tmp87_ = tmp86_ * tmp7_; double tmp88_ = tmp86_ * tmp6_; double tmp89_ = tmp87_ * tmp21_; double tmp90_ = tmp89_ * (tmp17_); double tmp91_ = tmp88_ * tmp21_; double tmp92_ = tmp91_ * (tmp29_); double tmp93_ = tmp90_ + tmp92_; double tmp94_ = tmp85_ * tmp21_; double tmp95_ = tmp94_ * (tmp37_); double tmp96_ = tmp93_ + tmp95_; double tmp97_ = -(tmp21_); double tmp98_ = tmp60_ * tmp18_; double tmp99_ = tmp97_ * tmp38_; double tmp100_ = tmp98_ * tmp39_; double tmp101_ = tmp99_ + tmp100_; double tmp102_ = (tmp101_) * (tmp17_); double tmp103_ = tmp97_ * tmp7_; double tmp104_ = tmp98_ * tmp40_; double tmp105_ = tmp103_ + tmp104_; double tmp106_ = (tmp105_) * (tmp29_); double tmp107_ = tmp102_ + tmp106_; double tmp108_ = tmp98_ * tmp2_; double tmp109_ = tmp108_ * (tmp37_); double tmp110_ = tmp107_ + tmp109_; double tmp111_ = tmp60_ * (tmp43_); double tmp112_ = tmp60_ * (tmp47_); double tmp113_ = tmp60_ * tmp50_; double tmp114_ = mLocProjI_x * (tmp43_); double tmp115_ = mLocProjI_y * (tmp47_); double tmp116_ = tmp114_ + tmp115_; double tmp117_ = mLocProjI_z * tmp50_; double tmp118_ = tmp116_ + tmp117_; double tmp119_ = mLocProjJ_x * (tmp43_); double tmp120_ = mLocProjJ_y * (tmp47_); double tmp121_ = tmp119_ + tmp120_; double tmp122_ = mLocProjJ_z * tmp50_; double tmp123_ = tmp121_ + tmp122_; double tmp124_ = mLocProjK_x * (tmp43_); double tmp125_ = mLocProjK_y * (tmp47_); double tmp126_ = tmp124_ + tmp125_; double tmp127_ = mLocProjK_z * tmp50_; double tmp128_ = tmp126_ + tmp127_; double tmp129_ = (tmp59_) / (tmp52_); double tmp130_ = (tmp75_) / (tmp52_); double tmp131_ = tmp61_ * tmp2_; double tmp132_ = tmp131_ * (tmp17_); double tmp133_ = tmp53_ * (tmp29_); double tmp134_ = tmp132_ + tmp133_; double tmp135_ = (tmp134_) * (tmp52_); double tmp136_ = (tmp59_) * (tmp83_); double tmp137_ = tmp135_ - tmp136_; double tmp138_ = (tmp137_) / tmp84_; double tmp139_ = tmp62_ * tmp21_; double tmp140_ = tmp63_ * tmp18_; double tmp141_ = tmp139_ + tmp140_; double tmp142_ = (tmp141_) * (tmp17_); double tmp143_ = tmp61_ * tmp21_; double tmp144_ = tmp143_ + tmp64_; double tmp145_ = (tmp144_) * (tmp29_); double tmp146_ = tmp142_ + tmp145_; double tmp147_ = (tmp146_) * (tmp52_); double tmp148_ = (tmp75_) * (tmp83_); double tmp149_ = tmp147_ - tmp148_; double tmp150_ = (tmp149_) / tmp84_; double tmp151_ = tmp85_ * tmp7_; double tmp152_ = tmp151_ * (tmp17_); double tmp153_ = tmp85_ * tmp6_; double tmp154_ = tmp153_ * (tmp29_); double tmp155_ = tmp152_ + tmp154_; double tmp156_ = tmp2_ * (tmp37_); double tmp157_ = tmp155_ + tmp156_; double tmp158_ = (tmp157_) * (tmp52_); double tmp159_ = (tmp59_) * (tmp96_); double tmp160_ = tmp158_ - tmp159_; double tmp161_ = (tmp160_) / tmp84_; double tmp162_ = tmp87_ * tmp18_; double tmp163_ = tmp162_ * (tmp17_); double tmp164_ = tmp88_ * tmp18_; double tmp165_ = tmp164_ * (tmp29_); double tmp166_ = tmp163_ + tmp165_; double tmp167_ = tmp85_ * tmp18_; double tmp168_ = tmp167_ * (tmp37_); double tmp169_ = tmp166_ + tmp168_; double tmp170_ = (tmp169_) * (tmp52_); double tmp171_ = (tmp75_) * (tmp96_); double tmp172_ = tmp170_ - tmp171_; double tmp173_ = (tmp172_) / tmp84_; double tmp174_ = (tmp59_) * (tmp110_); double tmp175_ = -(tmp174_); double tmp176_ = tmp175_ / tmp84_; double tmp177_ = tmp98_ * tmp38_; double tmp178_ = tmp21_ * tmp39_; double tmp179_ = tmp177_ + tmp178_; double tmp180_ = (tmp179_) * (tmp17_); double tmp181_ = tmp98_ * tmp7_; double tmp182_ = tmp21_ * tmp40_; double tmp183_ = tmp181_ + tmp182_; double tmp184_ = (tmp183_) * (tmp29_); double tmp185_ = tmp180_ + tmp184_; double tmp186_ = tmp21_ * tmp2_; double tmp187_ = tmp186_ * (tmp37_); double tmp188_ = tmp185_ + tmp187_; double tmp189_ = (tmp188_) * (tmp52_); double tmp190_ = (tmp75_) * (tmp110_); double tmp191_ = tmp189_ - tmp190_; double tmp192_ = (tmp191_) / tmp84_; double tmp193_ = tmp60_ * tmp53_; double tmp194_ = tmp193_ * (tmp52_); double tmp195_ = (tmp59_) * tmp111_; double tmp196_ = tmp194_ - tmp195_; double tmp197_ = (tmp196_) / tmp84_; double tmp198_ = tmp60_ * (tmp66_); double tmp199_ = tmp198_ * (tmp52_); double tmp200_ = (tmp75_) * tmp111_; double tmp201_ = tmp199_ - tmp200_; double tmp202_ = (tmp201_) / tmp84_; double tmp203_ = tmp60_ * tmp55_; double tmp204_ = tmp203_ * (tmp52_); double tmp205_ = (tmp59_) * tmp112_; double tmp206_ = tmp204_ - tmp205_; double tmp207_ = (tmp206_) / tmp84_; double tmp208_ = tmp60_ * (tmp70_); double tmp209_ = tmp208_ * (tmp52_); double tmp210_ = (tmp75_) * tmp112_; double tmp211_ = tmp209_ - tmp210_; double tmp212_ = (tmp211_) / tmp84_; double tmp213_ = tmp85_ * (tmp52_); double tmp214_ = (tmp59_) * tmp113_; double tmp215_ = tmp213_ - tmp214_; double tmp216_ = (tmp215_) / tmp84_; double tmp217_ = tmp60_ * tmp73_; double tmp218_ = tmp217_ * (tmp52_); double tmp219_ = (tmp75_) * tmp113_; double tmp220_ = tmp218_ - tmp219_; double tmp221_ = (tmp220_) / tmp84_; double tmp222_ = mLocProjI_x * tmp53_; double tmp223_ = mLocProjI_y * tmp55_; double tmp224_ = tmp222_ + tmp223_; double tmp225_ = mLocProjI_z * tmp8_; double tmp226_ = tmp224_ + tmp225_; double tmp227_ = (tmp226_) * (tmp52_); double tmp228_ = (tmp59_) * (tmp118_); double tmp229_ = tmp227_ - tmp228_; double tmp230_ = (tmp229_) / tmp84_; double tmp231_ = mLocProjI_x * (tmp66_); double tmp232_ = mLocProjI_y * (tmp70_); double tmp233_ = tmp231_ + tmp232_; double tmp234_ = mLocProjI_z * tmp73_; double tmp235_ = tmp233_ + tmp234_; double tmp236_ = (tmp235_) * (tmp52_); double tmp237_ = (tmp75_) * (tmp118_); double tmp238_ = tmp236_ - tmp237_; double tmp239_ = (tmp238_) / tmp84_; double tmp240_ = mLocProjJ_x * tmp53_; double tmp241_ = mLocProjJ_y * tmp55_; double tmp242_ = tmp240_ + tmp241_; double tmp243_ = mLocProjJ_z * tmp8_; double tmp244_ = tmp242_ + tmp243_; double tmp245_ = (tmp244_) * (tmp52_); double tmp246_ = (tmp59_) * (tmp123_); double tmp247_ = tmp245_ - tmp246_; double tmp248_ = (tmp247_) / tmp84_; double tmp249_ = mLocProjJ_x * (tmp66_); double tmp250_ = mLocProjJ_y * (tmp70_); double tmp251_ = tmp249_ + tmp250_; double tmp252_ = mLocProjJ_z * tmp73_; double tmp253_ = tmp251_ + tmp252_; double tmp254_ = (tmp253_) * (tmp52_); double tmp255_ = (tmp75_) * (tmp123_); double tmp256_ = tmp254_ - tmp255_; double tmp257_ = (tmp256_) / tmp84_; double tmp258_ = mLocProjK_x * tmp53_; double tmp259_ = mLocProjK_y * tmp55_; double tmp260_ = tmp258_ + tmp259_; double tmp261_ = mLocProjK_z * tmp8_; double tmp262_ = tmp260_ + tmp261_; double tmp263_ = (tmp262_) * (tmp52_); double tmp264_ = (tmp59_) * (tmp128_); double tmp265_ = tmp263_ - tmp264_; double tmp266_ = (tmp265_) / tmp84_; double tmp267_ = mLocProjK_x * (tmp66_); double tmp268_ = mLocProjK_y * (tmp70_); double tmp269_ = tmp267_ + tmp268_; double tmp270_ = mLocProjK_z * tmp73_; double tmp271_ = tmp269_ + tmp270_; double tmp272_ = (tmp271_) * (tmp52_); double tmp273_ = (tmp75_) * (tmp128_); double tmp274_ = tmp272_ - tmp273_; double tmp275_ = (tmp274_) / tmp84_; mVal[0] = ((mLocNDP0_x + mLocNDdx_x * (tmp129_) + mLocNDdy_x * (tmp130_)) - mLocXIm) * mLocScNorm; mCompDer[0][0] = 0; mCompDer[0][1] = 0; mCompDer[0][2] = 0; mCompDer[0][3] = ((tmp138_) * mLocNDdx_x + (tmp150_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][4] = ((tmp161_) * mLocNDdx_x + (tmp173_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][5] = ((tmp176_) * mLocNDdx_x + (tmp192_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][6] = ((tmp197_) * mLocNDdx_x + (tmp202_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][7] = ((tmp207_) * mLocNDdx_x + (tmp212_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][8] = ((tmp216_) * mLocNDdx_x + (tmp221_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][9] = ((tmp230_) * mLocNDdx_x + (tmp239_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][10] = ((tmp248_) * mLocNDdx_x + (tmp257_) * mLocNDdy_x) * mLocScNorm; mCompDer[0][11] = ((tmp266_) * mLocNDdx_x + (tmp275_) * mLocNDdy_x) * mLocScNorm; mVal[1] = ((mLocNDP0_y + mLocNDdx_y * (tmp129_) + mLocNDdy_y * (tmp130_)) - mLocYIm) * mLocScNorm; mCompDer[1][0] = 0; mCompDer[1][1] = 0; mCompDer[1][2] = 0; mCompDer[1][3] = ((tmp138_) * mLocNDdx_y + (tmp150_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][4] = ((tmp161_) * mLocNDdx_y + (tmp173_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][5] = ((tmp176_) * mLocNDdx_y + (tmp192_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][6] = ((tmp197_) * mLocNDdx_y + (tmp202_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][7] = ((tmp207_) * mLocNDdx_y + (tmp212_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][8] = ((tmp216_) * mLocNDdx_y + (tmp221_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][9] = ((tmp230_) * mLocNDdx_y + (tmp239_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][10] = ((tmp248_) * mLocNDdx_y + (tmp257_) * mLocNDdy_y) * mLocScNorm; mCompDer[1][11] = ((tmp266_) * mLocNDdx_y + (tmp275_) * mLocNDdy_y) * mLocScNorm; } void cEqAppui_NoDist__PProjInc_M2CPolyn0::ComputeValDerivHessian() { ELISE_ASSERT(false,"Foncteur cEqAppui_NoDist__PProjInc_M2CPolyn0 Has no Der Sec"); } void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetNDP0_x(double aVal){ mLocNDP0_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetNDP0_y(double aVal){ mLocNDP0_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetNDdx_x(double aVal){ mLocNDdx_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetNDdx_y(double aVal){ mLocNDdx_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetNDdy_x(double aVal){ mLocNDdy_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetNDdy_y(double aVal){ mLocNDdy_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjI_x(double aVal){ mLocProjI_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjI_y(double aVal){ mLocProjI_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjI_z(double aVal){ mLocProjI_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjJ_x(double aVal){ mLocProjJ_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjJ_y(double aVal){ mLocProjJ_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjJ_z(double aVal){ mLocProjJ_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjK_x(double aVal){ mLocProjK_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjK_y(double aVal){ mLocProjK_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjK_z(double aVal){ mLocProjK_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjP0_x(double aVal){ mLocProjP0_x = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjP0_y(double aVal){ mLocProjP0_y = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetProjP0_z(double aVal){ mLocProjP0_z = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetScNorm(double aVal){ mLocScNorm = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetXIm(double aVal){ mLocXIm = aVal;} void cEqAppui_NoDist__PProjInc_M2CPolyn0::SetYIm(double aVal){ mLocYIm = aVal;} double * cEqAppui_NoDist__PProjInc_M2CPolyn0::AdrVarLocFromString(const std::string & aName) { if (aName == "NDP0_x") return & mLocNDP0_x; if (aName == "NDP0_y") return & mLocNDP0_y; if (aName == "NDdx_x") return & mLocNDdx_x; if (aName == "NDdx_y") return & mLocNDdx_y; if (aName == "NDdy_x") return & mLocNDdy_x; if (aName == "NDdy_y") return & mLocNDdy_y; if (aName == "ProjI_x") return & mLocProjI_x; if (aName == "ProjI_y") return & mLocProjI_y; if (aName == "ProjI_z") return & mLocProjI_z; if (aName == "ProjJ_x") return & mLocProjJ_x; if (aName == "ProjJ_y") return & mLocProjJ_y; if (aName == "ProjJ_z") return & mLocProjJ_z; if (aName == "ProjK_x") return & mLocProjK_x; if (aName == "ProjK_y") return & mLocProjK_y; if (aName == "ProjK_z") return & mLocProjK_z; if (aName == "ProjP0_x") return & mLocProjP0_x; if (aName == "ProjP0_y") return & mLocProjP0_y; if (aName == "ProjP0_z") return & mLocProjP0_z; if (aName == "ScNorm") return & mLocScNorm; if (aName == "XIm") return & mLocXIm; if (aName == "YIm") return & mLocYIm; return 0; } cElCompiledFonc::cAutoAddEntry cEqAppui_NoDist__PProjInc_M2CPolyn0::mTheAuto("cEqAppui_NoDist__PProjInc_M2CPolyn0",cEqAppui_NoDist__PProjInc_M2CPolyn0::Alloc); cElCompiledFonc * cEqAppui_NoDist__PProjInc_M2CPolyn0::Alloc() { return new cEqAppui_NoDist__PProjInc_M2CPolyn0(); }
8,992
964
[ { "queryName": "Configuration Aggregator to All Regions Disabled", "severity": "HIGH", "line": 4, "fileName": "positive.tf" }, { "queryName": "Configuration Aggregator to All Regions Disabled", "severity": "HIGH", "line": 16, "fileName": "positive.tf" } ]
120
14,425
<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.hadoop.yarn.server.resourcemanager.reservation; import java.util.Map; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.classification.VisibleForTesting; /** * A ReservationAllocation represents a concrete allocation of resources over * time that satisfy a certain {@link ReservationDefinition}. This is used * internally by a {@link Plan} to store information about how each of the * accepted {@link ReservationDefinition} have been allocated. */ public interface ReservationAllocation extends Comparable<ReservationAllocation> { /** * Returns the unique identifier {@link ReservationId} that represents the * reservation * * @return reservationId the unique identifier {@link ReservationId} that * represents the reservation */ ReservationId getReservationId(); /** * Returns the original {@link ReservationDefinition} submitted by the client * * @return the {@link ReservationDefinition} submitted by the client */ ReservationDefinition getReservationDefinition(); /** * Returns the time at which the reservation is activated. * * @return the time at which the reservation is activated */ long getStartTime(); /** * Returns the time at which the reservation terminates. * * @return the time at which the reservation terminates */ long getEndTime(); /** * Returns the map of resources requested against the time interval for which * they were. * * @return the allocationRequests the map of resources requested against the * time interval for which they were */ Map<ReservationInterval, Resource> getAllocationRequests(); /** * Return a string identifying the plan to which the reservation belongs * * @return the plan to which the reservation belongs */ String getPlanName(); /** * Returns the user who requested the reservation * * @return the user who requested the reservation */ String getUser(); /** * Returns whether the reservation has gang semantics or not * * @return true if there is a gang request, false otherwise */ boolean containsGangs(); /** * Sets the time at which the reservation was accepted by the system * * @param acceptedAt the time at which the reservation was accepted by the * system */ void setAcceptanceTimestamp(long acceptedAt); /** * Returns the time at which the reservation was accepted by the system * * @return the time at which the reservation was accepted by the system */ long getAcceptanceTime(); /** * Returns the capacity represented by cumulative resources reserved by the * reservation at the specified point of time * * @param tick the time (UTC in ms) for which the reserved resources are * requested * @return the resources reserved at the specified time */ Resource getResourcesAtTime(long tick); /** * Return a RLE representation of used resources. * * @return a RLE encoding of resources allocated over time. */ RLESparseResourceAllocation getResourcesOverTime(); /** * Return a RLE representation of used resources. * * @param start start of the time interval. * @param end end of the time interval. * @return a RLE encoding of resources allocated over time. */ RLESparseResourceAllocation getResourcesOverTime(long start, long end); /** * Get the periodicity of this reservation representing the time period of the * periodic job. Period is represented in milliseconds for periodic jobs. * Period is 0 for non-periodic jobs. * * @return periodicity of this reservation */ long getPeriodicity(); /** * Set the periodicity of this reservation representing the time period of the * periodic job. Period is represented in milliseconds for periodic jobs. * Period is 0 for non-periodic jobs. * * @param period periodicity of this reservation */ @VisibleForTesting void setPeriodicity(long period); }
1,389
367
<reponame>AppSecAI-TEST/Bigbang<gh_stars>100-1000 package com.forfan.bigbang.entity; import java.util.List; /** * Created by wangyan-pd on 2016/10/26. */ public class WordSegs { private List<String> tag; private List<String> word; public List<String> getTag() { return tag; } public void setTag(List<String> tag) { this.tag = tag; } public List<String> getWord() { return word; } public void setWord(List<String> word) { this.word = word; } }
225
4,868
package com.cf.sms; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * 请在此填写描述 * * @ClassName SmsApiApplication * @Author 隔壁小王子 <EMAIL> * @Date 2019/11/21/021 23:36 * @Version 1.0 **/ @EnableAutoConfiguration @ComponentScan(basePackages = {"com.cf.sms.api"}) @ComponentScan(basePackages = {"com.cf.framework"}) //扫描common包,因为我们需要在Common中统一捕获异常和其它处理 @EnableSwagger2 public class SmsApiApplication { public static void main(String[] args) { SpringApplication.run(SmsApiApplication.class,args); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("**"); } }; } }
527
887
<reponame>traversaro/gazebo /* * Copyright (C) 2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <chrono> #include <map> #include <set> #include <thread> #include <ignition/transport.hh> #include "gazebo/common/Console.hh" #include "gazebo/common/URI.hh" #include "gazebo/util/IntrospectionClient.hh" // #include "gazebo/gui/Futures.hh" #include "gazebo/gui/GuiIface.hh" #include "gazebo/gui/plot/PlottingTypes.hh" #include "gazebo/gui/plot/PlotCurve.hh" #include "gazebo/gui/plot/IntrospectionCurveHandler.hh" using namespace gazebo; using namespace gui; namespace gazebo { namespace gui { /// \brief Private data for the IntrospectionCurveHandler class. class IntrospectionCurveHandlerPrivate { /// \def CurveVariableMapIt /// \brief Curve variable map iterator public: using CurveVariableMapIt = std::map<std::string, CurveVariableSet>::iterator; /// \brief Mutex to protect the introspection updates. public: std::recursive_mutex mutex; /// \brief A map of variable names to plot curves. public: std::map<std::string, CurveVariableSet> curves; /// \brief Introspection Client public: util::IntrospectionClient introspectClient; /// \brief Introspection manager Id public: std::string managerId; /// \brief Ign transport node. public: ignition::transport::Node ignNode; /// \brief Introspection thread. public: std::unique_ptr<std::thread> introspectThread; /// \brief Introspection filter. public: std::set<std::string> introspectFilter; /// \brief Number of subscribers to an introspection filter. public: std::map<std::string, int> introspectFilterCount; /// \brief Introspection filter ID. public: std::string introspectFilterId; /// \brief Introspection filter topic. public: std::string introspectFilterTopic; /// \brief The sim time variable string registered in the /// introspection manager. public: std::string simTimeVar; /// \brief Flag to indicate that the introspection client is initialized. public: bool initialized = false; }; } } ///////////////////////////////////////////////// IntrospectionCurveHandler::IntrospectionCurveHandler() : dataPtr(new IntrospectionCurveHandlerPrivate()) { // set up introspection client in another thread as it blocks on // discovery this->dataPtr->introspectThread.reset( new std::thread(&IntrospectionCurveHandler::SetupIntrospection, this)); } ///////////////////////////////////////////////// IntrospectionCurveHandler::~IntrospectionCurveHandler() { this->dataPtr->initialized = false; this->dataPtr->introspectThread->join(); } ///////////////////////////////////////////////// void IntrospectionCurveHandler::AddCurve(const std::string &_name, PlotCurveWeakPtr _curve) { { std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); if (!this->dataPtr->initialized) { gzerr << "Introspection client has not been initialized yet" << std::endl; return; } } auto c = _curve.lock(); if (!c) return; this->dataPtr->mutex.lock(); auto it = this->dataPtr->curves.find(_name); if (it == this->dataPtr->curves.end()) { // unlock immediately to prevent deadlock in introspection client // callback in AddItemToFilter this->dataPtr->mutex.unlock(); auto addItemToFilterCallback = [this, _curve, _name](const bool _result) { if (!_result) return; // create entry in map CurveVariableSet curveSet; curveSet.insert(_curve); this->dataPtr->curves[_name] = curveSet; }; this->AddItemToFilter(_name, addItemToFilterCallback); } else { auto cIt = it->second.find(_curve); if (cIt == it->second.end()) { it->second.insert(_curve); } this->dataPtr->mutex.unlock(); } } ///////////////////////////////////////////////// void IntrospectionCurveHandler::RemoveCurve(PlotCurveWeakPtr _curve) { std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); if (!this->dataPtr->initialized) { gzerr << "Introspection client has not been initialized yet" << std::endl; return; } auto c = _curve.lock(); if (!c) return; // find and remove the curve for (auto it = this->dataPtr->curves.begin(); it != this->dataPtr->curves.end(); ++it) { auto cIt = it->second.find(_curve); if (cIt != it->second.end()) { it->second.erase(cIt); if (it->second.empty()) { // remove item from introspection filter this->RemoveItemFromFilter(it->first); this->dataPtr->curves.erase(it); } return; } } } ///////////////////////////////////////////////// unsigned int IntrospectionCurveHandler::CurveCount() const { std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); unsigned int count = 0; for (const auto &it : this->dataPtr->curves) count += it.second.size(); return count; } ///////////////////////////////////////////////// bool IntrospectionCurveHandler::Initialized() const { std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); return this->dataPtr->initialized; } ///////////////////////////////////////////////// void IntrospectionCurveHandler::SetupIntrospection() { std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); // TODO re-enable once Futures is integrated // Make sure that the managers have been retreived. // if (Futures::introspectionClientFuture.valid()) // Futures::introspectionClientFuture.get(); gazebo::util::IntrospectionClient client; client.WaitForManagers(std::chrono::seconds(2)); // Get the managers std::set<std::string> managerIds = this->dataPtr->introspectClient.Managers(); if (managerIds.empty()) { gzerr << "No introspection managers detected." << std::endl; return; } // get the first manager this->dataPtr->managerId = *managerIds.begin(); if (this->dataPtr->managerId.empty()) { gzerr << "Introspection manager ID is empty" << std::endl; return; } this->dataPtr->simTimeVar= "data://world/" + gui::get_world() + "?p=time/sim_time"; if (!this->dataPtr->introspectClient.IsRegistered( this->dataPtr->managerId, this->dataPtr->simTimeVar)) { gzerr << "The sim_time item is not registered on the manager.\n"; return; } // Let's create a filter for sim_time. this->dataPtr->introspectFilter = {this->dataPtr->simTimeVar}; this->dataPtr->introspectFilterCount[this->dataPtr->simTimeVar] = 1; if (!this->dataPtr->introspectClient.NewFilter( this->dataPtr->managerId, this->dataPtr->introspectFilter, this->dataPtr->introspectFilterId, this->dataPtr->introspectFilterTopic)) { gzerr << "Unable to create introspection filter" << std::endl; return; } // Subscribe to custom introspection topic for receiving updates. if (!this->dataPtr->ignNode.Subscribe(this->dataPtr->introspectFilterTopic, &IntrospectionCurveHandler::OnIntrospection, this)) { gzerr << "Error subscribing to introspection manager" << std::endl; return; } this->dataPtr->initialized = true; } ///////////////////////////////////////////////// void IntrospectionCurveHandler::OnIntrospection( const gazebo::msgs::Param_V &_msg) { std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); // stores a list of curves iterators and their new values std::vector< std::pair<IntrospectionCurveHandlerPrivate::CurveVariableMapIt, double> > curvesUpdates; // collect data for updates double simTime = 0; bool hasSimTime = false; for (auto i = 0; i < _msg.param_size(); ++i) { auto param = _msg.param(i); if (param.name().empty() || !param.has_value()) continue; std::string paramName = param.name(); auto paramValue = param.value(); // x axis is hardcoded to sim time for now if (!hasSimTime && paramName == this->dataPtr->simTimeVar) { if (paramValue.has_time_value()) { common::Time t = msgs::Convert(paramValue.time_value()); simTime = t.Double(); hasSimTime = true; } } // see if there is a curve with variable name that matches param name or // a substring of the param name for (auto cIt = this->dataPtr->curves.begin(); cIt != this->dataPtr->curves.end(); ++cIt) { if (cIt->first.find(paramName) != 0) continue; // get the data double data = 0; bool validData = true; std::string curveVarName = cIt->first; switch (paramValue.type()) { case gazebo::msgs::Any::DOUBLE: { if (paramValue.has_double_value()) { data = paramValue.double_value(); } break; } case gazebo::msgs::Any::INT32: { if (paramValue.has_int_value()) { data = paramValue.int_value(); } break; } case gazebo::msgs::Any::BOOLEAN: { if (paramValue.has_bool_value()) { data = static_cast<int>(paramValue.bool_value()); } break; } case gazebo::msgs::Any::TIME: { if (paramValue.has_time_value()) { common::Time t = msgs::Convert(paramValue.time_value()); data = t.Double(); } break; } case gazebo::msgs::Any::POSE3D: { if (paramValue.has_pose3d_value()) { ignition::math::Pose3d p = msgs::ConvertIgn(paramValue.pose3d_value()); double d = 0; // use uri to parse and get specific attribute common::URI uri(curveVarName); common::URIQuery query = uri.Query(); std::string queryStr = query.Str(); // example position query string: // p=pose3d/world_pose/vector3d/position/double/x // example rotation query string: // p=pose3d/world_pose/quaterniond/orientation/double/roll if (queryStr.find("position") != std::string::npos) { validData = this->Vector3dFromQuery(queryStr, p.Pos(), d); } else if (queryStr.find("orientation") != std::string::npos) { validData = this->QuaterniondFromQuery(queryStr, p.Rot(), d); } else validData = false; data = d; } else validData = false; break; } case gazebo::msgs::Any::VECTOR3D: { if (paramValue.has_vector3d_value()) { ignition::math::Vector3d vec = msgs::ConvertIgn(paramValue.vector3d_value()); double d = 0; // use uri to parse and get specific attribute common::URI uri(curveVarName); common::URIQuery query = uri.Query(); std::string queryStr = query.Str(); validData = this->Vector3dFromQuery(queryStr, vec, d); data = d; } else validData = false; break; } case gazebo::msgs::Any::QUATERNIOND: { if (paramValue.has_quaternion_value()) { ignition::math::Quaterniond quat = msgs::ConvertIgn(paramValue.quaternion_value()); double d = 0; // use uri to parse and get specific attribute common::URI uri(curveVarName); common::URIQuery query = uri.Query(); std::string queryStr = query.Str(); validData = this->QuaterniondFromQuery(queryStr, quat, d); data = d; } else validData = false; break; } default: { validData = false; break; } } if (!validData) continue; // push to tmp list and update later curvesUpdates.push_back(std::make_pair(cIt, data)); } } // update curves! for (auto &curveUpdate : curvesUpdates) { for (auto cIt : curveUpdate.first->second) { auto curve = cIt.lock(); if (!curve) continue; curve->AddPoint(ignition::math::Vector2d(simTime, curveUpdate.second)); } } } ///////////////////////////////////////////////// void IntrospectionCurveHandler::AddItemToFilter(const std::string &_name, const std::function<void(const bool _result)> &_cb) { // callback from a async items service request auto itemsCallback = [this, _name, _cb](const std::set<std::string> &_items, const bool _itemsResult) { if (!_itemsResult) return; std::lock_guard<std::recursive_mutex> itemLock(this->dataPtr->mutex); common::URI itemURI(_name); common::URIPath itemPath = itemURI.Path(); common::URIQuery itemQuery = itemURI.Query(); for (auto item : _items) { common::URI uri(item); common::URIPath path = uri.Path(); common::URIQuery query = uri.Query(); // check if the entity matches if (itemPath == path) { // A registered variable can have the query // "?p=pose3d/world_pose" // and if the variable we are looking for has the query // "?p=pose3d/world_pose/vector3d/position/double/x" // we need to add "scheme://path?pose3d/world_pose" to filter instead of // "scheme://path?p=pose3d/world_pose/vector3d/position/double/x" // check substring if (itemQuery.Str().find(query.Str()) == 0) { // add item to introspection filter if (this->dataPtr->introspectFilter.find(item) == this->dataPtr->introspectFilter.end()) { auto filterCopy = this->dataPtr->introspectFilter; filterCopy.insert(item); // callback to update the filter and curve map if the // async service request is successful auto filterUpdateCallback = [this, item, _cb](const bool _result) { if (!_result) return; std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); this->dataPtr->introspectFilter.insert(item); this->dataPtr->introspectFilterCount[item] = 1; if (_cb) _cb(_result); }; // Update the filter. We're interested on "item1" and "item2". if (!this->dataPtr->introspectClient.UpdateFilter( this->dataPtr->managerId, this->dataPtr->introspectFilterId, filterCopy, filterUpdateCallback)) { gzerr << "Error updating introspection filter" << std::endl; return; } } else { // filter already exists, increment counter. int &count = this->dataPtr->introspectFilterCount[item]; count++; if (_cb) _cb(true); } break; } } } }; common::URI itemURI(_name); if (!itemURI.Valid()) return; this->dataPtr->introspectClient.Items( this->dataPtr->managerId, itemsCallback); } ///////////////////////////////////////////////// void IntrospectionCurveHandler::RemoveItemFromFilter(const std::string &_name, const std::function<void(const bool _result)> &_cb) { // callback from a async items service request auto itemsCallback = [this, _name, _cb](const std::set<std::string> &_items, const bool _itemsResult) { if (!_itemsResult) return; std::lock_guard<std::recursive_mutex> itemLock(this->dataPtr->mutex); common::URI itemURI(_name); common::URIPath itemPath = itemURI.Path(); common::URIQuery itemQuery = itemURI.Query(); for (auto item : _items) { common::URI uri(item); common::URIPath path = uri.Path(); common::URIQuery query = uri.Query(); // check if the entity matches if (itemPath == path) { // A registered variable can have the query // "?p=pose3d/world_pose" // and if the variable we are looking for has the query // "?p=pose3d/world_pose/vector3d/position/double/x" // we need to remove "scheme://path?pose3d/world_pose" from the filter // instead of // "scheme://path?p=pose3d/world_pose/vector3d/position/double/x" // check substring starts at index 0 if (itemQuery.Str().find(query.Str()) == 0) { // check if it is in the filter list auto itemIt = this->dataPtr->introspectFilter.find(item); if (itemIt == this->dataPtr->introspectFilter.end()) continue; // update filter only if no one else is subscribed to it int &count = this->dataPtr->introspectFilterCount[item]; count--; if (count <= 0) { auto filterCopy = this->dataPtr->introspectFilter; filterCopy.erase(item); // callback for updating the filter and curve map if the // async service request is successful auto filterUpdateCallback = [this, item, _cb](const bool _result) { if (!_result) return; std::lock_guard<std::recursive_mutex> lock(this->dataPtr->mutex); this->dataPtr->introspectFilter.erase(item); this->dataPtr->introspectFilterCount.erase(item); }; // update filter if (!this->dataPtr->introspectClient.UpdateFilter( this->dataPtr->managerId, this->dataPtr->introspectFilterId, filterCopy, filterUpdateCallback)) { gzerr << "Error updating introspection filter" << std::endl; return; } } if (_cb) _cb(true); break; } } } }; common::URI itemURI(_name); if (!itemURI.Valid()) return; this->dataPtr->introspectClient.Items( this->dataPtr->managerId, itemsCallback); } ///////////////////////////////////////////////// bool IntrospectionCurveHandler::Vector3dFromQuery(const std::string &_query, const ignition::math::Vector3d &_vec, double &_value) const { std::string elem = _query.substr(_query.size()-1); if (elem == "x") { _value = _vec.X(); } else if (elem == "y") { _value = _vec.Y(); } else if (elem == "z") { _value = _vec.Z(); } else return false; return true; } ///////////////////////////////////////////////// bool IntrospectionCurveHandler::QuaterniondFromQuery(const std::string &_query, const ignition::math::Quaterniond &_quat, double &_value) const { ignition::math::Vector3d euler = _quat.Euler(); if (_query.find("roll") != std::string::npos) { _value = euler.X(); } else if (_query.find("pitch") != std::string::npos) { _value = euler.Y(); } else if (_query.find("yaw") != std::string::npos) { _value = euler.Z(); } else return false; return true; }
8,236
672
/* * Copyright (c) 2000-2011 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * Copyright (c) 1982, 1986, 1993 * The Regents of the University of California. 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)if_ether.h 8.3 (Berkeley) 5/2/95 * $FreeBSD: src/sys/netinet/if_ether.h,v 1.24 1999/12/29 04:40:58 peter Exp $ */ #ifndef _NETINET_IF_ETHER_H_ #define _NETINET_IF_ETHER_H_ #include <sys/appleapiopts.h> #include <net/ethernet.h> #include <netinet/in.h> #include <net/if_arp.h> #define ea_byte ether_addr_octet /* * Macro to map an IP multicast address to an Ethernet multicast address. * The high-order 25 bits of the Ethernet address are statically assigned, * and the low-order 23 bits are taken from the low end of the IP address. */ #define ETHER_MAP_IP_MULTICAST(ipaddr, enaddr) \ /* struct in_addr *ipaddr; */ \ /* u_char enaddr[ETHER_ADDR_LEN]; */ \ { \ (enaddr)[0] = 0x01; \ (enaddr)[1] = 0x00; \ (enaddr)[2] = 0x5e; \ (enaddr)[3] = ((const u_char *)ipaddr)[1] & 0x7f; \ (enaddr)[4] = ((const u_char *)ipaddr)[2]; \ (enaddr)[5] = ((const u_char *)ipaddr)[3]; \ } /* * Macro to map an IP6 multicast address to an Ethernet multicast address. * The high-order 16 bits of the Ethernet address are statically assigned, * and the low-order 32 bits are taken from the low end of the IP6 address. */ #define ETHER_MAP_IPV6_MULTICAST(ip6addr, enaddr) \ /* struct in6_addr *ip6addr; */ \ /* u_char enaddr[ETHER_ADDR_LEN]; */ \ { \ (enaddr)[0] = 0x33; \ (enaddr)[1] = 0x33; \ (enaddr)[2] = ((const u_char *)ip6addr)[12]; \ (enaddr)[3] = ((const u_char *)ip6addr)[13]; \ (enaddr)[4] = ((const u_char *)ip6addr)[14]; \ (enaddr)[5] = ((const u_char *)ip6addr)[15]; \ } /* * Ethernet Address Resolution Protocol. * * See RFC 826 for protocol description. Structure below is adapted * to resolving internet addresses. Field names used correspond to * RFC 826. */ struct ether_arp { struct arphdr ea_hdr; /* fixed-size header */ u_char arp_sha[ETHER_ADDR_LEN]; /* sender hardware address */ u_char arp_spa[4]; /* sender protocol address */ u_char arp_tha[ETHER_ADDR_LEN]; /* target hardware address */ u_char arp_tpa[4]; /* target protocol address */ }; #define arp_hrd ea_hdr.ar_hrd #define arp_pro ea_hdr.ar_pro #define arp_hln ea_hdr.ar_hln #define arp_pln ea_hdr.ar_pln #define arp_op ea_hdr.ar_op struct sockaddr_inarp { u_char sin_len; u_char sin_family; u_short sin_port; struct in_addr sin_addr; struct in_addr sin_srcaddr; u_short sin_tos; u_short sin_other; #define SIN_PROXY 0x1 #define SIN_ROUTER 0x2 }; /* * IP and ethernet specific routing flags */ #define RTF_USETRAILERS RTF_PROTO1 /* use trailers */ #define RTF_ANNOUNCE RTF_PROTO2 /* announce new arp entry */ #ifdef BSD_KERNEL_PRIVATE extern u_char ether_ipmulticast_min[ETHER_ADDR_LEN]; extern u_char ether_ipmulticast_max[ETHER_ADDR_LEN]; extern struct ifqueue arpintrq; int arpresolve(struct ifnet *, struct rtentry *, struct mbuf *, struct sockaddr *, u_char *, struct rtentry *); void arp_ifinit(struct ifnet *, struct ifaddr *); #endif /* BSD_KERNEL_PRIVATE */ #endif /* _NETINET_IF_ETHER_H_ */
2,181
10,110
# Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """MAG240M-LSC models.""" from typing import Callable, NamedTuple, Sequence import haiku as hk import jax import jax.numpy as jnp import jraph _REDUCER_NAMES = { 'sum': jax.ops.segment_sum, 'mean': jraph.segment_mean, 'softmax': jraph.segment_softmax, } class ModelOutput(NamedTuple): node_embeddings: jnp.ndarray node_embedding_projections: jnp.ndarray node_projection_predictions: jnp.ndarray node_logits: jnp.ndarray def build_update_fn( name: str, output_sizes: Sequence[int], activation: Callable[[jnp.ndarray], jnp.ndarray], normalization_type: str, is_training: bool, ): """Builds update function.""" def single_mlp(inner_name: str): """Creates a single MLP performing the update.""" mlp = hk.nets.MLP( output_sizes=output_sizes, name=inner_name, activation=activation) mlp = jraph.concatenated_args(mlp) if normalization_type == 'layer_norm': norm = hk.LayerNorm( axis=-1, create_scale=True, create_offset=True, name=name + '_layer_norm') elif normalization_type == 'batch_norm': batch_norm = hk.BatchNorm( create_scale=True, create_offset=True, decay_rate=0.9, name=f'{inner_name}_batch_norm', cross_replica_axis=None if hk.running_init() else 'i', ) norm = lambda x: batch_norm(x, is_training) elif normalization_type == 'none': return mlp else: raise ValueError(f'Unknown normalization type {normalization_type}') return jraph.concatenated_args(hk.Sequential([mlp, norm])) return single_mlp(f'{name}_homogeneous') def build_gn( output_sizes: Sequence[int], activation: Callable[[jnp.ndarray], jnp.ndarray], suffix: str, use_sent_edges: bool, is_training: bool, dropedge_rate: float, normalization_type: str, aggregation_function: str, ): """Builds an InteractionNetwork with MLP update functions.""" node_update_fn = build_update_fn( f'node_processor_{suffix}', output_sizes, activation=activation, normalization_type=normalization_type, is_training=is_training, ) edge_update_fn = build_update_fn( f'edge_processor_{suffix}', output_sizes, activation=activation, normalization_type=normalization_type, is_training=is_training, ) def maybe_dropedge(x): """Dropout on edge messages.""" if not is_training: return x return x * hk.dropout( hk.next_rng_key(), dropedge_rate, jnp.ones([x.shape[0], 1]), ) dropped_edge_update_fn = lambda *args: maybe_dropedge(edge_update_fn(*args)) return jraph.InteractionNetwork( update_edge_fn=dropped_edge_update_fn, update_node_fn=node_update_fn, aggregate_edges_for_nodes_fn=_REDUCER_NAMES[aggregation_function], include_sent_messages_in_node_update=use_sent_edges, ) def _get_activation_fn(name: str) -> Callable[[jnp.ndarray], jnp.ndarray]: if name == 'identity': return lambda x: x if hasattr(jax.nn, name): return getattr(jax.nn, name) raise ValueError('Unknown activation function %s specified. ' 'See https://jax.readthedocs.io/en/latest/jax.nn.html' 'for the list of supported function names.') class NodePropertyEncodeProcessDecode(hk.Module): """Node Property Prediction Encode Process Decode Model.""" def __init__( self, mlp_hidden_sizes: Sequence[int], latent_size: int, num_classes: int, num_message_passing_steps: int = 2, activation: str = 'relu', dropout_rate: float = 0.0, dropedge_rate: float = 0.0, use_sent_edges: bool = False, disable_edge_updates: bool = False, normalization_type: str = 'layer_norm', aggregation_function: str = 'sum', name='NodePropertyEncodeProcessDecode', ): super().__init__(name=name) self._num_classes = num_classes self._latent_size = latent_size self._output_sizes = list(mlp_hidden_sizes) + [latent_size] self._num_message_passing_steps = num_message_passing_steps self._activation = _get_activation_fn(activation) self._dropout_rate = dropout_rate self._dropedge_rate = dropedge_rate self._use_sent_edges = use_sent_edges self._disable_edge_updates = disable_edge_updates self._normalization_type = normalization_type self._aggregation_function = aggregation_function def _dropout_graph(self, graph: jraph.GraphsTuple) -> jraph.GraphsTuple: node_key, edge_key = hk.next_rng_keys(2) nodes = hk.dropout(node_key, self._dropout_rate, graph.nodes) edges = graph.edges if not self._disable_edge_updates: edges = hk.dropout(edge_key, self._dropout_rate, edges) return graph._replace(nodes=nodes, edges=edges) def _encode( self, graph: jraph.GraphsTuple, is_training: bool, ) -> jraph.GraphsTuple: node_embed_fn = build_update_fn( 'node_encoder', self._output_sizes, activation=self._activation, normalization_type=self._normalization_type, is_training=is_training, ) edge_embed_fn = build_update_fn( 'edge_encoder', self._output_sizes, activation=self._activation, normalization_type=self._normalization_type, is_training=is_training, ) gn = jraph.GraphMapFeatures(edge_embed_fn, node_embed_fn) graph = gn(graph) if is_training: graph = self._dropout_graph(graph) return graph def _process( self, graph: jraph.GraphsTuple, is_training: bool, ) -> jraph.GraphsTuple: for idx in range(self._num_message_passing_steps): net = build_gn( output_sizes=self._output_sizes, activation=self._activation, suffix=str(idx), use_sent_edges=self._use_sent_edges, is_training=is_training, dropedge_rate=self._dropedge_rate, normalization_type=self._normalization_type, aggregation_function=self._aggregation_function) residual_graph = net(graph) graph = graph._replace(nodes=graph.nodes + residual_graph.nodes) if not self._disable_edge_updates: graph = graph._replace(edges=graph.edges + residual_graph.edges) if is_training: graph = self._dropout_graph(graph) return graph def _node_mlp( self, graph: jraph.GraphsTuple, is_training: bool, output_size: int, name: str, ) -> jnp.ndarray: decoder_sizes = list(self._output_sizes[:-1]) + [output_size] net = build_update_fn( name, decoder_sizes, self._activation, normalization_type=self._normalization_type, is_training=is_training, ) return net(graph.nodes) def __call__( self, graph: jraph.GraphsTuple, is_training: bool, stop_gradient_embedding_to_logits: bool = False, ) -> ModelOutput: # Note that these update configs may need to change if # we switch back to GraphNetwork rather than InteractionNetwork. graph = self._encode(graph, is_training) graph = self._process(graph, is_training) node_embeddings = graph.nodes node_projections = self._node_mlp(graph, is_training, self._latent_size, 'projector') node_predictions = self._node_mlp( graph._replace(nodes=node_projections), is_training, self._latent_size, 'predictor', ) if stop_gradient_embedding_to_logits: graph = jax.tree_map(jax.lax.stop_gradient, graph) node_logits = self._node_mlp(graph, is_training, self._num_classes, 'logits_decoder') return ModelOutput( node_embeddings=node_embeddings, node_logits=node_logits, node_embedding_projections=node_projections, node_projection_predictions=node_predictions, )
3,609
2,313
<gh_stars>1000+ /* * Copyright (c) 2019-2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef ARM_COMPUTE_CL_CROP_KERNEL_H #define ARM_COMPUTE_CL_CROP_KERNEL_H #include "src/core/common/Macros.h" #include "src/core/gpu/cl/ClCompileContext.h" #include "src/core/gpu/cl/IClKernel.h" namespace arm_compute { namespace opencl { namespace kernels { /** OpenCL kernel to perform a copy between two tensors */ class ClCropKernel : public IClKernel { public: ClCropKernel(); ARM_COMPUTE_DISALLOW_COPY_ALLOW_MOVE(ClCropKernel); /** Configure kernel * * @note Supported tensor rank: up to 4 * * @param[in] compile_context The compile context to be used. * @param[in] src Source tensor info. Data type supported: All. Data layouts supported: NHWC. * @param[out] dst Destination tensor info. Data type supported: F32 * @param[in] start Coordinates of where to start cropping the image. * @param[in] end Coordinates of where to end cropping the image. * @param[in] batch_index Fourth dimension index of the 3D image to crop in @p src. * @param[in] extrapolation_value Value to be used for values outside of the image. Default is 0. * @param[in] dst_window Output window to be used in case cropped image is being copied into a tensor. Default is nullptr. */ void configure(const CLCompileContext &compile_context, const ITensorInfo *src, ITensorInfo *dst, Coordinates2D start, Coordinates2D end, uint32_t batch_index, float extrapolation_value = 0, Window *dst_window = nullptr); /** Static function to check if given info will lead to a valid configuration * * Similar to @ref ClCropKernel::configure() * * @return a status */ static Status validate(const ITensorInfo *src, const ITensorInfo *dst, Coordinates2D start, Coordinates2D end, uint32_t batch_index, float extrapolation_value = 0, Window *dst_window = nullptr); // Inherited methods overridden: void run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) override; private: Coordinates2D _start{}; uint32_t _batch_index{}; float _extrapolation_value{}; }; } // namespace kernels } // namespace opencl } // namespace arm_compute #endif /* ARM_COMPUTE_CL_CROP_KERNEL_H */
1,229
528
<filename>tests/array/array/testArray1fViews.cpp #include "array/zfparray1.h" using namespace zfp; extern "C" { #include "utils/rand32.h" } #define ARRAY_DIMS_SCALAR_TEST Array1fTest #define ARRAY_DIMS_SCALAR_TEST_VIEWS Array1fTestViews #include "utils/gtest1fTest.h" #define ZFP_ARRAY_TYPE array1f #define SCALAR float #define DIMS 1 #include "testArrayViewsBase.cpp" #include "testArray1ViewsBase.cpp"
175
1,104
<filename>trunk/adhoc-wrapper/src/main/java/backtype/storm/utils/NimbusClient.java package backtype.storm.utils; import backtype.storm.Config; import backtype.storm.generated.Nimbus; import java.util.Map; import org.apache.thrift7.TException; import org.apache.thrift7.protocol.TBinaryProtocol; import org.apache.thrift7.transport.TFramedTransport; import org.apache.thrift7.transport.TSocket; import org.apache.thrift7.transport.TTransport; public class NimbusClient { public static NimbusClient getConfiguredClient(Map conf) { String nimbusHost = (String) conf.get(Config.NIMBUS_HOST); int nimbusPort = Utils.getInt(conf.get(Config.NIMBUS_THRIFT_PORT)); return new NimbusClient(nimbusHost, nimbusPort); } private TTransport conn; private Nimbus.Client client; public NimbusClient(String host) { this(host, 6627); } public NimbusClient(String host, int port) { try { if(host==null) { throw new IllegalArgumentException("Nimbus host is not set"); } conn = new TFramedTransport(new TSocket(host, port)); client = new Nimbus.Client(new TBinaryProtocol(conn)); conn.open(); } catch(TException e) { throw new RuntimeException(e); } } public Nimbus.Client getClient() { return client; } public void close() { conn.close(); } }
597
637
<filename>test/src/test/java/lib/form/FormTest.java package lib.form; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.model.RootAction; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; import org.xml.sax.SAXException; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Tests for lib/form.jelly. */ public class FormTest { @Rule public JenkinsRule j = new JenkinsRule(); @Test @Issue("JENKINS-18435") public void autocompleteOffByDefault() throws IOException, SAXException { HtmlPage page = j.createWebClient().goTo("autocompleteOffByDefault"); HtmlForm form = page.getFormByName("config"); String autocomplete = form.getAttribute("autocomplete"); assertNotNull(autocomplete); assertEquals("off", autocomplete); } @Test @Issue("JENKINS-18435") public void autocompleteOnWhenTrue() throws IOException, SAXException { HtmlPage page = j.createWebClient().goTo("autocompleteOnWhenTrue"); HtmlForm form = page.getFormByName("config"); String autocomplete = form.getAttribute("autocomplete"); assertNotNull(autocomplete); assertEquals("on", autocomplete); } @Test @Issue("JENKINS-18435") public void inputsCanSetAutocomplete() throws IOException, SAXException { HtmlPage page = j.createWebClient().goTo("inputsCanSetAutocomplete"); HtmlForm form = page.getFormByName("config"); HtmlInput a = form.getInputByName("a"); String autocomplete = a.getAttribute("autocomplete"); assertNotNull(autocomplete); assertEquals("on", autocomplete); } @TestExtension("autocompleteOffByDefault") public static class AutocompleteOffByDefault implements RootAction { @Override public String getIconFileName() { return "gear2.png"; } @Override public String getDisplayName() { return "AutocompleteOffByDefault"; } @Override public String getUrlName() { return "autocompleteOffByDefault"; } } @TestExtension("autocompleteOnWhenTrue") public static class AutocompleteOnWhenTrue implements RootAction { @Override public String getIconFileName() { return "gear2.png"; } @Override public String getDisplayName() { return "AutocompleteOnWhenTrue"; } @Override public String getUrlName() { return "autocompleteOnWhenTrue"; } } @TestExtension("inputsCanSetAutocomplete") public static class InputsCanSetAutocomplete implements RootAction { @Override public String getIconFileName() { return "gear2.png"; } @Override public String getDisplayName() { return "InputsCanSetAutocomplete"; } @Override public String getUrlName() { return "inputsCanSetAutocomplete"; } } }
1,360
558
<reponame>pratikadarsh/Algorithms ''' * @file MergeSort.py * @author (original JAVA) <NAME>, <EMAIL> * (conversion to Python) <NAME>, <EMAIL> * @date 27 Jun 2020 * @version 0.1 * @brief Merge sort implementation ''' import sys class MergeSort(): """ Mergesort implements InplaceSort for ease of testings, but in reality it is not really a good fit for an inplace sorting algorithm. """ def __init__(self): pass def sort(self, values): return self.mergesort(values) def mergesort(self, ar): """ Base case is when a single element (which is already sorted) """ n = len(ar) if n <= 1: return ar # Split array into two parts and recursively sort them left = self.mergesort(ar[:n // 2]) right = self.mergesort(ar[n // 2::]) # Combine the two arrays into one larger array return self.merge(left, right) def merge(self, ar1, ar2): """ Merge two sorted arrays into a larger sorted array """ n1 = len(ar1) n2 = len(ar2) n = n1 + n2 i1 = 0 i2 = 0 ar = [0]*n for i in range(0, n): if i1 == n1: ar[i] = ar2[i2] i2 += 1 elif i2 == n2: ar[i] = ar1[i1] i1 += 1 else: if ar1[i1] < ar2[i2]: ar[i] = ar1[i1] i1 += 1 else: ar[i] = ar2[i2] i2 += 1 return ar if __name__ == '__main__': """ Example usage """ array = [10, 4, 6, 4, 8, -13, 2, 3] sorter = MergeSort() array = sorter.sort(array) # Prints: # [-13, 2, 3, 4, 4, 6, 8, 10] print(array)
749
2,151
<reponame>cohortfsllc/cohort-cocl2-sandbox /* * Copyright (c) 2013 The Native Client 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 <errno.h> #include <fcntl.h> #include <limits.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "native_client/src/include/nacl_macros.h" #include "native_client/src/public/imc_syscalls.h" #include "native_client/src/public/imc_types.h" static char const quote[] = " En tibi norma Poli, & divae libramina Molis," " Computus atque Jovis; quas, dum primordia rerum" " Pangeret, omniparens Leges violare Creator" " Noluit, aeternique operis fundamina fixit." " Intima panduntur victi penetralia caeli," " Nec latet extremos quae Vis circumrotat Orbes." " Sol solio residens ad se jubet omnia prono" " Tendere descensu, nec recto tramite currus" " Sidereos patitur vastum per inane moveri;" " Sed rapit immotis, se centro, singula Gyris." " Jam patet horrificis quae sit via flexa Cometis;" " Jam non miramur barbati Phaenomena Astri." " Discimus hinc tandem qua causa argentea Phoebe" " Passibus haud aequis graditur; cur subdita nulli" " Hactenus Astronomo numerorum fraena recuset:" " Cur remeant Nodi, curque Auges progrediuntur."; int CreateTestFile(char const *fn, int open_flags) { FILE *iob; int d; iob = fopen(fn, "w"); if (NULL == iob) { fprintf(stderr, "CreateTestFile: could not open for initial contents, errno %d\n", errno); } if (EOF == fputs(quote, iob)) { fprintf(stderr, "CreateTestFile: could not write initial contents, errno %d\n", errno); exit(1); } if (EOF == fclose(iob)) { fprintf(stderr, "CreateTestFile: could not close/flush initial contents," " errno %d\n", errno); exit(1); } d = open(fn, open_flags); if (-1 == d) { fprintf(stderr, "CreateTestFile: could not open for test access, errno %d\n", errno); exit(1); } return d; } int CheckReadExpectations(int fd, size_t start, size_t num_bytes) { char buffer[1<<16]; size_t got; if (num_bytes > sizeof buffer) { fprintf(stderr, "CheckReadExpectations: num_bytes too large\n"); return 1; } got = read(fd, buffer, num_bytes); if (got != num_bytes) { fprintf(stderr, "CheckReadExpectations: read got %zu, expected %zu\n", got, num_bytes); return 1; } if (0 != memcmp(quote + start, buffer, num_bytes)) { fprintf(stderr, "CheckReadExpectations: data differs\n" " expected: %.*s\n" " got: %.*s\n", (int) num_bytes, quote + start, (int) num_bytes, buffer); return 1; } return 0; } int CheckPartialRead(int fd) { return CheckReadExpectations(fd, 0, 100); } int CheckContinuedRead(int fd) { return CheckReadExpectations(fd, 100, 64); } int CheckSharedFilePosOrig(int fd) { return CheckReadExpectations(fd, 164, 32); } static int GetReplicatedDescDup(int d) { return dup(d); } struct ThreadWork { pthread_mutex_t mu; pthread_cond_t cv; int imc_d; int d; }; static void ThreadWorkCtor(struct ThreadWork *tw, int d) { int err; err = pthread_mutex_init(&tw->mu, (pthread_mutexattr_t *) NULL); if (0 != err) { fprintf(stderr, "ThreadWorkCtor: pthread_mutex_init failed, errno %d\n", err); exit(1); } err = pthread_cond_init(&tw->cv, (pthread_condattr_t *) NULL); if (0 != err) { fprintf(stderr, "ThreadWorkCtor: pthread_cond_init failed, errno %d\n", err); exit(1); } tw->imc_d = d; tw->d = -1; } static void CheckedClose(int d, char const *component) { if (close(d) != 0) { fprintf(stderr, "%s: close failed, errno %d\n", component, errno); exit(1); } } static void ThreadWorkDtor(struct ThreadWork *tw) { int err; err = pthread_mutex_destroy(&tw->mu); if (0 != err) { fprintf(stderr, "ThreadWorkDtor: pthread_mutex_destroy failed, errno %d\n", err); } err = pthread_cond_destroy(&tw->cv); if (0 != err) { fprintf(stderr, "ThreadWorkDtor: pthread_cond_destroy failed, errno %d\n", err); } if (tw->d != -1) { CheckedClose(tw->d, "ThreadWorkDtor"); tw->d = -1; } } static void *thread_func(void *state) { struct ThreadWork *tw = (struct ThreadWork *) state; int connected; struct NaClAbiNaClImcMsgHdr msg; int d; connected = imc_connect(tw->imc_d); if (-1 == connected) { fprintf(stderr, "thread_func: imc_connect failed, errno %d\n", errno); exit(1); } msg.iov = NULL; msg.iov_length = 0; msg.descv = &d; msg.desc_length = 1; if (0 != imc_recvmsg(connected, &msg, 0)) { fprintf(stderr, "thread_func: imc_recvmsg failed, errno %d\n", errno); exit(1); } pthread_mutex_lock(&tw->mu); tw->d = d; pthread_cond_broadcast(&tw->cv); pthread_mutex_unlock(&tw->mu); CheckedClose(connected, "thread_func: connected descriptor"); return NULL; } static int GetReplicatedDescImc(int d) { int bound_pair[2]; struct ThreadWork tw; pthread_t tid; int err; int connected; struct NaClAbiNaClImcMsgHdr msg; int got_d; if (0 != imc_makeboundsock(bound_pair)) { fprintf(stderr, "GetReplicatedDescImc: imc_makeboundsock failed, errno %d\n", errno); exit(1); } ThreadWorkCtor(&tw, bound_pair[1]); err = pthread_create(&tid, (pthread_attr_t const *) NULL, thread_func, (void *) &tw); if (0 != err) { fprintf(stderr, "GetReplicatedDescImc: pthread_create failed, errno %d\n", err); exit(1); } connected = imc_accept(bound_pair[0]); if (-1 == connected) { fprintf(stderr, "GetReplicatedDescImc: imc_accept failed, errno %d\n", errno); exit(1); } msg.iov = NULL; msg.iov_length = 0; msg.descv = &d; msg.desc_length = 1; if (0 != imc_sendmsg(connected, &msg, 0)) { fprintf(stderr, "GetReplicatedDescImc: imc_sendmsg failed, errno %d\n", errno); exit(1); } pthread_mutex_lock(&tw.mu); while (tw.d == -1) { pthread_cond_wait(&tw.cv, &tw.mu); } got_d = tw.d; tw.d = -1; pthread_mutex_unlock(&tw.mu); err = pthread_join(tid, NULL); if (0 != err) { fprintf(stderr, "GetReplicatedDescImc: pthread_join failed, errno %d\n", err); exit(1); } CheckedClose(bound_pair[0], "GetReplicatedDescImc: bound_pair[0]"); CheckedClose(bound_pair[1], "GetReplicatedDescImc: bound_pair[1]"); CheckedClose(connected, "GetReplicatedDescImc: connected descriptor"); ThreadWorkDtor(&tw); return got_d; } struct TestParams { char const *test_name; int (*get_desc)(int original_desc); int open_flags; /* ensure O_RDONLY and O_RDWR operates the same */ }; static struct TestParams const tests[] = { { "dup, ronly", GetReplicatedDescDup, O_RDONLY }, { "dup, rw", GetReplicatedDescDup, O_RDWR }, { "imc, ronly", GetReplicatedDescImc, O_RDONLY }, { "imc, rw", GetReplicatedDescImc, O_RDWR }, }; int main(int ac, char **av) { char const *test_file_dir = "/tmp/filepos_test"; int fd, fd_copy; size_t err_count; size_t test_errors; size_t ix; int opt; int num_runs = 1; int test_run; while (EOF != (opt = getopt(ac, av, "c:t:"))) { switch (opt) { case 'c': num_runs = atoi(optarg); break; case 't': test_file_dir = optarg; break; default: fprintf(stderr, "Usage: filepos_test [-c run_count]\n" " [-t test_temporary_dir]\n"); exit(1); } } err_count = 0; for (test_run = 0; test_run < num_runs; ++test_run) { printf("Test run %d\n\n", test_run); for (ix = 0; ix < NACL_ARRAY_SIZE(tests); ++ix) { char test_file_name[PATH_MAX]; printf("%s\n", tests[ix].test_name); snprintf(test_file_name, sizeof test_file_name, "%s/f%d.%u", test_file_dir, test_run, ix); fd = CreateTestFile(test_file_name, tests[ix].open_flags); CheckPartialRead(fd); fd_copy = tests[ix].get_desc(fd); test_errors = CheckContinuedRead(fd_copy); printf("continued read, copy: %s\n", (0 == test_errors) ? "PASS" : "FAIL"); err_count += test_errors; test_errors = CheckSharedFilePosOrig(fd); printf("continued read, orig: %s\n", (0 == test_errors) ? "PASS" : "FAIL"); err_count += test_errors; CheckedClose(fd, "filepos_test: main: test file, orig fd"); CheckedClose(fd_copy, "filepos_test: main: test file, fd copy"); } } /* we ignore the 2^32 or 2^64 total errors case */ return (err_count > 255) ? 255 : err_count; }
4,013
19,438
<filename>Userland/Libraries/LibCrypto/BigInt/Algorithms/ModularPower.cpp /* * Copyright (c) 2020, <NAME> <<EMAIL>> * Copyright (c) 2020-2021, Dex♪ <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #include "UnsignedBigIntegerAlgorithms.h" namespace Crypto { void UnsignedBigIntegerAlgorithms::destructive_modular_power_without_allocation( UnsignedBigInteger& ep, UnsignedBigInteger& base, UnsignedBigInteger const& m, UnsignedBigInteger& temp_1, UnsignedBigInteger& temp_2, UnsignedBigInteger& temp_3, UnsignedBigInteger& temp_4, UnsignedBigInteger& temp_multiply, UnsignedBigInteger& temp_quotient, UnsignedBigInteger& temp_remainder, UnsignedBigInteger& exp) { exp.set_to(1); while (!(ep < 1)) { if (ep.words()[0] % 2 == 1) { // exp = (exp * base) % m; multiply_without_allocation(exp, base, temp_1, temp_2, temp_3, temp_multiply); divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder); exp.set_to(temp_remainder); } // ep = ep / 2; divide_u16_without_allocation(ep, 2, temp_quotient, temp_remainder); ep.set_to(temp_quotient); // base = (base * base) % m; multiply_without_allocation(base, base, temp_1, temp_2, temp_3, temp_multiply); divide_without_allocation(temp_multiply, m, temp_1, temp_2, temp_3, temp_4, temp_quotient, temp_remainder); base.set_to(temp_remainder); // Note that not clamping here would cause future calculations (multiply, specifically) to allocate even more unused space // which would then persist through the temp bigints, and significantly slow down later loops. // To avoid that, we can clamp to a specific max size, or just clamp to the min needed amount of space. ep.clamp_to_trimmed_length(); exp.clamp_to_trimmed_length(); base.clamp_to_trimmed_length(); } } /** * Compute (1/value) % 2^32. * This needs an odd input value * Algorithm from: <NAME>. "On Newton–Raphson Iteration for Multiplicative Inverses Modulo Prime Powers". */ ALWAYS_INLINE static u32 inverse_wrapped(u32 value) { VERIFY(value & 1); u64 b = static_cast<u64>(value); u64 k0 = (2 - b); u64 t = (b - 1); size_t i = 1; while (i < 32) { t = t * t; k0 = k0 * (t + 1); i <<= 1; } return static_cast<u32>(-k0); } /** * Computes z = x * y + c. z_carry contains the top bits, z contains the bottom bits. */ ALWAYS_INLINE static void linear_multiplication_with_carry(u32 x, u32 y, u32 c, u32& z_carry, u32& z) { u64 result = static_cast<u64>(x) * static_cast<u64>(y) + static_cast<u64>(c); z_carry = static_cast<u32>(result >> 32); z = static_cast<u32>(result); } /** * Computes z = a + b. z_carry contains the top bit (1 or 0), z contains the bottom bits. */ ALWAYS_INLINE static void addition_with_carry(u32 a, u32 b, u32& z_carry, u32& z) { u64 result = static_cast<u64>(a) + static_cast<u64>(b); z_carry = static_cast<u32>(result >> 32); z = static_cast<u32>(result); } /** * Computes a montgomery "fragment" for y_i. This computes "z[i] += x[i] * y_i" for all words while rippling the carry, and returns the carry. * Algorithm from: Gueron, "Efficient Software Implementations of Modular Exponentiation". (https://eprint.iacr.org/2011/239.pdf) */ UnsignedBigInteger::Word UnsignedBigIntegerAlgorithms::montgomery_fragment(UnsignedBigInteger& z, size_t offset_in_z, UnsignedBigInteger const& x, UnsignedBigInteger::Word y_digit, size_t num_words) { UnsignedBigInteger::Word carry { 0 }; for (size_t i = 0; i < num_words; ++i) { UnsignedBigInteger::Word a_carry; UnsignedBigInteger::Word a; linear_multiplication_with_carry(x.m_words[i], y_digit, z.m_words[offset_in_z + i], a_carry, a); UnsignedBigInteger::Word b_carry; UnsignedBigInteger::Word b; addition_with_carry(a, carry, b_carry, b); z.m_words[offset_in_z + i] = b; carry = a_carry + b_carry; } return carry; } /** * Computes the "almost montgomery" product : x * y * 2 ^ (-num_words * BITS_IN_WORD) % modulo * [Note : that means that the result z satisfies z * 2^(num_words * BITS_IN_WORD) % modulo = x * y % modulo] * assuming : * - x, y and modulo are all already padded to num_words * - k = inverse_wrapped(modulo) (optimization to not recompute K each time) * Algorithm from: Gueron, "Efficient Software Implementations of Modular Exponentiation". (https://eprint.iacr.org/2011/239.pdf) */ void UnsignedBigIntegerAlgorithms::almost_montgomery_multiplication_without_allocation( UnsignedBigInteger const& x, UnsignedBigInteger const& y, UnsignedBigInteger const& modulo, UnsignedBigInteger& z, UnsignedBigInteger::Word k, size_t num_words, UnsignedBigInteger& result) { VERIFY(x.length() >= num_words); VERIFY(y.length() >= num_words); VERIFY(modulo.length() >= num_words); z.set_to(0); z.resize_with_leading_zeros(num_words * 2); UnsignedBigInteger::Word previous_double_carry { 0 }; for (size_t i = 0; i < num_words; ++i) { // z[i->num_words+i] += x * y_i UnsignedBigInteger::Word carry_1 = montgomery_fragment(z, i, x, y.m_words[i], num_words); // z[i->num_words+i] += modulo * (z_i * k) UnsignedBigInteger::Word t = z.m_words[i] * k; UnsignedBigInteger::Word carry_2 = montgomery_fragment(z, i, modulo, t, num_words); // Compute the carry by combining all of the carrys of the previous computations // Put it "right after" the range that we computed above UnsignedBigInteger::Word temp_carry = previous_double_carry + carry_1; UnsignedBigInteger::Word overall_carry = temp_carry + carry_2; z.m_words[num_words + i] = overall_carry; // Detect if there was a "double carry" for this word by checking if our carry results are smaller than their components previous_double_carry = (temp_carry < carry_1 || overall_carry < carry_2) ? 1 : 0; } if (previous_double_carry == 0) { // Return the top num_words bytes of Z, which contains our result. shift_right_by_n_words(z, num_words, result); result.resize_with_leading_zeros(num_words); return; } // We have a carry, so we're "one bigger" than we need to be. // Subtract the modulo from the result (the top half of z), and write it to the bottom half of Z since we have space. // (With carry, of course.) UnsignedBigInteger::Word c { 0 }; for (size_t i = 0; i < num_words; ++i) { UnsignedBigInteger::Word z_digit = z.m_words[num_words + i]; UnsignedBigInteger::Word modulo_digit = modulo.m_words[i]; UnsignedBigInteger::Word new_z_digit = z_digit - modulo_digit - c; z.m_words[i] = new_z_digit; // Detect if the subtraction underflowed - from "Hacker's Delight" c = ((modulo_digit & ~z_digit) | ((modulo_digit | ~z_digit) & new_z_digit)) >> (UnsignedBigInteger::BITS_IN_WORD - 1); } // Return the bottom num_words bytes of Z (with the carry bit handled) z.m_words.resize(num_words); result.set_to(z); result.resize_with_leading_zeros(num_words); } /** * Complexity: still O(N^3) with N the number of words in the largest word, but less complex than the classical mod power. * Note: the montgomery multiplications requires an inverse modulo over 2^32, which is only defined for odd numbers. */ void UnsignedBigIntegerAlgorithms::montgomery_modular_power_with_minimal_allocations( UnsignedBigInteger const& base, UnsignedBigInteger const& exponent, UnsignedBigInteger const& modulo, UnsignedBigInteger& temp_z, UnsignedBigInteger& rr, UnsignedBigInteger& one, UnsignedBigInteger& z, UnsignedBigInteger& zz, UnsignedBigInteger& x, UnsignedBigInteger& temp_extra, UnsignedBigInteger& result) { VERIFY(modulo.is_odd()); // Note: While this is a constexpr variable for clarity and could be changed in theory, // various optimized parts of the algorithm rely on this value being exactly 4. constexpr size_t window_size = 4; size_t num_words = modulo.trimmed_length(); UnsignedBigInteger::Word k = inverse_wrapped(modulo.m_words[0]); one.set_to(1); // rr = ( 2 ^ (2 * modulo.length() * BITS_IN_WORD) ) % modulo shift_left_by_n_words(one, 2 * num_words, x); divide_without_allocation(x, modulo, temp_z, one, z, zz, temp_extra, rr); rr.resize_with_leading_zeros(num_words); // x = base [% modulo, if x doesn't already fit in modulo's words] x.set_to(base); if (x.trimmed_length() > num_words) divide_without_allocation(base, modulo, temp_z, one, z, zz, temp_extra, x); x.resize_with_leading_zeros(num_words); one.set_to(1); one.resize_with_leading_zeros(num_words); // Compute the montgomery powers from 0 to 2^window_size. powers[i] = x^i UnsignedBigInteger powers[1 << window_size]; almost_montgomery_multiplication_without_allocation(one, rr, modulo, temp_z, k, num_words, powers[0]); almost_montgomery_multiplication_without_allocation(x, rr, modulo, temp_z, k, num_words, powers[1]); for (size_t i = 2; i < (1 << window_size); ++i) almost_montgomery_multiplication_without_allocation(powers[i - 1], powers[1], modulo, temp_z, k, num_words, powers[i]); z.set_to(powers[0]); z.resize_with_leading_zeros(num_words); zz.set_to(0); zz.resize_with_leading_zeros(num_words); ssize_t exponent_length = exponent.trimmed_length(); for (ssize_t word_in_exponent = exponent_length - 1; word_in_exponent >= 0; --word_in_exponent) { UnsignedBigInteger::Word exponent_word = exponent.m_words[word_in_exponent]; size_t bit_in_word = 0; while (bit_in_word < UnsignedBigInteger::BITS_IN_WORD) { if (word_in_exponent != exponent_length - 1 || bit_in_word != 0) { almost_montgomery_multiplication_without_allocation(z, z, modulo, temp_z, k, num_words, zz); almost_montgomery_multiplication_without_allocation(zz, zz, modulo, temp_z, k, num_words, z); almost_montgomery_multiplication_without_allocation(z, z, modulo, temp_z, k, num_words, zz); almost_montgomery_multiplication_without_allocation(zz, zz, modulo, temp_z, k, num_words, z); } auto power_index = exponent_word >> (UnsignedBigInteger::BITS_IN_WORD - window_size); auto& power = powers[power_index]; almost_montgomery_multiplication_without_allocation(z, power, modulo, temp_z, k, num_words, zz); swap(z, zz); // Move to the next window exponent_word <<= window_size; bit_in_word += window_size; } } almost_montgomery_multiplication_without_allocation(z, one, modulo, temp_z, k, num_words, zz); if (zz < modulo) { result.set_to(zz); result.clamp_to_trimmed_length(); return; } // Note : Since we were using "almost montgomery" multiplications, we aren't guaranteed to be under the modulo already. // So, if we're here, we need to respect the modulo. // We can, however, start by trying to subtract the modulo, just in case we're close. subtract_without_allocation(zz, modulo, result); if (modulo < zz) { // Note: This branch shouldn't happen in theory (as noted in https://github.com/rust-num/num-bigint/blob/master/src/biguint/monty.rs#L210) // Let's dbgln the values we used. That way, if we hit this branch, we can contribute these values for test cases. dbgln("Encountered the modulo branch during a montgomery modular power. Params : {} - {} - {}", base, exponent, modulo); // We just clobber all the other temporaries that we don't need for the division. // This is wasteful, but we're on the edgiest of cases already. divide_without_allocation(zz, modulo, temp_z, rr, z, x, temp_extra, result); } result.clamp_to_trimmed_length(); return; } }
4,892
530
from functools import partial from typing import Any, Dict, Optional from tartiflette.types.argument import GraphQLArgument from tartiflette.types.exceptions.tartiflette import TartifletteError from tartiflette.types.field import GraphQLField from tartiflette.types.non_null import GraphQLNonNull __all__ = ( "SCHEMA_ROOT_FIELD_DEFINITION", "prepare_type_root_field", "TYPENAME_ROOT_FIELD_DEFINITION", ) async def __schema_resolver( parent: Optional[Any], args: Dict[str, Any], ctx: Optional[Any], info: "ResolveInfo", ) -> "GraphQLSchema": """ Callable to use to resolve the `__schema` field. :param parent: default root value or field parent value :param args: computed arguments related to the resolved field :param ctx: context passed to the query execution :param info: information related to the execution and the resolved field :type parent: Optional[Any] :type args: Dict[str, Any] :type ctx: Optional[Any] :type info: ResolveInfo :return: the computed field value :rtype: Any """ # pylint: disable=unused-argument if info.schema.is_introspectable: info.is_introspection = True return info.schema raise TartifletteError("Introspection is disabled for this schema") SCHEMA_ROOT_FIELD_DEFINITION = partial( GraphQLField, name="__schema", description="Access the current type schema of this server.", arguments=None, resolver=__schema_resolver, ) async def __type_resolver( parent: Optional[Any], args: Dict[str, Any], ctx: Optional[Any], info: "ResolveInfo", ) -> "GraphQLType": """ Callable to use to resolve the `__type` field. :param parent: default root value or field parent value :param args: computed arguments related to the resolved field :param ctx: context passed to the query execution :param info: information related to the execution and the resolved field :type parent: Optional[Any] :type args: Dict[str, Any] :type ctx: Optional[Any] :type info: ResolveInfo :return: the computed field value :rtype: GraphQLType """ # pylint: disable=unused-argument if not info.schema.is_introspectable: raise TartifletteError("Introspection is disabled for this schema") info.is_introspection = True try: return info.schema.find_type(args["name"]) except KeyError: pass return None def prepare_type_root_field(schema: "GraphQLSchema") -> "GraphQLField": """ Factory to generate a `__type` field. :param schema: the GraphQLSchema instance linked to the engine :type schema: GraphQLSchema :return: the `__type` field :rtype: GraphQLField """ return GraphQLField( name="__type", description="Request the type information of a single type.", arguments={ "name": GraphQLArgument( name="name", gql_type=GraphQLNonNull("String", schema=schema) ) }, gql_type="__Type", resolver=__type_resolver, ) async def __typename_resolver( parent: Optional[Any], args: Dict[str, Any], ctx: Optional[Any], info: "ResolveInfo", ) -> "GraphQLType": """ Callable to use to resolve the `__typename` field. :param parent: default root value or field parent value :param args: computed arguments related to the resolved field :param ctx: context passed to the query execution :param info: information related to the execution and the resolved field :type parent: Optional[Any] :type args: Dict[str, Any] :type ctx: Optional[Any] :type info: ResolveInfo :return: the computed field value :rtype: GraphQLType """ # pylint: disable=unused-argument return info.parent_type.name TYPENAME_ROOT_FIELD_DEFINITION = partial( GraphQLField, name="__typename", description="The name of the current Object type at runtime.", arguments=None, resolver=__typename_resolver, )
1,481
550
from play.utils import * COMMANDS = ['secret'] HELP = { 'secret': 'Generate a new secret key' } def execute(**kargs): app = kargs.get("app") app.check() print "~ Generating the secret key..." sk = secretKey() replaceAll(os.path.join(app.path, 'conf', 'application.conf'), r'application.secret=.*', 'application.secret=%s' % sk, True) print "~ Keep the secret : %s" % sk print "~"
162
3,614
<filename>api/chalicelib/core/issues.py from chalicelib.utils import pg_client, helper ISSUE_TYPES = ['click_rage', 'dead_click', 'excessive_scrolling', 'bad_request', 'missing_resource', 'memory', 'cpu', 'slow_resource', 'slow_page_load', 'crash', 'ml_cpu', 'ml_memory', 'ml_dead_click', 'ml_click_rage', 'ml_mouse_thrashing', 'ml_excessive_scrolling', 'ml_slow_resources', 'custom', 'js_exception', 'custom_event_error', 'js_error'] ORDER_QUERY = """\ (CASE WHEN type = 'js_exception' THEN 0 WHEN type = 'bad_request' THEN 1 WHEN type = 'missing_resource' THEN 2 WHEN type = 'click_rage' THEN 3 WHEN type = 'dead_click' THEN 4 WHEN type = 'memory' THEN 5 WHEN type = 'cpu' THEN 6 WHEN type = 'crash' THEN 7 ELSE -1 END)::INTEGER """ NAME_QUERY = """\ (CASE WHEN type = 'js_exception' THEN 'Errors' WHEN type = 'bad_request' THEN 'Bad Requests' WHEN type = 'missing_resource' THEN 'Missing Images' WHEN type = 'click_rage' THEN 'Click Rage' WHEN type = 'dead_click' THEN 'Dead Clicks' WHEN type = 'memory' THEN 'High Memory' WHEN type = 'cpu' THEN 'High CPU' WHEN type = 'crash' THEN 'Crashes' ELSE type::text END)::text """ def get(project_id, issue_id): with pg_client.PostgresClient() as cur: query = cur.mogrify( """\ SELECT * FROM public.issues WHERE project_id = %(project_id)s AND issue_id = %(issue_id)s;""", {"project_id": project_id, "issue_id": issue_id} ) cur.execute(query=query) data = cur.fetchone() return helper.dict_to_camel_case(data) def get_by_session_id(session_id, issue_type=None): with pg_client.PostgresClient() as cur: cur.execute( cur.mogrify(f"""\ SELECT * FROM events_common.issues INNER JOIN public.issues USING (issue_id) WHERE session_id = %(session_id)s {"AND type = %(type)s" if issue_type is not None else ""} ORDER BY timestamp;""", {"session_id": session_id, "type": issue_type}) ) return helper.list_to_camel_case(cur.fetchall()) def get_types_by_project(project_id): with pg_client.PostgresClient() as cur: cur.execute( cur.mogrify(f"""SELECT type, {ORDER_QUERY}>=0 AS visible, {ORDER_QUERY} AS order, {NAME_QUERY} AS name FROM (SELECT DISTINCT type FROM public.issues WHERE project_id = %(project_id)s) AS types ORDER BY "order";""", {"project_id": project_id})) return helper.list_to_camel_case(cur.fetchall()) def get_all_types(): return [ { "type": "js_exception", "visible": True, "order": 0, "name": "Errors" }, { "type": "bad_request", "visible": True, "order": 1, "name": "Bad Requests" }, { "type": "missing_resource", "visible": True, "order": 2, "name": "Missing Images" }, { "type": "click_rage", "visible": True, "order": 3, "name": "Click Rage" }, { "type": "dead_click", "visible": True, "order": 4, "name": "Dead Clicks" }, { "type": "memory", "visible": True, "order": 5, "name": "High Memory" }, { "type": "cpu", "visible": True, "order": 6, "name": "High CPU" }, { "type": "crash", "visible": True, "order": 7, "name": "Crashes" } ]
2,260
356
from e2cnn.kernels import Basis, EmptyBasisException from .basisexpansion import BasisExpansion from typing import Callable, Dict, List, Iterable, Union import torch import numpy as np __all__ = ["SingleBlockBasisExpansion", "block_basisexpansion"] class SingleBlockBasisExpansion(BasisExpansion): def __init__(self, basis: Basis, points: np.ndarray, basis_filter: Callable[[dict], bool] = None, ): r""" Basis expansion method for a single contiguous block, i.e. for kernels/PDOs whose input type and output type contain only fields of one type. This class should be instantiated through the factory method :func:`~e2cnn.nn.modules.r2_conv.block_basisexpansion` to enable caching. Args: basis (Basis): analytical basis to sample points (ndarray): points where the analytical basis should be sampled basis_filter (callable, optional): filter for the basis elements. Should take a dictionary containing an element's attributes and return whether to keep it or not. """ super(SingleBlockBasisExpansion, self).__init__() self.basis = basis # compute the mask of the sampled basis containing only the elements allowed by the filter mask = np.zeros(len(basis), dtype=bool) for b, attr in enumerate(basis): mask[b] = basis_filter(attr) if not any(mask): raise EmptyBasisException attributes = [attr for b, attr in enumerate(basis) if mask[b]] # we need to know the real output size of the basis elements (i.e. without the change of basis and the padding) # to perform the normalization sizes = [] for attr in attributes: sizes.append(attr["shape"][0]) # sample the basis on the grid # and filter out the basis elements discarded by the filter sampled_basis = torch.Tensor(basis.sample_masked(points, mask=mask)).permute(2, 0, 1, 3) # DEPRECATED FROM PyTorch 1.2 # PyTorch 1.2 suggests using BoolTensor instead of ByteTensor for boolean indexing # but BoolTensor have been introduced only in PyTorch 1.2 # Hence, for the moment we use ByteTensor mask = mask.astype(np.uint8) mask = torch.tensor(mask) # normalize the basis sizes = torch.tensor(sizes, dtype=sampled_basis.dtype) assert sizes.shape[0] == mask.to(torch.int).sum(), sizes.shape assert sizes.shape[0] == sampled_basis.shape[0], (sizes.shape, sampled_basis.shape) sampled_basis = normalize_basis(sampled_basis, sizes) # discard the basis which are close to zero everywhere norms = (sampled_basis ** 2).reshape(sampled_basis.shape[0], -1).sum(1) > 1e-2 if not any(norms): raise EmptyBasisException sampled_basis = sampled_basis[norms, ...] full_mask = torch.zeros_like(mask) full_mask[mask] = norms.to(torch.uint8) self._mask = full_mask self.attributes = [attr for b, attr in enumerate(attributes) if norms[b]] # register the bases tensors as parameters of this module self.register_buffer('sampled_basis', sampled_basis) self._idx_to_ids = [] self._ids_to_idx = {} for idx, attr in enumerate(self.attributes): if "radius" in attr: radial_info = attr["radius"] elif "order" in attr: radial_info = attr["order"] else: raise ValueError("No radial information found.") id = '({}-{},{}-{})_({}/{})_{}'.format( attr["in_irrep"], attr["in_irrep_idx"], # name and index within the field of the input irrep attr["out_irrep"], attr["out_irrep_idx"], # name and index within the field of the output irrep radial_info, attr["frequency"], # frequency of the basis element # int(np.abs(attr["frequency"])), # absolute frequency of the basis element attr["inner_idx"], # index of the basis element within the basis of radially independent kernels between the irreps ) attr["id"] = id self._ids_to_idx[id] = idx self._idx_to_ids.append(id) def forward(self, weights: torch.Tensor) -> torch.Tensor: assert len(weights.shape) == 2 and weights.shape[1] == self.dimension() # expand the current subset of basis vectors and set the result in the appropriate place in the filter return torch.einsum('boi...,kb->koi...', self.sampled_basis, weights) #.transpose(1, 2).contiguous() def get_basis_names(self) -> List[str]: return self._idx_to_ids def get_element_info(self, name: Union[str, int]) -> Dict: if isinstance(name, str): name = self._ids_to_idx[name] return self.attributes[name] def get_basis_info(self) -> Iterable: return iter(self.attributes) def dimension(self) -> int: return self.sampled_basis.shape[0] def __eq__(self, other): if isinstance(other, SingleBlockBasisExpansion): return ( self.basis == other.basis and torch.allclose(self.sampled_basis, other.sampled_basis) and (self._mask == other._mask).all() ) else: return False def __hash__(self): return 10000 * hash(self.basis) + 100 * hash(self.sampled_basis) + hash(self._mask) # dictionary storing references to already built basis tensors # when a new filter tensor is built, it is also stored here # when the same basis is built again (eg. in another layer), the already existing filter tensor is retrieved _stored_filters = {} def block_basisexpansion(basis: Basis, points: np.ndarray, basis_filter: Callable[[dict], bool] = None, recompute: bool = False ) -> SingleBlockBasisExpansion: r""" Return an instance of :class:`~e2cnn.nn.modules.r2_conv.SingleBlockBasisExpansion`. This function support caching through the argument ``recompute``. Args: basis (Basis): basis defining the space of kernels points (~np.ndarray): points where the analytical basis should be sampled basis_filter (callable, optional): filter for the basis elements. Should take a dictionary containing an element's attributes and return whether to keep it or not. recompute (bool, optional): whether to recompute new bases (``True``) or reuse, if possible, already built tensors (``False``, default). """ if not recompute: # compute the mask of the sampled basis containing only the elements allowed by the filter mask = np.zeros(len(basis), dtype=bool) for b, attr in enumerate(basis): mask[b] = basis_filter(attr) key = (basis, mask.tobytes(), points.tobytes()) if key not in _stored_filters: _stored_filters[key] = SingleBlockBasisExpansion(basis, points, basis_filter) return _stored_filters[key] else: return SingleBlockBasisExpansion(basis, points, basis_filter) def normalize_basis(basis: torch.Tensor, sizes: torch.Tensor) -> torch.Tensor: r""" Normalize the filters in the input tensor. The tensor of shape :math:`(B, O, I, ...)` is interpreted as a basis containing ``B`` filters/elements, each with ``I`` inputs and ``O`` outputs. The spatial dimensions ``...`` can be anything. .. notice :: Notice that the method changes the input tensor inplace Args: basis (torch.Tensor): tensor containing the basis to normalize sizes (torch.Tensor): original input size of the basis elements, without the padding and the change of basis Returns: the normalized basis (the operation is done inplace, so this is ust a reference to the input tensor) """ b = basis.shape[0] assert len(basis.shape) > 2 assert sizes.shape == (b,) # compute the norm of each basis vector norms = torch.einsum('bop...,bpq...->boq...', (basis, basis.transpose(1, 2))) # Removing the change of basis, these matrices should be multiples of the identity # where the scalar on the diagonal is the variance # in order to find this variance, we can compute the trace (which is invariant to the change of basis) # and divide by the number of elements in the diagonal ignoring the padding. # Therefore, we need to know the original size of each basis element. norms = torch.einsum("bii...->b", norms) # norms = norms.reshape(b, -1).sum(1) norms /= sizes norms[norms < 1e-15] = 0 norms = torch.sqrt(norms) norms[norms < 1e-6] = 1 norms[norms != norms] = 1 norms = norms.view(b, *([1] * (len(basis.shape) - 1))) # divide by the norm basis /= norms return basis
4,006
1,264
/* * Copyright 2018-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.mongodb.core.schema; import static org.springframework.data.domain.Range.from; import static org.springframework.data.domain.Range.Bound.*; import static org.springframework.data.mongodb.core.schema.JsonSchemaObject.*; import static org.springframework.data.mongodb.core.schema.JsonSchemaObject.array; import static org.springframework.data.mongodb.core.schema.JsonSchemaObject.of; import static org.springframework.data.mongodb.test.util.Assertions.*; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.bson.Document; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Range; import org.springframework.data.domain.Range.*; /** * Tests verifying {@link org.bson.Document} representation of {@link JsonSchemaObject}s. * * @author <NAME> * @author <NAME> * @author <NAME> */ class JsonSchemaObjectUnitTests { // ----------------- // type from class // ----------------- @Test // DATAMONGO-1849 void primitiveType() { assertThat(JsonSchemaObject.of(boolean.class).getTypes()).containsExactly(Type.booleanType()); assertThat(JsonSchemaObject.of(int.class).getTypes()).containsExactly(Type.intType()); assertThat(JsonSchemaObject.of(long.class).getTypes()).containsExactly(Type.longType()); assertThat(JsonSchemaObject.of(float.class).getTypes()).containsExactly(Type.doubleType()); assertThat(JsonSchemaObject.of(double.class).getTypes()).containsExactly(Type.doubleType()); assertThat(JsonSchemaObject.of(short.class).getTypes()).containsExactly(Type.numberType()); } @Test // DATAMONGO-1849 void objectType() { assertThat(JsonSchemaObject.of(Object.class).getTypes()).containsExactly(Type.objectType()); assertThat(JsonSchemaObject.of(Map.class).getTypes()).containsExactly(Type.objectType()); assertThat(JsonSchemaObject.of(Document.class).getTypes()).containsExactly(Type.objectType()); } @Test // DATAMONGO-1849 void binaryData() { assertThat(JsonSchemaObject.of(byte[].class).getTypes()).containsExactly(Type.binaryType()); } @Test // DATAMONGO-1849 void collectionType() { assertThat(JsonSchemaObject.of(Object[].class).getTypes()).containsExactly(Type.arrayType()); assertThat(JsonSchemaObject.of(Collection.class).getTypes()).containsExactly(Type.arrayType()); assertThat(JsonSchemaObject.of(List.class).getTypes()).containsExactly(Type.arrayType()); assertThat(JsonSchemaObject.of(Set.class).getTypes()).containsExactly(Type.arrayType()); } @Test // DATAMONGO-1849 void dateType() { assertThat(JsonSchemaObject.of(Date.class).getTypes()).containsExactly(Type.dateType()); } // ----------------- // type : 'object' // ----------------- @Test // DATAMONGO-1835 void objectObjectShouldRenderTypeCorrectly() { assertThat(object().generatedDescription().toDocument()) .isEqualTo(new Document("type", "object").append("description", "Must be an object.")); } @Test // DATAMONGO-1835 void objectObjectShouldRenderNrPropertiesCorrectly() { assertThat(object().propertiesCount(from(inclusive(10)).to(inclusive(20))).generatedDescription().toDocument()) .isEqualTo(new Document("type", "object").append("description", "Must be an object with [10-20] properties.") .append("minProperties", 10).append("maxProperties", 20)); } @Test // DATAMONGO-1835 void objectObjectShouldRenderRequiredPropertiesCorrectly() { assertThat(object().required("spring", "data", "mongodb").generatedDescription().toDocument()) .isEqualTo(new Document("type", "object") .append("description", "Must be an object where spring, data, mongodb are mandatory.") .append("required", Arrays.asList("spring", "data", "mongodb"))); } @Test // DATAMONGO-1835 void objectObjectShouldRenderAdditionalPropertiesCorrectlyWhenBoolean() { assertThat(object().additionalProperties(true).generatedDescription().toDocument()).isEqualTo( new Document("type", "object").append("description", "Must be an object allowing additional properties.") .append("additionalProperties", true)); assertThat(object().additionalProperties(false).generatedDescription().toDocument()).isEqualTo( new Document("type", "object").append("description", "Must be an object not allowing additional properties.") .append("additionalProperties", false)); } @Test // DATAMONGO-1835 void objectObjectShouldRenderPropertiesCorrectly() { Document expected = new Document("type", "object") .append("description", "Must be an object defining restrictions for name, active.").append("properties", new Document("name", new Document("type", "string") .append("description", "Must be a string with length unbounded-10].").append("maxLength", 10)) .append("active", new Document("type", "boolean"))); assertThat(object().generatedDescription() .properties(JsonSchemaProperty.string("name").maxLength(10).generatedDescription(), JsonSchemaProperty.bool("active")) .generatedDescription().toDocument()).isEqualTo(expected); } @Test // DATAMONGO-1835 void objectObjectShouldRenderNestedObjectPropertiesCorrectly() { Document expected = new Document("type", "object") .append("description", "Must be an object defining restrictions for address.") .append("properties", new Document("address", new Document("type", "object").append("description", "Must be an object defining restrictions for city.") .append("properties", new Document("city", new Document("type", "string") .append("description", "Must be a string with length [3-unbounded.").append("minLength", 3))))); assertThat(object() .properties(JsonSchemaProperty.object("address") .properties(JsonSchemaProperty.string("city").minLength(3).generatedDescription()).generatedDescription()) .generatedDescription().toDocument()).isEqualTo(expected); } @Test // DATAMONGO-1835 void objectObjectShouldRenderPatternPropertiesCorrectly() { Document expected = new Document("type", "object") .append("description", "Must be an object defining restrictions for patterns na.*.") .append("patternProperties", new Document("na.*", new Document("type", "string") .append("description", "Must be a string with length unbounded-10].").append("maxLength", 10))); assertThat(object().patternProperties(JsonSchemaProperty.string("na.*").maxLength(10).generatedDescription()) .generatedDescription().toDocument()).isEqualTo(expected); } @Test // DATAMONGO-1849 void objectShouldIncludeRequiredNestedCorrectly() { assertThat(object() // .properties( // JsonSchemaProperty.required(JsonSchemaProperty.string("lastname")) // ).toDocument()) .isEqualTo(new Document("type", "object").append("required", Collections.singletonList("lastname")) .append("properties", new Document("lastname", new Document("type", "string")))); } // ----------------- // type : 'string' // ----------------- @Test // DATAMONGO-1835 void stringObjectShouldRenderTypeCorrectly() { assertThat(string().generatedDescription().toDocument()) .isEqualTo(new Document("type", "string").append("description", "Must be a string.")); } @Test // DATAMONGO-1835 void stringObjectShouldRenderDescriptionCorrectly() { assertThat(string().description("error msg").toDocument()) .isEqualTo(new Document("type", "string").append("description", "error msg")); } @Test // DATAMONGO-1835 void stringObjectShouldRenderRangeCorrectly() { assertThat(string().length(from(inclusive(10)).to(inclusive(20))).generatedDescription().toDocument()) .isEqualTo(new Document("type", "string").append("description", "Must be a string with length [10-20].") .append("minLength", 10).append("maxLength", 20)); } @Test // DATAMONGO-1835 void stringObjectShouldRenderPatternCorrectly() { assertThat(string().matching("^spring$").generatedDescription().toDocument()) .isEqualTo(new Document("type", "string").append("description", "Must be a string matching ^spring$.") .append("pattern", "^spring$")); } // ----------------- // type : 'number' // ----------------- @Test // DATAMONGO-1835 void numberObjectShouldRenderMultipleOfCorrectly() { assertThat(number().multipleOf(3.141592F).generatedDescription().toDocument()) .isEqualTo(new Document("type", "number").append("description", "Must be a numeric value multiple of 3.141592.") .append("multipleOf", 3.141592F)); } @Test // DATAMONGO-1835 void numberObjectShouldRenderMaximumCorrectly() { assertThat( number().within(Range.of(Bound.unbounded(), Bound.inclusive(3.141592F))).generatedDescription().toDocument()) .isEqualTo(new Document("type", "number") .append("description", "Must be a numeric value within range unbounded-3.141592].") .append("maximum", 3.141592F)); assertThat( number().within(Range.of(Bound.unbounded(), Bound.exclusive(3.141592F))).generatedDescription().toDocument()) .isEqualTo(new Document("type", "number") .append("description", "Must be a numeric value within range unbounded-3.141592).") .append("maximum", 3.141592F).append("exclusiveMaximum", true)); } @Test // DATAMONGO-1835 void numberObjectShouldRenderMinimumCorrectly() { assertThat( number().within(Range.of(Bound.inclusive(3.141592F), Bound.unbounded())).generatedDescription().toDocument()) .isEqualTo(new Document("type", "number") .append("description", "Must be a numeric value within range [3.141592-unbounded.") .append("minimum", 3.141592F)); assertThat( number().within(Range.of(Bound.exclusive(3.141592F), Bound.unbounded())).generatedDescription().toDocument()) .isEqualTo(new Document("type", "number") .append("description", "Must be a numeric value within range (3.141592-unbounded.") .append("minimum", 3.141592F).append("exclusiveMinimum", true)); } // ----------------- // type : 'arrays' // ----------------- @Test // DATAMONGO-1835 void arrayObjectShouldRenderItemsCorrectly() { assertThat(array().items(Arrays.asList(string(), bool())).toDocument()).isEqualTo(new Document("type", "array") .append("items", Arrays.asList(new Document("type", "string"), new Document("type", "boolean")))); } @Test // DATAMONGO-2613 void arrayObjectShouldRenderItemsCorrectlyAsObjectIfContainsOnlyOneElement() { assertThat(array().items(Collections.singletonList(string())).toDocument()) .isEqualTo(new Document("type", "array").append("items", new Document("type", "string"))); } @Test // DATAMONGO-1835 void arrayObjectShouldRenderMaxItemsCorrectly() { assertThat(array().maxItems(5).generatedDescription().toDocument()).isEqualTo(new Document("type", "array") .append("description", "Must be an array having size unbounded-5].").append("maxItems", 5)); } @Test // DATAMONGO-1835 void arrayObjectShouldRenderMinItemsCorrectly() { assertThat(array().minItems(5).generatedDescription().toDocument()).isEqualTo(new Document("type", "array") .append("description", "Must be an array having size [5-unbounded.").append("minItems", 5)); } @Test // DATAMONGO-1835 void arrayObjectShouldRenderUniqueItemsCorrectly() { assertThat(array().uniqueItems(true).generatedDescription().toDocument()).isEqualTo(new Document("type", "array") .append("description", "Must be an array of unique values.").append("uniqueItems", true)); } @Test // DATAMONGO-1835 void arrayObjectShouldRenderAdditionalItemsItemsCorrectly() { assertThat(array().additionalItems(true).generatedDescription().toDocument()) .isEqualTo(new Document("type", "array").append("description", "Must be an array with additional items.") .append("additionalItems", true)); assertThat(array().additionalItems(false).generatedDescription().toDocument()) .isEqualTo(new Document("type", "array").append("description", "Must be an array with no additional items.") .append("additionalItems", false)); } // ----------------- // type : 'boolean' // ----------------- @Test // DATAMONGO-1835 void booleanShouldRenderCorrectly() { assertThat(bool().generatedDescription().toDocument()) .isEqualTo(new Document("type", "boolean").append("description", "Must be a boolean.")); } // ----------------- // type : 'null' // ----------------- @Test // DATAMONGO-1835 void nullShouldRenderCorrectly() { assertThat(nil().generatedDescription().toDocument()) .isEqualTo(new Document("type", "null").append("description", "Must be null.")); } // ----------------- // type : 'date' // ----------------- @Test // DATAMONGO-1877 void dateShouldRenderCorrectly() { assertThat(date().generatedDescription().toDocument()) .isEqualTo(new Document("bsonType", "date").append("description", "Must be a date.")); } // ----------------- // type : 'timestamp' // ----------------- @Test // DATAMONGO-1877 void timestampShouldRenderCorrectly() { assertThat(timestamp().generatedDescription().toDocument()) .isEqualTo(new Document("bsonType", "timestamp").append("description", "Must be a timestamp.")); } // ----------------- // type : 'any' // ----------------- @Test // DATAMONGO-1835 void typedObjectShouldRenderEnumCorrectly() { assertThat(of(String.class).possibleValues(Arrays.asList("one", "two")).toDocument()) .isEqualTo(new Document("type", "string").append("enum", Arrays.asList("one", "two"))); } @Test // DATAMONGO-1835 void typedObjectShouldRenderAllOfCorrectly() { assertThat(of(Object.class).allOf(Arrays.asList(string())).toDocument()) .isEqualTo(new Document("type", "object").append("allOf", Arrays.asList(new Document("type", "string")))); } @Test // DATAMONGO-1835 void typedObjectShouldRenderAnyOfCorrectly() { assertThat(of(String.class).anyOf(Arrays.asList(string())).toDocument()) .isEqualTo(new Document("type", "string").append("anyOf", Arrays.asList(new Document("type", "string")))); } @Test // DATAMONGO-1835 void typedObjectShouldRenderOneOfCorrectly() { assertThat(of(String.class).oneOf(Arrays.asList(string())).toDocument()) .isEqualTo(new Document("type", "string").append("oneOf", Arrays.asList(new Document("type", "string")))); } @Test // DATAMONGO-1835 void typedObjectShouldRenderNotCorrectly() { assertThat(untyped().notMatch(string()).toDocument()) .isEqualTo(new Document("not", new Document("type", "string"))); } }
4,945
3,102
<filename>clang/test/CodeGen/2008-03-26-PackedBitFields.c // RUN: %clang_cc1 %s -emit-llvm -o - struct S1757 { long double c; long int __attribute__((packed)) e:28; } x;
78
12,278
/* Copyright <NAME> 2013 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) */ /* * OSX can masquerade as BSD when sys/param.h is previously included. * So we test that we only detect OSX in this combination. */ #if defined(__APPLE__) # include <sys/param.h> # include <boost/predef/os/bsd.h> # include <boost/predef/os/macos.h> # if !BOOST_OS_MACOS || BOOST_OS_BSD # error "BOOST_OS_MACOS not detected and/or BOOST_OS_BSD mis-detected." # endif #endif
222
758
// // TKBitmapRendition+Pasteboard.h // ThemeEngine // // Created by <NAME> on 6/21/15. // Copyright © 2015 <NAME>. All rights reserved. // #import <ThemeKit/ThemeKit.h> #import "TERenditionPasteboardItem.h" extern NSString *const TEBitmapPasteboardType; @interface TKBitmapRendition (Pasteboard) <TERenditionPasteboardItem> @end
127
1,016
package com.thinkbiganalytics.metadata.sla; /*- * #%L * thinkbig-operational-metadata-integration-service * %% * Copyright (C) 2017 ThinkBig Analytics * %% * 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. * #L% */ import com.thinkbiganalytics.metadata.api.MetadataAccess; import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess; import com.thinkbiganalytics.metadata.sla.api.AssessmentResult; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement; import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment; import com.thinkbiganalytics.metadata.sla.spi.core.DefaultServiceLevelAgreementChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; /** * SLA Checker that will lookup the SLA data from JCR and use it with the JPA SLA Assessments. */ public class JpaJcrServiceLevelAgreementChecker extends DefaultServiceLevelAgreementChecker { private static final Logger LOG = LoggerFactory.getLogger(JpaJcrServiceLevelAgreementChecker.class); @Inject MetadataAccess metadataAccess; /** * Runs the assessment provider on the provided agreement and acts accordingly. * * @param agreement The agreement to assess * @param assessment The strategy of assessment * @return true if the assessment succeeds or is not found */ @Override protected boolean shouldAlert(ServiceLevelAgreement agreement, ServiceLevelAssessment assessment) { boolean shouldAlert = false; try { shouldAlert = metadataAccess.read(() -> { // Get the last assessment that was created for this SLA (if any). ServiceLevelAssessment previous = this.assessmentProvider.findLatestAssessmentNotEqualTo(agreement.getId(), assessment.getId()); boolean alert = false; if (previous != null) { assessmentProvider.ensureServiceLevelAgreementOnAssessment(previous); boolean matchesPreviousAssessment = assessment.compareTo(previous) == 0; alert = (!assessment.getResult().equals(AssessmentResult.SUCCESS) && !matchesPreviousAssessment); LOG.debug("{}. {} ",alert ? "Generating an alert ":" Not generating an alert " , matchesPreviousAssessment ? "This assessment is the same as the previous assessment": "This assessment is different than the previous assessment"); } else { LOG.debug("Unable to find a previous assessment for agreement {}. {}", agreement.getId(),alert ? "Generating Alert ":" Not generating an alert " ); alert = !assessment.getResult().equals(AssessmentResult.SUCCESS); } return alert; },MetadataAccess.SERVICE); } catch (Exception e) { LOG.error("Error checking shouldAlert for {}. {} ", agreement.getName(), e.getMessage(), e); } return shouldAlert; } private boolean isAssessable(ServiceLevelAgreement agreement) { // TODO: validate that this is a kind of agreement that we assess. Assume we assess all SLAs for now. return true; } }
1,275
18,965
<filename>samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/fragments/SettingsFragment.java /* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.samples.scrollperf.fragments; import android.app.Dialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import androidx.preference.CheckBoxPreference; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import com.facebook.common.webp.WebpSupportStatus; import com.facebook.samples.scrollperf.R; import com.facebook.samples.scrollperf.conf.Const; import com.facebook.samples.scrollperf.preferences.SizePreferences; import com.facebook.samples.scrollperf.util.SizeUtil; /** The Fragment for settings */ public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { /** The Tag for this Fragment */ public static final String TAG = SettingsFragment.class.getSimpleName(); private ShowRestartMessageDialog mShowRestartMessageDialog; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(false); } @Override public void onCreatePreferences(Bundle bundle, String s) { addPreferencesFromResource(R.xml.preferences); getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // Update summaries updateDataSourceSummary(findPreference(Const.DATA_SOURCE_KEY)); updateInfiniteDataSourceSummary(findPreference(Const.INFINITE_DATA_SOURCE_KEY)); updateDistinctDataSourceSummary(findPreference(Const.DISTINCT_DATA_SOURCE_KEY)); updateRecyclerLayoutSummary(findPreference(Const.RECYCLER_LAYOUT_KEY)); updateReuseOldControllerSummary(findPreference(Const.REUSE_OLD_CONTROLLER_KEY)); updateRoundedCornersSummary(findPreference(Const.ROUNDED_CORNERS_KEY)); updateRoundedAsCircleSummary(findPreference(Const.ROUNDED_AS_CIRCLE_KEY)); updateUsePostprocessorSummary(findPreference(Const.USE_POSTPROCESSOR_KEY)); updateWhatPostprocessorSummary(findPreference(Const.POSTPROCESSOR_TYPE_KEY)); updateWhatScaleTypeSummary(findPreference(Const.SCALE_TYPE_KEY)); updateAutoRotateSummary(findPreference(Const.AUTO_ROTATE_KEY)); updateRotationAngleSummary(findPreference(Const.FORCED_ROTATION_ANGLE_KEY)); updateDownsamplingSummary(findPreference(Const.DOWNSAMPLING_KEY)); updateOverrideSizeSummary(findPreference(Const.OVERRIDE_SIZE_KEY)); updateDraweeOverlaySummary(findPreference(Const.DRAWEE_OVERLAY_KEY)); updateBgColorSummary(findPreference(Const.BG_COLOR_KEY)); updateInstrumentationSummary(findPreference(Const.INSTRUMENTATION_ENABLED_KEY)); updateNumberOfDecodingThreadSummary(findPreference(Const.DECODING_THREAD_KEY)); // Set sizes SizePreferences widthPreferences = (SizePreferences) findPreference(Const.OVERRIDEN_WIDTH_KEY); widthPreferences.setSeekBarMaxValue(SizeUtil.DISPLAY_WIDTH); SizePreferences heightPreferences = (SizePreferences) findPreference(Const.OVERRIDEN_HEIGHT_KEY); heightPreferences.setSeekBarMaxValue(SizeUtil.DISPLAY_HEIGHT); updateFadeDurationSummary(findPreference(Const.FADE_DURATION_KEY)); updateDrawBorderSummary(findPreference(Const.DRAW_BORDER_KEY)); updateDecodeCancellationSummary(findPreference(Const.DECODE_CANCELLATION_KEY)); // This has no meaning for Android > JELLY_BEAN_MR1 because it already supports WebP if (WebpSupportStatus.sIsWebpSupportRequired) { updateWebpSupportSummary(findPreference(Const.WEBP_SUPPORT_KEY)); } else { findPreference(Const.WEBP_SUPPORT_KEY).setVisible(false); } } @Override public void onDestroy() { super.onDestroy(); getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Preference preference = findPreference(key); switch (key) { case Const.DATA_SOURCE_KEY: updateDataSourceSummary(preference); break; case Const.RECYCLER_LAYOUT_KEY: updateRecyclerLayoutSummary(preference); break; case Const.GRID_SPAN_COUNT_KEY: updateGridRecyclerLayoutSummary(); break; case Const.INFINITE_DATA_SOURCE_KEY: updateInfiniteDataSourceSummary(preference); break; case Const.DISTINCT_DATA_SOURCE_KEY: updateDistinctDataSourceSummary(preference); break; case Const.REUSE_OLD_CONTROLLER_KEY: updateReuseOldControllerSummary(preference); break; case Const.ROUNDED_CORNERS_KEY: updateRoundedCornersSummary(preference); break; case Const.ROUNDED_AS_CIRCLE_KEY: updateRoundedAsCircleSummary(preference); break; case Const.USE_POSTPROCESSOR_KEY: updateUsePostprocessorSummary(preference); break; case Const.POSTPROCESSOR_TYPE_KEY: updateWhatPostprocessorSummary(preference); break; case Const.SCALE_TYPE_KEY: updateWhatScaleTypeSummary(preference); break; case Const.AUTO_ROTATE_KEY: updateAutoRotateSummary(preference); break; case Const.FORCED_ROTATION_ANGLE_KEY: updateRotationAngleSummary(preference); break; case Const.DOWNSAMPLING_KEY: updateDownsamplingSummary(preference); getShowRestartMessageDialog().show(getChildFragmentManager(), null); break; case Const.WEBP_SUPPORT_KEY: updateWebpSupportSummary(preference); getShowRestartMessageDialog().show(getChildFragmentManager(), null); break; case Const.DECODING_THREAD_KEY: updateNumberOfDecodingThreadSummary(preference); getShowRestartMessageDialog().show(getChildFragmentManager(), null); break; case Const.INSTRUMENTATION_ENABLED_KEY: updateInstrumentationSummary(preference); break; case Const.DECODE_CANCELLATION_KEY: updateDecodeCancellationSummary(preference); getShowRestartMessageDialog().show(getChildFragmentManager(), null); break; case Const.DRAWEE_OVERLAY_KEY: updateDraweeOverlaySummary(preference); getShowRestartMessageDialog().show(getChildFragmentManager(), null); break; case Const.BG_COLOR_KEY: updateBgColorSummary(preference); break; case Const.OVERRIDE_SIZE_KEY: updateOverrideSizeSummary(preference); break; case Const.FADE_DURATION_KEY: updateFadeDurationSummary(preference); break; case Const.DRAW_BORDER_KEY: updateDrawBorderSummary(preference); break; } } private void updateDataSourceSummary(final Preference preference) { updateListPreference( getResources(), (ListPreference) preference, R.array.data_source_summaries); } private void updateInfiniteDataSourceSummary(final Preference preference) { final boolean currentState = updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_infinite_data_source_summary, R.string.unchecked_infinite_data_source_summary); // We disableDistinct Uris if infinite is not enabled findPreference(Const.DISTINCT_DATA_SOURCE_KEY).setEnabled(currentState); } private void updateDistinctDataSourceSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_distinct_uri_data_source_summary, R.string.unchecked_distinct_uri_data_source_summary); } private void updateRecyclerLayoutSummary(final Preference preference) { updateListPreference( getResources(), (ListPreference) preference, R.array.recycler_layout_summaries); updateGridRecyclerLayoutSummary(); } private void updateGridRecyclerLayoutSummary() { final ListPreference listPreference = (ListPreference) findPreference(Const.RECYCLER_LAYOUT_KEY); // We have to enable the Grid settings only if the selection is the related on final ListPreference gridPreference = (ListPreference) findPreference(Const.GRID_SPAN_COUNT_KEY); final String value = listPreference.getValue(); final boolean gridGroupVisible = Const.GRID_RECYCLER_VIEW_LAYOUT_VALUE.equals(value); // We update summary if (gridGroupVisible) { final String spanCountValue = gridPreference.getValue(); gridPreference.setSummary( getString(R.string.label_grid_recycler_span_count_summary, spanCountValue)); } gridPreference.setVisible(gridGroupVisible); } private void updateReuseOldControllerSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_reuse_old_controller_summary, R.string.unchecked_reuse_old_controller_summary); } private void updateRoundedCornersSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_rounded_corners_summary, R.string.unchecked_rounded_corners_summary); } private void updateRoundedAsCircleSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_rounded_as_circle_summary, R.string.unchecked_rounded_as_circle_summary); } private void updateUsePostprocessorSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_postprocessor_summary, R.string.unchecked_postprocessor_summary); } private void updateWhatPostprocessorSummary(final Preference preference) { updateListPreference( getResources(), (ListPreference) preference, R.array.postprocessor_summaries); } private void updateBgColorSummary(final Preference preference) { updateListPreference(getResources(), (ListPreference) preference, R.array.bg_color_summaries); } private void updateWhatScaleTypeSummary(final Preference preference) { updateListPreference(getResources(), (ListPreference) preference, R.array.scale_type_summaries); } private void updateDecodeCancellationSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_decode_cancellation_summary, R.string.unchecked_decode_cancellation_summary); } private void updateWebpSupportSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_webp_support_summary, R.string.unchecked_webp_support_summary); } private static boolean updateCheckBoxPreference( Resources resources, CheckBoxPreference preference, int checkedSummaryRes, int uncheckedSummaryRes) { final boolean checkboxState = preference.isChecked(); if (checkboxState) { preference.setSummary(resources.getString(checkedSummaryRes)); } else { preference.setSummary(resources.getString(uncheckedSummaryRes)); } return checkboxState; } private static void updateListPreference( Resources resources, ListPreference preference, int arrayValuesId) { final int valueIndex = preference.findIndexOfValue(preference.getValue()); final String summary = resources.getStringArray(arrayValuesId)[valueIndex]; preference.setSummary(summary); } private void updateAutoRotateSummary(final Preference preference) { boolean currentState = updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_auto_rotate_summary, R.string.unchecked_auto_rotate_summary); findPreference(Const.FORCED_ROTATION_ANGLE_KEY).setEnabled(!currentState); } private void updateRotationAngleSummary(final Preference preference) { updateListPreference( getResources(), (ListPreference) preference, R.array.rotation_angle_summaries); } private void updateDownsamplingSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_downsampling_summary, R.string.unchecked_downsampling_summary); } private void updateNumberOfDecodingThreadSummary(final Preference preference) { final ListPreference listPreference = (ListPreference) preference; final int valueIndex = listPreference.findIndexOfValue(listPreference.getValue()); String summary = getResources().getStringArray(R.array.decoding_thread_summaries)[valueIndex]; if (valueIndex == 0) { summary += Const.NUMBER_OF_PROCESSORS; } preference.setSummary(summary); } private void updateDraweeOverlaySummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_drawee_overlay_summary, R.string.unchecked_drawee_overlay_summary); } private void updateInstrumentationSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_instrumentation_summary, R.string.unchecked_instrumentation_summary); } private void updateOverrideSizeSummary(final Preference preference) { boolean currentState = updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_auto_size_override, R.string.unchecked_auto_size_override); findPreference(Const.FORCED_ROTATION_ANGLE_KEY).setEnabled(!currentState); } private void updateFadeDurationSummary(final Preference preference) { updateListPreference( getResources(), (ListPreference) preference, R.array.fade_duration_summaries); } private void updateDrawBorderSummary(final Preference preference) { updateCheckBoxPreference( getResources(), (CheckBoxPreference) preference, R.string.checked_draw_border_summary, R.string.unchecked_draw_border_summary); } private ShowRestartMessageDialog getShowRestartMessageDialog() { if (mShowRestartMessageDialog == null) { mShowRestartMessageDialog = new ShowRestartMessageDialog(); } return mShowRestartMessageDialog; } public static class ShowRestartMessageDialog extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder .setMessage(R.string.message_application_needs_restart) .setPositiveButton(android.R.string.ok, null) .setNeutralButton( R.string.message_restart_now, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.exit(0); } }); return builder.create(); } } }
5,685
1,016
@ModuleGen(name = "vertx-web-api-service", groupPackage = "io.vertx") package io.vertx.ext.web.api.service; import io.vertx.codegen.annotations.ModuleGen;
58
798
<reponame>thomas-watchmaker/picard package picard.annotation; import htsjdk.samtools.util.IOUtil; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import picard.cmdline.CommandLineProgramTest; import java.io.File; import java.io.IOException; public class SortGffTest extends CommandLineProgramTest { private static final File TEST_DATA_DIR = new File("testdata/picard/annotation/SortGff"); public String getCommandLineProgramName() { return SortGff.class.getSimpleName(); } @DataProvider(name = "testSortGffDataProvider") public Object[][] testSortGffDataProvider() { return new Object[][] { {new File(TEST_DATA_DIR, "basic.unsorted.gff3"), new File(TEST_DATA_DIR, "basic.sorted.gff3")}, {new File(TEST_DATA_DIR, "basic.unsorted.with.comments.and.directives.gff3"), new File(TEST_DATA_DIR, "basic.sorted.with.comments.and.directives.gff3")}, {new File(TEST_DATA_DIR, "child.before.parent.belongs.after.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.belongs.after.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "child.after.parent.belongs.after.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.belongs.after.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "child.before.parent.belongs.before.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.belongs.before.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "child.after.parent.belongs.before.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.belongs.before.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "parent.parent.child.should.be.parent.parent.child.unsorted.gff3"), new File(TEST_DATA_DIR, "parent.parent.child.sorted.gff3")}, {new File(TEST_DATA_DIR, "parent.child.parent.should.be.parent.parent.child.unsorted.gff3"), new File(TEST_DATA_DIR, "parent.parent.child.sorted.gff3")}, {new File(TEST_DATA_DIR, "child.parent.parent.should.be.parent.parent.child.unsorted.gff3"), new File(TEST_DATA_DIR, "parent.parent.child.sorted.gff3")}, {new File(TEST_DATA_DIR, "parent.parent.child.should.be.parent.child.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "parent.child.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "parent.child.parent.should.be.parent.child.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "parent.child.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "child.parent.parent.should.be.parent.child.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "parent.child.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "parent.parent.child.should.be.child.parent.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.parent.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "parent.child.parent.should.be.child.parent.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.parent.parent.sorted.gff3")}, {new File(TEST_DATA_DIR, "child.parent.parent.should.be.child.parent.parent.unsorted.gff3"), new File(TEST_DATA_DIR, "child.parent.parent.sorted.gff3")} }; } @Test(dataProvider = "testSortGffDataProvider") public void testBasicGff(final File inputGff, final File expectedOutputGff) throws IOException { final File outGff = File.createTempFile("testBasicGff", ".gff3"); outGff.deleteOnExit(); final String[] args = { "I=" + inputGff.getAbsolutePath(), "O=" + outGff.getAbsolutePath(), "nRecordsInMemory=1" }; new SortGff().instanceMain(args); IOUtil.assertFilesEqual(expectedOutputGff, outGff); } @DataProvider(name = "testSortByDictDataProvider") public Object[][] testSortByDictDataProvider() { return new Object[][] { {new File(TEST_DATA_DIR, "basic.unsorted.gff3"), new File(TEST_DATA_DIR, "standard.dict"), new File(TEST_DATA_DIR, "basic.sorted.gff3")}, {new File(TEST_DATA_DIR, "basic.unsorted.gff3"), new File(TEST_DATA_DIR, "reverse.dict"), new File(TEST_DATA_DIR, "basic.sorted.reverse.dict.gff3")} }; } @Test(dataProvider = "testSortByDictDataProvider") public void testSortByDictDataProvider(final File inputGff, final File dict, final File expectedOutputGff) throws IOException { final File outGff = File.createTempFile("testBasicGff", ".gff3"); outGff.deleteOnExit(); final String[] args = { "I=" + inputGff.getAbsolutePath(), "O=" + outGff.getAbsolutePath(), "SD=" + dict.getAbsolutePath(), "nRecordsInMemory=1" }; new SortGff().instanceMain(args); IOUtil.assertFilesEqual(expectedOutputGff, outGff); } }
2,108
957
<reponame>emadurandal/Effekseer<gh_stars>100-1000  //---------------------------------------------------------------------------------- // Include //---------------------------------------------------------------------------------- #include "EffekseerTool.Sound.h" #ifdef _WIN32 #endif //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- namespace EffekseerTool { //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- Sound::Sound() : m_sound(nullptr) , m_manager(nullptr) , m_mute(false) , m_volume(1.0f) { } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- Sound::~Sound() { if (m_sound != nullptr) { m_sound.Reset(); } if (m_manager) { m_manager->Release(); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- bool Sound::Initialize() { m_manager = osm::Manager::Create(); if (m_manager == nullptr) { return false; } if (!m_manager->Initialize()) { return false; } m_sound = EffekseerSound::Sound::Create(m_manager); if (m_sound == nullptr) { return false; } return true; } void Sound::Update() { // m_sound->Update(); } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Sound::SetVolume(float volume) { m_volume = volume; if (m_sound != nullptr) { // m_sound->SetMasterVolume(volume); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Sound::SetMute(bool mute) { m_mute = mute; if (m_sound != nullptr) { m_sound->SetMute(mute); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void Sound::SetListener(const Effekseer::Vector3D& pos, const Effekseer::Vector3D& at, const Effekseer::Vector3D& up) { if (m_sound != nullptr) { m_sound->SetListener(pos, at, up); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- } // namespace EffekseerTool //---------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------
638
60,067
#pragma once #include <torch/optim/schedulers/lr_scheduler.h> namespace torch { namespace optim { class TORCH_API StepLR : public LRScheduler { public: StepLR(torch::optim::Optimizer& optimizer, const unsigned step_size, const double gamma = 0.1); private: std::vector<double> get_lrs() override; const unsigned step_size_; const double gamma_; }; } // namespace optim } // namespace torch
156
1,091
<gh_stars>1000+ /* * Copyright 2015-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cli.app; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.apache.karaf.shell.api.console.CommandLine; import org.apache.karaf.shell.api.console.Session; import org.apache.karaf.shell.support.completers.StringsCompleter; import org.onosproject.app.ApplicationService; import org.onosproject.app.ApplicationState; import org.onosproject.cli.AbstractCompleter; import org.onosproject.core.Application; import com.google.common.base.Strings; import com.google.common.collect.Lists; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.SortedSet; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.onosproject.app.ApplicationState.ACTIVE; import static org.onosproject.app.ApplicationState.INSTALLED; import static org.onosproject.cli.AbstractShellCommand.get; /** * Application name completer. */ @Service public class ApplicationNameCompleter extends AbstractCompleter { @Override public int complete(Session session, CommandLine commandLine, List<String> candidates) { // Delegate string completer StringsCompleter delegate = new StringsCompleter(); // Command name is the second argument. String cmd = commandLine.getArguments()[1]; // Fetch our service and feed it's offerings to the string completer ApplicationService service = get(ApplicationService.class); Iterator<Application> it = service.getApplications().iterator(); SortedSet<String> strings = delegate.getStrings(); if ("install".equals(cmd)) { it = service.getRegisteredApplications().iterator(); while (it.hasNext()) { strings.add(it.next().id().name()); } } else { while (it.hasNext()) { Application app = it.next(); ApplicationState state = service.getState(app.id()); if ("uninstall".equals(cmd) || "download".equals(cmd) || ("activate".equals(cmd) && state == INSTALLED) || ("deactivate".equals(cmd) && state == ACTIVE)) { strings.add(app.id().name()); } } } // add unique suffix to candidates, if user has something in buffer if (!Strings.isNullOrEmpty(commandLine.getCursorArgument())) { List<String> suffixCandidates = strings.stream() // remove onos common prefix .map(full -> full.replaceFirst("org\\.onosproject\\.", "")) // a.b.c -> [c, b.c, a.b.c] .flatMap(appName -> { List<String> suffixes = new ArrayList<>(); Deque<String> frags = new ArrayDeque<>(); // a.b.c -> [c, b, a] -> [c, b.c, a.b.c] Lists.reverse(asList(appName.split("\\."))).forEach(frag -> { frags.addFirst(frag); suffixes.add(frags.stream().collect(Collectors.joining("."))); }); return suffixes.stream(); }) // convert to occurrence map .collect(Collectors.groupingBy(e -> e, Collectors.counting())) .entrySet().stream() // only accept unique suffix .filter(e -> e.getValue() == 1L) .map(Entry::getKey) .collect(Collectors.toList()); delegate.getStrings().addAll(suffixCandidates); } // Now let the completer do the work for figuring out what to offer. return delegate.complete(session, commandLine, candidates); } }
1,902
3,810
package com.birbit.android.jobqueue; public class ConsumerControllerTest { }
24
30,023
<filename>homeassistant/components/vulcan/manifest.json { "domain": "vulcan", "name": "Uonet+ Vulcan", "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/vulcan", "requirements": ["vulcan-api==2.1.1"], "codeowners": ["@Antoni-Czaplicki"], "iot_class": "cloud_polling", "quality_scale": "silver" }
137
592
{ "name": "@styled-icons/crypto", "version": "10.38.0", "license": "MIT", "description": "Crypto icons available as Styled Components", "author": "<NAME> <<EMAIL>>", "homepage": "https://github.com/styled-icons/styled-icons", "repository": "git://github.com/styled-icons/styled-icons.git", "keywords": [ "styled-icons" ], "funding": { "type": "GitHub", "url": "https://github.com/sponsors/jacobwgillespie" }, "main": "./index.js", "module": "./index.esm.js", "types": "./index.d.ts", "sideEffects": false, "publishConfig": { "access": "public" }, "scripts": { "clean": "clean-package", "generate": "generate-icon-package @svg-icons/crypto" }, "dependencies": { "@babel/runtime": "^7.15.4", "@styled-icons/styled-icon": "^10.6.3" }, "peerDependencies": { "react": "*", "styled-components": "*" }, "devDependencies": { "@styled-icons/pack-builder": "^10.6.0", "@svg-icons/crypto": "1.66.0", "react": "^17.0.2", "react-dom": "^17.0.2", "react-is": "^17.0.2", "styled-components": "^5.3.1" } }
500
550
<filename>playframework-dist/play-1.1/framework/src/play/data/validation/Email.java package play.data.validation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.sf.oval.configuration.annotation.Constraint; /** * This field must be a valid email. * Message key: validation.email * $1: field name */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @Constraint(checkWith = EmailCheck.class) public @interface Email { String message() default EmailCheck.mes; }
201
3,281
package carbon.widget; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.StyleRes; import androidx.core.view.MenuItemCompat; import carbon.Carbon; import carbon.R; import carbon.component.Component; import carbon.component.LayoutComponent; import carbon.databinding.CarbonBottomnavigationviewItemBinding; import carbon.drawable.ColorStateListFactory; import carbon.recycler.RowFactory; public class BottomNavigationView extends LinearLayout { public static class Item { private int id; private Drawable icon; private CharSequence text; private ColorStateList iconTint; public Item() { } public Item(int id, Drawable icon, CharSequence text) { this.id = id; this.icon = icon; this.text = text; } public Item(MenuItem menuItem) { id = menuItem.getItemId(); try { // breaks preview this.icon = menuItem.getIcon(); } catch (Exception e) { } this.text = menuItem.getTitle(); iconTint = MenuItemCompat.getIconTintList(menuItem); } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setIcon(Drawable icon) { this.icon = icon; } public Drawable getIcon() { return icon; } public void setTitle(CharSequence text) { this.text = text; } public CharSequence getTitle() { return text; } public void setIconTintList(ColorStateList iconTint) { this.iconTint = iconTint; } public ColorStateList getIconTintList() { return iconTint; } } private static class ItemComponent extends LayoutComponent<Item> { ItemComponent(ViewGroup parent) { super(parent, R.layout.carbon_bottomnavigationview_item); } private final CarbonBottomnavigationviewItemBinding binding = CarbonBottomnavigationviewItemBinding.bind(getView()); @Override public void bind(Item data) { binding.carbonBottomIcon.setImageDrawable(data.icon); binding.carbonBottomIcon.setTintList(data.getIconTintList() != null ? data.getIconTintList() : ColorStateListFactory.INSTANCE.makeIconSecondary(getView().getContext())); binding.carbonBottomText.setText(data.text); binding.carbonBottomText.setTextColor(data.getIconTintList() != null ? data.getIconTintList() : ColorStateListFactory.INSTANCE.makeIconSecondary(getView().getContext())); } } private Item[] items; private View activeView; private RowFactory<Item> itemFactory; RecyclerView.OnItemClickedListener<Item> listener; public BottomNavigationView(Context context) { super(context, null, R.attr.carbon_bottomNavigationViewStyle); initBottomNavigationView(null, R.attr.carbon_bottomNavigationViewStyle, R.style.carbon_BottomNavigationView); } public BottomNavigationView(Context context, AttributeSet attrs) { super(context, attrs, R.attr.carbon_bottomNavigationViewStyle); initBottomNavigationView(attrs, R.attr.carbon_bottomNavigationViewStyle, R.style.carbon_BottomNavigationView); } public BottomNavigationView(Context context, AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); initBottomNavigationView(attrs, defStyleAttr, R.style.carbon_BottomNavigationView); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public BottomNavigationView(Context context, AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initBottomNavigationView(attrs, defStyleAttr, defStyleRes); } private void initBottomNavigationView(AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.BottomNavigationView, defStyleAttr, defStyleRes); itemFactory = ItemComponent::new; int menuId = a.getResourceId(R.styleable.BottomNavigationView_carbon_menu, 0); if (menuId != 0) setMenu(menuId); a.recycle(); } public void setMenuItems(Item[] items) { this.items = items; initItems(); } public Item[] getMenuItems() { return items; } public void setMenu(int resId) { setMenu(Carbon.getMenu(getContext(), resId)); } public void setMenu(Menu menu) { items = new Item[menu.size()]; for (int i = 0; i < menu.size(); i++) items[i] = new Item(menu.getItem(i)); initItems(); } @Deprecated public void setItemLayout(int itemLayoutId) { } public void setItemFactory(RowFactory<Item> factory) { this.itemFactory = factory; initItems(); } private void initItems() { removeAllViews(); int width = getOrientation() == HORIZONTAL ? 0 : ViewGroup.LayoutParams.WRAP_CONTENT; int height = getOrientation() != HORIZONTAL ? 0 : ViewGroup.LayoutParams.WRAP_CONTENT; setWeightSum(items.length); for (int i = 0; i < items.length; i++) { Item item = items[i]; if (!isInEditMode()) { Component<Item> component = itemFactory.create(this); int finalI = i; component.getView().setOnClickListener(v -> { if (component.getView() == activeView) return; selectItem(component.getView()); if (listener != null) listener.onItemClicked(component.getView(), item, finalI); }); component.setData(item); addView(component.getView(), new LinearLayout.LayoutParams(width, height, 1)); } else { View view = new LinearLayout(getContext()); addView(view, new LinearLayout.LayoutParams(width, height, 1)); } } } private void selectItem(final View item) { if (activeView != null) activeView.setSelected(false); activeView = item; if (activeView != null) activeView.setSelected(true); } public int getSelectedIndex() { if (activeView == null) return -1; return indexOfChild(activeView); } public void setSelectedIndex(int index) { selectItem(getChildAt(index)); } public void setOnItemClickListener(RecyclerView.OnItemClickedListener<Item> listener) { this.listener = listener; } @Override public Parcelable onSaveInstanceState() { //begin boilerplate code that allows parent classes to save state Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); //end ss.selectedIndex = getSelectedIndex(); return ss; } @Override public void onRestoreInstanceState(Parcelable state) { //begin boilerplate code so parent classes can restore state if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); //end this.setSelectedIndex(ss.selectedIndex); } static class SavedState implements Parcelable { public static final SavedState EMPTY_STATE = new SavedState() { }; int selectedIndex; Parcelable superState; SavedState() { superState = null; } SavedState(Parcelable superState) { this.superState = superState != EMPTY_STATE ? superState : null; } private SavedState(Parcel in) { Parcelable superState = in.readParcelable(BottomNavigationView.class.getClassLoader()); this.superState = superState != null ? superState : EMPTY_STATE; this.selectedIndex = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(@NonNull Parcel out, int flags) { out.writeParcelable(superState, flags); out.writeInt(this.selectedIndex); } public Parcelable getSuperState() { return superState; } //required field that makes Parcelables from a Parcel public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
4,080
1,338
// ResourceItem.h #ifndef RESOURCE_ITEM_H #define RESOURCE_ITEM_H #include <String.h> #include <SupportDefs.h> class BPositionIO; class ResourceItem { public: typedef int32 roff_t; public: ResourceItem(); virtual ~ResourceItem(); void SetLocation(roff_t offset, roff_t size); void SetIdentity(type_code type, int32 id, const char* name); void SetOffset(roff_t offset); roff_t GetOffset() const; void SetSize(roff_t size); roff_t GetSize() const; void SetType(type_code type); type_code GetType() const; void SetID(int32 id); int32 GetID() const; void SetName(const char* name); const char* GetName() const; void SetData(const void* data, roff_t size = -1); void UnsetData(); void* AllocData(roff_t size = -1); void* GetData() const; status_t LoadData(BPositionIO& file, roff_t position = -1, roff_t size = -1); status_t WriteData(BPositionIO& file) const; void PrintToStream(); private: roff_t fOffset; roff_t fSize; type_code fType; int32 fID; BString fName; void* fData; }; #endif // RESOURCE_ITEM_H
604
617
/** * Copyright 2011-2013 FoundationDB, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* The original from which this derives bore the following: */ /* Derby - Class org.apache.derby.impl.sql.compile.CreateSchemaNode 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 com.bj58.sql.parser; import com.bj58.sql.StandardException; import com.bj58.sql.types.CharacterTypeAttributes; /** * A CreateSchemaNode is the root of a QueryTree that * represents a CREATE SCHEMA statement. * */ public class CreateSchemaNode extends DDLStatementNode { private String name; private String aid; private CharacterTypeAttributes defaultCharacterAttributes; private ExistenceCheck existenceCheck; /** * Initializer for a CreateSchemaNode * * @param schemaName The name of the new schema * @param aid The authorization id * * @exception StandardException Thrown on error */ public void init(Object schemaName, Object aid, Object defaultCharacterAttributes, Object c ) throws StandardException { /* ** DDLStatementNode expects tables, null out ** objectName explicitly to clarify that we ** can't hang with schema.object specifiers. */ initAndCheck(null); this.name = (String)schemaName; this.aid = (String)aid; this.defaultCharacterAttributes = (CharacterTypeAttributes)defaultCharacterAttributes; this.existenceCheck = (ExistenceCheck)c; } /** * Fill this node with a deep copy of the given node. */ public void copyFrom(QueryTreeNode node) throws StandardException { super.copyFrom(node); CreateSchemaNode other = (CreateSchemaNode)node; this.name = other.name; this.aid = other.aid; this.defaultCharacterAttributes = other.defaultCharacterAttributes; this.existenceCheck = other.existenceCheck; } /** * Convert this object to a String. See comments in QueryTreeNode.java * for how this should be done for tree printing. * * @return This object as a String */ public String toString() { return super.toString() + "schemaName: " + "\n" + name + "\n" + "authorizationId: " + "\n" + aid + "\n" + "defaultChar: " + "\n" + defaultCharacterAttributes + "\n" + "existenceCheck:\n" + existenceCheck + "\n" ; } public String statementToString() { return "CREATE SCHEMA"; } public String getSchemaName() { return this.name; } public String getAuthorizationID() { return this.aid; } public CharacterTypeAttributes getDefaultCharacterAttributes() { return defaultCharacterAttributes; } public ExistenceCheck getExistenceCheck() { return existenceCheck; } }
1,446
671
package com.asha.nightowllib.handler.impls; import android.widget.ImageView; import com.asha.nightowllib.NightOwlTable; import com.asha.nightowllib.handler.annotations.OwlHandle; /** * Created by hzqiujiadi on 15/11/5. * hzqiujiadi <EMAIL> */ @OwlHandle({ImageView.class}) public class ImageViewHandler extends AbsSkinHandler implements NightOwlTable.OwlImageView { }
131
348
{"nom":"Cuzieu","circ":"5ème circonscription","dpt":"Ain","inscrits":365,"abs":172,"votants":193,"blancs":12,"nuls":1,"exp":180,"res":[{"nuance":"LR","nom":"<NAME>","voix":120},{"nuance":"REM","nom":"<NAME>","voix":60}]}
88
503
/** * Yobi, Project Hosting SW * * Copyright 2012 NAVER Corp. * http://yobi.io * * @author <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package playRepository; import models.*; import models.enumeration.ResourceType; import models.resource.Resource; import java.util.*; public abstract class Commit { public abstract String getShortId(); public abstract String getId(); public abstract String getShortMessage(); public abstract String getMessage(); public abstract User getAuthor(); public abstract String getAuthorName(); public abstract String getAuthorEmail(); public abstract Date getAuthorDate(); public abstract TimeZone getAuthorTimezone(); public abstract String getCommitterName(); public abstract String getCommitterEmail(); public abstract Date getCommitterDate(); public abstract TimeZone getCommitterTimezone(); public abstract int getParentCount(); public Set<User> getWatchers(Project project) { return getWatchers(project, true); } public Set<User> getWatchers(Project project, boolean allowedWatchersOnly) { Set<User> actualWatchers = new HashSet<>(); // Add the author if (!getAuthor().isAnonymous()) { actualWatchers.add(getAuthor()); } // Add every user who comments on this commit if (project.vcs.equals(RepositoryService.VCS_GIT)) { List<CommentThread> threads = CommentThread.find.where() .eq("project.id", project.id) .eq("commitId", getId()) .eq("pullRequest.id", null).findList(); for (CommentThread thread : threads) { for (ReviewComment comment : thread.reviewComments) { User user = User.find.byId(comment.author.id); if (user != null) { actualWatchers.add(user); } } } } else { List<CommitComment> comments = CommitComment.find.where() .eq("project.id", project.id).eq("commitId", getId()).findList(); for (CommitComment c : comments) { User user = User.find.byId(c.authorId); if (user != null) { actualWatchers.add(user); } } } return Watch.findActualWatchers(actualWatchers, asResource(project), allowedWatchersOnly); } public static Project getProjectFromResourceId(String resourceId) { String[] pair = resourceId.split(":"); return Project.find.byId(Long.valueOf(pair[0])); } public static Resource getAsResource(Project project, String commitId) { return getAsResource(project.id + ":" + commitId); } public static Resource getAsResource(final String resourceId) { return new Resource() { @Override public String getId() { return resourceId; } @Override public Project getProject() { return getProjectFromResourceId(resourceId); } @Override public ResourceType getType() { return ResourceType.COMMIT; } }; } public Resource asResource(final Project project) { return new Resource() { @Override public String getId() { return project.id + ":" + Commit.this.getId(); } @Override public Project getProject() { return project; } @Override public ResourceType getType() { return ResourceType.COMMIT; } @Override public Long getAuthorId() { User author = getAuthor(); if (author != null) { return getAuthor().id; } else { return null; } } }; } }
1,951
471
import datetime import decimal from jsonobject.base_properties import AbstractDateProperty from jsonobject import * import re from jsonobject.api import re_date, re_time, re_decimal from dimagi.utils.dates import safe_strftime from dimagi.utils.parsing import ISO_DATETIME_FORMAT from django.conf import settings OldJsonObject = JsonObject OldDateTimeProperty = DateTimeProperty HISTORICAL_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' try: # this isn't actually part of dimagi-utils # but this is temporary and don't want to do a bigger reorg from corehq.util.soft_assert import soft_assert except ImportError: def _assert(assertion, msg): assert assertion, msg else: _assert = soft_assert('{}<EMAIL>('<EMAIL>', '<EMAIL>'), # should still fail in tests fail_if_debug=settings.UNIT_TESTING) class DateTimeProperty(AbstractDateProperty): """ Accepts and produces ISO8601 string in UTC (with the Z suffix) Accepts with or without microseconds (must have all six digits if any) Always produces with microseconds (USec stands for microsecond) """ _type = datetime.datetime def _wrap(self, value): if '.' in value: fmt = ISO_DATETIME_FORMAT if len(value.split('.')[-1]) != 7: raise ValueError( 'USecDateTimeProperty ' 'must have 6 decimal places ' 'or none at all: {}'.format(value) ) else: fmt = HISTORICAL_DATETIME_FORMAT try: result = datetime.datetime.strptime(value, fmt) except ValueError as e: raise ValueError( 'Invalid date/time {0!r} [{1}]'.format(value, e)) _assert(result.tzinfo is None, "USecDateTimeProperty shouldn't ever return offset-aware!") return result def _unwrap(self, value): _assert(value.tzinfo is None, "Can't set a USecDateTimeProperty to an offset-aware datetime") return value, safe_strftime(value, '%Y-%m-%dT%H:%M:%S.%fZ') re_trans_datetime = re.compile(r""" ^ (\d{4}) # year - (0[1-9]|1[0-2]) # month - ([12]\d|0[1-9]|3[01]) # day T ([01]\d|2[0-3]) # hour : [0-5]\d # minute : [0-5]\d # second (\.\d{6})? # millisecond (optional) Z # timezone $ """, re.VERBOSE) class USecDateTimeMeta(object): update_properties = { datetime.datetime: DateTimeProperty, } string_conversions = ( (re_date, datetime.date), (re_time, datetime.time), (re_trans_datetime, datetime.datetime), (re_decimal, decimal.Decimal), ) class JsonObject(OldJsonObject): Meta = USecDateTimeMeta class StrictJsonObject(JsonObject): _allow_dynamic_properties = False
1,310
661
<gh_stars>100-1000 import copy import torch import torch.nn as nn import torch.nn.functional as F from .ssdsbase import SSDSBase from ssds.modeling.layers.basic_layers import ConvBNReLU class SharedHead(nn.Sequential): def __init__(self, out_planes): layers = [] for _ in range(4): layers += [ ConvBNReLU(256, 256, 3) ] # [nn.Conv2d(256, 256, 3, padding=1), nn.ReLU()] layers += [nn.Conv2d(256, out_planes, 3, padding=1)] super(SharedHead, self).__init__(*layers) class SSDFPN(SSDSBase): """RetinaNet in Focal Loss for Dense Object Detection See: https://arxiv.org/abs/1708.02002v2 for more details. Compared with the original implementation, change the conv2d in the extra and head to ConvBNReLU to helps the model converage easily Not add the bn&relu to transforms cause it is followed by interpolate and element-wise sum Args: backbone: backbone layers for input extras: contains transforms and extra layers that feed to multibox loc and conf layers head: "multibox head" consists of loc and conf conv layers num_classes: num of classes """ def __init__(self, backbone, extras, head, num_classes): super(SSDFPN, self).__init__(backbone, num_classes) # SSD network self.transforms = nn.ModuleList(extras[0]) self.extras = nn.ModuleList(extras[1]) self.loc = head[0] self.conf = head[1] self.initialize() def initialize(self): r""" :meta private: """ self.backbone.initialize() self.transforms.apply(self.initialize_extra) self.extras.apply(self.initialize_extra) self.loc.apply(self.initialize_head) self.conf.apply(self.initialize_head) self.conf[-1].apply(self.initialize_prior) def forward(self, x): r"""Applies network layers and ops on input image(s) x. Args: x: input image or batch of images. Return: When self.training==True, loc and conf for each anchor box; When self.training==False. loc and conf.sigmoid() for each anchor box; For each player, conf with shape [batch, num_anchor*num_classes, height, width]; For each player, loc with shape [batch, num_anchor*4, height, width]. """ loc, conf = [list() for _ in range(2)] # apply bases layers and cache source layer outputs features = self.backbone(x) x = features[-1] features_len = len(features) for i in range(len(features))[::-1]: if i != features_len - 1: xx = F.interpolate( xx, scale_factor=2, mode="nearest" ) + self.transforms[i](features[i]) else: xx = self.transforms[i](features[i]) features[i] = xx for i, v in enumerate(self.extras): if i < features_len: xx = v(features[i]) elif i == features_len: xx = v(x) else: xx = v(xx) loc.append(self.loc(xx)) conf.append(self.conf(xx)) if not self.training: conf = [c.sigmoid() for c in conf] return tuple(loc), tuple(conf) @staticmethod def add_extras(feature_layer, mbox, num_classes): r"""Define and declare the extras, loc and conf modules for the ssdfpn model. The feature_layer is defined in cfg.MODEL.FEATURE_LAYER. For ssdfpn model can be int, list of int and str: * int The int in the feature_layer represents the output feature in the backbone. * list of int The list of int in the feature_layer represents the output feature in the backbone, the first int is the \ backbone output and the second int is the upsampling branch to fuse feature. * str The str in the feature_layer represents the extra layers append at the end of the backbone. Args: feature_layer: the feature layers with detection head, defined by cfg.MODEL.FEATURE_LAYER mbox: the number of boxes for each feature map num_classes: the number of classes, defined by cfg.MODEL.NUM_CLASSES """ nets_outputs, transform_layers, extra_layers = [list() for _ in range(3)] if not all(mbox[i] == mbox[i + 1] for i in range(len(mbox) - 1)): raise ValueError( "For SSDFPN module, the number of box have to be same in every layer" ) loc_layers = SharedHead(mbox[0] * 4) conf_layers = SharedHead(mbox[0] * num_classes) for layer, depth in zip(feature_layer[0], feature_layer[1]): if isinstance(layer, int): nets_outputs.append(layer) transform_layers += [ nn.Conv2d(depth, 256, 1) ] # [ConvBNReLU(depth, 256, 1)] extra_layers += [ ConvBNReLU(256, 256, 3) ] # [nn.Conv2d(256, 256, 3, padding=1)] elif layer == "Conv:S": extra_layers += [ ConvBNReLU(depth, 256, 3, stride=2) ] # [nn.Conv2d(depth, 256, 3, stride=2, padding=1)] else: raise ValueError(layer + " does not support by SSDFPN") return nets_outputs, (transform_layers, extra_layers), (loc_layers, conf_layers)
2,515
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.apisupport.project.ui.customizer; import java.awt.Dialog; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.event.ChangeListener; import org.apache.tools.ant.module.api.AntProjectCookie; import org.apache.tools.ant.module.api.AntTargetExecutor; import org.apache.tools.ant.module.api.support.AntScriptUtils; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.project.Project; import org.netbeans.modules.apisupport.project.api.ManifestManager; import org.netbeans.modules.apisupport.project.api.Util; import org.netbeans.spi.project.support.ant.GeneratedFilesHelper; import org.openide.DialogDisplayer; import org.openide.WizardDescriptor; import org.openide.WizardDescriptor.Panel; import org.openide.execution.ExecutorTask; import org.openide.filesystems.FileObject; import org.openide.nodes.Node; import org.openide.util.NbBundle; public final class Clusterize implements WizardDescriptor.ProgressInstantiatingIterator<Clusterize> { final File file; final Project project; final ClusterizeInfo modules; private WizardDescriptor.Panel[] panels; final WizardDescriptor wizardDescriptor; int index; private Clusterize(Project p, File f) { this.file = f; this.project = p; this.modules = new ClusterizeInfo("", null, f); this.modules.setDisplayName(f.getPath()); this.wizardDescriptor = new WizardDescriptor(this, this); } public static boolean clusterize(Project p, File f) { return new Clusterize(p, f).perform(); } private boolean perform() { wizardDescriptor.createNotificationLineSupport(); wizardDescriptor.setTitleFormat(new MessageFormat("{0}")); wizardDescriptor.setTitle(NbBundle.getMessage(Clusterize.class, "LAB_ClusterizeWizard")); Dialog dialog = DialogDisplayer.getDefault().createDialog(wizardDescriptor); dialog.setVisible(true); dialog.toFront(); return wizardDescriptor.getValue() == WizardDescriptor.FINISH_OPTION; } @SuppressWarnings("unchecked") private WizardDescriptor.Panel<Clusterize>[] getPanels() { if (panels == null) { panels = new WizardDescriptor.Panel<?>[]{ new ClusterizeWizardPanel1(), new ClusterizeWizardPanel2(), new ClusterizeWizardPanel3() }; } return panels; } String getStep(int i) { return getSteps()[i]; } String[] getSteps() { return new String[] { NbBundle.getMessage(Clusterize.class, "LAB_ClusterizeNotValid"), NbBundle.getMessage(Clusterize.class, "LAB_ClusterizeChoose"), NbBundle.getMessage(Clusterize.class, "LAB_ClusterizeSummary"), }; } void scanForJars() { try { scanForJars(modules); } catch (InterruptedException ex) { Logger.getLogger(Clusterize.class.getName()).log(Level.FINE, null, ex); } } private static boolean scanForJars(ClusterizeInfo folder) throws InterruptedException { File[] children = folder.jar.listFiles(); folder.getChildren().remove(folder.getChildren().getNodes()); if (children == null) { return false; } String pref = folder.path.length() == 0 ? "" : folder.path + '/'; List<Node> arr = new ArrayList<Node>(); for (File file : children) { if (Thread.interrupted()) { throw new InterruptedException(); } if (file.isDirectory()) { ClusterizeInfo subdir = new ClusterizeInfo(pref + file.getName(), null, file); if (scanForJars(subdir)) { arr.add(subdir); } continue; } if (!file.getName().endsWith(".jar")) { continue; } ManifestManager mm = ManifestManager.getInstanceFromJAR(file); if (mm != null && mm.getCodeNameBase() != null) { arr.add(new ClusterizeInfo(pref + file.getName(), mm, file)); } } folder.getChildren().add(arr.toArray(new Node[0])); return folder.getChildren().getNodesCount() > 0; } void generateConfigFiles() { Set<String> autoload = new HashSet<String>(); Set<String> eager = new HashSet<String>(); Set<String> enabled = new HashSet<String>(); modules.categorize(autoload, eager, enabled); try { AntProjectCookie apc = AntScriptUtils.antProjectCookieFor(findBuildXml(project)); AntTargetExecutor.Env execenv = new AntTargetExecutor.Env(); // execenv.setLogger(new NullOutputStream()); Properties p = execenv.getProperties(); toProperty(p, "include.autoload", autoload); // NOI18N toProperty(p, "include.enabled", enabled); // NOI18N toProperty(p, "include.eager", eager); // NOI18N p.setProperty("cluster", file.getPath()); // NOI18N execenv.setProperties(p); String[] targetNames = { "clusterize" }; // NOI18N ExecutorTask t = AntTargetExecutor.createTargetExecutor(execenv).execute(apc, targetNames); t.waitFinished(); } catch (IOException e) { Util.err.notify(e); } } private void toProperty(Properties p, String property, Set<String> strings) { if (strings.size() == 0) { return; } String sep = ""; // NOI18N StringBuilder sb = new StringBuilder(); for (String s : strings) { sb.append(sep); sb.append(s); sep = ","; // NOI18N } p.setProperty(property, sb.toString()); } private static FileObject findBuildXml(Project project) { return project.getProjectDirectory().getFileObject(GeneratedFilesHelper.BUILD_XML_PATH); } @Override public Set instantiate(ProgressHandle handle) throws IOException { handle.start(); generateConfigFiles(); handle.finish(); return Collections.emptySet(); } @Override public Set instantiate() throws IOException { assert false; generateConfigFiles(); return Collections.emptySet(); } @Override public void initialize(WizardDescriptor wizard) { } @Override public void uninitialize(WizardDescriptor wizard) { } @Override public Panel<Clusterize> current() { return getPanels()[index]; } @Override public String name() { return getStep(index); } @Override public boolean hasNext() { return index < getPanels().length - 1; } @Override public boolean hasPrevious() { return index > 0; } @Override public void nextPanel() { index++; } @Override public void previousPanel() { index--; } @Override public void addChangeListener(ChangeListener l) { } @Override public void removeChangeListener(ChangeListener l) { } }
3,325
995
<filename>deps/boost/include/boost/intrusive/set.hpp ///////////////////////////////////////////////////////////////////////////// // // (C) Copyright <NAME> 2004-2006. // (C) Copyright <NAME> 2006-2014 // // 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) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_SET_HPP #define BOOST_INTRUSIVE_SET_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/detail/mpl.hpp> #include <boost/intrusive/rbtree.hpp> #include <boost/move/utility_core.hpp> #include <boost/static_assert.hpp> #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif namespace boost { namespace intrusive { #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class ValueTraits, class VoidOrKeyOfValue, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder> class multiset_impl; #endif //! The class template set is an intrusive container, that mimics most of //! the interface of std::set as described in the C++ standard. //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c constant_time_size<>, \c size_type<> and //! \c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class ValueTraits, class VoidOrKeyOfValue, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder> #endif class set_impl #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED : public bstree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder> #endif { /// @cond typedef bstree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder> tree_type; BOOST_MOVABLE_BUT_NOT_COPYABLE(set_impl) typedef tree_type implementation_defined; /// @endcond public: typedef typename implementation_defined::value_type value_type; typedef typename implementation_defined::key_type key_type; typedef typename implementation_defined::key_of_value key_of_value; typedef typename implementation_defined::value_traits value_traits; typedef typename implementation_defined::pointer pointer; typedef typename implementation_defined::const_pointer const_pointer; typedef typename implementation_defined::reference reference; typedef typename implementation_defined::const_reference const_reference; typedef typename implementation_defined::difference_type difference_type; typedef typename implementation_defined::size_type size_type; typedef typename implementation_defined::value_compare value_compare; typedef typename implementation_defined::key_compare key_compare; typedef typename implementation_defined::iterator iterator; typedef typename implementation_defined::const_iterator const_iterator; typedef typename implementation_defined::reverse_iterator reverse_iterator; typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; typedef typename implementation_defined::insert_commit_data insert_commit_data; typedef typename implementation_defined::node_traits node_traits; typedef typename implementation_defined::node node; typedef typename implementation_defined::node_ptr node_ptr; typedef typename implementation_defined::const_node_ptr const_node_ptr; typedef typename implementation_defined::node_algorithms node_algorithms; static const bool constant_time_size = tree_type::constant_time_size; public: //! @copydoc ::boost::intrusive::rbtree::rbtree() set_impl() : tree_type() {} //! @copydoc ::boost::intrusive::rbtree::rbtree(const key_compare &,const value_traits &) explicit set_impl( const key_compare &cmp, const value_traits &v_traits = value_traits()) : tree_type(cmp, v_traits) {} //! @copydoc ::boost::intrusive::rbtree::rbtree(bool,Iterator,Iterator,const key_compare &,const value_traits &) template<class Iterator> set_impl( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : tree_type(true, b, e, cmp, v_traits) {} //! @copydoc ::boost::intrusive::rbtree::rbtree(rbtree &&) set_impl(BOOST_RV_REF(set_impl) x) : tree_type(BOOST_MOVE_BASE(tree_type, x)) {} //! @copydoc ::boost::intrusive::rbtree::operator=(rbtree &&) set_impl& operator=(BOOST_RV_REF(set_impl) x) { return static_cast<set_impl&>(tree_type::operator=(BOOST_MOVE_BASE(tree_type, x))); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::~rbtree() ~set_impl(); //! @copydoc ::boost::intrusive::rbtree::begin() iterator begin(); //! @copydoc ::boost::intrusive::rbtree::begin()const const_iterator begin() const; //! @copydoc ::boost::intrusive::rbtree::cbegin()const const_iterator cbegin() const; //! @copydoc ::boost::intrusive::rbtree::end() iterator end(); //! @copydoc ::boost::intrusive::rbtree::end()const const_iterator end() const; //! @copydoc ::boost::intrusive::rbtree::cend()const const_iterator cend() const; //! @copydoc ::boost::intrusive::rbtree::rbegin() reverse_iterator rbegin(); //! @copydoc ::boost::intrusive::rbtree::rbegin()const const_reverse_iterator rbegin() const; //! @copydoc ::boost::intrusive::rbtree::crbegin()const const_reverse_iterator crbegin() const; //! @copydoc ::boost::intrusive::rbtree::rend() reverse_iterator rend(); //! @copydoc ::boost::intrusive::rbtree::rend()const const_reverse_iterator rend() const; //! @copydoc ::boost::intrusive::rbtree::crend()const const_reverse_iterator crend() const; //! @copydoc ::boost::intrusive::rbtree::root() iterator root(); //! @copydoc ::boost::intrusive::rbtree::root()const const_iterator root() const; //! @copydoc ::boost::intrusive::rbtree::croot()const const_iterator croot() const; //! @copydoc ::boost::intrusive::rbtree::container_from_end_iterator(iterator) static set_impl &container_from_end_iterator(iterator end_iterator); //! @copydoc ::boost::intrusive::rbtree::container_from_end_iterator(const_iterator) static const set_impl &container_from_end_iterator(const_iterator end_iterator); //! @copydoc ::boost::intrusive::rbtree::container_from_iterator(iterator) static set_impl &container_from_iterator(iterator it); //! @copydoc ::boost::intrusive::rbtree::container_from_iterator(const_iterator) static const set_impl &container_from_iterator(const_iterator it); //! @copydoc ::boost::intrusive::rbtree::key_comp()const key_compare key_comp() const; //! @copydoc ::boost::intrusive::rbtree::value_comp()const value_compare value_comp() const; //! @copydoc ::boost::intrusive::rbtree::empty()const bool empty() const; //! @copydoc ::boost::intrusive::rbtree::size()const size_type size() const; //! @copydoc ::boost::intrusive::rbtree::swap void swap(set_impl& other); //! @copydoc ::boost::intrusive::rbtree::clone_from(const rbtree&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(const set_impl &src, Cloner cloner, Disposer disposer); #else using tree_type::clone_from; #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::clone_from(rbtree&&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(BOOST_RV_REF(set_impl) src, Cloner cloner, Disposer disposer) { tree_type::clone_from(BOOST_MOVE_BASE(tree_type, src), cloner, disposer); } //! @copydoc ::boost::intrusive::rbtree::insert_unique(reference) std::pair<iterator, bool> insert(reference value) { return tree_type::insert_unique(value); } //! @copydoc ::boost::intrusive::rbtree::insert_unique(const_iterator,reference) iterator insert(const_iterator hint, reference value) { return tree_type::insert_unique(hint, value); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_check(const key_type&,insert_commit_data&) std::pair<iterator, bool> insert_check (const key_type &key, insert_commit_data &commit_data) { return tree_type::insert_unique_check(key, commit_data); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_check(const_iterator,const key_type&,insert_commit_data&) std::pair<iterator, bool> insert_check (const_iterator hint, const key_type &key ,insert_commit_data &commit_data) { return tree_type::insert_unique_check(hint, key, commit_data); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_check(const KeyType&,KeyTypeKeyCompare,insert_commit_data&) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_check (const KeyType &key, KeyTypeKeyCompare comp, insert_commit_data &commit_data) { return tree_type::insert_unique_check(key, comp, commit_data); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_check(const_iterator,const KeyType&,KeyTypeKeyCompare,insert_commit_data&) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator, bool> insert_check (const_iterator hint, const KeyType &key ,KeyTypeKeyCompare comp, insert_commit_data &commit_data) { return tree_type::insert_unique_check(hint, key, comp, commit_data); } //! @copydoc ::boost::intrusive::rbtree::insert_unique(Iterator,Iterator) template<class Iterator> void insert(Iterator b, Iterator e) { tree_type::insert_unique(b, e); } //! @copydoc ::boost::intrusive::rbtree::insert_unique_commit iterator insert_commit(reference value, const insert_commit_data &commit_data) { return tree_type::insert_unique_commit(value, commit_data); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::insert_before iterator insert_before(const_iterator pos, reference value); //! @copydoc ::boost::intrusive::rbtree::push_back void push_back(reference value); //! @copydoc ::boost::intrusive::rbtree::push_front void push_front(reference value); //! @copydoc ::boost::intrusive::rbtree::erase(const_iterator) iterator erase(const_iterator i); //! @copydoc ::boost::intrusive::rbtree::erase(const_iterator,const_iterator) iterator erase(const_iterator b, const_iterator e); //! @copydoc ::boost::intrusive::rbtree::erase(const key_type &) size_type erase(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::erase(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> size_type erase(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator i, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const_iterator,const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const key_type &, Disposer) template<class Disposer> size_type erase_and_dispose(const key_type &key, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const KeyType&,KeyTypeKeyCompare,Disposer) template<class KeyType, class KeyTypeKeyCompare, class Disposer> size_type erase_and_dispose(const KeyType& key, KeyTypeKeyCompare comp, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::clear void clear(); //! @copydoc ::boost::intrusive::rbtree::clear_and_dispose template<class Disposer> void clear_and_dispose(Disposer disposer); #endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::count(const key_type &)const size_type count(const key_type &key) const { return static_cast<size_type>(this->tree_type::find(key) != this->tree_type::cend()); } //! @copydoc ::boost::intrusive::rbtree::count(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType& key, KeyTypeKeyCompare comp) const { return static_cast<size_type>(this->tree_type::find(key, comp) != this->tree_type::cend()); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::lower_bound(const key_type &) iterator lower_bound(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::lower_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::lower_bound(const key_type &)const const_iterator lower_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::lower_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::upper_bound(const key_type &) iterator upper_bound(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::upper_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::upper_bound(const key_type &)const const_iterator upper_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::upper_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::find(const key_type &) iterator find(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::find(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator find(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::find(const key_type &)const const_iterator find(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::find(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator find(const KeyType& key, KeyTypeKeyCompare comp) const; #endif // #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::equal_range(const key_type &) std::pair<iterator,iterator> equal_range(const key_type &key) { return this->tree_type::lower_bound_range(key); } //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp) { return this->tree_type::equal_range(key, comp); } //! @copydoc ::boost::intrusive::rbtree::equal_range(const key_type &)const std::pair<const_iterator, const_iterator> equal_range(const key_type &key) const { return this->tree_type::lower_bound_range(key); } //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp) const { return this->tree_type::equal_range(key, comp); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::bounded_range(const key_type &,const key_type &,bool,bool) std::pair<iterator,iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::rbtree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::rbtree::bounded_range(const key_type &,const key_type &,bool,bool)const std::pair<const_iterator, const_iterator> bounded_range(const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::rbtree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::rbtree::s_iterator_to(reference) static iterator s_iterator_to(reference value); //! @copydoc ::boost::intrusive::rbtree::s_iterator_to(const_reference) static const_iterator s_iterator_to(const_reference value); //! @copydoc ::boost::intrusive::rbtree::iterator_to(reference) iterator iterator_to(reference value); //! @copydoc ::boost::intrusive::rbtree::iterator_to(const_reference)const const_iterator iterator_to(const_reference value) const; //! @copydoc ::boost::intrusive::rbtree::init_node(reference) static void init_node(reference value); //! @copydoc ::boost::intrusive::rbtree::unlink_leftmost_without_rebalance pointer unlink_leftmost_without_rebalance(); //! @copydoc ::boost::intrusive::rbtree::replace_node void replace_node(iterator replace_this, reference with_this); //! @copydoc ::boost::intrusive::rbtree::remove_node void remove_node(reference value); //! @copydoc ::boost::intrusive::rbtree::merge_unique template<class ...Options2> void merge(set<T, Options2...> &source); //! @copydoc ::boost::intrusive::rbtree::merge_unique template<class ...Options2> void merge(multiset<T, Options2...> &source); #else template<class Compare2> void merge(set_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_unique(source); } template<class Compare2> void merge(multiset_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_unique(source); } #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED }; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> bool operator!= (const set_impl<T, Options...> &x, const set_impl<T, Options...> &y); template<class T, class ...Options> bool operator>(const set_impl<T, Options...> &x, const set_impl<T, Options...> &y); template<class T, class ...Options> bool operator<=(const set_impl<T, Options...> &x, const set_impl<T, Options...> &y); template<class T, class ...Options> bool operator>=(const set_impl<T, Options...> &x, const set_impl<T, Options...> &y); template<class T, class ...Options> void swap(set_impl<T, Options...> &x, set_impl<T, Options...> &y); #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! Helper metafunction to define a \c set that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = void, class O2 = void , class O3 = void, class O4 = void , class O5 = void, class O6 = void> #endif struct make_set { /// @cond typedef typename pack_options < rbtree_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::proto_value_traits>::type value_traits; typedef set_impl < value_traits , typename packed_options::key_of_value , typename packed_options::compare , typename packed_options::size_type , packed_options::constant_time_size , typename packed_options::header_holder_type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4, class O5, class O6> #else template<class T, class ...Options> #endif class set : public make_set<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type { typedef typename make_set <T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(set) public: typedef typename Base::key_compare key_compare; typedef typename Base::value_traits value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value)); BOOST_INTRUSIVE_FORCEINLINE set() : Base() {} BOOST_INTRUSIVE_FORCEINLINE explicit set( const key_compare &cmp, const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template<class Iterator> BOOST_INTRUSIVE_FORCEINLINE set( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : Base(b, e, cmp, v_traits) {} BOOST_INTRUSIVE_FORCEINLINE set(BOOST_RV_REF(set) x) : Base(BOOST_MOVE_BASE(Base, x)) {} BOOST_INTRUSIVE_FORCEINLINE set& operator=(BOOST_RV_REF(set) x) { return static_cast<set &>(this->Base::operator=(BOOST_MOVE_BASE(Base, x))); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(const set &src, Cloner cloner, Disposer disposer) { Base::clone_from(src, cloner, disposer); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(BOOST_RV_REF(set) src, Cloner cloner, Disposer disposer) { Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); } BOOST_INTRUSIVE_FORCEINLINE static set &container_from_end_iterator(iterator end_iterator) { return static_cast<set &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static const set &container_from_end_iterator(const_iterator end_iterator) { return static_cast<const set &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static set &container_from_iterator(iterator it) { return static_cast<set &>(Base::container_from_iterator(it)); } BOOST_INTRUSIVE_FORCEINLINE static const set &container_from_iterator(const_iterator it) { return static_cast<const set &>(Base::container_from_iterator(it)); } }; #endif //! The class template multiset is an intrusive container, that mimics most of //! the interface of std::multiset as described in the C++ standard. //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c constant_time_size<>, \c size_type<> and //! \c compare<>. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class ValueTraits, class VoidOrKeyOfValue, class Compare, class SizeType, bool ConstantTimeSize, typename HeaderHolder> #endif class multiset_impl #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED : public bstree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder> #endif { /// @cond typedef bstree_impl<ValueTraits, VoidOrKeyOfValue, Compare, SizeType, ConstantTimeSize, RbTreeAlgorithms, HeaderHolder> tree_type; BOOST_MOVABLE_BUT_NOT_COPYABLE(multiset_impl) typedef tree_type implementation_defined; /// @endcond public: typedef typename implementation_defined::value_type value_type; typedef typename implementation_defined::key_type key_type; typedef typename implementation_defined::key_of_value key_of_value; typedef typename implementation_defined::value_traits value_traits; typedef typename implementation_defined::pointer pointer; typedef typename implementation_defined::const_pointer const_pointer; typedef typename implementation_defined::reference reference; typedef typename implementation_defined::const_reference const_reference; typedef typename implementation_defined::difference_type difference_type; typedef typename implementation_defined::size_type size_type; typedef typename implementation_defined::value_compare value_compare; typedef typename implementation_defined::key_compare key_compare; typedef typename implementation_defined::iterator iterator; typedef typename implementation_defined::const_iterator const_iterator; typedef typename implementation_defined::reverse_iterator reverse_iterator; typedef typename implementation_defined::const_reverse_iterator const_reverse_iterator; typedef typename implementation_defined::insert_commit_data insert_commit_data; typedef typename implementation_defined::node_traits node_traits; typedef typename implementation_defined::node node; typedef typename implementation_defined::node_ptr node_ptr; typedef typename implementation_defined::const_node_ptr const_node_ptr; typedef typename implementation_defined::node_algorithms node_algorithms; static const bool constant_time_size = tree_type::constant_time_size; public: //! @copydoc ::boost::intrusive::rbtree::rbtree() multiset_impl() : tree_type() {} //! @copydoc ::boost::intrusive::rbtree::rbtree(const key_compare &,const value_traits &) explicit multiset_impl( const key_compare &cmp, const value_traits &v_traits = value_traits()) : tree_type(cmp, v_traits) {} //! @copydoc ::boost::intrusive::rbtree::rbtree(bool,Iterator,Iterator,const key_compare &,const value_traits &) template<class Iterator> multiset_impl( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : tree_type(false, b, e, cmp, v_traits) {} //! @copydoc ::boost::intrusive::rbtree::rbtree(rbtree &&) multiset_impl(BOOST_RV_REF(multiset_impl) x) : tree_type(BOOST_MOVE_BASE(tree_type, x)) {} //! @copydoc ::boost::intrusive::rbtree::operator=(rbtree &&) multiset_impl& operator=(BOOST_RV_REF(multiset_impl) x) { return static_cast<multiset_impl&>(tree_type::operator=(BOOST_MOVE_BASE(tree_type, x))); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::~rbtree() ~multiset_impl(); //! @copydoc ::boost::intrusive::rbtree::begin() iterator begin(); //! @copydoc ::boost::intrusive::rbtree::begin()const const_iterator begin() const; //! @copydoc ::boost::intrusive::rbtree::cbegin()const const_iterator cbegin() const; //! @copydoc ::boost::intrusive::rbtree::end() iterator end(); //! @copydoc ::boost::intrusive::rbtree::end()const const_iterator end() const; //! @copydoc ::boost::intrusive::rbtree::cend()const const_iterator cend() const; //! @copydoc ::boost::intrusive::rbtree::rbegin() reverse_iterator rbegin(); //! @copydoc ::boost::intrusive::rbtree::rbegin()const const_reverse_iterator rbegin() const; //! @copydoc ::boost::intrusive::rbtree::crbegin()const const_reverse_iterator crbegin() const; //! @copydoc ::boost::intrusive::rbtree::rend() reverse_iterator rend(); //! @copydoc ::boost::intrusive::rbtree::rend()const const_reverse_iterator rend() const; //! @copydoc ::boost::intrusive::rbtree::crend()const const_reverse_iterator crend() const; //! @copydoc ::boost::intrusive::rbtree::root() iterator root(); //! @copydoc ::boost::intrusive::rbtree::root()const const_iterator root() const; //! @copydoc ::boost::intrusive::rbtree::croot()const const_iterator croot() const; //! @copydoc ::boost::intrusive::rbtree::container_from_end_iterator(iterator) static multiset_impl &container_from_end_iterator(iterator end_iterator); //! @copydoc ::boost::intrusive::rbtree::container_from_end_iterator(const_iterator) static const multiset_impl &container_from_end_iterator(const_iterator end_iterator); //! @copydoc ::boost::intrusive::rbtree::container_from_iterator(iterator) static multiset_impl &container_from_iterator(iterator it); //! @copydoc ::boost::intrusive::rbtree::container_from_iterator(const_iterator) static const multiset_impl &container_from_iterator(const_iterator it); //! @copydoc ::boost::intrusive::rbtree::key_comp()const key_compare key_comp() const; //! @copydoc ::boost::intrusive::rbtree::value_comp()const value_compare value_comp() const; //! @copydoc ::boost::intrusive::rbtree::empty()const bool empty() const; //! @copydoc ::boost::intrusive::rbtree::size()const size_type size() const; //! @copydoc ::boost::intrusive::rbtree::swap void swap(multiset_impl& other); //! @copydoc ::boost::intrusive::rbtree::clone_from(const rbtree&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(const multiset_impl &src, Cloner cloner, Disposer disposer); #else using tree_type::clone_from; #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::clone_from(rbtree&&,Cloner,Disposer) template <class Cloner, class Disposer> void clone_from(BOOST_RV_REF(multiset_impl) src, Cloner cloner, Disposer disposer) { tree_type::clone_from(BOOST_MOVE_BASE(tree_type, src), cloner, disposer); } //! @copydoc ::boost::intrusive::rbtree::insert_equal(reference) iterator insert(reference value) { return tree_type::insert_equal(value); } //! @copydoc ::boost::intrusive::rbtree::insert_equal(const_iterator,reference) iterator insert(const_iterator hint, reference value) { return tree_type::insert_equal(hint, value); } //! @copydoc ::boost::intrusive::rbtree::insert_equal(Iterator,Iterator) template<class Iterator> void insert(Iterator b, Iterator e) { tree_type::insert_equal(b, e); } #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED //! @copydoc ::boost::intrusive::rbtree::insert_before iterator insert_before(const_iterator pos, reference value); //! @copydoc ::boost::intrusive::rbtree::push_back void push_back(reference value); //! @copydoc ::boost::intrusive::rbtree::push_front void push_front(reference value); //! @copydoc ::boost::intrusive::rbtree::erase(const_iterator) iterator erase(const_iterator i); //! @copydoc ::boost::intrusive::rbtree::erase(const_iterator,const_iterator) iterator erase(const_iterator b, const_iterator e); //! @copydoc ::boost::intrusive::rbtree::erase(const key_type &) size_type erase(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::erase(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> size_type erase(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator i, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const_iterator,const_iterator,Disposer) template<class Disposer> iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const key_type &, Disposer) template<class Disposer> size_type erase_and_dispose(const key_type &key, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::erase_and_dispose(const KeyType&,KeyTypeKeyCompare,Disposer) template<class KeyType, class KeyTypeKeyCompare, class Disposer> size_type erase_and_dispose(const KeyType& key, KeyTypeKeyCompare comp, Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::clear void clear(); //! @copydoc ::boost::intrusive::rbtree::clear_and_dispose template<class Disposer> void clear_and_dispose(Disposer disposer); //! @copydoc ::boost::intrusive::rbtree::count(const key_type &)const size_type count(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::count(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> size_type count(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::lower_bound(const key_type &) iterator lower_bound(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::lower_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::lower_bound(const key_type &)const const_iterator lower_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::lower_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::upper_bound(const key_type &) iterator upper_bound(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::upper_bound(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::upper_bound(const key_type &)const const_iterator upper_bound(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::upper_bound(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::find(const key_type &) iterator find(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::find(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> iterator find(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::find(const key_type &)const const_iterator find(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::find(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> const_iterator find(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::equal_range(const key_type &) std::pair<iterator,iterator> equal_range(const key_type &key); //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyTypeKeyCompare) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp); //! @copydoc ::boost::intrusive::rbtree::equal_range(const key_type &)const std::pair<const_iterator, const_iterator> equal_range(const key_type &key) const; //! @copydoc ::boost::intrusive::rbtree::equal_range(const KeyType&,KeyTypeKeyCompare)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp) const; //! @copydoc ::boost::intrusive::rbtree::bounded_range(const key_type &,const key_type &,bool,bool) std::pair<iterator,iterator> bounded_range (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::rbtree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool) template<class KeyType, class KeyTypeKeyCompare> std::pair<iterator,iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed); //! @copydoc ::boost::intrusive::rbtree::bounded_range(const key_type &,const key_type &,bool,bool)const std::pair<const_iterator, const_iterator> bounded_range(const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::rbtree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool)const template<class KeyType, class KeyTypeKeyCompare> std::pair<const_iterator, const_iterator> bounded_range (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const; //! @copydoc ::boost::intrusive::rbtree::s_iterator_to(reference) static iterator s_iterator_to(reference value); //! @copydoc ::boost::intrusive::rbtree::s_iterator_to(const_reference) static const_iterator s_iterator_to(const_reference value); //! @copydoc ::boost::intrusive::rbtree::iterator_to(reference) iterator iterator_to(reference value); //! @copydoc ::boost::intrusive::rbtree::iterator_to(const_reference)const const_iterator iterator_to(const_reference value) const; //! @copydoc ::boost::intrusive::rbtree::init_node(reference) static void init_node(reference value); //! @copydoc ::boost::intrusive::rbtree::unlink_leftmost_without_rebalance pointer unlink_leftmost_without_rebalance(); //! @copydoc ::boost::intrusive::rbtree::replace_node void replace_node(iterator replace_this, reference with_this); //! @copydoc ::boost::intrusive::rbtree::remove_node void remove_node(reference value); //! @copydoc ::boost::intrusive::rbtree::merge_equal template<class ...Options2> void merge(multiset<T, Options2...> &source); //! @copydoc ::boost::intrusive::rbtree::merge_equal template<class ...Options2> void merge(set<T, Options2...> &source); #else template<class Compare2> void merge(multiset_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_equal(source); } template<class Compare2> void merge(set_impl<ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, ConstantTimeSize, HeaderHolder> &source) { return tree_type::merge_equal(source); } #endif //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED }; #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> bool operator!= (const multiset_impl<T, Options...> &x, const multiset_impl<T, Options...> &y); template<class T, class ...Options> bool operator>(const multiset_impl<T, Options...> &x, const multiset_impl<T, Options...> &y); template<class T, class ...Options> bool operator<=(const multiset_impl<T, Options...> &x, const multiset_impl<T, Options...> &y); template<class T, class ...Options> bool operator>=(const multiset_impl<T, Options...> &x, const multiset_impl<T, Options...> &y); template<class T, class ...Options> void swap(multiset_impl<T, Options...> &x, multiset_impl<T, Options...> &y); #endif //#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! Helper metafunction to define a \c multiset that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = void, class O2 = void , class O3 = void, class O4 = void , class O5 = void, class O6 = void> #endif struct make_multiset { /// @cond typedef typename pack_options < rbtree_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::proto_value_traits>::type value_traits; typedef multiset_impl < value_traits , typename packed_options::key_of_value , typename packed_options::compare , typename packed_options::size_type , packed_options::constant_time_size , typename packed_options::header_holder_type > implementation_defined; /// @endcond typedef implementation_defined type; }; #ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4, class O5, class O6> #else template<class T, class ...Options> #endif class multiset : public make_multiset<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type { typedef typename make_multiset<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif >::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(multiset) public: typedef typename Base::key_compare key_compare; typedef typename Base::value_traits value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value)); BOOST_INTRUSIVE_FORCEINLINE multiset() : Base() {} BOOST_INTRUSIVE_FORCEINLINE explicit multiset( const key_compare &cmp, const value_traits &v_traits = value_traits()) : Base(cmp, v_traits) {} template<class Iterator> BOOST_INTRUSIVE_FORCEINLINE multiset( Iterator b, Iterator e , const key_compare &cmp = key_compare() , const value_traits &v_traits = value_traits()) : Base(b, e, cmp, v_traits) {} BOOST_INTRUSIVE_FORCEINLINE multiset(BOOST_RV_REF(multiset) x) : Base(BOOST_MOVE_BASE(Base, x)) {} BOOST_INTRUSIVE_FORCEINLINE multiset& operator=(BOOST_RV_REF(multiset) x) { return static_cast<multiset &>(this->Base::operator=(BOOST_MOVE_BASE(Base, x))); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(const multiset &src, Cloner cloner, Disposer disposer) { Base::clone_from(src, cloner, disposer); } template <class Cloner, class Disposer> BOOST_INTRUSIVE_FORCEINLINE void clone_from(BOOST_RV_REF(multiset) src, Cloner cloner, Disposer disposer) { Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer); } BOOST_INTRUSIVE_FORCEINLINE static multiset &container_from_end_iterator(iterator end_iterator) { return static_cast<multiset &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static const multiset &container_from_end_iterator(const_iterator end_iterator) { return static_cast<const multiset &>(Base::container_from_end_iterator(end_iterator)); } BOOST_INTRUSIVE_FORCEINLINE static multiset &container_from_iterator(iterator it) { return static_cast<multiset &>(Base::container_from_iterator(it)); } BOOST_INTRUSIVE_FORCEINLINE static const multiset &container_from_iterator(const_iterator it) { return static_cast<const multiset &>(Base::container_from_iterator(it)); } }; #endif } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_SET_HPP
18,105
8,197
<reponame>infernix/ConEmu<filename>src/ConEmuHk/DbgHooks.h  #pragma once /* Hook GetLastError/SetLastError procedures */ //#define HOOK_ERROR_PROC #undef HOOK_ERROR_PROC /* Define macros HLOGx and DLOGx */ /* SKIPHOOKLOG is not defined or undefined here, by it */ /* may be used to disable logging in the exact *.cpp file */ #ifdef _DEBUG //#define USEHOOKLOG #undef USEHOOKLOG #else #undef USEHOOKLOG #undef USEHOOKLOGANALYZE #endif /* USEHOOKLOGANALYZE used to determine voracious steps on exit */ #ifdef USEHOOKLOG #define USEHOOKLOGANALYZE #else #undef USEHOOKLOGANALYZE #endif /* Print to console on ExitProcess/TerminateProcess */ //#define PRINT_ON_EXITPROCESS_CALLS #undef PRINT_ON_EXITPROCESS_CALLS /* gh#272: Crash if NVIDIA CoProcManager dlls are loaded */ //#define USE_GH_272_WORKAROUND #undef USE_GH_272_WORKAROUND #ifdef _DEBUG //#define FORCE_GH_272_WORKAROUND #endif /* Print to console, if GetMainThreadId is forced to CreateToolhelp32Snapshot */ #ifdef _DEBUG #define FORCE_GETMAINTHREAD_PRINTF #else #undef FORCE_GETMAINTHREAD_PRINTF #endif
421
1,988
<filename>src/cli/cipher.cpp /* * (C) 2015,2017 <NAME> (Kullo GmbH) * (C) 2020 <NAME> * * Botan is released under the Simplified BSD License (see license.txt) */ #include "cli.h" #if defined(BOTAN_HAS_CIPHER_MODES) #include <botan/cipher_mode.h> #include <botan/hex.h> #include <sstream> #if defined(BOTAN_HAS_AEAD_MODES) #include <botan/aead.h> #endif namespace Botan_CLI { class Cipher final : public Command { public: Cipher() : Command("cipher --cipher=AES-256/GCM --decrypt --key= --nonce= --ad= --buf-size=4096 input-file") {} std::string group() const override { return "crypto"; } std::string description() const override { return "Encrypt or decrypt with a symmetric cipher"; } void go() override { const std::string cipher_algo = get_arg_or("cipher", ""); const std::string key_hex = get_arg("key"); const std::string nonce_hex = get_arg("nonce"); const std::string ad_hex = get_arg_or("ad", ""); const std::string input_file = get_arg_or("input-file", "-"); const size_t buf_size = get_arg_sz("buf-size"); const Botan::SymmetricKey key(key_hex); const Botan::InitializationVector nonce(nonce_hex); const std::vector<uint8_t> ad = Botan::hex_decode(ad_hex); auto direction = flag_set("decrypt") ? Botan::Cipher_Dir::DECRYPTION : Botan::Cipher_Dir::ENCRYPTION; auto cipher = Botan::Cipher_Mode::create(cipher_algo, direction); if(!cipher) throw CLI_Error_Unsupported("Cipher algorithm '" + cipher_algo + "' not available"); // Set key cipher->set_key(key); // Set associated data if(!ad.empty()) { #if defined(BOTAN_HAS_AEAD_MODES) if(Botan::AEAD_Mode* aead = dynamic_cast<Botan::AEAD_Mode*>(cipher.get())) { aead->set_ad(ad); } else #endif { throw CLI_Usage_Error("Cannot specify associated data with non-AEAD mode"); } } // Set nonce cipher->start(nonce.bits_of()); const std::vector<uint8_t> input = this->slurp_file(input_file, buf_size); Botan::secure_vector<uint8_t> buf(input.begin(), input.end()); cipher->finish(buf); write_output(buf); } }; BOTAN_REGISTER_COMMAND("cipher", Cipher); } #endif
1,183
892
<reponame>github/advisory-database { "schema_version": "1.2.0", "id": "GHSA-jhjp-3hp8-fjch", "modified": "2022-05-13T01:31:50Z", "published": "2022-05-13T01:31:50Z", "aliases": [ "CVE-2018-7603" ], "details": "In Drupal's 3rd party module search auto complete prior to versions 7.x-4.8 there is a Cross Site Scripting vulnerability. This Search Autocomplete module enables you to autocomplete textfield using data from your website (nodes, comments, etc.). The module doesn't sufficiently filter user-entered text among the autocompletion items leading to a Cross Site Scripting (XSS) vulnerability. This vulnerability can be exploited by any user allowed to create one of the autocompletion item, for instance, nodes, users, comments.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2018-7603" }, { "type": "WEB", "url": "https://www.drupal.org/sa-contrib-2018-070" } ], "database_specific": { "cwe_ids": [ "CWE-79" ], "severity": "MODERATE", "github_reviewed": false } }
507
508
<gh_stars>100-1000 package com.github.instagram4j.instagram4j.models.direct.item; import com.fasterxml.jackson.annotation.JsonTypeName; import com.github.instagram4j.instagram4j.models.media.Link; import lombok.Data; @Data @JsonTypeName("link") public class ThreadLinkItem extends ThreadItem { private Link link; }
115
723
package com.github.zxh0.luago.state; import com.github.zxh0.luago.api.*; import com.github.zxh0.luago.binchunk.Prototype; import static com.github.zxh0.luago.api.ArithOp.*; import static com.github.zxh0.luago.api.LuaType.*; public class LuaStateImpl implements LuaState, LuaVM { private LuaStack stack = new LuaStack(); private Prototype proto; private int pc; public LuaStateImpl(Prototype proto) { this.proto = proto; } public LuaStateImpl() { proto = null; } /* basic stack manipulation */ @Override public int getTop() { return stack.top(); } @Override public int absIndex(int idx) { return stack.absIndex(idx); } @Override public boolean checkStack(int n) { return true; // TODO } @Override public void pop(int n) { for (int i = 0; i < n; i++) { stack.pop(); } } @Override public void copy(int fromIdx, int toIdx) { stack.set(toIdx, stack.get(fromIdx)); } @Override public void pushValue(int idx) { stack.push(stack.get(idx)); } @Override public void replace(int idx) { stack.set(idx, stack.pop()); } @Override public void insert(int idx) { rotate(idx, 1); } @Override public void remove(int idx) { rotate(idx, -1); pop(1); } @Override public void rotate(int idx, int n) { int t = stack.top() - 1; /* end of stack segment being rotated */ int p = stack.absIndex(idx) - 1; /* start of segment */ int m = n >= 0 ? t - n : p - n - 1; /* end of prefix */ stack.reverse(p, m); /* reverse the prefix with length 'n' */ stack.reverse(m + 1, t); /* reverse the suffix */ stack.reverse(p, t); /* reverse the entire segment */ } @Override public void setTop(int idx) { int newTop = stack.absIndex(idx); if (newTop < 0) { throw new RuntimeException("stack underflow!"); } int n = stack.top() - newTop; if (n > 0) { for (int i = 0; i < n; i++) { stack.pop(); } } else if (n < 0) { for (int i = 0; i > n; i--) { stack.push(null); } } } /* access functions (stack -> Go); */ @Override public String typeName(LuaType tp) { switch (tp) { case LUA_TNONE: return "no value"; case LUA_TNIL: return "nil"; case LUA_TBOOLEAN: return "boolean"; case LUA_TNUMBER: return "number"; case LUA_TSTRING: return "string"; case LUA_TTABLE: return "table"; case LUA_TFUNCTION: return "function"; case LUA_TTHREAD: return "thread"; default: return "userdata"; } } @Override public LuaType type(int idx) { return stack.isValid(idx) ? LuaValue.typeOf(stack.get(idx)) : LUA_TNONE; } @Override public boolean isNone(int idx) { return type(idx) == LUA_TNONE; } @Override public boolean isNil(int idx) { return type(idx) == LUA_TNIL; } @Override public boolean isNoneOrNil(int idx) { LuaType t = type(idx); return t == LUA_TNONE || t == LUA_TNIL; } @Override public boolean isBoolean(int idx) { return type(idx) == LUA_TBOOLEAN; } @Override public boolean isInteger(int idx) { return stack.get(idx) instanceof Long; } @Override public boolean isNumber(int idx) { return toNumberX(idx) != null; } @Override public boolean isString(int idx) { LuaType t = type(idx); return t == LUA_TSTRING || t == LUA_TNUMBER; } @Override public boolean isTable(int idx) { return type(idx) == LUA_TTABLE; } @Override public boolean isThread(int idx) { return type(idx) == LUA_TTHREAD; } @Override public boolean isFunction(int idx) { return type(idx) == LUA_TFUNCTION; } @Override public boolean toBoolean(int idx) { return LuaValue.toBoolean(stack.get(idx)); } @Override public long toInteger(int idx) { Long i = toIntegerX(idx); return i == null ? 0 : i; } @Override public Long toIntegerX(int idx) { Object val = stack.get(idx); return val instanceof Long ? (Long) val : null; } @Override public double toNumber(int idx) { Double n = toNumberX(idx); return n == null ? 0 : n; } @Override public Double toNumberX(int idx) { Object val = stack.get(idx); if (val instanceof Double) { return (Double) val; } else if (val instanceof Long) { return ((Long) val).doubleValue(); } else { return null; } } @Override public String toString(int idx) { Object val = stack.get(idx); if (val instanceof String) { return (String) val; } else if (val instanceof Long || val instanceof Double) { return val.toString(); } else { return null; } } /* push functions (Go -> stack); */ @Override public void pushNil() { stack.push(null); } @Override public void pushBoolean(boolean b) { stack.push(b); } @Override public void pushInteger(long n) { stack.push(n); } @Override public void pushNumber(double n) { stack.push(n); } @Override public void pushString(String s) { stack.push(s); } /* comparison and arithmetic functions */ @Override public void arith(ArithOp op) { Object b = stack.pop(); Object a = op != LUA_OPUNM && op != LUA_OPBNOT ? stack.pop() : b; Object result = Arithmetic.arith(a, b, op); if (result != null) { stack.push(result); } else { throw new RuntimeException("arithmetic error!"); } } @Override public boolean compare(int idx1, int idx2, CmpOp op) { if (!stack.isValid(idx1) || !stack.isValid(idx2)) { return false; } Object a = stack.get(idx1); Object b = stack.get(idx2); switch (op) { case LUA_OPEQ: return Comparison.eq(a, b); case LUA_OPLT: return Comparison.lt(a, b); case LUA_OPLE: return Comparison.le(a, b); default: throw new RuntimeException("invalid compare op!"); } } /* get functions (Lua -> stack) */ @Override public void newTable() { createTable(0, 0); } @Override public void createTable(int nArr, int nRec) { stack.push(new LuaTable(nArr, nRec)); } @Override public LuaType getTable(int idx) { Object t = stack.get(idx); Object k = stack.pop(); return getTable(t, k); } @Override public LuaType getField(int idx, String k) { Object t = stack.get(idx); return getTable(t, k); } @Override public LuaType getI(int idx, long i) { Object t = stack.get(idx); return getTable(t, i); } private LuaType getTable(Object t, Object k) { if (t instanceof LuaTable) { Object v = ((LuaTable) t).get(k); stack.push(v); return LuaValue.typeOf(v); } throw new RuntimeException("not a table!"); // todo } /* set functions (stack -> Lua) */ @Override public void setTable(int idx) { Object t = stack.get(idx); Object v = stack.pop(); Object k = stack.pop(); setTable(t, k, v); } @Override public void setField(int idx, String k) { Object t = stack.get(idx); Object v = stack.pop(); setTable(t, k, v); } @Override public void setI(int idx, long i) { Object t = stack.get(idx); Object v = stack.pop(); setTable(t, i, v); } private void setTable(Object t, Object k, Object v) { if (t instanceof LuaTable) { ((LuaTable) t).put(k, v); return; } throw new RuntimeException("not a table!"); } /* miscellaneous functions */ @Override public void len(int idx) { Object val = stack.get(idx); if (val instanceof String) { pushInteger(((String) val).length()); } else if (val instanceof LuaTable) { pushInteger(((LuaTable) val).length()); } else { throw new RuntimeException("length error!"); } } @Override public void concat(int n) { if (n == 0) { stack.push(""); } else if (n >= 2) { for (int i = 1; i < n; i++) { if (isString(-1) && isString(-2)) { String s2 = toString(-1); String s1 = toString(-2); pop(2); pushString(s1 + s2); continue; } throw new RuntimeException("concatenation error!"); } } // n == 1, do nothing } /* LuaVM */ @Override public int getPC() { return pc; } @Override public void addPC(int n) { pc += n; } @Override public int fetch() { return proto.getCode()[pc++]; } @Override public void getConst(int idx) { stack.push(proto.getConstants()[idx]); } @Override public void getRK(int rk) { if (rk > 0xFF) { // constant getConst(rk & 0xFF); } else { // register pushValue(rk + 1); } } }
4,785
3,428
{"id":"02451","group":"easy-ham-1","checksum":{"type":"MD5","value":"2d85b62408d45e219d34e55a1439f795"},"text":"From sentto-2242572-60173-1038799103-jm=<EMAIL> Mon Dec 2 11:25:56 2002\nReturn-Path: <<EMAIL>-2242572-60173-1038799103-yyyy=<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id E6E5316F6E\n\tfor <jm@localhost>; Mon, 2 Dec 2002 11:23:50 +0000 (GMT)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 02 Dec 2002 11:23:50 +0000 (GMT)\nReceived: from n2.grp.scd.yahoo.com (n2.grp.scd.yahoo.com [66.218.66.75])\n by dogma.slashnull.org (8.11.6/8.11.6) with SMTP id gB23Gt805746 for\n <<EMAIL>>; Mon, 2 Dec 2002 03:16:55 GMT\nX-Egroups-Return: sentto-2242572-60173-1038799103-yyyy=<EMAIL>\nReceived: from [192.168.3.11] by n2.grp.scd.yahoo.com with NNFMP;\n 02 Dec 2002 03:18:23 -0000\nX-Sender: <EMAIL>\nX-Apparently-To: <EMAIL>\nReceived: (EGP: mail-8_2_3_0); 2 Dec 2002 03:18:22 -0000\nReceived: (qmail 31199 invoked from network); 2 Dec 2002 03:18:22 -0000\nReceived: from unknown (192.168.3.11) by m7.grp.scd.yahoo.com with QMQP;\n 2 Dec 2002 03:18:22 -0000\nReceived: from unknown (HELO pimout2-ext.prodigy.net) (172.16.58.3) by\n mta1.grp.scd.yahoo.com with SMTP; 2 Dec 2002 03:18:22 -0000\nReceived: from trashotron.com (adsl-64-161-200-6.dsl.snfc21.pacbell.net\n [64.161.200.6]) by pimout2-ext.prodigy.net (8.12.3 da nor stuldap/8.12.3)\n with ESMTP id gB23ILrr471946 for <<EMAIL>>;\n Sun, 1 Dec 2002 22:18:21 -0500\nMessage-Id: <<EMAIL>>\nX-Mailer: Mozilla 4.79 (Macintosh; U; PPC)\nX-Accept-Language: en\nTo: z<EMAIL>\nReferences: <M<EMAIL>>\nFrom: <NAME> <<EMAIL>>\nMIME-Version: 1.0\nMailing-List: list <EMAIL>; contact\n <EMAIL>\nDelivered-To: mailing list <EMAIL>\nPrecedence: bulk\nList-Unsubscribe: <mailto:<EMAIL>>\nDate: Sun, 01 Dec 2002 19:14:15 -0800\nSubject: Re: [zzzzteana] Argh!\nReply-To: <EMAIL>\nContent-Type: text/plain; charset=US-ASCII\nContent-Transfer-Encoding: 7bit\n\nJay Lake wrote:\n \n>It's official, I'm a failure. Just finished listening to one of my high\n>school classmates being interviewed on NPR about her new film that she\n>wrote and directed, based on her recent successful book. Do I have a\n>film out? No. Do I have a successful book? No? Me, I spent nine months\n>this year on the dole. Becky was off in Hollywood.\n\n#1 Those of us who are envious of your success as a writer and artist\nmight find this a bit hard to understand. \n\n#2 Once, when forced to mix with a wife's associate's [French] husband\nwho spent most of his time blowing his horn about how he had wined and\ndined and hung out with the famous and wonderful, I became\nprogressively more and more Jethro-like until I was using phrases like\n\"Heehaw y'all -- you done talked to him!?\" My counterpart never\nnoticed my evolutionary decline, even as hair sprouted from my\nknuckles, my forehead contracted, my eyebrows merged and I started\ngrunting. Fortunately, my wife intervened and I was prevented from\ndoing my Moonwatcher imitation with the chicken bones left from\ndinner. Regression is a wonderful curative. \n\nRickk\nno truth to the rumour I scratched my armpit\n\nTo unsubscribe from this group, send an email to:\n<EMAIL>\n\n \n\nYour use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ \n\n\n\n"}
1,345
3,999
<reponame>discohead/jesse<gh_stars>1000+ from .candle_factory import fake_candle from .candle_factory import fake_range_candle from .candle_factory import fake_range_candle_from_range_prices from .order_factory import fake_order
80
1,444
package mage.sets; import mage.cards.ExpansionSet; import mage.constants.Rarity; import mage.constants.SetType; /** * https://scryfall.com/sets/f07 */ public class FridayNightMagic2007 extends ExpansionSet { private static final FridayNightMagic2007 instance = new FridayNightMagic2007(); public static FridayNightMagic2007 getInstance() { return instance; } private FridayNightMagic2007() { super("Friday Night Magic 2007", "F07", ExpansionSet.buildDate(2007, 1, 1), SetType.PROMOTIONAL); this.hasBoosters = false; this.hasBasicLands = false; cards.add(new SetCardInfo("Basking Rootwalla", 4, Rarity.RARE, mage.cards.b.BaskingRootwalla.class)); cards.add(new SetCardInfo("Cabal Coffers", 10, Rarity.RARE, mage.cards.c.CabalCoffers.class)); cards.add(new SetCardInfo("Deep Analysis", 2, Rarity.RARE, mage.cards.d.DeepAnalysis.class)); cards.add(new SetCardInfo("Engineered Plague", 7, Rarity.RARE, mage.cards.e.EngineeredPlague.class)); cards.add(new SetCardInfo("Firebolt", 1, Rarity.RARE, mage.cards.f.Firebolt.class)); cards.add(new SetCardInfo("Force Spike", 12, Rarity.RARE, mage.cards.f.ForceSpike.class)); cards.add(new SetCardInfo("Gerrard's Verdict", 3, Rarity.RARE, mage.cards.g.GerrardsVerdict.class)); cards.add(new SetCardInfo("Goblin Legionnaire", 6, Rarity.RARE, mage.cards.g.GoblinLegionnaire.class)); cards.add(new SetCardInfo("Goblin Ringleader", 8, Rarity.RARE, mage.cards.g.GoblinRingleader.class)); cards.add(new SetCardInfo("Roar of the Wurm", 11, Rarity.RARE, mage.cards.r.RoarOfTheWurm.class)); cards.add(new SetCardInfo("Wing Shards", 9, Rarity.RARE, mage.cards.w.WingShards.class)); cards.add(new SetCardInfo("Wonder", 5, Rarity.RARE, mage.cards.w.Wonder.class)); } }
709
7,482
<reponame>rockonedege/rt-thread /* $NetBSD: uaudioreg.h,v 1.15.38.1 2012/06/02 11:09:29 mrg Exp $ */ /* * Copyright (c) 1999 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by <NAME> (<EMAIL>) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <rtdef.h> typedef uint8_t uByte; typedef uint16_t uWord; #define UPACKED __attribute__ ((packed)) #define UAUDIO_VERSION 0x100 #define USB_SUBCLASS_AUDIOCONTROL 1 #define USB_SUBCLASS_AUDIOSTREAMING 2 #define USB_SUBCLASS_AUDIOMIDISTREAM 3 #define UDESC_CS_CONFIG 0x22 #define UDESC_CS_STRING 0x23 #define UDESC_CS_INTERFACE 0x24 #define UDESC_CS_ENDPOINT 0x25 #define UDESCSUB_AC_HEADER 1 #define UDESCSUB_AC_INPUT 2 #define UDESCSUB_AC_OUTPUT 3 #define UDESCSUB_AC_MIXER 4 #define UDESCSUB_AC_SELECTOR 5 #define UDESCSUB_AC_FEATURE 6 #define UDESCSUB_AC_PROCESSING 7 #define UDESCSUB_AC_EXTENSION 8 #ifndef AUFMT_MAX_FREQUENCIES #define AUFMT_MAX_FREQUENCIES 1 #endif /* The first fields are identical to usb_endpoint_descriptor_t */ typedef struct { uByte bLength; uByte bDescriptorType; uByte bEndpointAddress; uByte bmAttributes; uWord wMaxPacketSize; uByte bInterval; /* * The following two entries are only used by the Audio Class. * And according to the specs the Audio Class is the only one * allowed to extend the endpoint descriptor. * Who knows what goes on in the minds of the people in the USB * standardization? :-( */ uByte bRefresh; uByte bSynchAddress; } UPACKED usb_endpoint_descriptor_audio_t; /* generic, for iteration */ typedef struct { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; } UPACKED uaudio_cs_descriptor_t; struct usb_audio_control_descriptor { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uWord bcdADC; uWord wTotalLength; uByte bInCollection; uByte baInterfaceNr[1]; } UPACKED; struct usb_audio_streaming_interface_descriptor { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bTerminalLink; uByte bDelay; uWord wFormatTag; } UPACKED; struct usb_audio_streaming_endpoint_descriptor { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bmAttributes; #define UA_SED_FREQ_CONTROL 0x01 #define UA_SED_PITCH_CONTROL 0x02 #define UA_SED_MAXPACKETSONLY 0x80 uByte bLockDelayUnits; uWord wLockDelay; } UPACKED; struct usb_audio_streaming_type1_descriptor { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bFormatType; uByte bNrChannels; uByte bSubFrameSize; uByte bBitResolution; uByte bSamFreqType; #define UA_SAMP_CONTNUOUS 0 uByte tSamFreq[3*AUFMT_MAX_FREQUENCIES]; #define UA_GETSAMP(p, n) ((p)->tSamFreq[(n)*3+0] | ((p)->tSamFreq[(n)*3+1] << 8) | ((p)->tSamFreq[(n)*3+2] << 16)) #define UA_SAMP_LO(p) UA_GETSAMP(p, 0) #define UA_SAMP_HI(p) UA_GETSAMP(p, 1) } UPACKED; struct usb_audio_cluster { uByte bNrChannels; uWord wChannelConfig; #define UA_CHANNEL_LEFT 0x0001 #define UA_CHANNEL_RIGHT 0x0002 #define UA_CHANNEL_CENTER 0x0004 #define UA_CHANNEL_LFE 0x0008 #define UA_CHANNEL_L_SURROUND 0x0010 #define UA_CHANNEL_R_SURROUND 0x0020 #define UA_CHANNEL_L_CENTER 0x0040 #define UA_CHANNEL_R_CENTER 0x0080 #define UA_CHANNEL_SURROUND 0x0100 #define UA_CHANNEL_L_SIDE 0x0200 #define UA_CHANNEL_R_SIDE 0x0400 #define UA_CHANNEL_TOP 0x0800 uByte iChannelNames; } UPACKED; /* Shared by all units and terminals */ struct usb_audio_unit { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bUnitId; }; /* UDESCSUB_AC_INPUT */ struct usb_audio_input_terminal { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bTerminalId; uWord wTerminalType; uByte bAssocTerminal; uByte bNrChannels; uWord wChannelConfig; uByte iChannelNames; uByte iTerminal; } UPACKED; /* UDESCSUB_AC_OUTPUT */ struct usb_audio_output_terminal { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bTerminalId; uWord wTerminalType; uByte bAssocTerminal; uByte bSourceId; uByte iTerminal; } UPACKED; /* UDESCSUB_AC_MIXER */ struct usb_audio_mixer_unit { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bUnitId; uByte bNrInPins; uByte baSourceId[255]; /* [bNrInPins] */ /* struct usb_audio_mixer_unit_1 */ } UPACKED; struct usb_audio_mixer_unit_1 { uByte bNrChannels; uWord wChannelConfig; uByte iChannelNames; uByte bmControls[255]; /* [bNrChannels] */ /*uByte iMixer;*/ } UPACKED; /* UDESCSUB_AC_SELECTOR */ struct usb_audio_selector_unit { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bUnitId; uByte bNrInPins; uByte baSourceId[255]; /* [bNrInPins] */ /* uByte iSelector; */ } UPACKED; /* UDESCSUB_AC_FEATURE */ struct usb_audio_feature_unit { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bUnitId; uByte bSourceId; uByte bControlSize; uByte bmaControls[2]; /* size for more than enough */ /* uByte iFeature; */ } UPACKED; /* UDESCSUB_AC_PROCESSING */ struct usb_audio_processing_unit { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bUnitId; uWord wProcessType; uByte bNrInPins; uByte baSourceId[255]; /* [bNrInPins] */ /* struct usb_audio_processing_unit_1 */ } UPACKED; struct usb_audio_processing_unit_1{ uByte bNrChannels; uWord wChannelConfig; uByte iChannelNames; uByte bControlSize; uByte bmControls[255]; /* [bControlSize] */ #define UA_PROC_ENABLE_MASK 1 } UPACKED; struct usb_audio_processing_unit_updown { uByte iProcessing; uByte bNrModes; uWord waModes[255]; /* [bNrModes] */ } UPACKED; /* UDESCSUB_AC_EXTENSION */ struct usb_audio_extension_unit { uByte bLength; uByte bDescriptorType; uByte bDescriptorSubtype; uByte bUnitId; uWord wExtensionCode; uByte bNrInPins; uByte baSourceId[255]; /* [bNrInPins] */ /* struct usb_audio_extension_unit_1 */ } UPACKED; struct usb_audio_extension_unit_1 { uByte bNrChannels; uWord wChannelConfig; uByte iChannelNames; uByte bControlSize; uByte bmControls[255]; /* [bControlSize] */ #define UA_EXT_ENABLE_MASK 1 #define UA_EXT_ENABLE 1 /*uByte iExtension;*/ } UPACKED; /* USB terminal types */ #define UAT_UNDEFINED 0x0100 #define UAT_STREAM 0x0101 #define UAT_VENDOR 0x01ff /* input terminal types */ #define UATI_UNDEFINED 0x0200 #define UATI_MICROPHONE 0x0201 #define UATI_DESKMICROPHONE 0x0202 #define UATI_PERSONALMICROPHONE 0x0203 #define UATI_OMNIMICROPHONE 0x0204 #define UATI_MICROPHONEARRAY 0x0205 #define UATI_PROCMICROPHONEARR 0x0206 /* output terminal types */ #define UATO_UNDEFINED 0x0300 #define UATO_SPEAKER 0x0301 #define UATO_HEADPHONES 0x0302 #define UATO_DISPLAYAUDIO 0x0303 #define UATO_DESKTOPSPEAKER 0x0304 #define UATO_ROOMSPEAKER 0x0305 #define UATO_COMMSPEAKER 0x0306 #define UATO_SUBWOOFER 0x0307 /* bidir terminal types */ #define UATB_UNDEFINED 0x0400 #define UATB_HANDSET 0x0401 #define UATB_HEADSET 0x0402 #define UATB_SPEAKERPHONE 0x0403 #define UATB_SPEAKERPHONEESUP 0x0404 #define UATB_SPEAKERPHONEECANC 0x0405 /* telephony terminal types */ #define UATT_UNDEFINED 0x0500 #define UATT_PHONELINE 0x0501 #define UATT_TELEPHONE 0x0502 #define UATT_DOWNLINEPHONE 0x0503 /* external terminal types */ #define UATE_UNDEFINED 0x0600 #define UATE_ANALOGCONN 0x0601 #define UATE_DIGITALAUIFC 0x0602 #define UATE_LINECONN 0x0603 #define UATE_LEGACYCONN 0x0604 #define UATE_SPDIF 0x0605 #define UATE_1394DA 0x0606 #define UATE_1394DV 0x0607 /* embedded function terminal types */ #define UATF_UNDEFINED 0x0700 #define UATF_CALIBNOISE 0x0701 #define UATF_EQUNOISE 0x0702 #define UATF_CDPLAYER 0x0703 #define UATF_DAT 0x0704 #define UATF_DCC 0x0705 #define UATF_MINIDISK 0x0706 #define UATF_ANALOGTAPE 0x0707 #define UATF_PHONOGRAPH 0x0708 #define UATF_VCRAUDIO 0x0709 #define UATF_VIDEODISCAUDIO 0x070a #define UATF_DVDAUDIO 0x070b #define UATF_TVTUNERAUDIO 0x070c #define UATF_SATELLITE 0x070d #define UATF_CABLETUNER 0x070e #define UATF_DSS 0x070f #define UATF_RADIORECV 0x0710 #define UATF_RADIOXMIT 0x0711 #define UATF_MULTITRACK 0x0712 #define UATF_SYNTHESIZER 0x0713 #define SET_CUR 0x01 #define GET_CUR 0x81 #define SET_MIN 0x02 #define GET_MIN 0x82 #define SET_MAX 0x03 #define GET_MAX 0x83 #define SET_RES 0x04 #define GET_RES 0x84 #define SET_MEM 0x05 #define GET_MEM 0x85 #define GET_STAT 0xff #define MUTE_CONTROL 0x01 #define VOLUME_CONTROL 0x02 #define BASS_CONTROL 0x03 #define MID_CONTROL 0x04 #define TREBLE_CONTROL 0x05 #define GRAPHIC_EQUALIZER_CONTROL 0x06 #define AGC_CONTROL 0x07 #define DELAY_CONTROL 0x08 #define BASS_BOOST_CONTROL 0x09 #define LOUDNESS_CONTROL 0x0a #define FU_MASK(u) (1 << ((u)-1)) #define MASTER_CHAN 0 #define AS_GENERAL 1 #define FORMAT_TYPE 2 #define FORMAT_SPECIFIC 3 #define UA_FMT_PCM 1 #define UA_FMT_PCM8 2 #define UA_FMT_IEEE_FLOAT 3 #define UA_FMT_ALAW 4 #define UA_FMT_MULAW 5 #define UA_FMT_MPEG 0x1001 #define UA_FMT_AC3 0x1002 #define SAMPLING_FREQ_CONTROL 0x01 #define PITCH_CONTROL 0x02 #define FORMAT_TYPE_UNDEFINED 0 #define FORMAT_TYPE_I 1 #define FORMAT_TYPE_II 2 #define FORMAT_TYPE_III 3 #define UA_PROC_MASK(n) (1<< ((n)-1)) #define PROCESS_UNDEFINED 0 #define XX_ENABLE_CONTROL 1 #define UPDOWNMIX_PROCESS 1 #define UD_ENABLE_CONTROL 1 #define UD_MODE_SELECT_CONTROL 2 #define DOLBY_PROLOGIC_PROCESS 2 #define DP_ENABLE_CONTROL 1 #define DP_MODE_SELECT_CONTROL 2 #define P3D_STEREO_EXTENDER_PROCESS 3 #define P3D_ENABLE_CONTROL 1 #define P3D_SPACIOUSNESS_CONTROL 2 #define REVERBATION_PROCESS 4 #define RV_ENABLE_CONTROL 1 #define RV_LEVEL_CONTROL 2 #define RV_TIME_CONTROL 3 #define RV_FEEDBACK_CONTROL 4 #define CHORUS_PROCESS 5 #define CH_ENABLE_CONTROL 1 #define CH_LEVEL_CONTROL 2 #define CH_RATE_CONTROL 3 #define CH_DEPTH_CONTROL 4 #define DYN_RANGE_COMP_PROCESS 6 #define DR_ENABLE_CONTROL 1 #define DR_COMPRESSION_RATE_CONTROL 2 #define DR_MAXAMPL_CONTROL 3 #define DR_THRESHOLD_CONTROL 4 #define DR_ATTACK_TIME_CONTROL 5 #define DR_RELEASE_TIME_CONTROL 6
6,278
1,132
<gh_stars>1000+ #include "gb-include.h" #include <errno.h> #include <sys/types.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> // . we should not read in more than 1M from input file // . if g_conf.m_httpMaxReadSize is ever bigger than 1M, this should be inc'd #define MAX_READ_SIZE (20*1024*1024) // the various content types #define CT_UNKNOWN 0 #define CT_HTML 1 #define CT_TEXT 2 #define CT_XML 3 #define CT_PDF 4 #define CT_DOC 5 #define CT_XLS 6 #define CT_PPT 7 #define CT_PS 8 // . declare useful subroutines // . "buf" is the mime + content, the whole HTTP reply gigabot received // . "mime" is just the mime of the HTTP reply, the top portion of "buf" int32_t getMimeLen ( char *buf , int32_t bufLen ) ; char getContentType ( char *mime , int32_t mimeLen ) ; int filterContent ( char *buf , int32_t bufLen , int32_t mimeLen , char ctype , int32_t id ) ; // . returns -1 on error, 0 on success // . reads HTTP reply from filename given as argument, filters it, // and then writes it to stdout // . originally, we read from stdin, but popen was causing problems when called // from a thread on linux 2.4.17 with the old linux threads int main ( int argc , char *argv[] ) { // should have one and only 1 arg (excluding filename) if ( argc != 2 ) { fprintf(stderr,"gbfilter: usage: gbfilter <inputfilename>\n"); return -1; } // . read HTTP reply in from file, gigablast will give it to us there // . this should be the HTTP mime followed by the content char *buf = (char *)malloc ( MAX_READ_SIZE ); if ( ! buf ) { fprintf(stderr,"gbfilter:malloc:%s: %s: %s\n", argv[1],strerror(errno)); return -1; } // first and only arg is the input file to read from int fd = open ( argv[1] , O_RDONLY ); if ( fd < 0 ) { fprintf(stderr,"gbfilter:open: %s: %s\n", argv[1],strerror(errno)); free ( buf ); return -1; } int n = read ( fd , buf , MAX_READ_SIZE ); close ( fd ); // return -1 on read error if ( n < 0 ) { fprintf(stderr,"gbfilter:fread: %s\n",strerror(errno)); free ( buf ); return -1; } // warn if the doc was bigger than expected if ( n >= MAX_READ_SIZE ) fprintf(stderr,"gbfilter: WARNING: MAX_READ_SIZE " "needs boost\n"); //sleep(45); //srand(time(NULL)); //int32_t i = rand() % 30; //fprintf(stderr,"sleep(%"INT32")\n",i); //sleep(i); // if nothing came in then nothing goes out, we're done if ( n == 0 ) { free ( buf ) ; return 0; } // get the end of the mime of this HTTP reply int32_t mimeLen = getMimeLen ( buf , n ); // if it is -1, no mime boundary was found, so return an error if ( mimeLen < 0 ) { fprintf(stderr,"gbfilter: no mime boundary\n"); free ( buf ); return -1; } // . get the id from the input filename // . use that for out tmp files as well so parent caller can remove // our cruft if we core int32_t id ; char *p = argv[1]; // get id in the file while ( *p && ! isdigit(*p) ) p++; id = atol ( p ); // ... begin filter logic here ... // get the content type (the various types are #define'd above) char ctype = getContentType ( buf , mimeLen ); bool filter = false; if ( ctype == CT_PDF ) filter = true ; if ( ctype == CT_DOC ) filter = true ; if ( ctype == CT_XLS ) filter = true ; if ( ctype == CT_PPT ) filter = true ; if ( ctype == CT_PS ) filter = true ; if ( filter ) { int status = filterContent ( buf, n, mimeLen, ctype, id ); free ( buf ); return status; } // ... end filter logic here ... // if not filtered, write the input to stdout unaltered // no! make it 0 bytes! //int32_t w = fwrite ( buf , 1 , n , stdout ); //if ( w == n ) { free ( buf ) ; return 0; } free ( buf ); return 0; // note any errors fprintf(stderr,"gbfilter: fwrite: %s\n",strerror(errno)); free ( buf ); return -1; } // returns -1 if no boundary found int32_t getMimeLen ( char *buf , int32_t bufLen ) { // size of the boundary int32_t bsize = 0; // find the boundary int32_t i; for ( i = 0 ; i < bufLen ; i++ ) { // continue until we hit a \r or \n if ( buf[i] != '\r' && buf[i] != '\n' ) continue; // boundary check if ( i + 1 >= bufLen ) continue; // prepare for a smaller mime size bsize = 2; // \r\r if ( buf[i ] == '\r' && buf[i+1] == '\r' ) break; // \n\n if ( buf[i ] == '\n' && buf[i+1] == '\n' ) break; // boundary check if ( i + 3 >= bufLen ) continue; // prepare for a larger mime size bsize = 4; // \r\n\r\n if ( buf[i ] == '\r' && buf[i+1] == '\n' && buf[i+2] == '\r' && buf[i+3] == '\n' ) break; // \n\r\n\r if ( buf[i ] == '\n' && buf[i+1] == '\r' && buf[i+2] == '\n' && buf[i+3] == '\r' ) break; } // return false if could not find the end of the MIME if ( i == bufLen ) return -1; return i + bsize; } // get content-type char getContentType ( char *mime , int32_t mimeLen ) { // temp null terminate so we can call strstr char c = mime [ mimeLen ]; mime [ mimeLen ] = '\0'; // find "content-type:" field in mime char *s = strstr ( mime , "Content-Type:" ); if ( ! s ) s = strstr ( mime , "content-type:" ); if ( ! s ) s = strstr ( mime , "Content-type:" ); if ( ! s ) s = strstr ( mime , "CONTENT-TYPE:" ); // set back mime [ mimeLen ] = c; // if no content-type specified, it's unknown if ( ! s ) return CT_UNKNOWN ; // otherwise, is it application/pdf ? char *mimeEnd = mime + mimeLen; // skip to field data s += 13; // skip spaces while ( s < mimeEnd && (*s == ' ' || *s == '\t') ) s++; // if s passed end, we had no field data, assume not pdf if ( s >= mimeEnd ) return CT_UNKNOWN ; // is it pdf? if ( s + 15 < mimeEnd && strncasecmp ( s , "application/pdf" , 15 ) == 0 ) return CT_PDF; // it it word? if ( s + 18 < mimeEnd && strncasecmp ( s , "application/msword",18 ) == 0 ) return CT_DOC; // it it xls? if ( s + 24 < mimeEnd && strncasecmp ( s , "application/vnd.ms-excel",24 ) == 0 ) return CT_XLS; // it it ppt? if ( s + 24 < mimeEnd && strncasecmp ( s , "application/mspowerpoint",24 ) == 0 ) return CT_PPT; // it it ps? if ( s + 22 < mimeEnd && strncasecmp ( s , "application/postscript",22 ) == 0 ) return CT_PS; // otherwise assume unknown even though may be text/html, etc. return CT_UNKNOWN; } int filterContent ( char *buf , int32_t n , int32_t mimeLen , char ctype , int32_t id) { // write mime to stdout unaltered int w = fwrite ( buf , 1 , mimeLen , stdout ); if ( w != mimeLen ) { // note any errors fprintf(stderr,"gbfilter: fwrite: %s\n",strerror(errno)); return -1; } // flush it so it comes first, before filtered content fflush ( stdout ); // this is set on the call from gigablast server char *wdir = getenv ("HOME" ); // save the content to a file so pdftohtml,etc. can work with it char in[64]; sprintf ( in , "%s/content.%"INT32"", wdir , id ); // (int32_t)getpid() ); //fprintf(stderr,"in=%s\n",in); int fd = open ( in , O_CREAT | O_RDWR , S_IRWXU | S_IRWXG ); if ( fd < 0 ) { fprintf(stderr,"gbfilter: open: %s\n",strerror(errno)); return -1; } int32_t b = n - mimeLen ; if ( write ( fd , buf + mimeLen , b ) != b ) { close ( fd ); fprintf(stderr,"gbfilter: write: %s\n",strerror(errno)); unlink ( in ); return -1; } close(fd); // . open a pipe to pdf2html program // . the output will go to stdout char cmd[128]; // different commands to filter differt ctypes // -i : ignore images // -stdout: send output to stdout // -c : generate complex document // Google generates complex docs, but the large ones are horribly slow // in the browser, but docs with 2 cols don't display right w/o -c. // damn, -stdout doesn't work when -c is specified. // These ulimit sizes are max virtual memory in kilobytes. let's // keep them to 25 Megabytes if ( ctype == CT_PDF ) sprintf ( cmd , "ulimit -v 25000 -t 30 ; nice -n 19 %s/pdftohtml -q -i -noframes -stdout %s", wdir , in ); else if ( ctype == CT_DOC ) sprintf ( cmd , "ulimit -v 25000 -t 30 ; nice -n 19 %s/antiword %s" , wdir , in ); else if ( ctype == CT_XLS ) sprintf ( cmd , "ulimit -v 25000 -t 30 ; nice -n 19 %s/xlhtml %s" , wdir , in ); else if ( ctype == CT_PPT ) sprintf ( cmd , "ulimit -v 25000 -t 30 ; nice -n 19 %s/ppthtml %s" , wdir , in ); else if ( ctype == CT_PS ) sprintf ( cmd , "ulimit -v 25000 -t 30; nice -n 19 %s/pstotext %s" , wdir , in ); // don't use too much memory, i think xhtml uses so much that it // swaps out all the gb processes? //struct rlimit lim; //lim.rlim_cur = lim.rlim_max = 24 * 1024 * 1024 ; //if ( setrlimit ( RLIMIT_AS , &lim ) ) // fprintf (stderr,"gbfilter:setrlimit: %s", strerror(errno) ); FILE *pd = popen ( cmd , "w" ); if ( ! pd ) { fprintf(stderr,"gbfilter: popen: %s\n",strerror(errno)); unlink ( in ); return -1; } // success pclose(pd); fflush ( stdout ); // clean up the binary file from disk if ( unlink ( in ) == 0 ) return 0; fprintf(stderr,"gbfilter: unlink (%s): %s\n",in,strerror(errno)); // ignore it, since it was not a processing error per se errno = 0; return 0; }
3,714
2,793
#include "ruby/ruby.h" #include "ruby/encoding.h" static VALUE enc_str_buf_cat(VALUE str, VALUE str2) { return rb_enc_str_buf_cat(str, RSTRING_PTR(str2), RSTRING_LEN(str2), rb_enc_get(str2)); } void Init_string_enc_str_buf_cat(VALUE klass) { rb_define_method(klass, "enc_str_buf_cat", enc_str_buf_cat, 1); }
152
577
<gh_stars>100-1000 package org.fluentlenium.example.spring.page; import org.fluentlenium.core.FluentPage; import org.fluentlenium.core.annotation.PageUrl; import org.fluentlenium.core.domain.FluentWebElement; import org.openqa.selenium.support.FindBy; import static org.fluentlenium.assertj.FluentLeniumAssertions.assertThat; @PageUrl("/") public class MainPage extends FluentPage { @FindBy(linkText = "Selenium") private FluentWebElement seleniumLink; @FindBy(className = "whats-fluentlenium") private FluentWebElement content; public MainPage verifyIfIsLoaded() { assertThat(content).isPresent(); return this; } public void clickOnSeleniumLink() { seleniumLink.click(); } }
274
834
from setuptools import setup setup( name='swapy', version='0.2.2', description='Easy and modular web development', author='<NAME>', author_email='<EMAIL>', url='https://github.com/danieldaeschle/swapy', packages=['swapy'], install_requires=['werkzeug', 'jinja2'], license='MIT' )
130
3,200
<gh_stars>1000+ # Copyright 2020 Huawei Technologies Co., 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. # ============================================================================ import numpy as np import mindspore.context as context import mindspore.nn as nn from mindspore import Tensor from mindspore.ops import operations as P context.set_context(mode=context.GRAPH_MODE, device_target="Ascend") class EditDistance(nn.Cell): def __init__(self, hypothesis_shape, truth_shape, normalize=True): super(EditDistance, self).__init__() self.edit_distance = P.EditDistance(normalize) self.hypothesis_shape = hypothesis_shape self.truth_shape = truth_shape def construct(self, hypothesis_indices, hypothesis_values, truth_indices, truth_values): return self.edit_distance(hypothesis_indices, hypothesis_values, self.hypothesis_shape, truth_indices, truth_values, self.truth_shape) def test_edit_distance(): h1, h2, h3 = np.array([[0, 0, 0], [1, 0, 1], [1, 1, 1]]), np.array([1, 2, 3]), np.array([2, 2, 2]) t1, t2, t3 = np.array([[0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1]]), np.array([1, 2, 3, 1]), np.array([2, 2, 2]) hypothesis_indices = Tensor(h1.astype(np.int64)) hypothesis_values = Tensor(h2.astype(np.int64)) hypothesis_shape = Tensor(h3.astype(np.int64)) truth_indices = Tensor(t1.astype(np.int64)) truth_values = Tensor(t2.astype(np.int64)) truth_shape = Tensor(t3.astype(np.int64)) edit_distance = EditDistance(hypothesis_shape, truth_shape) out = edit_distance(hypothesis_indices, hypothesis_values, truth_indices, truth_values) print(out)
800
3,102
int *A1;
6
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/crostini/crostini_expired_container_warning_view.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/webui/chromeos/crostini_upgrader/crostini_upgrader_dialog.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/layout_provider.h" namespace { CrostiniExpiredContainerWarningView* g_crostini_expired_container_warning_view = nullptr; } // namespace void CrostiniExpiredContainerWarningView::Show( Profile* profile, std::vector<base::OnceClosure> callbacks) { if (g_crostini_expired_container_warning_view) { for (auto&& callback : callbacks) { g_crostini_expired_container_warning_view->callbacks_.push_back( std::move(callback)); } } else { g_crostini_expired_container_warning_view = new CrostiniExpiredContainerWarningView(profile, std::move(callbacks)); CreateDialogWidget(g_crostini_expired_container_warning_view, nullptr, nullptr); } // Always call Show to bring the dialog to the front of the screen. g_crostini_expired_container_warning_view->GetWidget()->Show(); } CrostiniExpiredContainerWarningView::CrostiniExpiredContainerWarningView( Profile* profile, std::vector<base::OnceClosure> callbacks) : profile_(profile), callbacks_(std::move(callbacks)), weak_ptr_factory_(this) { // Make the dialog modal to force the user to make a decision. SetModalType(ui::MODAL_TYPE_SYSTEM); SetTitle(IDS_CROSTINI_EXPIRED_CONTAINER_WARNING_TITLE); SetButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL); SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, l10n_util::GetStringUTF16( IDS_CROSTINI_EXPIRED_CONTAINER_WARNING_CONTINUE_BUTTON)); SetButtonLabel(ui::DIALOG_BUTTON_OK, l10n_util::GetStringUTF16( IDS_CROSTINI_EXPIRED_CONTAINER_WARNING_UPGRADE_BUTTON)); SetShowCloseButton(false); // Show upgrade dialog on accept, and pass in the callback. SetAcceptCallback(base::BindOnce( [](base::WeakPtr<CrostiniExpiredContainerWarningView> weak_this) { chromeos::CrostiniUpgraderDialog::Show( weak_this->profile_, base::BindOnce( [](std::vector<base::OnceClosure> callbacks) { for (auto&& callback : callbacks) { std::move(callback).Run(); } }, std::move(weak_this->callbacks_))); }, weak_ptr_factory_.GetWeakPtr())); // On cancel, call the callback directly. SetCancelCallback(base::BindOnce( [](base::WeakPtr<CrostiniExpiredContainerWarningView> weak_this) { for (auto&& callback : weak_this->callbacks_) { std::move(callback).Run(); } }, weak_ptr_factory_.GetWeakPtr())); set_fixed_width(ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_STANDALONE_BUBBLE_PREFERRED_WIDTH)); views::LayoutProvider* provider = views::LayoutProvider::Get(); SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, provider->GetInsetsMetric(views::InsetsMetric::INSETS_DIALOG), provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_VERTICAL))); const std::u16string message = l10n_util::GetStringUTF16(IDS_CROSTINI_EXPIRED_CONTAINER_WARNING_BODY); views::Label* message_label = new views::Label(message); message_label->SetMultiLine(true); message_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); AddChildView(message_label); } CrostiniExpiredContainerWarningView::~CrostiniExpiredContainerWarningView() { g_crostini_expired_container_warning_view = nullptr; } BEGIN_METADATA(CrostiniExpiredContainerWarningView, views::BubbleDialogDelegateView) END_METADATA
1,684
2,759
// Copyright (c) YugaByte, 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. // #include "yb/util/async_task_util.h" #include <glog/logging.h> namespace yb { // AsyncTaskTracker methods. Status AsyncTaskTracker::Start() { if (started_) { return STATUS(IllegalState, "Task has already started"); } started_ = true; return Status::OK(); } bool AsyncTaskTracker::Started() const { return started_; } void AsyncTaskTracker::Abort() { started_ = false; } // AsyncTaskThrottler methods. AsyncTaskThrottler::AsyncTaskThrottler() : outstanding_task_count_limit_(std::numeric_limits<int>::max()) { } AsyncTaskThrottler::AsyncTaskThrottler(uint64_t limit) : outstanding_task_count_limit_(limit) { } void AsyncTaskThrottler::RefreshLimit(uint64_t limit) { std::lock_guard<std::mutex> l(mutex_); outstanding_task_count_limit_ = limit; } bool AsyncTaskThrottler::Throttle() { std::lock_guard<std::mutex> l(mutex_); if (ShouldThrottle()) { return true; } AddOutstandingTask(); return false; } bool AsyncTaskThrottler::RemoveOutstandingTask() { std::lock_guard<std::mutex> l(mutex_); DCHECK_GT(current_outstanding_task_count_, 0); current_outstanding_task_count_--; return current_outstanding_task_count_ == 0; } bool AsyncTaskThrottler::ShouldThrottle() { return current_outstanding_task_count_ >= outstanding_task_count_limit_; } void AsyncTaskThrottler::AddOutstandingTask() { DCHECK_LT(current_outstanding_task_count_, outstanding_task_count_limit_); current_outstanding_task_count_++; } } // namespace yb
766
389
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2020 Adobe ~ ~ 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.adobe.cq.wcm.core.components.internal.models.v1.datalayer; import java.util.Calendar; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; import com.adobe.cq.wcm.core.components.models.datalayer.AssetData; import com.adobe.cq.wcm.core.components.models.datalayer.builder.DataLayerBuilder; import com.day.cq.dam.api.DamConstants; import org.apache.jackrabbit.JcrConstants; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ValueMap; import org.junit.jupiter.api.Test; import com.day.cq.dam.api.Asset; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AssetDataImplTest { @Test void testGetLastModifiedDate() { Asset asset = mock(Asset.class); when(asset.getLastModified()).thenReturn(0L); ValueMap valueMap = mock(ValueMap.class); when(asset.adaptTo(ValueMap.class)).thenReturn(valueMap); Calendar now = Calendar.getInstance(); when(valueMap.get(JcrConstants.JCR_CREATED, Calendar.class)).thenReturn(now); AssetData assetData = DataLayerBuilder.forAsset(asset).build(); assertEquals(now.getTime(), assetData.getLastModifiedDate()); } @Test void testGetSmartTags() { Asset asset = mock(Asset.class); Resource assetResource = mock(Resource.class); when(asset.adaptTo(Resource.class)).thenReturn(assetResource); // mock smart tags Resource predictedTagsResource = mock(Resource.class); List<Resource> children = new ArrayList<>(); for (int i=2; i>0; --i) { Resource tagResource = mock(Resource.class); ValueMap valueMap = mock(ValueMap.class); when(valueMap.get("name")).thenReturn("tag"+i); when(valueMap.get("confidence")).thenReturn(0.78); when(tagResource.adaptTo(ValueMap.class)).thenReturn(valueMap); children.add(tagResource); } when(assetResource.getChild(DamConstants.PREDICTED_TAGS)).thenReturn(predictedTagsResource); when(predictedTagsResource.getChildren()).thenReturn(children); Map<String, Double> expectedSmartTags = new HashMap<String, Double>(){{ put("tag1", 0.78); put("tag2", 0.78); }}; AssetData assetData = DataLayerBuilder.forAsset(asset).build(); assertEquals(expectedSmartTags, assetData.getSmartTags()); } }
1,177
348
{"nom":"Saint-Julien-du-Sault","circ":"3ème circonscription","dpt":"Yonne","inscrits":1601,"abs":879,"votants":722,"blancs":9,"nuls":70,"exp":643,"res":[{"nuance":"REM","nom":"<NAME>","voix":384},{"nuance":"FN","nom":"<NAME>","voix":259}]}
97
1,139
package com.journaldev.servlet.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.journaldev.servlet.dao.UserDAO; import com.journaldev.servlet.dao.UserDAOImpl; import com.journaldev.servlet.model.User; public class RegistrationController extends HttpServlet { private static final long serialVersionUID = -4006561145676424435L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String email = request.getParameter("email"); String password = request.getParameter("password"); String address = request.getParameter("address"); if ((name == null || "".equals(name)) || (email == null || "".equals(email)) || (password == null || "".equals(password)) || (address == null || "".equals(address))) { String error = "Mandatory Parameters Missing"; request.getSession().setAttribute("errorReg", error); response.sendRedirect("index.jsp#register"); } else { User user = new User(name, email, password, address); UserDAO userDAO = new UserDAOImpl(); int result = userDAO.createUser(user); if (result == 1) { request.getSession().removeAttribute("errorReg"); response.sendRedirect("success.jsp"); }else{ request.getSession().setAttribute("errorReg", "Internal Server Error, Please try again later."); response.sendRedirect("index.jsp#register"); } } } }
593
26,932
import java.security.AccessController; import java.security.PrivilegedExceptionAction; public class B implements PrivilegedExceptionAction { public B() { try { AccessController.doPrivileged(this); } catch (Exception e) { } } public Object run() { System.setSecurityManager(null); return new Object(); } }
134
2,151
<reponame>zipated/src // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wallpaper/wallpaper_controller.h" #include <cmath> #include <cstdlib> #include "ash/public/cpp/ash_switches.h" #include "ash/public/cpp/config.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/root_window_controller.h" #include "ash/session/session_controller.h" #include "ash/session/test_session_controller_client.h" #include "ash/shell.h" #include "ash/shell_test_api.h" #include "ash/test/ash_test_base.h" #include "ash/wallpaper/wallpaper_controller_observer.h" #include "ash/wallpaper/wallpaper_view.h" #include "ash/wallpaper/wallpaper_widget_controller.h" #include "ash/wm/window_state.h" #include "base/command_line.h" #include "base/files/scoped_temp_dir.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_current.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/task_scheduler/post_task.h" #include "base/task_scheduler/task_scheduler.h" #include "base/test/bind_test_util.h" #include "chromeos/chromeos_switches.h" #include "components/prefs/testing_pref_service.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/aura/window.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/test/layer_animator_test_controller.h" #include "ui/gfx/canvas.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/views/widget/widget.h" using session_manager::SessionState; namespace ash { namespace { // Containers IDs used for tests. constexpr int kWallpaperId = kShellWindowId_WallpaperContainer; constexpr int kLockScreenWallpaperId = kShellWindowId_LockScreenWallpaperContainer; constexpr char kDefaultSmallWallpaperName[] = "small.jpg"; constexpr char kDefaultLargeWallpaperName[] = "large.jpg"; constexpr char kGuestSmallWallpaperName[] = "guest_small.jpg"; constexpr char kGuestLargeWallpaperName[] = "guest_large.jpg"; constexpr char kChildSmallWallpaperName[] = "child_small.jpg"; constexpr char kChildLargeWallpaperName[] = "child_large.jpg"; // Colors used to distinguish between wallpapers with large and small // resolution. constexpr SkColor kLargeCustomWallpaperColor = SK_ColorDKGRAY; constexpr SkColor kSmallCustomWallpaperColor = SK_ColorLTGRAY; // A color that can be passed to |CreateImage|. Specifically chosen to not // conflict with any of the custom wallpaper colors. constexpr SkColor kWallpaperColor = SK_ColorMAGENTA; std::string GetDummyFileId(const AccountId& account_id) { return account_id.GetUserEmail() + "-hash"; } std::string GetDummyFileName(const AccountId& account_id) { return account_id.GetUserEmail() + "-file"; } constexpr char kUser1[] = "<EMAIL>"; const AccountId account_id_1 = AccountId::FromUserEmail(kUser1); const std::string wallpaper_files_id_1 = GetDummyFileId(account_id_1); const std::string file_name_1 = GetDummyFileName(account_id_1); constexpr char kUser2[] = "<EMAIL>"; const AccountId account_id_2 = AccountId::FromUserEmail(kUser2); const std::string wallpaper_files_id_2 = GetDummyFileId(account_id_2); const std::string file_name_2 = GetDummyFileName(account_id_2); const std::string kDummyUrl = "https://best_wallpaper/1"; const std::string kDummyUrl2 = "https://best_wallpaper/2"; const base::FilePath user_data_dir = base::FilePath(FILE_PATH_LITERAL("user_data")); const base::FilePath wallpapers_dir = base::FilePath(FILE_PATH_LITERAL("chrome_os_wallpapers")); const base::FilePath custom_wallpapers_dir = base::FilePath(FILE_PATH_LITERAL("chrome_os_custom_wallpapers")); // Creates an image of size |size|. gfx::ImageSkia CreateImage(int width, int height, SkColor color) { SkBitmap bitmap; bitmap.allocN32Pixels(width, height); bitmap.eraseColor(color); gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); return image; } // Returns number of child windows in a shell window container. int ChildCountForContainer(int container_id) { aura::Window* root = Shell::Get()->GetPrimaryRootWindow(); aura::Window* container = root->GetChildById(container_id); return static_cast<int>(container->children().size()); } // Steps a widget's layer animation until it is completed. Animations must be // enabled. void RunAnimationForWidget(views::Widget* widget) { // Animations must be enabled for stepping to work. ASSERT_NE(ui::ScopedAnimationDurationScaleMode::duration_scale_mode(), ui::ScopedAnimationDurationScaleMode::ZERO_DURATION); ui::Layer* layer = widget->GetLayer(); ui::LayerAnimatorTestController controller(layer->GetAnimator()); // Multiple steps are required to complete complex animations. // TODO(vollick): This should not be necessary. crbug.com/154017 while (controller.animator()->is_animating()) { controller.StartThreadedAnimationsIfNeeded(); base::TimeTicks step_time = controller.animator()->last_step_time(); layer->GetAnimator()->Step(step_time + base::TimeDelta::FromMilliseconds(1000)); } } // Writes a JPEG image of the specified size and color to |path|. Returns true // on success. bool WriteJPEGFile(const base::FilePath& path, int width, int height, SkColor color) { base::ScopedAllowBlockingForTesting allow_blocking; SkBitmap bitmap; bitmap.allocN32Pixels(width, height); bitmap.eraseColor(color); std::vector<unsigned char> output; if (!gfx::JPEGCodec::Encode(bitmap, 80 /*quality*/, &output)) { LOG(ERROR) << "Unable to encode " << width << "x" << height << " bitmap"; return false; } size_t bytes_written = base::WriteFile( path, reinterpret_cast<const char*>(&output[0]), output.size()); if (bytes_written != output.size()) { LOG(ERROR) << "Wrote " << bytes_written << " byte(s) instead of " << output.size() << " to " << path.value(); return false; } return true; } // Returns custom wallpaper path. Creates the directory if it doesn't exist. base::FilePath GetCustomWallpaperPath(const char* sub_dir, const std::string& wallpaper_files_id, const std::string& file_name) { base::ScopedAllowBlockingForTesting allow_blocking; base::FilePath wallpaper_path = WallpaperController::GetCustomWallpaperPath( sub_dir, wallpaper_files_id, file_name); if (!base::DirectoryExists(wallpaper_path.DirName())) base::CreateDirectory(wallpaper_path.DirName()); return wallpaper_path; } void WaitUntilCustomWallpapersDeleted(const AccountId& account_id) { const std::string wallpaper_file_id = GetDummyFileId(account_id); base::FilePath small_wallpaper_dir = WallpaperController::GetCustomWallpaperDir( WallpaperController::kSmallWallpaperSubDir) .Append(wallpaper_file_id); base::FilePath large_wallpaper_dir = WallpaperController::GetCustomWallpaperDir( WallpaperController::kLargeWallpaperSubDir) .Append(wallpaper_file_id); base::FilePath original_wallpaper_dir = WallpaperController::GetCustomWallpaperDir( WallpaperController::kOriginalWallpaperSubDir) .Append(wallpaper_file_id); while (base::PathExists(small_wallpaper_dir) || base::PathExists(large_wallpaper_dir) || base::PathExists(original_wallpaper_dir)) { } } void DeleteWallpaperDirectories() { base::DeleteFile(user_data_dir, true /*recursive=*/); base::DeleteFile(wallpapers_dir, true /*recursive=*/); base::DeleteFile(custom_wallpapers_dir, true /*recursive=*/); } // Monitors if any task is processed by the message loop. class TaskObserver : public base::MessageLoop::TaskObserver { public: TaskObserver() : processed_(false) {} ~TaskObserver() override = default; // MessageLoop::TaskObserver: void WillProcessTask(const base::PendingTask& pending_task) override {} void DidProcessTask(const base::PendingTask& pending_task) override { processed_ = true; } // Returns true if any task was processed. bool processed() const { return processed_; } private: bool processed_; DISALLOW_COPY_AND_ASSIGN(TaskObserver); }; // See content::RunAllTasksUntilIdle(). void RunAllTasksUntilIdle() { while (true) { TaskObserver task_observer; base::MessageLoopCurrent::Get()->AddTaskObserver(&task_observer); // May spin message loop. base::TaskScheduler::GetInstance()->FlushForTesting(); base::RunLoop().RunUntilIdle(); base::MessageLoopCurrent::Get()->RemoveTaskObserver(&task_observer); if (!task_observer.processed()) break; } } // A test implementation of the WallpaperObserver mojo interface. class TestWallpaperObserver : public mojom::WallpaperObserver { public: TestWallpaperObserver() = default; ~TestWallpaperObserver() override = default; // mojom::WallpaperObserver: void OnWallpaperChanged(uint32_t image_id) override {} void OnWallpaperColorsChanged( const std::vector<SkColor>& prominent_colors) override { ++wallpaper_colors_changed_count_; if (run_loop_) run_loop_->Quit(); } void OnWallpaperBlurChanged(bool blurred) override {} int wallpaper_colors_changed_count() const { return wallpaper_colors_changed_count_; } void set_run_loop(base::RunLoop* loop) { run_loop_ = loop; } private: base::RunLoop* run_loop_ = nullptr; int wallpaper_colors_changed_count_ = 0; DISALLOW_COPY_AND_ASSIGN(TestWallpaperObserver); }; class TestWallpaperControllerObserver : public WallpaperControllerObserver { public: TestWallpaperControllerObserver() = default; void OnWallpaperBlurChanged() override { ++wallpaper_blur_changed_count_; } void Reset() { wallpaper_blur_changed_count_ = 0; } int wallpaper_blur_changed_count_ = 0; }; } // namespace class WallpaperControllerTest : public AshTestBase { public: WallpaperControllerTest() : controller_(nullptr) {} ~WallpaperControllerTest() override = default; void SetUp() override { AshTestBase::SetUp(); // Ash shell initialization creates wallpaper. Reset it so we can manually // control wallpaper creation and animation in our tests. Shell::Get() ->GetPrimaryRootWindowController() ->wallpaper_widget_controller() ->ResetWidgetsForTesting(); controller_ = Shell::Get()->wallpaper_controller(); controller_->set_wallpaper_reload_no_delay_for_test(); controller_->InitializePathsForTesting(user_data_dir, wallpapers_dir, custom_wallpapers_dir); } void TearDown() override { base::PostTaskWithTraits(FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::Bind(&DeleteWallpaperDirectories)); AshTestBase::TearDown(); } WallpaperView* wallpaper_view() { WallpaperWidgetController* controller = Shell::Get() ->GetPrimaryRootWindowController() ->wallpaper_widget_controller(); EXPECT_TRUE(controller); EXPECT_TRUE(controller->GetAnimatingWidget()); return static_cast<WallpaperView*>( controller->GetAnimatingWidget()->GetContentsView()->child_at(0)); } protected: // Helper function that tests the wallpaper is always fitted to the native // display resolution when the layout is WALLPAPER_LAYOUT_CENTER. void WallpaperFitToNativeResolution(WallpaperView* view, float device_scale_factor, int image_width, int image_height, SkColor color) { gfx::Size size = view->bounds().size(); gfx::Canvas canvas(size, device_scale_factor, true); view->OnPaint(&canvas); SkBitmap bitmap = canvas.GetBitmap(); int bitmap_width = bitmap.width(); int bitmap_height = bitmap.height(); for (int i = 0; i < bitmap_width; i++) { for (int j = 0; j < bitmap_height; j++) { if (i >= (bitmap_width - image_width) / 2 && i < (bitmap_width + image_width) / 2 && j >= (bitmap_height - image_height) / 2 && j < (bitmap_height + image_height) / 2) { EXPECT_EQ(color, bitmap.getColor(i, j)); } else { EXPECT_EQ(SK_ColorBLACK, bitmap.getColor(i, j)); } } } } // Runs AnimatingWallpaperWidgetController's animation to completion. // TODO(bshe): Don't require tests to run animations; it's slow. void RunDesktopControllerAnimation() { WallpaperWidgetController* controller = Shell::Get() ->GetPrimaryRootWindowController() ->wallpaper_widget_controller(); ASSERT_TRUE(controller); ASSERT_TRUE(controller->GetAnimatingWidget()); ASSERT_NO_FATAL_FAILURE( RunAnimationForWidget(controller->GetAnimatingWidget())); } // Convenience function to ensure ShouldCalculateColors() returns true. void EnableShelfColoring() { const gfx::ImageSkia kImage = CreateImage(10, 10, kWallpaperColor); controller_->ShowWallpaperImage( kImage, CreateWallpaperInfo(WALLPAPER_LAYOUT_STRETCH), false /*preview_mode=*/); SetSessionState(SessionState::ACTIVE); EXPECT_TRUE(ShouldCalculateColors()); } // Convenience function to set the SessionState. void SetSessionState(SessionState session_state) { GetSessionControllerClient()->SetSessionState(session_state); } // Helper function to create a |WallpaperInfo| struct with dummy values // given the desired layout. WallpaperInfo CreateWallpaperInfo(WallpaperLayout layout) { return WallpaperInfo("", layout, DEFAULT, base::Time::Now().LocalMidnight()); } // Helper function to create a new |mojom::WallpaperUserInfoPtr| instance with // default values. In addition, clear the wallpaper count and the decoding // request list. May be called multiple times for the same |account_id|. mojom::WallpaperUserInfoPtr InitializeUser(const AccountId& account_id) { mojom::WallpaperUserInfoPtr wallpaper_user_info = mojom::WallpaperUserInfo::New(); wallpaper_user_info->account_id = account_id; wallpaper_user_info->type = user_manager::USER_TYPE_REGULAR; wallpaper_user_info->is_ephemeral = false; wallpaper_user_info->has_gaia_account = true; ClearWallpaperCount(); ClearDecodeFilePaths(); return wallpaper_user_info; } // Saves images with different resolution to corresponding paths and saves // wallpaper info to local state, so that subsequent calls of |ShowWallpaper| // can retrieve the images and info. void CreateAndSaveWallpapers(const AccountId& account_id) { std::string wallpaper_files_id = GetDummyFileId(account_id); std::string file_name = GetDummyFileName(account_id); base::FilePath small_wallpaper_path = GetCustomWallpaperPath(WallpaperController::kSmallWallpaperSubDir, wallpaper_files_id, file_name); base::FilePath large_wallpaper_path = GetCustomWallpaperPath(WallpaperController::kLargeWallpaperSubDir, wallpaper_files_id, file_name); // Saves the small/large resolution wallpapers to small/large custom // wallpaper paths. ASSERT_TRUE(WriteJPEGFile(small_wallpaper_path, kSmallWallpaperMaxWidth, kSmallWallpaperMaxHeight, kSmallCustomWallpaperColor)); ASSERT_TRUE(WriteJPEGFile(large_wallpaper_path, kLargeWallpaperMaxWidth, kLargeWallpaperMaxHeight, kLargeCustomWallpaperColor)); std::string relative_path = base::FilePath(wallpaper_files_id).Append(file_name).value(); // Saves wallpaper info to local state for user. WallpaperInfo info = {relative_path, WALLPAPER_LAYOUT_CENTER_CROPPED, CUSTOMIZED, base::Time::Now().LocalMidnight()}; ASSERT_TRUE(controller_->SetUserWallpaperInfo(account_id, info, false /*is_ephemeral=*/)); } // Simulates setting a custom wallpaper by directly setting the wallpaper // info. void SimulateSettingCustomWallpaper(const AccountId& account_id) { ASSERT_TRUE(controller_->SetUserWallpaperInfo( account_id, WallpaperInfo("dummy_file_location", WALLPAPER_LAYOUT_CENTER, CUSTOMIZED, base::Time::Now().LocalMidnight()), false /*is_ephemeral=*/)); } // Initializes default wallpaper paths "*default_*file" and writes JPEG // wallpaper images to them. Only needs to be called (once) by tests that // want to test loading of default wallpapers. void CreateDefaultWallpapers() { base::ScopedAllowBlockingForTesting allow_blocking; wallpaper_dir_.reset(new base::ScopedTempDir); ASSERT_TRUE(wallpaper_dir_->CreateUniqueTempDir()); base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); const base::FilePath small_file = wallpaper_dir_->GetPath().Append( FILE_PATH_LITERAL(kDefaultSmallWallpaperName)); command_line->AppendSwitchASCII(chromeos::switches::kDefaultWallpaperSmall, small_file.value()); const base::FilePath large_file = wallpaper_dir_->GetPath().Append( FILE_PATH_LITERAL(kDefaultLargeWallpaperName)); command_line->AppendSwitchASCII(chromeos::switches::kDefaultWallpaperLarge, large_file.value()); const base::FilePath guest_small_file = wallpaper_dir_->GetPath().Append( FILE_PATH_LITERAL(kGuestSmallWallpaperName)); command_line->AppendSwitchASCII(chromeos::switches::kGuestWallpaperSmall, guest_small_file.value()); const base::FilePath guest_large_file = wallpaper_dir_->GetPath().Append( FILE_PATH_LITERAL(kGuestLargeWallpaperName)); command_line->AppendSwitchASCII(chromeos::switches::kGuestWallpaperLarge, guest_large_file.value()); const base::FilePath child_small_file = wallpaper_dir_->GetPath().Append( FILE_PATH_LITERAL(kChildSmallWallpaperName)); command_line->AppendSwitchASCII(chromeos::switches::kChildWallpaperSmall, child_small_file.value()); const base::FilePath child_large_file = wallpaper_dir_->GetPath().Append( FILE_PATH_LITERAL(kChildLargeWallpaperName)); command_line->AppendSwitchASCII(chromeos::switches::kChildWallpaperLarge, child_large_file.value()); const int kWallpaperSize = 2; ASSERT_TRUE(WriteJPEGFile(small_file, kWallpaperSize, kWallpaperSize, kWallpaperColor)); ASSERT_TRUE(WriteJPEGFile(large_file, kWallpaperSize, kWallpaperSize, kWallpaperColor)); ASSERT_TRUE(WriteJPEGFile(guest_small_file, kWallpaperSize, kWallpaperSize, kWallpaperColor)); ASSERT_TRUE(WriteJPEGFile(guest_large_file, kWallpaperSize, kWallpaperSize, kWallpaperColor)); ASSERT_TRUE(WriteJPEGFile(child_small_file, kWallpaperSize, kWallpaperSize, kWallpaperColor)); ASSERT_TRUE(WriteJPEGFile(child_large_file, kWallpaperSize, kWallpaperSize, kWallpaperColor)); } // A helper to test the behavior of setting online wallpaper after the image // is decoded. This is needed because image decoding is not supported in unit // tests (the connector for the mojo service manager is null). void SetOnlineWallpaperFromImage(const AccountId& account_id, const gfx::ImageSkia& image, const std::string& url, WallpaperLayout layout, bool save_file, bool preview_mode) { const WallpaperController::OnlineWallpaperParams params = { account_id, false /*is_ephemeral=*/, url, layout, preview_mode}; controller_->OnOnlineWallpaperDecoded(params, save_file, image); } // Returns color of the current wallpaper. Note: this function assumes the // wallpaper has a solid color. SkColor GetWallpaperColor() { const gfx::ImageSkiaRep& representation = controller_->GetWallpaper().GetRepresentation(1.0f); return representation.sk_bitmap().getColor(0, 0); } // Wrapper for private ShouldCalculateColors(). bool ShouldCalculateColors() { return controller_->ShouldCalculateColors(); } // Wrapper for private IsActiveUserWallpaperControlledByPolicyImpl(). bool IsActiveUserWallpaperControlledByPolicy() { return controller_->IsActiveUserWallpaperControlledByPolicyImpl(); } // Wrapper for private IsDevicePolicyWallpaper(). bool IsDevicePolicyWallpaper() { return controller_->IsDevicePolicyWallpaper(); } int GetWallpaperCount() { return controller_->wallpaper_count_for_testing_; } void SetBypassDecode() { controller_->bypass_decode_for_testing_ = true; } void ClearWallpaperCount() { controller_->wallpaper_count_for_testing_ = 0; } void ClearDecodeFilePaths() { controller_->decode_requests_for_testing_.clear(); } bool CompareDecodeFilePaths(const std::vector<base::FilePath> expected) { if (controller_->decode_requests_for_testing_.size() != expected.size()) return false; for (size_t i = 0; i < expected.size(); ++i) { if (controller_->decode_requests_for_testing_[i] != expected[i]) return false; } return true; } WallpaperController* controller_; // Not owned. // Directory created by |CreateDefaultWallpapers| to store default wallpaper // images. std::unique_ptr<base::ScopedTempDir> wallpaper_dir_; private: DISALLOW_COPY_AND_ASSIGN(WallpaperControllerTest); }; TEST_F(WallpaperControllerTest, BasicReparenting) { WallpaperController* controller = Shell::Get()->wallpaper_controller(); controller->CreateEmptyWallpaperForTesting(); // Wallpaper view/window exists in the wallpaper container and nothing is in // the lock screen wallpaper container. EXPECT_EQ(1, ChildCountForContainer(kWallpaperId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenWallpaperId)); // Moving wallpaper to lock container should succeed the first time but // subsequent calls should do nothing. EXPECT_TRUE(controller->MoveToLockedContainer()); EXPECT_FALSE(controller->MoveToLockedContainer()); // One window is moved from desktop to lock container. EXPECT_EQ(0, ChildCountForContainer(kWallpaperId)); EXPECT_EQ(1, ChildCountForContainer(kLockScreenWallpaperId)); // Moving wallpaper to desktop container should succeed the first time. EXPECT_TRUE(controller->MoveToUnlockedContainer()); EXPECT_FALSE(controller->MoveToUnlockedContainer()); // One window is moved from lock to desktop container. EXPECT_EQ(1, ChildCountForContainer(kWallpaperId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenWallpaperId)); } TEST_F(WallpaperControllerTest, SwitchWallpapersWhenNewWallpaperAnimationEnds) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); // Create the wallpaper and its view. WallpaperController* controller = Shell::Get()->wallpaper_controller(); controller->CreateEmptyWallpaperForTesting(); // The new wallpaper is ready to animate. WallpaperWidgetController* widget_controller = Shell::Get() ->GetPrimaryRootWindowController() ->wallpaper_widget_controller(); EXPECT_TRUE(widget_controller->GetAnimatingWidget()); EXPECT_FALSE(widget_controller->GetWidget()); // Force the animation to play to completion. RunDesktopControllerAnimation(); EXPECT_FALSE(widget_controller->GetAnimatingWidget()); EXPECT_TRUE(widget_controller->GetWidget()); } // Test for crbug.com/149043 "Unlock screen, no launcher appears". Ensure we // move all wallpaper views if there are more than one. TEST_F(WallpaperControllerTest, WallpaperMovementDuringUnlock) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); // Reset wallpaper state, see ControllerOwnership above. WallpaperController* controller = Shell::Get()->wallpaper_controller(); controller->CreateEmptyWallpaperForTesting(); // Run wallpaper show animation to completion. RunDesktopControllerAnimation(); // User locks the screen, which moves the wallpaper forward. controller->MoveToLockedContainer(); // Suspend/resume cycle causes wallpaper to refresh, loading a new wallpaper // that will animate in on top of the old one. controller->CreateEmptyWallpaperForTesting(); // In this state we have two wallpaper views stored in different properties. // Both are in the lock screen wallpaper container. WallpaperWidgetController* widget_controller = Shell::Get() ->GetPrimaryRootWindowController() ->wallpaper_widget_controller(); EXPECT_TRUE(widget_controller->GetAnimatingWidget()); EXPECT_TRUE(widget_controller->GetWidget()); EXPECT_EQ(0, ChildCountForContainer(kWallpaperId)); EXPECT_EQ(2, ChildCountForContainer(kLockScreenWallpaperId)); // Before the wallpaper's animation completes, user unlocks the screen, which // moves the wallpaper to the back. controller->MoveToUnlockedContainer(); // Ensure both wallpapers have moved. EXPECT_EQ(2, ChildCountForContainer(kWallpaperId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenWallpaperId)); // Finish the new wallpaper animation. RunDesktopControllerAnimation(); // Now there is one wallpaper, in the back. EXPECT_EQ(1, ChildCountForContainer(kWallpaperId)); EXPECT_EQ(0, ChildCountForContainer(kLockScreenWallpaperId)); } // Test for crbug.com/156542. Animating wallpaper should immediately finish // animation and replace current wallpaper before next animation starts. TEST_F(WallpaperControllerTest, ChangeWallpaperQuick) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); // Reset wallpaper state, see ControllerOwnership above. WallpaperController* controller = Shell::Get()->wallpaper_controller(); controller->CreateEmptyWallpaperForTesting(); // Run wallpaper show animation to completion. RunDesktopControllerAnimation(); // Change to a new wallpaper. controller->CreateEmptyWallpaperForTesting(); WallpaperWidgetController* widget_controller = Shell::Get() ->GetPrimaryRootWindowController() ->wallpaper_widget_controller(); views::Widget* animating_widget = widget_controller->GetAnimatingWidget(); EXPECT_TRUE(animating_widget); EXPECT_TRUE(widget_controller->GetWidget()); // Change to another wallpaper before animation finished. controller->CreateEmptyWallpaperForTesting(); // The animating widget should become active immediately. EXPECT_EQ(animating_widget, widget_controller->GetWidget()); // Cache the new animating widget. animating_widget = widget_controller->GetAnimatingWidget(); // Run wallpaper show animation to completion. ASSERT_NO_FATAL_FAILURE(RunAnimationForWidget(animating_widget)); EXPECT_TRUE(widget_controller->GetWidget()); EXPECT_FALSE(widget_controller->GetAnimatingWidget()); // The last animating widget should be active at this point. EXPECT_EQ(animating_widget, widget_controller->GetWidget()); } TEST_F(WallpaperControllerTest, ResizeCustomWallpaper) { UpdateDisplay("320x200"); gfx::ImageSkia image = CreateImage(640, 480, kWallpaperColor); // Set the image as custom wallpaper, wait for the resize to finish, and check // that the resized image is the expected size. controller_->ShowWallpaperImage(image, CreateWallpaperInfo(WALLPAPER_LAYOUT_STRETCH), false /*preview_mode=*/); EXPECT_TRUE(image.BackedBySameObjectAs(controller_->GetWallpaper())); RunAllTasksUntilIdle(); gfx::ImageSkia resized_image = controller_->GetWallpaper(); EXPECT_FALSE(image.BackedBySameObjectAs(resized_image)); EXPECT_EQ(gfx::Size(320, 200).ToString(), resized_image.size().ToString()); // Load the original wallpaper again and check that we're still using the // previously-resized image instead of doing another resize // (http://crbug.com/321402). controller_->ShowWallpaperImage(image, CreateWallpaperInfo(WALLPAPER_LAYOUT_STRETCH), false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_TRUE(resized_image.BackedBySameObjectAs(controller_->GetWallpaper())); } TEST_F(WallpaperControllerTest, GetMaxDisplaySize) { // Device scale factor shouldn't affect the native size. UpdateDisplay("1000x300*2"); EXPECT_EQ("1000x300", WallpaperController::GetMaxDisplaySizeInNative().ToString()); // Rotated display should return the rotated size. UpdateDisplay("1000x300*2/r"); EXPECT_EQ("300x1000", WallpaperController::GetMaxDisplaySizeInNative().ToString()); // UI Scaling shouldn't affect the native size. UpdateDisplay("1000x300*[email protected]"); EXPECT_EQ("1000x300", WallpaperController::GetMaxDisplaySizeInNative().ToString()); // First display has maximum size. UpdateDisplay("400x300,100x100"); EXPECT_EQ("400x300", WallpaperController::GetMaxDisplaySizeInNative().ToString()); // Second display has maximum size. UpdateDisplay("400x300,500x600"); EXPECT_EQ("500x600", WallpaperController::GetMaxDisplaySizeInNative().ToString()); // Maximum width and height belongs to different displays. UpdateDisplay("400x300,100x500"); EXPECT_EQ("400x500", WallpaperController::GetMaxDisplaySizeInNative().ToString()); } // Test that the wallpaper is always fitted to the native display resolution // when the layout is WALLPAPER_LAYOUT_CENTER to prevent blurry images. TEST_F(WallpaperControllerTest, DontScaleWallpaperWithCenterLayout) { // We cannot short-circuit animations for this test. ui::ScopedAnimationDurationScaleMode test_duration_mode( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); const gfx::Size high_resolution(3600, 2400); const gfx::Size low_resolution(360, 240); const float high_dsf = 2.0f; const float low_dsf = 1.0f; gfx::ImageSkia image_high_res = CreateImage( high_resolution.width(), high_resolution.height(), kWallpaperColor); gfx::ImageSkia image_low_res = CreateImage( low_resolution.width(), low_resolution.height(), kWallpaperColor); UpdateDisplay("1200x600*2"); { SCOPED_TRACE(base::StringPrintf("1200x600*2 high resolution")); controller_->ShowWallpaperImage( image_high_res, CreateWallpaperInfo(WALLPAPER_LAYOUT_CENTER), false /*preview_mode=*/); WallpaperFitToNativeResolution(wallpaper_view(), high_dsf, high_resolution.width(), high_resolution.height(), kWallpaperColor); } { SCOPED_TRACE(base::StringPrintf("1200x600*2 low resolution")); controller_->ShowWallpaperImage( image_low_res, CreateWallpaperInfo(WALLPAPER_LAYOUT_CENTER), false /*preview_mode=*/); WallpaperFitToNativeResolution(wallpaper_view(), high_dsf, low_resolution.width(), low_resolution.height(), kWallpaperColor); } UpdateDisplay("1200x600"); { SCOPED_TRACE(base::StringPrintf("1200x600 high resolution")); controller_->ShowWallpaperImage( image_high_res, CreateWallpaperInfo(WALLPAPER_LAYOUT_CENTER), false /*preview_mode=*/); WallpaperFitToNativeResolution(wallpaper_view(), low_dsf, high_resolution.width(), high_resolution.height(), kWallpaperColor); } { SCOPED_TRACE(base::StringPrintf("1200x600 low resolution")); controller_->ShowWallpaperImage( image_low_res, CreateWallpaperInfo(WALLPAPER_LAYOUT_CENTER), false /*preview_mode=*/); WallpaperFitToNativeResolution(wallpaper_view(), low_dsf, low_resolution.width(), low_resolution.height(), kWallpaperColor); } UpdateDisplay("1200x600/[email protected]"); // 1.5 ui scale { SCOPED_TRACE(base::StringPrintf("1200x600/[email protected] high resolution")); controller_->ShowWallpaperImage( image_high_res, CreateWallpaperInfo(WALLPAPER_LAYOUT_CENTER), false /*preview_mode=*/); WallpaperFitToNativeResolution(wallpaper_view(), low_dsf, high_resolution.width(), high_resolution.height(), kWallpaperColor); } { SCOPED_TRACE(base::StringPrintf("1200x600/[email protected] low resolution")); controller_->ShowWallpaperImage( image_low_res, CreateWallpaperInfo(WALLPAPER_LAYOUT_CENTER), false /*preview_mode=*/); WallpaperFitToNativeResolution(wallpaper_view(), low_dsf, low_resolution.width(), low_resolution.height(), kWallpaperColor); } } TEST_F(WallpaperControllerTest, ShouldCalculateColorsBasedOnImage) { EnableShelfColoring(); EXPECT_TRUE(ShouldCalculateColors()); controller_->CreateEmptyWallpaperForTesting(); EXPECT_FALSE(ShouldCalculateColors()); } TEST_F(WallpaperControllerTest, ShouldCalculateColorsBasedOnSessionState) { EnableShelfColoring(); SetSessionState(SessionState::UNKNOWN); EXPECT_FALSE(ShouldCalculateColors()); SetSessionState(SessionState::OOBE); EXPECT_FALSE(ShouldCalculateColors()); SetSessionState(SessionState::LOGIN_PRIMARY); EXPECT_FALSE(ShouldCalculateColors()); SetSessionState(SessionState::LOGGED_IN_NOT_ACTIVE); EXPECT_FALSE(ShouldCalculateColors()); SetSessionState(SessionState::ACTIVE); EXPECT_TRUE(ShouldCalculateColors()); SetSessionState(SessionState::LOCKED); EXPECT_FALSE(ShouldCalculateColors()); SetSessionState(SessionState::LOGIN_SECONDARY); EXPECT_FALSE(ShouldCalculateColors()); } TEST_F(WallpaperControllerTest, MojoWallpaperObserverTest) { TestWallpaperObserver observer; mojom::WallpaperObserverAssociatedPtr observer_ptr; mojo::AssociatedBinding<mojom::WallpaperObserver> binding( &observer, mojo::MakeRequestAssociatedWithDedicatedPipe(&observer_ptr)); controller_->AddObserver(observer_ptr.PassInterface()); controller_->FlushForTesting(); // Adding an observer fires OnWallpaperColorsChanged() immediately. EXPECT_EQ(1, observer.wallpaper_colors_changed_count()); // Enable shelf coloring will set a customized wallpaper image and change // session state to ACTIVE, which will trigger wallpaper colors calculation. base::RunLoop run_loop; observer.set_run_loop(&run_loop); EnableShelfColoring(); // Color calculation may be asynchronous. run_loop.Run(); // Mojo methods are called after color calculation finishes. controller_->FlushForTesting(); EXPECT_EQ(2, observer.wallpaper_colors_changed_count()); } TEST_F(WallpaperControllerTest, SetCustomWallpaper) { gfx::ImageSkia image = CreateImage(640, 480, kWallpaperColor); WallpaperLayout layout = WALLPAPER_LAYOUT_CENTER; SimulateUserLogin(kUser1); // Set a custom wallpaper for |kUser1|. Verify the wallpaper is set // successfully and wallpaper info is updated. controller_->SetCustomWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, image, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); EXPECT_EQ(controller_->GetWallpaperType(), CUSTOMIZED); WallpaperInfo wallpaper_info; EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_wallpaper_info( base::FilePath(wallpaper_files_id_1).Append(file_name_1).value(), layout, CUSTOMIZED, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_wallpaper_info); // Now set another custom wallpaper for |kUser1|. Verify that the on-screen // wallpaper doesn't change since |kUser1| is not active, but wallpaper info // is updated properly. SimulateUserLogin(kUser2); const SkColor custom_wallpaper_color = SK_ColorCYAN; image = CreateImage(640, 480, custom_wallpaper_color); controller_->SetCustomWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, image, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(wallpaper_info, expected_wallpaper_info); // Verify the updated wallpaper is shown after |kUser1| becomes active again. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(custom_wallpaper_color, GetWallpaperColor()); } TEST_F(WallpaperControllerTest, SetOnlineWallpaper) { SetBypassDecode(); gfx::ImageSkia image = CreateImage(640, 480, kWallpaperColor); WallpaperLayout layout = WALLPAPER_LAYOUT_CENTER_CROPPED; SimulateUserLogin(kUser1); // Verify that there's no offline wallpaper available in the beginning. std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); controller_->GetOfflineWallpaperList(base::BindLambdaForTesting( [&run_loop](const std::vector<std::string>& url_list) { EXPECT_TRUE(url_list.empty()); run_loop->Quit(); })); run_loop->Run(); // Verify that the attempt to set an online wallpaper without providing image // data fails. run_loop.reset(new base::RunLoop()); controller_->SetOnlineWallpaperIfExists( InitializeUser(account_id_1), kDummyUrl, layout, false /*preview_mode=*/, base::BindLambdaForTesting([&run_loop](bool file_exists) { EXPECT_FALSE(file_exists); run_loop->Quit(); })); run_loop->Run(); EXPECT_EQ(0, GetWallpaperCount()); // Set an online wallpaper with image data. Verify that the wallpaper is set // successfully. controller_->SetOnlineWallpaperFromData( InitializeUser(account_id_1), std::string() /*image_data=*/, kDummyUrl, layout, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), ONLINE); // Verify that the user wallpaper info is updated. WallpaperInfo wallpaper_info; EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_wallpaper_info(kDummyUrl, layout, ONLINE, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_wallpaper_info); // Change the on-screen wallpaper to a different one. (Otherwise the // subsequent calls will be no-op since we intentionally prevent reloading the // same wallpaper.) controller_->SetCustomWallpaper( InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, CreateImage(640, 480, kWallpaperColor), false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), CUSTOMIZED); // Attempt to set an online wallpaper without providing the image data. Verify // it succeeds this time because |SetOnlineWallpaperFromData| has saved the // file. run_loop.reset(new base::RunLoop()); controller_->SetOnlineWallpaperIfExists( InitializeUser(account_id_1), kDummyUrl, layout, false /*preview_mode=*/, base::BindLambdaForTesting([&run_loop](bool file_exists) { EXPECT_TRUE(file_exists); run_loop->Quit(); })); run_loop->Run(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), ONLINE); // Verify that the wallpaper with |url| is available offline, and the returned // file name should not contain the small wallpaper suffix. run_loop.reset(new base::RunLoop()); controller_->GetOfflineWallpaperList(base::BindLambdaForTesting( [&run_loop](const std::vector<std::string>& url_list) { EXPECT_EQ(1U, url_list.size()); EXPECT_EQ(GURL(kDummyUrl).ExtractFileName(), url_list[0]); run_loop->Quit(); })); run_loop->Run(); // Log in |kUser2|, and set another online wallpaper for |kUser1|. Verify that // the on-screen wallpaper doesn't change since |kUser1| is not active, but // wallpaper info is updated properly. SimulateUserLogin(kUser2); controller_->SetOnlineWallpaperFromData( InitializeUser(account_id_1), std::string() /*image_data=*/, kDummyUrl2, layout, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_wallpaper_info_2(kDummyUrl2, layout, ONLINE, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_wallpaper_info_2); } TEST_F(WallpaperControllerTest, SetAndRemovePolicyWallpaper) { SetBypassDecode(); // Simulate the login screen. ClearLogin(); // The user starts with no wallpaper info and is not controlled by policy. WallpaperInfo wallpaper_info; EXPECT_FALSE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); EXPECT_FALSE( controller_->IsPolicyControlled(account_id_1, false /*is_ephemeral=*/)); // A default wallpaper is shown for the user. controller_->ShowUserWallpaper(InitializeUser(account_id_1)); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); // Set a policy wallpaper. Verify that the user becomes policy controlled and // the wallpaper info is updated. controller_->SetPolicyWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, std::string() /*data=*/); RunAllTasksUntilIdle(); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo policy_wallpaper_info(base::FilePath(wallpaper_files_id_1) .Append("policy-controlled.jpeg") .value(), WALLPAPER_LAYOUT_CENTER_CROPPED, POLICY, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, policy_wallpaper_info); EXPECT_TRUE( controller_->IsPolicyControlled(account_id_1, false /*is_ephemeral=*/)); // Verify the wallpaper is not updated since the user hasn't logged in. EXPECT_EQ(0, GetWallpaperCount()); // Log in the user. Verify the policy wallpaper is now being shown. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), POLICY); // Log out the user and remove the policy wallpaper. Verify the wallpaper // info is reset to default and the user is no longer policy controlled. ClearLogin(); controller_->RemovePolicyWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1); WaitUntilCustomWallpapersDeleted(account_id_1); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo default_wallpaper_info(std::string(), WALLPAPER_LAYOUT_CENTER_CROPPED, DEFAULT, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, default_wallpaper_info); EXPECT_FALSE( controller_->IsPolicyControlled(account_id_1, false /*is_ephemeral=*/)); // Verify the wallpaper is not updated since the user hasn't logged in. EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), POLICY); // Log in the user. Verify the default wallpaper is now being shown. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); } TEST_F(WallpaperControllerTest, SetThirdPartyWallpaper) { SetBypassDecode(); SimulateUserLogin(kUser1); // Verify the user starts with no wallpaper info. WallpaperInfo wallpaper_info; EXPECT_FALSE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); // Set a third-party wallpaper for |kUser1|. const WallpaperLayout layout = WALLPAPER_LAYOUT_CENTER; gfx::ImageSkia third_party_wallpaper = CreateImage(640, 480, kWallpaperColor); bool allowed_to_update_wallpaper = false; std::unique_ptr<base::RunLoop> run_loop = std::make_unique<base::RunLoop>(); controller_->SetThirdPartyWallpaper( InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, third_party_wallpaper, base::BindLambdaForTesting([&allowed_to_update_wallpaper, &run_loop]( bool allowed, uint32_t image_id) { allowed_to_update_wallpaper = allowed; run_loop->Quit(); })); run_loop->Run(); // Verify the wallpaper is shown. EXPECT_EQ(1, GetWallpaperCount()); // Verify the callback function gets the correct value. EXPECT_TRUE(allowed_to_update_wallpaper); // Verify the user wallpaper info is updated. EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_wallpaper_info( base::FilePath(wallpaper_files_id_1).Append(file_name_1).value(), layout, CUSTOMIZED, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_wallpaper_info); // Switch active user to |kUser2|, but set another third-party wallpaper for // |kUser1|. allowed_to_update_wallpaper = true; SimulateUserLogin(kUser2); run_loop.reset(new base::RunLoop()); controller_->SetThirdPartyWallpaper( InitializeUser(account_id_1), wallpaper_files_id_2, file_name_2, layout, third_party_wallpaper, base::BindLambdaForTesting([&allowed_to_update_wallpaper, &run_loop]( bool allowed, uint32_t image_id) { allowed_to_update_wallpaper = allowed; run_loop->Quit(); })); run_loop->Run(); // Verify the wallpaper is not shown because |kUser1| is not the active user. EXPECT_EQ(0, GetWallpaperCount()); // Verify the callback function gets the correct value. EXPECT_FALSE(allowed_to_update_wallpaper); // Verify the wallpaper info for |kUser1| is updated, because setting // wallpaper is still allowed for non-active users. EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_wallpaper_info_2( base::FilePath(wallpaper_files_id_2).Append(file_name_2).value(), layout, CUSTOMIZED, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_wallpaper_info_2); // Set a policy wallpaper for |kUser2|. Verify that |kUser2| becomes policy // controlled. controller_->SetPolicyWallpaper(InitializeUser(account_id_2), wallpaper_files_id_2, std::string() /*data=*/); RunAllTasksUntilIdle(); EXPECT_TRUE( controller_->IsPolicyControlled(account_id_2, false /*is_ephemeral=*/)); EXPECT_TRUE(IsActiveUserWallpaperControlledByPolicy()); // Set a third-party wallpaper for |kUser2|. allowed_to_update_wallpaper = true; run_loop.reset(new base::RunLoop()); controller_->SetThirdPartyWallpaper( InitializeUser(account_id_2), wallpaper_files_id_1, file_name_1, layout, third_party_wallpaper, base::BindLambdaForTesting([&allowed_to_update_wallpaper, &run_loop]( bool allowed, uint32_t image_id) { allowed_to_update_wallpaper = allowed; run_loop->Quit(); })); run_loop->Run(); // Verify the wallpaper is not shown because third-party wallpaper cannot be // set for policy controlled users. EXPECT_EQ(0, GetWallpaperCount()); // Verify the callback gets the correct value. EXPECT_FALSE(allowed_to_update_wallpaper); // Verify |kUser2| is still policy controlled and has the policy wallpaper // info. EXPECT_TRUE( controller_->IsPolicyControlled(account_id_2, false /*is_ephemeral=*/)); EXPECT_TRUE(IsActiveUserWallpaperControlledByPolicy()); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_2, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo policy_wallpaper_info(base::FilePath(wallpaper_files_id_2) .Append("policy-controlled.jpeg") .value(), WALLPAPER_LAYOUT_CENTER_CROPPED, POLICY, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, policy_wallpaper_info); } TEST_F(WallpaperControllerTest, SetDefaultWallpaperForRegularAccount) { CreateDefaultWallpapers(); SimulateUserLogin(kUser1); // First, simulate setting a user custom wallpaper. SimulateSettingCustomWallpaper(account_id_1); WallpaperInfo wallpaper_info; EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo default_wallpaper_info(std::string(), WALLPAPER_LAYOUT_CENTER_CROPPED, DEFAULT, base::Time::Now().LocalMidnight()); EXPECT_NE(wallpaper_info.type, default_wallpaper_info.type); // Verify |SetDefaultWallpaper| removes the previously set custom wallpaper // info, and the large default wallpaper is set successfully with the correct // file path. UpdateDisplay("1600x1200"); RunAllTasksUntilIdle(); controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kDefaultLargeWallpaperName)})); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); // The user wallpaper info has been reset to the default value. EXPECT_EQ(wallpaper_info, default_wallpaper_info); SimulateSettingCustomWallpaper(account_id_1); // Verify |SetDefaultWallpaper| removes the previously set custom wallpaper // info, and the small default wallpaper is set successfully with the correct // file path. UpdateDisplay("800x600"); RunAllTasksUntilIdle(); controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kDefaultSmallWallpaperName)})); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); // The user wallpaper info has been reset to the default value. EXPECT_EQ(wallpaper_info, default_wallpaper_info); SimulateSettingCustomWallpaper(account_id_1); // Verify that when screen is rotated, |SetDefaultWallpaper| removes the // previously set custom wallpaper info, and the small default wallpaper is // set successfully with the correct file path. UpdateDisplay("800x600/r"); RunAllTasksUntilIdle(); controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kDefaultSmallWallpaperName)})); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); // The user wallpaper info has been reset to the default value. EXPECT_EQ(wallpaper_info, default_wallpaper_info); } TEST_F(WallpaperControllerTest, SetDefaultWallpaperForChildAccount) { CreateDefaultWallpapers(); const std::string child_email = "<EMAIL>"; const AccountId child_account_id = AccountId::FromUserEmail(child_email); const std::string child_wallpaper_files_id = GetDummyFileId(child_account_id); SimulateUserLogin(child_email); // Verify the large child wallpaper is set successfully with the correct file // path. UpdateDisplay("1600x1200"); RunAllTasksUntilIdle(); mojom::WallpaperUserInfoPtr wallpaper_user_info = InitializeUser(child_account_id); wallpaper_user_info->type = user_manager::USER_TYPE_CHILD; controller_->SetDefaultWallpaper(std::move(wallpaper_user_info), child_wallpaper_files_id, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kChildLargeWallpaperName)})); // Verify the small child wallpaper is set successfully with the correct file // path. UpdateDisplay("800x600"); RunAllTasksUntilIdle(); wallpaper_user_info = InitializeUser(child_account_id); wallpaper_user_info->type = user_manager::USER_TYPE_CHILD; controller_->SetDefaultWallpaper(std::move(wallpaper_user_info), child_wallpaper_files_id, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kChildSmallWallpaperName)})); } TEST_F(WallpaperControllerTest, SetDefaultWallpaperForGuestSession) { CreateDefaultWallpapers(); // First, simulate setting a custom wallpaper for a regular user. SimulateUserLogin(kUser1); SimulateSettingCustomWallpaper(account_id_1); WallpaperInfo wallpaper_info; EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo default_wallpaper_info(std::string(), WALLPAPER_LAYOUT_CENTER_CROPPED, DEFAULT, base::Time::Now().LocalMidnight()); EXPECT_NE(wallpaper_info.type, default_wallpaper_info.type); SimulateGuestLogin(); // Verify that during a guest session, |SetDefaultWallpaper| removes the user // custom wallpaper info, but a guest specific wallpaper should be set, // instead of the regular default wallpaper. UpdateDisplay("1600x1200"); RunAllTasksUntilIdle(); controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(wallpaper_info, default_wallpaper_info); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kGuestLargeWallpaperName)})); UpdateDisplay("800x600"); RunAllTasksUntilIdle(); controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kGuestSmallWallpaperName)})); } TEST_F(WallpaperControllerTest, IgnoreWallpaperRequestInKioskMode) { gfx::ImageSkia image = CreateImage(640, 480, kWallpaperColor); const std::string kiosk_app = "kiosk"; // Simulate kiosk login. TestSessionControllerClient* session = GetSessionControllerClient(); session->AddUserSession(kiosk_app, user_manager::USER_TYPE_KIOSK_APP); session->SwitchActiveUser(AccountId::FromUserEmail(kiosk_app)); session->SetSessionState(SessionState::ACTIVE); // Verify that |SetCustomWallpaper| doesn't set wallpaper in kiosk mode, and // |account_id|'s wallpaper info is not updated. controller_->SetCustomWallpaper( InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, WALLPAPER_LAYOUT_CENTER, image, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); WallpaperInfo wallpaper_info; EXPECT_FALSE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); // Verify that |SetOnlineWallpaperFromData| doesn't set wallpaper in kiosk // mode, and |account_id|'s wallpaper info is not updated. controller_->SetOnlineWallpaperFromData( InitializeUser(account_id_1), std::string() /*image_data=*/, kDummyUrl, WALLPAPER_LAYOUT_CENTER, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_FALSE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); // Verify that |SetDefaultWallpaper| doesn't set wallpaper in kiosk mode, and // |account_id|'s wallpaper info is not updated. controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_FALSE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); } TEST_F(WallpaperControllerTest, IgnoreWallpaperRequestWhenPolicyIsEnforced) { SetBypassDecode(); gfx::ImageSkia image = CreateImage(640, 480, kWallpaperColor); SimulateUserLogin(kUser1); // Set a policy wallpaper for the user. Verify the user is policy controlled. controller_->SetPolicyWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, std::string() /*data=*/); RunAllTasksUntilIdle(); EXPECT_TRUE( controller_->IsPolicyControlled(account_id_1, false /*is_ephemeral=*/)); // Verify that |SetCustomWallpaper| doesn't set wallpaper when policy is // enforced, and the user wallpaper info is not updated. controller_->SetCustomWallpaper( InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, WALLPAPER_LAYOUT_CENTER, image, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); WallpaperInfo wallpaper_info; EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo policy_wallpaper_info(base::FilePath(wallpaper_files_id_1) .Append("policy-controlled.jpeg") .value(), WALLPAPER_LAYOUT_CENTER_CROPPED, POLICY, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, policy_wallpaper_info); // Verify that |SetOnlineWallpaperFromData| doesn't set wallpaper when policy // is enforced, and the user wallpaper info is not updated. controller_->SetOnlineWallpaperFromData( InitializeUser(account_id_1), std::string() /*image_data=*/, kDummyUrl, WALLPAPER_LAYOUT_CENTER_CROPPED, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(wallpaper_info, policy_wallpaper_info); // Verify that |SetDefaultWallpaper| doesn't set wallpaper when policy is // enforced, and the user wallpaper info is not updated. controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(wallpaper_info, policy_wallpaper_info); } TEST_F(WallpaperControllerTest, VerifyWallpaperCache) { SetBypassDecode(); gfx::ImageSkia image = CreateImage(640, 480, kWallpaperColor); SimulateUserLogin(kUser1); // |kUser1| doesn't have wallpaper cache in the beginning. gfx::ImageSkia cached_wallpaper; EXPECT_FALSE( controller_->GetWallpaperFromCache(account_id_1, &cached_wallpaper)); base::FilePath path; EXPECT_FALSE(controller_->GetPathFromCache(account_id_1, &path)); // Verify |SetOnlineWallpaperFromData| updates wallpaper cache for |user1|. controller_->SetOnlineWallpaperFromData( InitializeUser(account_id_1), std::string() /*image_data=*/, kDummyUrl, WALLPAPER_LAYOUT_CENTER, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_TRUE( controller_->GetWallpaperFromCache(account_id_1, &cached_wallpaper)); EXPECT_TRUE(controller_->GetPathFromCache(account_id_1, &path)); // After |kUser2| is logged in, |user1|'s wallpaper cache should still be kept // (crbug.com/339576). Note the active user is still |user1|. TestSessionControllerClient* session = GetSessionControllerClient(); session->AddUserSession(kUser2); EXPECT_TRUE( controller_->GetWallpaperFromCache(account_id_1, &cached_wallpaper)); EXPECT_TRUE(controller_->GetPathFromCache(account_id_1, &path)); // Verify |SetDefaultWallpaper| clears wallpaper cache. controller_->SetDefaultWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, true /*show_wallpaper=*/); EXPECT_FALSE( controller_->GetWallpaperFromCache(account_id_1, &cached_wallpaper)); EXPECT_FALSE(controller_->GetPathFromCache(account_id_1, &path)); // Verify |SetCustomWallpaper| updates wallpaper cache for |user1|. controller_->SetCustomWallpaper( InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, WALLPAPER_LAYOUT_CENTER, image, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_TRUE( controller_->GetWallpaperFromCache(account_id_1, &cached_wallpaper)); EXPECT_TRUE(controller_->GetPathFromCache(account_id_1, &path)); // Verify |RemoveUserWallpaper| clears wallpaper cache. controller_->RemoveUserWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1); EXPECT_FALSE( controller_->GetWallpaperFromCache(account_id_1, &cached_wallpaper)); EXPECT_FALSE(controller_->GetPathFromCache(account_id_1, &path)); } // Tests that the appropriate wallpaper (large vs. small) is shown depending // on the desktop resolution. TEST_F(WallpaperControllerTest, ShowCustomWallpaperWithCorrectResolution) { CreateDefaultWallpapers(); base::FilePath small_wallpaper_path = GetCustomWallpaperPath(WallpaperController::kSmallWallpaperSubDir, wallpaper_files_id_1, file_name_1); base::FilePath large_wallpaper_path = GetCustomWallpaperPath(WallpaperController::kLargeWallpaperSubDir, wallpaper_files_id_1, file_name_1); CreateAndSaveWallpapers(account_id_1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); // Display is initialized to 800x600. The small resolution custom wallpaper is // expected. A second decode request with small resolution default wallpaper // is also expected. (Because unit tests don't support actual wallpaper // decoding, it falls back to the default wallpaper.) EXPECT_EQ(1, GetWallpaperCount()); EXPECT_TRUE(CompareDecodeFilePaths( {small_wallpaper_path, wallpaper_dir_->GetPath().Append(kDefaultSmallWallpaperName)})); // Hook up another 800x600 display. This shouldn't trigger a reload. ClearWallpaperCount(); ClearDecodeFilePaths(); UpdateDisplay("800x600,800x600"); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_TRUE(CompareDecodeFilePaths({})); // Detach the secondary display. UpdateDisplay("800x600"); RunAllTasksUntilIdle(); // Hook up a 2000x2000 display. The large resolution custom wallpaper should // be loaded. ClearWallpaperCount(); ClearDecodeFilePaths(); UpdateDisplay("800x600,2000x2000"); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_TRUE(CompareDecodeFilePaths( {large_wallpaper_path, wallpaper_dir_->GetPath().Append(kDefaultLargeWallpaperName)})); // Detach the secondary display. UpdateDisplay("800x600"); RunAllTasksUntilIdle(); // Hook up the 2000x2000 display again. The large resolution default wallpaper // should persist. Test for crbug/165788. ClearWallpaperCount(); ClearDecodeFilePaths(); UpdateDisplay("800x600,2000x2000"); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_TRUE(CompareDecodeFilePaths( {large_wallpaper_path, wallpaper_dir_->GetPath().Append(kDefaultLargeWallpaperName)})); } // After the display is rotated, the sign in wallpaper should be kept. Test for // crbug.com/794725. TEST_F(WallpaperControllerTest, SigninWallpaperIsKeptAfterRotation) { CreateDefaultWallpapers(); UpdateDisplay("800x600"); RunAllTasksUntilIdle(); controller_->ShowSigninWallpaper(); RunAllTasksUntilIdle(); // Display is initialized to 800x600. The small resolution default wallpaper // is expected. EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kDefaultSmallWallpaperName)})); ClearWallpaperCount(); ClearDecodeFilePaths(); // After rotating the display, the small resolution default wallpaper should // still be expected, instead of a custom wallpaper. UpdateDisplay("800x600/r"); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_TRUE(CompareDecodeFilePaths( {wallpaper_dir_->GetPath().Append(kDefaultSmallWallpaperName)})); } // Display size change should trigger reload for both user wallpaper and preview // wallpaper. TEST_F(WallpaperControllerTest, ReloadWallpaper) { CreateAndSaveWallpapers(account_id_1); // Show a user wallpaper. UpdateDisplay("800x600"); RunAllTasksUntilIdle(); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); // Rotating the display should trigger a wallpaper reload. ClearWallpaperCount(); UpdateDisplay("800x600/r"); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); // Calling |ShowUserWallpaper| again with the same account id and display // size should not trigger wallpaper reload (crbug.com/158383). ClearWallpaperCount(); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); // Start wallpaper preview. SimulateUserLogin(kUser1); std::unique_ptr<aura::Window> wallpaper_picker_window( CreateTestWindow(gfx::Rect(0, 0, 100, 100))); wm::GetWindowState(wallpaper_picker_window.get())->Activate(); ClearWallpaperCount(); controller_->SetCustomWallpaper( InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, WALLPAPER_LAYOUT_CENTER, CreateImage(640, 480, kWallpaperColor), true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); // Rotating the display should trigger a wallpaper reload. ClearWallpaperCount(); UpdateDisplay("800x600"); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); } TEST_F(WallpaperControllerTest, UpdateCustomWallpaperLayout) { SetBypassDecode(); gfx::ImageSkia image = CreateImage(640, 480, kSmallCustomWallpaperColor); WallpaperLayout layout = WALLPAPER_LAYOUT_STRETCH; WallpaperLayout new_layout = WALLPAPER_LAYOUT_CENTER; SimulateUserLogin(kUser1); // Set a custom wallpaper for the user. Verify that it's set successfully // and the wallpaper info is updated. controller_->SetCustomWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, image, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperLayout(), layout); WallpaperInfo wallpaper_info; EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_custom_wallpaper_info( base::FilePath(wallpaper_files_id_1).Append(file_name_1).value(), layout, CUSTOMIZED, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_custom_wallpaper_info); // Now change to a different layout. Verify that the layout is updated for // both the current wallpaper and the saved wallpaper info. controller_->UpdateCustomWallpaperLayout(InitializeUser(account_id_1), new_layout); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperLayout(), new_layout); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); expected_custom_wallpaper_info.layout = new_layout; EXPECT_EQ(wallpaper_info, expected_custom_wallpaper_info); // Now set an online wallpaper. Verify that it's set successfully and the // wallpaper info is updated. image = CreateImage(640, 480, kWallpaperColor); controller_->SetOnlineWallpaperFromData( InitializeUser(account_id_1), std::string() /*image_data=*/, kDummyUrl, layout, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperType(), ONLINE); EXPECT_EQ(controller_->GetWallpaperLayout(), layout); EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); WallpaperInfo expected_online_wallpaper_info( kDummyUrl, layout, ONLINE, base::Time::Now().LocalMidnight()); EXPECT_EQ(wallpaper_info, expected_online_wallpaper_info); // Now change the layout of the online wallpaper. Verify that it's a no-op. controller_->UpdateCustomWallpaperLayout(InitializeUser(account_id_1), new_layout); RunAllTasksUntilIdle(); // The wallpaper is not updated. EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(controller_->GetWallpaperLayout(), layout); // The saved wallpaper info is not updated. EXPECT_TRUE(controller_->GetUserWallpaperInfo(account_id_1, &wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(wallpaper_info, expected_online_wallpaper_info); } // Tests that if a user who has a custom wallpaper is removed from the device, // only the directory that contains the user's custom wallpapers gets removed. // The other user's custom wallpaper is not affected. TEST_F(WallpaperControllerTest, RemoveUserWithCustomWallpaper) { SimulateUserLogin(kUser1); base::FilePath small_wallpaper_path_1 = GetCustomWallpaperPath(WallpaperController::kSmallWallpaperSubDir, wallpaper_files_id_1, file_name_1); // Set a custom wallpaper for |kUser1| and verify the wallpaper exists. CreateAndSaveWallpapers(account_id_1); EXPECT_TRUE(base::PathExists(small_wallpaper_path_1)); // Now login another user and set a custom wallpaper for the user. SimulateUserLogin(kUser2); base::FilePath small_wallpaper_path_2 = GetCustomWallpaperPath( WallpaperController::kSmallWallpaperSubDir, wallpaper_files_id_2, GetDummyFileName(account_id_2)); CreateAndSaveWallpapers(account_id_2); EXPECT_TRUE(base::PathExists(small_wallpaper_path_2)); // Simulate the removal of |kUser2|. controller_->RemoveUserWallpaper(InitializeUser(account_id_2), wallpaper_files_id_2); // Wait until all files under the user's custom wallpaper directory are // removed. WaitUntilCustomWallpapersDeleted(account_id_2); EXPECT_FALSE(base::PathExists(small_wallpaper_path_2)); // Verify that the other user's wallpaper is not affected. EXPECT_TRUE(base::PathExists(small_wallpaper_path_1)); } // Tests that if a user who has a default wallpaper is removed from the device, // the other user's custom wallpaper is not affected. TEST_F(WallpaperControllerTest, RemoveUserWithDefaultWallpaper) { SimulateUserLogin(kUser1); base::FilePath small_wallpaper_path_1 = GetCustomWallpaperPath(WallpaperController::kSmallWallpaperSubDir, wallpaper_files_id_1, file_name_1); // Set a custom wallpaper for |kUser1| and verify the wallpaper exists. CreateAndSaveWallpapers(account_id_1); EXPECT_TRUE(base::PathExists(small_wallpaper_path_1)); // Now login another user and set a default wallpaper for the user. SimulateUserLogin(kUser2); controller_->SetDefaultWallpaper(InitializeUser(account_id_2), wallpaper_files_id_2, true /*show_wallpaper=*/); // Simulate the removal of |kUser2|. controller_->RemoveUserWallpaper(InitializeUser(account_id_2), wallpaper_files_id_2); // Verify that the other user's wallpaper is not affected. EXPECT_TRUE(base::PathExists(small_wallpaper_path_1)); } TEST_F(WallpaperControllerTest, IsActiveUserWallpaperControlledByPolicy) { SetBypassDecode(); // Simulate the login screen. Verify that it returns false since there's no // active user. ClearLogin(); EXPECT_FALSE(IsActiveUserWallpaperControlledByPolicy()); SimulateUserLogin(kUser1); EXPECT_FALSE(IsActiveUserWallpaperControlledByPolicy()); // Set a policy wallpaper for the active user. Verify that the active user // becomes policy controlled. controller_->SetPolicyWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, std::string() /*data=*/); RunAllTasksUntilIdle(); EXPECT_TRUE(IsActiveUserWallpaperControlledByPolicy()); // Switch the active user. Verify the active user is not policy controlled. SimulateUserLogin(kUser2); EXPECT_FALSE(IsActiveUserWallpaperControlledByPolicy()); // Logs out. Verify that it returns false since there's no active user. ClearLogin(); EXPECT_FALSE(IsActiveUserWallpaperControlledByPolicy()); } TEST_F(WallpaperControllerTest, WallpaperBlur) { ASSERT_TRUE(controller_->IsBlurEnabled()); ASSERT_FALSE(controller_->IsWallpaperBlurred()); TestWallpaperControllerObserver observer; controller_->AddObserver(&observer); SetSessionState(SessionState::ACTIVE); EXPECT_FALSE(controller_->IsWallpaperBlurred()); EXPECT_EQ(0, observer.wallpaper_blur_changed_count_); SetSessionState(SessionState::LOCKED); EXPECT_TRUE(controller_->IsWallpaperBlurred()); EXPECT_EQ(1, observer.wallpaper_blur_changed_count_); SetSessionState(SessionState::LOGGED_IN_NOT_ACTIVE); EXPECT_FALSE(controller_->IsWallpaperBlurred()); EXPECT_EQ(2, observer.wallpaper_blur_changed_count_); SetSessionState(SessionState::LOGIN_SECONDARY); EXPECT_TRUE(controller_->IsWallpaperBlurred()); EXPECT_EQ(3, observer.wallpaper_blur_changed_count_); // Blur state does not change below. observer.Reset(); SetSessionState(SessionState::LOGIN_PRIMARY); EXPECT_TRUE(controller_->IsWallpaperBlurred()); EXPECT_EQ(0, observer.wallpaper_blur_changed_count_); SetSessionState(SessionState::OOBE); EXPECT_TRUE(controller_->IsWallpaperBlurred()); EXPECT_EQ(0, observer.wallpaper_blur_changed_count_); SetSessionState(SessionState::UNKNOWN); EXPECT_TRUE(controller_->IsWallpaperBlurred()); EXPECT_EQ(0, observer.wallpaper_blur_changed_count_); controller_->RemoveObserver(&observer); } TEST_F(WallpaperControllerTest, WallpaperBlurDuringLockScreenTransition) { ASSERT_TRUE(controller_->IsBlurEnabled()); ASSERT_FALSE(controller_->IsWallpaperBlurred()); TestWallpaperControllerObserver observer; controller_->AddObserver(&observer); // Simulate lock and unlock sequence. controller_->PrepareWallpaperForLockScreenChange(true); EXPECT_TRUE(controller_->IsWallpaperBlurred()); EXPECT_EQ(1, observer.wallpaper_blur_changed_count_); SetSessionState(SessionState::LOCKED); EXPECT_TRUE(controller_->IsWallpaperBlurred()); // Change of state to ACTIVE trigers post lock animation and // PrepareWallpaperForLockScreenChange(false) SetSessionState(SessionState::ACTIVE); EXPECT_FALSE(controller_->IsWallpaperBlurred()); EXPECT_EQ(2, observer.wallpaper_blur_changed_count_); controller_->RemoveObserver(&observer); } TEST_F(WallpaperControllerTest, OnlyShowDevicePolicyWallpaperOnLoginScreen) { SetBypassDecode(); // Verify the device policy wallpaper is shown on login screen. SetSessionState(SessionState::LOGIN_PRIMARY); controller_->SetDeviceWallpaperPolicyEnforced(true); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_TRUE(IsDevicePolicyWallpaper()); // Verify the device policy wallpaper shouldn't be blurred. ASSERT_FALSE(controller_->IsBlurEnabled()); ASSERT_FALSE(controller_->IsWallpaperBlurred()); // Verify the device policy wallpaper is replaced when session state is no // longer LOGIN_PRIMARY. SetSessionState(SessionState::LOGGED_IN_NOT_ACTIVE); RunAllTasksUntilIdle(); EXPECT_EQ(2, GetWallpaperCount()); EXPECT_FALSE(IsDevicePolicyWallpaper()); // Verify the device policy wallpaper never shows up again when session // state changes. SetSessionState(SessionState::ACTIVE); RunAllTasksUntilIdle(); EXPECT_EQ(2, GetWallpaperCount()); EXPECT_FALSE(IsDevicePolicyWallpaper()); SetSessionState(SessionState::LOCKED); RunAllTasksUntilIdle(); EXPECT_EQ(2, GetWallpaperCount()); EXPECT_FALSE(IsDevicePolicyWallpaper()); SetSessionState(SessionState::LOGIN_SECONDARY); RunAllTasksUntilIdle(); EXPECT_EQ(2, GetWallpaperCount()); EXPECT_FALSE(IsDevicePolicyWallpaper()); } TEST_F(WallpaperControllerTest, ShouldShowInitialAnimationAfterBoot) { CreateDefaultWallpapers(); // Simulate the login screen after system boot. base::CommandLine::ForCurrentProcess()->AppendSwitch( chromeos::switches::kFirstExecAfterBoot); base::CommandLine::ForCurrentProcess()->AppendSwitch( chromeos::switches::kLoginManager); ClearLogin(); // Show the first wallpaper. Verify that the slower animation should be used. controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_TRUE(controller_->ShouldShowInitialAnimation()); EXPECT_EQ(1, GetWallpaperCount()); // Show the second wallpaper. Verify that the slower animation should not be // used. (Use a different user type to ensure a different wallpaper is shown, // otherwise requests of loading the same wallpaper are ignored.) controller_->ShowUserWallpaper( InitializeUser(AccountId::FromUserEmail("<EMAIL>"))); RunAllTasksUntilIdle(); EXPECT_FALSE(controller_->ShouldShowInitialAnimation()); EXPECT_EQ(1, GetWallpaperCount()); // Log in the user and show the wallpaper. Verify that the slower animation // should not be used. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_FALSE(controller_->ShouldShowInitialAnimation()); EXPECT_EQ(1, GetWallpaperCount()); } TEST_F(WallpaperControllerTest, ShouldNotShowInitialAnimationAfterSignOut) { CreateDefaultWallpapers(); // Simulate the login screen after user sign-out. Verify that the slower // animation should never be used. base::CommandLine::ForCurrentProcess()->AppendSwitch( chromeos::switches::kLoginManager); CreateAndSaveWallpapers(account_id_1); ClearLogin(); // Show the first wallpaper. controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_FALSE(controller_->ShouldShowInitialAnimation()); EXPECT_EQ(1, GetWallpaperCount()); // Show the second wallpaper. controller_->ShowUserWallpaper( InitializeUser(AccountId::FromUserEmail("<EMAIL>"))); RunAllTasksUntilIdle(); EXPECT_FALSE(controller_->ShouldShowInitialAnimation()); EXPECT_EQ(1, GetWallpaperCount()); // Log in the user and show the wallpaper. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_FALSE(controller_->ShouldShowInitialAnimation()); EXPECT_EQ(1, GetWallpaperCount()); } TEST_F(WallpaperControllerTest, ConfirmPreviewWallpaper) { // Verify the user starts with a default wallpaper and the user wallpaper info // is initialized with default values. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); WallpaperInfo user_wallpaper_info; WallpaperInfo default_wallpaper_info(std::string(), WALLPAPER_LAYOUT_CENTER_CROPPED, DEFAULT, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Simulate opening the wallpaper picker window. std::unique_ptr<aura::Window> wallpaper_picker_window( CreateTestWindow(gfx::Rect(0, 0, 100, 100))); wm::GetWindowState(wallpaper_picker_window.get())->Activate(); // Set a custom wallpaper for the user and enable preview. Verify that the // wallpaper is changed to the expected color. const WallpaperLayout layout = WALLPAPER_LAYOUT_CENTER; gfx::ImageSkia custom_wallpaper = CreateImage(640, 480, kWallpaperColor); EXPECT_NE(kWallpaperColor, GetWallpaperColor()); controller_->SetCustomWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, custom_wallpaper, true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // Verify that the user wallpaper info remains unchanged during the preview. EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Now confirm the preview wallpaper, verify that there's no wallpaper change // because the wallpaper is already shown. ClearWallpaperCount(); controller_->ConfirmPreviewWallpaper(); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // Verify that the user wallpaper info is now updated to the custom wallpaper // info. WallpaperInfo custom_wallpaper_info( base::FilePath(wallpaper_files_id_1).Append(file_name_1).value(), layout, CUSTOMIZED, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, custom_wallpaper_info); // Now set an online wallpaper for the user and enable preview. Verify that // the wallpaper is changed to the expected color. const SkColor online_wallpaper_color = SK_ColorCYAN; gfx::ImageSkia online_wallpaper = CreateImage(640, 480, online_wallpaper_color); EXPECT_NE(online_wallpaper_color, GetWallpaperColor()); ClearWallpaperCount(); SetOnlineWallpaperFromImage(account_id_1, online_wallpaper, kDummyUrl, layout, false /*save_file=*/, true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(online_wallpaper_color, GetWallpaperColor()); // Verify that the user wallpaper info remains unchanged during the preview. EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, custom_wallpaper_info); // Now confirm the preview wallpaper, verify that there's no wallpaper change // because the wallpaper is already shown. ClearWallpaperCount(); controller_->ConfirmPreviewWallpaper(); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(online_wallpaper_color, GetWallpaperColor()); // Verify that the user wallpaper info is now updated to the online wallpaper // info. WallpaperInfo online_wallpaper_info(kDummyUrl, layout, ONLINE, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, online_wallpaper_info); } TEST_F(WallpaperControllerTest, CancelPreviewWallpaper) { // Verify the user starts with a default wallpaper and the user wallpaper info // is initialized with default values. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); WallpaperInfo user_wallpaper_info; WallpaperInfo default_wallpaper_info(std::string(), WALLPAPER_LAYOUT_CENTER_CROPPED, DEFAULT, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Simulate opening the wallpaper picker window. std::unique_ptr<aura::Window> wallpaper_picker_window( CreateTestWindow(gfx::Rect(0, 0, 100, 100))); wm::GetWindowState(wallpaper_picker_window.get())->Activate(); // Set a custom wallpaper for the user and enable preview. Verify that the // wallpaper is changed to the expected color. const WallpaperLayout layout = WALLPAPER_LAYOUT_CENTER; gfx::ImageSkia custom_wallpaper = CreateImage(640, 480, kWallpaperColor); EXPECT_NE(kWallpaperColor, GetWallpaperColor()); controller_->SetCustomWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, custom_wallpaper, true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // Verify that the user wallpaper info remains unchanged during the preview. EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Now cancel the preview. Verify the wallpaper changes back to the default // and the user wallpaper info remains unchanged. ClearWallpaperCount(); controller_->CancelPreviewWallpaper(); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_NE(kWallpaperColor, GetWallpaperColor()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Now set an online wallpaper for the user and enable preview. Verify that // the wallpaper is changed to the expected color. const SkColor online_wallpaper_color = SK_ColorCYAN; gfx::ImageSkia online_wallpaper = CreateImage(640, 480, online_wallpaper_color); EXPECT_NE(online_wallpaper_color, GetWallpaperColor()); ClearWallpaperCount(); SetOnlineWallpaperFromImage(account_id_1, online_wallpaper, kDummyUrl, layout, false /*save_file=*/, true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(online_wallpaper_color, GetWallpaperColor()); // Verify that the user wallpaper info remains unchanged during the preview. EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Now cancel the preview. Verify the wallpaper changes back to the default // and the user wallpaper info remains unchanged. ClearWallpaperCount(); controller_->CancelPreviewWallpaper(); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_NE(online_wallpaper_color, GetWallpaperColor()); EXPECT_EQ(controller_->GetWallpaperType(), DEFAULT); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); } TEST_F(WallpaperControllerTest, WallpaperSyncedDuringPreview) { // Verify the user starts with a default wallpaper and the user wallpaper info // is initialized with default values. SimulateUserLogin(kUser1); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); WallpaperInfo user_wallpaper_info; WallpaperInfo default_wallpaper_info(std::string(), WALLPAPER_LAYOUT_CENTER_CROPPED, DEFAULT, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Simulate opening the wallpaper picker window. std::unique_ptr<aura::Window> wallpaper_picker_window( CreateTestWindow(gfx::Rect(0, 0, 100, 100))); wm::GetWindowState(wallpaper_picker_window.get())->Activate(); // Set a custom wallpaper for the user and enable preview. Verify that the // wallpaper is changed to the expected color. const WallpaperLayout layout = WALLPAPER_LAYOUT_CENTER; gfx::ImageSkia custom_wallpaper = CreateImage(640, 480, kWallpaperColor); EXPECT_NE(kWallpaperColor, GetWallpaperColor()); controller_->SetCustomWallpaper(InitializeUser(account_id_1), wallpaper_files_id_1, file_name_1, layout, custom_wallpaper, true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // Verify that the user wallpaper info remains unchanged during the preview. EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, default_wallpaper_info); // Now set another custom wallpaper for the user and disable preview (this // happens if a custom wallpaper set on another device is being synced). // Verify there's no wallpaper change since preview mode shouldn't be // interrupted. const SkColor synced_custom_wallpaper_color = SK_ColorBLUE; gfx::ImageSkia synced_custom_wallpaper = CreateImage(640, 480, synced_custom_wallpaper_color); ClearWallpaperCount(); controller_->SetCustomWallpaper( InitializeUser(account_id_1), wallpaper_files_id_2, file_name_2, layout, synced_custom_wallpaper, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // However, the user wallpaper info should already be updated to the new info. WallpaperInfo synced_custom_wallpaper_info( base::FilePath(wallpaper_files_id_2).Append(file_name_2).value(), layout, CUSTOMIZED, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, synced_custom_wallpaper_info); // Now cancel the preview. Verify the synced custom wallpaper is shown instead // of the initial default wallpaper, and the user wallpaper info is still // correct. ClearWallpaperCount(); controller_->CancelPreviewWallpaper(); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(synced_custom_wallpaper_color, GetWallpaperColor()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, synced_custom_wallpaper_info); // Repeat the above steps for online wallpapers: set a online wallpaper for // the user and enable preview. Verify that the wallpaper is changed to the // expected color. gfx::ImageSkia online_wallpaper = CreateImage(640, 480, kWallpaperColor); EXPECT_NE(kWallpaperColor, GetWallpaperColor()); ClearWallpaperCount(); SetOnlineWallpaperFromImage(account_id_1, online_wallpaper, kDummyUrl, layout, false /*save_file=*/, true /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // Verify that the user wallpaper info remains unchanged during the preview. EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, synced_custom_wallpaper_info); // Now set another online wallpaper for the user and disable preview. Verify // there's no wallpaper change since preview mode shouldn't be interrupted. const SkColor synced_online_wallpaper_color = SK_ColorCYAN; gfx::ImageSkia synced_online_wallpaper = CreateImage(640, 480, synced_online_wallpaper_color); ClearWallpaperCount(); SetOnlineWallpaperFromImage(account_id_1, synced_online_wallpaper, kDummyUrl2, layout, false /*save_file=*/, false /*preview_mode=*/); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(kWallpaperColor, GetWallpaperColor()); // However, the user wallpaper info should already be updated to the new info. WallpaperInfo synced_online_wallpaper_info(kDummyUrl2, layout, ONLINE, base::Time::Now().LocalMidnight()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, synced_online_wallpaper_info); // Now cancel the preview. Verify the synced online wallpaper is shown instead // of the previous custom wallpaper, and the user wallpaper info is still // correct. ClearWallpaperCount(); controller_->CancelPreviewWallpaper(); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(synced_online_wallpaper_color, GetWallpaperColor()); EXPECT_TRUE(controller_->GetUserWallpaperInfo( account_id_1, &user_wallpaper_info, false /*is_ephemeral=*/)); EXPECT_EQ(user_wallpaper_info, synced_online_wallpaper_info); } // A test wallpaper controller client class. class TestWallpaperControllerClient : public mojom::WallpaperControllerClient { public: TestWallpaperControllerClient() : binding_(this) {} ~TestWallpaperControllerClient() override = default; int ready_to_set_wallpaper_count() const { return ready_to_set_wallpaper_count_; } mojom::WallpaperControllerClientPtr CreateInterfacePtr() { mojom::WallpaperControllerClientPtr ptr; binding_.Bind(mojo::MakeRequest(&ptr)); return ptr; } // mojom::WallpaperControllerClient: void OnReadyToSetWallpaper() override { ++ready_to_set_wallpaper_count_; } void OpenWallpaperPicker() override {} void OnFirstWallpaperAnimationFinished() override {} private: int ready_to_set_wallpaper_count_ = 0; mojo::Binding<mojom::WallpaperControllerClient> binding_; DISALLOW_COPY_AND_ASSIGN(TestWallpaperControllerClient); }; // Tests for cases when local state is not available. class WallpaperControllerDisableLocalStateTest : public WallpaperControllerTest { public: WallpaperControllerDisableLocalStateTest() = default; ~WallpaperControllerDisableLocalStateTest() override = default; void SetUp() override { disable_provide_local_state(); WallpaperControllerTest::SetUp(); } private: DISALLOW_COPY_AND_ASSIGN(WallpaperControllerDisableLocalStateTest); }; TEST_F(WallpaperControllerDisableLocalStateTest, IgnoreShowUserWallpaper) { TestWallpaperControllerClient client; controller_->SetClientForTesting(client.CreateInterfacePtr()); SimulateUserLogin(kUser1); // When local state is not available, verify |ShowUserWallpaper| request is // ignored. controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(0, GetWallpaperCount()); EXPECT_EQ(0, client.ready_to_set_wallpaper_count()); // Make local state available, verify |ShowUserWallpaper| successfully shows // the wallpaper, and |OnReadyToSetWallpaper| is invoked. std::unique_ptr<TestingPrefServiceSimple> local_state = std::make_unique<TestingPrefServiceSimple>(); Shell::RegisterLocalStatePrefs(local_state->registry(), true); ShellTestApi().OnLocalStatePrefServiceInitialized(std::move(local_state)); controller_->ShowUserWallpaper(InitializeUser(account_id_1)); RunAllTasksUntilIdle(); EXPECT_EQ(1, GetWallpaperCount()); EXPECT_EQ(1, client.ready_to_set_wallpaper_count()); } } // namespace ash
37,117
404
// // MidiSourceFile.c - MrsWatson // Copyright (c) 2016 <NAME>. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // #include "MidiSourceFile.h" #include "audio/AudioSettings.h" #include "base/Endian.h" #include "logging/EventLogger.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static boolByte _openMidiSourceFile(void *midiSourcePtr) { MidiSource midiSource = midiSourcePtr; MidiSourceFileData extraData = midiSource->extraData; extraData->fileHandle = fopen(midiSource->sourceName->data, "rb"); if (extraData->fileHandle == NULL) { logError("MIDI file '%s' could not be opened for reading", midiSource->sourceName->data); return false; } return true; } static boolByte _readMidiFileChunkHeader(FILE *midiFile, const char *expectedChunkId) { byte chunkId[5]; size_t itemsRead; memset(chunkId, 0, 5); itemsRead = fread(chunkId, sizeof(byte), 4, midiFile); if (itemsRead < 4) { logError("Short read of MIDI file (at chunk ID)"); return false; } else if (strncmp((char *)chunkId, expectedChunkId, 4)) { logError("MIDI file does not have valid chunk ID"); return false; } else { return true; } } static boolByte _readMidiFileHeader(FILE *midiFile, unsigned short *formatType, unsigned short *numTracks, unsigned short *timeDivision) { unsigned int numBytesBuffer; size_t itemsRead; unsigned int numBytes; unsigned short wordBuffer; if (!_readMidiFileChunkHeader(midiFile, "MThd")) { return false; } itemsRead = fread(&numBytesBuffer, sizeof(unsigned int), 1, midiFile); if (itemsRead < 1) { logError("Short read of MIDI file (at header, num items)"); return false; } numBytes = convertBigEndianIntToPlatform(numBytesBuffer); if (numBytes != 6) { logError("MIDI file has %d bytes in header chunk, expected 6", numBytes); return false; } itemsRead = fread(&wordBuffer, sizeof(unsigned short), 1, midiFile); if (itemsRead != 1) { logError("Short read of MIDI file (at header, format type)"); return false; } *formatType = convertBigEndianShortToPlatform(wordBuffer); itemsRead = fread(&wordBuffer, sizeof(unsigned short), 1, midiFile); if (itemsRead != 1) { logError("Short read of MIDI file (at header, num tracks)"); return false; } *numTracks = convertBigEndianShortToPlatform(wordBuffer); itemsRead = fread(&wordBuffer, sizeof(unsigned short), 1, midiFile); if (itemsRead != 1) { logError("Short read of MIDI file (at header, time division)"); return false; } *timeDivision = convertBigEndianShortToPlatform(wordBuffer); logDebug("Time division is %d", *timeDivision); return true; } static boolByte _readMidiFileTrack(FILE *midiFile, const int trackNumber, const int timeDivision, const MidiFileTimeDivisionType divisionType, MidiSequence midiSequence) { unsigned int numBytesBuffer; byte *trackData, *currentByte, *endByte; size_t itemsRead, numBytes; unsigned long currentTimeInSampleFrames = 0; unsigned long unpackedVariableLength; MidiEvent midiEvent = NULL; unsigned int i; if (!_readMidiFileChunkHeader(midiFile, "MTrk")) { return false; } itemsRead = fread(&numBytesBuffer, sizeof(unsigned int), 1, midiFile); if (itemsRead < 1) { logError("Short read of MIDI file (at track %d header, num items)", trackNumber); return false; } // Read in the entire track in one pass and parse the events from the buffer // data. Much easier // than having to call fread() for each event. numBytes = (size_t)convertBigEndianIntToPlatform(numBytesBuffer); trackData = (byte *)malloc(numBytes); itemsRead = fread(trackData, 1, numBytes, midiFile); if (itemsRead != numBytes) { logError("Short read of MIDI file (at track %d)", trackNumber); free(trackData); return false; } currentByte = trackData; endByte = trackData + numBytes; while (currentByte < endByte) { // Unpack variable length timestamp unpackedVariableLength = *currentByte; if (unpackedVariableLength & 0x80) { unpackedVariableLength &= 0x7f; do { unpackedVariableLength = (unpackedVariableLength << 7) + (*(++currentByte) & 0x7f); } while (*currentByte & 0x80); } currentByte++; freeMidiEvent(midiEvent); midiEvent = newMidiEvent(); switch (*currentByte) { case 0xff: midiEvent->eventType = MIDI_TYPE_META; currentByte++; midiEvent->status = *(currentByte++); numBytes = *(currentByte++); midiEvent->extraData = (byte *)malloc(numBytes); for (i = 0; i < numBytes; i++) { midiEvent->extraData[i] = *(currentByte++); } break; case 0x7f: logUnsupportedFeature("MIDI files containing sysex events"); free(trackData); freeMidiEvent(midiEvent); return false; default: midiEvent->eventType = MIDI_TYPE_REGULAR; midiEvent->status = *currentByte++; midiEvent->data1 = *currentByte++; // All regular MIDI events have 3 bytes except for program change and // channel aftertouch if (!((midiEvent->status & 0xf0) == 0xc0 || (midiEvent->status & 0xf0) == 0xd0)) { midiEvent->data2 = *currentByte++; } break; } switch (divisionType) { case TIME_DIVISION_TYPE_TICKS_PER_BEAT: { double ticksPerSecond = (double)timeDivision * getTempo() / 60.0; double sampleFramesPerTick = getSampleRate() / ticksPerSecond; currentTimeInSampleFrames += (long)(unpackedVariableLength * sampleFramesPerTick); } break; case TIME_DIVISION_TYPE_FRAMES_PER_SECOND: // Actually, this should be caught when parsing the file type logUnsupportedFeature("Time division frames/sec"); free(trackData); freeMidiEvent(midiEvent); return false; case TIME_DIVISION_TYPE_INVALID: default: logInternalError("Invalid time division type"); free(trackData); freeMidiEvent(midiEvent); return false; } midiEvent->timestamp = currentTimeInSampleFrames; if (midiEvent->eventType == MIDI_TYPE_META) { switch (midiEvent->status) { case MIDI_META_TYPE_TEXT: case MIDI_META_TYPE_COPYRIGHT: case MIDI_META_TYPE_SEQUENCE_NAME: case MIDI_META_TYPE_INSTRUMENT: case MIDI_META_TYPE_LYRIC: case MIDI_META_TYPE_MARKER: case MIDI_META_TYPE_CUE_POINT: // This event type could theoretically be supported, as long as the // plugin supports it case MIDI_META_TYPE_PROGRAM_NAME: case MIDI_META_TYPE_DEVICE_NAME: case MIDI_META_TYPE_KEY_SIGNATURE: case MIDI_META_TYPE_PROPRIETARY: logDebug("Ignoring MIDI meta event of type 0x%x at %ld", midiEvent->status, midiEvent->timestamp); break; case MIDI_META_TYPE_TEMPO: case MIDI_META_TYPE_TIME_SIGNATURE: case MIDI_META_TYPE_TRACK_END: logDebug("Parsed MIDI meta event of type 0x%02x at %ld", midiEvent->status, midiEvent->timestamp); appendMidiEventToSequence(midiSequence, midiEvent); midiEvent = NULL; break; default: logWarn("Ignoring MIDI meta event of type 0x%x at %ld", midiEvent->status, midiEvent->timestamp); break; } } else { logDebug("MIDI event of type 0x%02x parsed at %ld", midiEvent->status, midiEvent->timestamp); appendMidiEventToSequence(midiSequence, midiEvent); midiEvent = NULL; } } free(trackData); freeMidiEvent(midiEvent); return true; } static boolByte _readMidiEventsFile(void *midiSourcePtr, MidiSequence midiSequence) { MidiSource midiSource = (MidiSource)midiSourcePtr; MidiSourceFileData extraData = (MidiSourceFileData)(midiSource->extraData); unsigned short formatType, numTracks, timeDivision = 0; int track; if (!_readMidiFileHeader(extraData->fileHandle, &formatType, &numTracks, &timeDivision)) { return false; } if (formatType != 0) { logUnsupportedFeature("MIDI file types other than 0"); return false; } else if (formatType == 0 && numTracks != 1) { logError("MIDI file '%s' is of type 0, but contains %d tracks", midiSource->sourceName->data, numTracks); return false; } // Determine time division type if (timeDivision & 0x7fff) { extraData->divisionType = TIME_DIVISION_TYPE_TICKS_PER_BEAT; } else { extraData->divisionType = TIME_DIVISION_TYPE_FRAMES_PER_SECOND; logUnsupportedFeature("MIDI file with time division in frames/second"); return false; } logDebug( "MIDI file is type %d, has %d tracks, and time division %d (type %d)", formatType, numTracks, timeDivision, extraData->divisionType); for (track = 0; track < numTracks; track++) { if (!_readMidiFileTrack(extraData->fileHandle, track, timeDivision, extraData->divisionType, midiSequence)) { return false; } } return true; } static void _freeMidiEventsFile(void *midiSourceDataPtr) { MidiSourceFileData extraData = midiSourceDataPtr; if (extraData->fileHandle != NULL) { fclose(extraData->fileHandle); } free(extraData); } MidiSource newMidiSourceFile(const CharString midiSourceName) { MidiSource midiSource = (MidiSource)malloc(sizeof(MidiSourceMembers)); MidiSourceFileData extraData = (MidiSourceFileData)malloc(sizeof(MidiSourceFileDataMembers)); midiSource->midiSourceType = MIDI_SOURCE_TYPE_FILE; midiSource->sourceName = newCharString(); charStringCopy(midiSource->sourceName, midiSourceName); midiSource->openMidiSource = _openMidiSourceFile; midiSource->readMidiEvents = _readMidiEventsFile; midiSource->freeMidiSourceData = _freeMidiEventsFile; extraData->divisionType = TIME_DIVISION_TYPE_INVALID; extraData->fileHandle = NULL; midiSource->extraData = extraData; return midiSource; }
4,391
319
{ "contentVersion": "1.0.0.0", "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "parameters": { "adminUsername": { "type": "string", "metadata": { "description": "Username for the Virtual Machine." } }, "adminPassword": { "type": "securestring", "metadata": { "description": "Password for the Virtual Machine." } }, "vmName": { "type": "string", "metadata": { "description": "Name for the Virtual Machine." } } }, "variables": { "location": "[resourceGroup().location]" }, "resources": [ { "type": "Microsoft.Compute/virtualMachines/extensions", "name": "[concat(parameters('vmName'),'/EnergyDemandForecastingSetup')]", "apiVersion": "2015-05-01-preview", "location": "[variables('location')]", "properties": { "publisher": "Microsoft.Compute", "type": "CustomScriptExtension", "typeHandlerVersion": "1.7", "autoUpgradeMinorVersion": false, "settings": { "fileUris": [ "https://raw.githubusercontent.com/Microsoft/SQL-Server-R-Services-Samples/master/EnergyDemandForecasting/SQLR/EnergyDemandForecastingSetup.ps1" ], "commandToExecute": "[concat('powershell.exe -ExecutionPolicy Unrestricted -File EnergyDemandForecastingSetup.ps1 -serverName ', parameters('vmName') ,' -username ',parameters('adminUsername'),' -password ',parameters('adminPassword'))]" } } } ], "outputs": { } }
652
1,320
// // Loggeer.hpp // Pods // // Created by <NAME> on 15/10/8. // // #ifndef Loggeer_hpp #define Loggeer_hpp #include <videocore/system/util.h> #include <string> namespace videocore { class Logger { public: static void log(bool synchronous, int level, int flag, int ctx, const char *file, const char *function, int line, const char* frmt, ...) __attribute__ ((format (printf, 8, 9))); static void dumpBuffer(const char *desc, uint8_t *buf, size_t size, const char *sep=" ", size_t breaklen = 16); }; // Define DLOG_LEVEL_DEF to control the output log message #define DLOG_MACRO(isAsynchronous, lvl, flg, ctx, fnct, frmt, ...) \ videocore::Logger::log(isAsynchronous, lvl, flg, ctx, __FILE__, fnct, __LINE__, frmt, ##__VA_ARGS__); #define SYNC_DLOG_MACRO(lvl, flg, ctx, frmt, ...) \ DLOG_MACRO(false, lvl, flg, ctx, frmt, ##__VA_ARGS__) #define ASYNC_DLOG_MACRO(lvl, flg, ctx, frmt, ...) \ DLOG_MACRO(true , lvl, flg, ctx, frmt, ##__VA_ARGS__) } #define DLOG_MAYBE(async, lvl, flg, ctx, frmt, ...) \ do { if(lvl & flg) DLOG_MACRO(async, lvl, flg, ctx, __FUNCTION__, frmt, ##__VA_ARGS__); } while(0) #define SYNC_DLOG_MAYBE(lvl, flg, ctx, frmt, ...) \ DLOG_MAYBE( NO, lvl, flg, ctx, frmt, ##__VA_ARGS__) #define ASYNC_LOG_MAYBE(lvl, flg, ctx, frmt, ...) \ DLOG_MAYBE(YES, lvl, flg, ctx, frmt, ##__VA_ARGS__) // FLAG value #define DLOG_FLAG_ERROR (1 << 0) #define DLOG_FLAG_WARN (1 << 1) #define DLOG_FLAG_INFO (1 << 2) #define DLOG_FLAG_DEBUG (1 << 3) #define DLOG_FLAG_VERBOSE (1 << 4) // LAVEL value #define DLOG_LEVEL_OFF 0 #define DLOG_LEVEL_ERROR (DLOG_FLAG_ERROR) #define DLOG_LEVEL_WARN (DLOG_FLAG_ERROR | DLOG_FLAG_WARN) #define DLOG_LEVEL_INFO (DLOG_FLAG_ERROR | DLOG_FLAG_WARN | DLOG_FLAG_INFO) #define DLOG_LEVEL_DEBUG (DLOG_FLAG_ERROR | DLOG_FLAG_WARN | DLOG_FLAG_INFO | DLOG_FLAG_DEBUG) #define DLOG_LEVEL_VERBOSE (DLOG_FLAG_ERROR | DLOG_FLAG_WARN | DLOG_FLAG_INFO | DLOG_FLAG_DEBUG | DLOG_FLAG_VERBOSE) // Can log value #define DLOG_ERROR (DLOG_LEVEL_DEF & DLOG_FLAG_ERROR) #define DLOG_WARN (DLOG_LEVEL_DEF & DLOG_FLAG_WARN) #define DLOG_INFO (DLOG_LEVEL_DEF & DLOG_FLAG_INFO) #define DLOG_DEBUG (DLOG_LEVEL_DEF & DLOG_FLAG_DEBUG) #define DLOG_VERBOSE (DLOG_LEVEL_DEF & DLOG_FLAG_VERBOSE) #define DLOG_ASYNC_ENABLED 1 // Can async log value #define DLOG_ASYNC_ERROR (0 && DLOG_ASYNC_ENABLED) #define DLOG_ASYNC_WARN (1 && DLOG_ASYNC_ENABLED) #define DLOG_ASYNC_INFO (1 && DLOG_ASYNC_ENABLED) #define DLOG_ASYNC_DEBUG (1 && DLOG_ASYNC_ENABLED) #define DLOG_ASYNC_VERBOSE (1 && DLOG_ASYNC_ENABLED) // Log macros #define DLogError(frmt, ...) DLOG_MAYBE(DLOG_ASYNC_ERROR, DLOG_LEVEL_DEF, DLOG_FLAG_ERROR, 0, frmt, ##__VA_ARGS__) #define DLogWarn(frmt, ...) DLOG_MAYBE(DLOG_ASYNC_WARN, DLOG_LEVEL_DEF, DLOG_FLAG_WARN, 0, frmt, ##__VA_ARGS__) #define DLogInfo(frmt, ...) DLOG_MAYBE(DLOG_ASYNC_INFO, DLOG_LEVEL_DEF, DLOG_FLAG_INFO, 0, frmt, ##__VA_ARGS__) #define DLogDebug(frmt, ...) DLOG_MAYBE(DLOG_ASYNC_DEBUG, DLOG_LEVEL_DEF, DLOG_FLAG_DEBUG, 0, frmt, ##__VA_ARGS__) #define DLogVerbose(frmt, ...) DLOG_MAYBE(DLOG_ASYNC_VERBOSE, DLOG_LEVEL_DEF, DLOG_FLAG_VERBOSE, 0, frmt, ##__VA_ARGS__) #endif /* Loggeer_hpp */
1,724
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.displayvideo.v1.model; /** * A single manual trigger in Display & Video 360. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Display & Video 360 API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class ManualTrigger extends com.google.api.client.json.GenericJson { /** * Required. The maximum duration of each activation in minutes. Must be between 1 and 360 * inclusive. After this duration, the trigger will be automatically deactivated. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long activationDurationMinutes; /** * Required. Immutable. The unique ID of the advertiser that the manual trigger belongs to. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long advertiserId; /** * Required. The display name of the manual trigger. Must be UTF-8 encoded with a maximum size of * 240 bytes. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String displayName; /** * Output only. The timestamp of the trigger's latest activation. * The value may be {@code null}. */ @com.google.api.client.util.Key private String latestActivationTime; /** * Output only. The resource name of the manual trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Output only. The state of the manual trigger. Will be set to the `INACTIVE` state upon * creation. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String state; /** * Output only. The unique ID of the manual trigger. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long triggerId; /** * Required. The maximum duration of each activation in minutes. Must be between 1 and 360 * inclusive. After this duration, the trigger will be automatically deactivated. * @return value or {@code null} for none */ public java.lang.Long getActivationDurationMinutes() { return activationDurationMinutes; } /** * Required. The maximum duration of each activation in minutes. Must be between 1 and 360 * inclusive. After this duration, the trigger will be automatically deactivated. * @param activationDurationMinutes activationDurationMinutes or {@code null} for none */ public ManualTrigger setActivationDurationMinutes(java.lang.Long activationDurationMinutes) { this.activationDurationMinutes = activationDurationMinutes; return this; } /** * Required. Immutable. The unique ID of the advertiser that the manual trigger belongs to. * @return value or {@code null} for none */ public java.lang.Long getAdvertiserId() { return advertiserId; } /** * Required. Immutable. The unique ID of the advertiser that the manual trigger belongs to. * @param advertiserId advertiserId or {@code null} for none */ public ManualTrigger setAdvertiserId(java.lang.Long advertiserId) { this.advertiserId = advertiserId; return this; } /** * Required. The display name of the manual trigger. Must be UTF-8 encoded with a maximum size of * 240 bytes. * @return value or {@code null} for none */ public java.lang.String getDisplayName() { return displayName; } /** * Required. The display name of the manual trigger. Must be UTF-8 encoded with a maximum size of * 240 bytes. * @param displayName displayName or {@code null} for none */ public ManualTrigger setDisplayName(java.lang.String displayName) { this.displayName = displayName; return this; } /** * Output only. The timestamp of the trigger's latest activation. * @return value or {@code null} for none */ public String getLatestActivationTime() { return latestActivationTime; } /** * Output only. The timestamp of the trigger's latest activation. * @param latestActivationTime latestActivationTime or {@code null} for none */ public ManualTrigger setLatestActivationTime(String latestActivationTime) { this.latestActivationTime = latestActivationTime; return this; } /** * Output only. The resource name of the manual trigger. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Output only. The resource name of the manual trigger. * @param name name or {@code null} for none */ public ManualTrigger setName(java.lang.String name) { this.name = name; return this; } /** * Output only. The state of the manual trigger. Will be set to the `INACTIVE` state upon * creation. * @return value or {@code null} for none */ public java.lang.String getState() { return state; } /** * Output only. The state of the manual trigger. Will be set to the `INACTIVE` state upon * creation. * @param state state or {@code null} for none */ public ManualTrigger setState(java.lang.String state) { this.state = state; return this; } /** * Output only. The unique ID of the manual trigger. * @return value or {@code null} for none */ public java.lang.Long getTriggerId() { return triggerId; } /** * Output only. The unique ID of the manual trigger. * @param triggerId triggerId or {@code null} for none */ public ManualTrigger setTriggerId(java.lang.Long triggerId) { this.triggerId = triggerId; return this; } @Override public ManualTrigger set(String fieldName, Object value) { return (ManualTrigger) super.set(fieldName, value); } @Override public ManualTrigger clone() { return (ManualTrigger) super.clone(); } }
2,116
530
<reponame>ajaybhat/strongbox package org.carlspring.strongbox.providers.layout; import java.io.IOException; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.commons.codec.digest.MessageDigestAlgorithms; import org.carlspring.strongbox.artifact.coordinates.NpmArtifactCoordinates; import org.carlspring.strongbox.providers.io.RepositoryFileAttributeType; import org.carlspring.strongbox.providers.io.RepositoryFiles; import org.carlspring.strongbox.providers.io.RepositoryPath; import org.carlspring.strongbox.repository.NpmRepositoryFeatures; import org.carlspring.strongbox.repository.NpmRepositoryManagementStrategy; import org.carlspring.strongbox.repository.RepositoryManagementStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * @author <NAME> */ @Component public class NpmLayoutProvider extends AbstractLayoutProvider<NpmArtifactCoordinates> { private static final Logger logger = LoggerFactory.getLogger(NpmLayoutProvider.class); public static final String ALIAS = NpmArtifactCoordinates.LAYOUT_NAME; public static final String NPM_USER_PATH = "-/user/org.couchdb.user:"; public static final Pattern NPM_URL_USERNAME_PATTERN = Pattern.compile( "(?:" + NpmLayoutProvider.NPM_USER_PATH + ")(.*)"); @Inject private NpmRepositoryManagementStrategy npmRepositoryManagementStrategy; @Inject private NpmRepositoryFeatures npmRepositoryFeatures; @PostConstruct public void register() { logger.info("Registered layout provider '{}' with alias '{}'.", getClass().getCanonicalName(), ALIAS); } protected NpmArtifactCoordinates getArtifactCoordinates(RepositoryPath path) throws IOException { return NpmArtifactCoordinates.parse(RepositoryFiles.relativizePath(path)); } public boolean isArtifactMetadata(RepositoryPath path) { return path.getFileName().toString().endsWith("package.json"); } public boolean isNpmMetadata(RepositoryPath path) { return path.getFileName().toString().endsWith("package-lock.json") || path.getFileName().toString().endsWith("npm-shrinkwrap.json"); } @Override protected Map<RepositoryFileAttributeType, Object> getRepositoryFileAttributes(RepositoryPath repositoryPath, RepositoryFileAttributeType... attributeTypes) throws IOException { Map<RepositoryFileAttributeType, Object> result = super.getRepositoryFileAttributes(repositoryPath, attributeTypes); for (RepositoryFileAttributeType attributeType : attributeTypes) { Object value = result.get(attributeType); switch (attributeType) { case ARTIFACT: value = (Boolean) value && !isNpmMetadata(repositoryPath); if (value != null) { result.put(attributeType, value); } break; case METADATA: value = (Boolean) value || isNpmMetadata(repositoryPath); if (value != null) { result.put(attributeType, value); } break; default: break; } } return result; } @Override public RepositoryManagementStrategy getRepositoryManagementStrategy() { return npmRepositoryManagementStrategy; } @Override public Set<String> getDefaultArtifactCoordinateValidators() { return npmRepositoryFeatures.getDefaultArtifactCoordinateValidators(); } @Override public String getAlias() { return ALIAS; } @Override public Set<String> getDigestAlgorithmSet() { return Stream.of(MessageDigestAlgorithms.SHA_1) .collect(Collectors.toSet()); } }
1,876
713
package org.infinispan.search.mapper.mapping.impl; import org.hibernate.search.engine.mapper.mapping.building.spi.MappingKey; import org.infinispan.search.mapper.log.impl.InfinispanEventContextMessages; import org.infinispan.search.mapper.mapping.SearchMapping; import org.jboss.logging.Messages; public final class InfinispanMappingKey implements MappingKey<InfinispanMappingPartialBuildState, SearchMapping> { private static final InfinispanEventContextMessages MESSAGES = Messages.getBundle(InfinispanEventContextMessages.class); @Override public String render() { return MESSAGES.mapping(); } }
216
1,511
<reponame>s4-2/scancode-toolkit<filename>tests/cluecode/data/ics/freetype-src-base/ftlcdfil.c /* */ /* FreeType API for color filtering of subpixel bitmap glyphs (body). */ /* */ /* Copyright 2006, 2008, 2009, 2010 by */ /* <NAME>, <NAME>, and <NAME>. */ /* */
375
2,151
// 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 CHROME_BROWSER_UI_VIEWS_FRAME_GLOBAL_MENU_BAR_REGISTRAR_X11_H_ #define CHROME_BROWSER_UI_VIEWS_FRAME_GLOBAL_MENU_BAR_REGISTRAR_X11_H_ #include <gio/gio.h> #include <set> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "ui/base/glib/glib_signal.h" // Advertises our menu bars to Unity. // // GlobalMenuBarX11 is responsible for managing the DbusmenuServer for each // XID. We need a separate object to own the dbus channel to // com.canonical.AppMenu.Registrar and to register/unregister the mapping // between a XID and the DbusmenuServer instance we are offering. class GlobalMenuBarRegistrarX11 { public: static GlobalMenuBarRegistrarX11* GetInstance(); void OnWindowMapped(unsigned long xid); void OnWindowUnmapped(unsigned long xid); private: friend struct base::DefaultSingletonTraits<GlobalMenuBarRegistrarX11>; GlobalMenuBarRegistrarX11(); ~GlobalMenuBarRegistrarX11(); // Sends the actual message. void RegisterXID(unsigned long xid); void UnregisterXID(unsigned long xid); CHROMEG_CALLBACK_1(GlobalMenuBarRegistrarX11, void, OnProxyCreated, GObject*, GAsyncResult*); CHROMEG_CALLBACK_1(GlobalMenuBarRegistrarX11, void, OnNameOwnerChanged, GObject*, GParamSpec*); GDBusProxy* registrar_proxy_; // Window XIDs which want to be registered, but haven't yet been because // we're waiting for the proxy to become available. std::set<unsigned long> live_xids_; DISALLOW_COPY_AND_ASSIGN(GlobalMenuBarRegistrarX11); }; #endif // CHROME_BROWSER_UI_VIEWS_FRAME_GLOBAL_MENU_BAR_REGISTRAR_X11_H_
661
590
package hype.interfaces; public interface HDirectable extends HLocatable, HRotatable {}
23
327
<filename>analysis/correspondence/visualize_correspondence.py # Copyright (c) ByteDance, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import os import argparse import torch import torchvision import torch.nn as nn import numpy as np import random import matplotlib.pyplot as plt import utils import torchvision.transforms.functional as TF import models from PIL import Image, ImageDraw, ImageFile from tqdm import tqdm from torchvision import transforms from torch.utils.data import DataLoader, Sampler from loader import ImageFolderInstance ImageFile.LOAD_TRUNCATED_IMAGES = True def main(): parser = argparse.ArgumentParser("Visualize Correspondence") parser.add_argument('--arch', default='vit_small', type=str, choices=['vit_tiny', 'vit_small', 'vit_base', 'vit_large', 'swin_tiny','swin_small', 'swin_base', 'swin_large'], help='Architecture.') parser.add_argument('--data_path', default='/path/to/imagenet/val/', type=str, help='Path of the images\' folder.') parser.add_argument("--pretrained_weights", type=str, default="", help="the pretraining models") parser.add_argument("--batch_size", type=int, default=2, help="batch size") parser.add_argument("--patch_size", type=int, default=16, help="patch size") parser.add_argument("--img_size", type=int, default=224, help="image size") parser.add_argument("--output_path", type=str, default='pics/', help="patch for output images") parser.add_argument("--topk", type=int, default=12, help="top k matched pairs") parser.add_argument("--show_pics", type=utils.bool_flag, default=True) parser.add_argument("--show_with_attn", type=utils.bool_flag, default=False) parser.add_argument("--show_nums", type=int, default=100) parser.add_argument("--sample_type", type=str, default='class', choices=['class', 'instance'], help="""sample pairs from the same class or from one instance (two views)""") parser.add_argument("--eval_radius", type=int, default=0) args = parser.parse_args() torch.manual_seed(1) np.random.seed(1) random.seed(1) device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") # for attention attentioner = models.__dict__['vit_base'](patch_size=8, num_classes=0) print("We load the reference pretrained DINO weights to extract self-attention for fair comparison.") state_dict = torch.hub.load_state_dict_from_url(url="https://dl.fbaipublicfiles.com/dino/" + "dino_vitbase8_pretrain/dino_vitbase8_pretrain.pth") attentioner.load_state_dict(state_dict, strict=True) attentioner.eval() attentioner.to(device) network = models.__dict__[args.arch]( patch_size=args.patch_size, return_all_tokens=True, ) network.eval() network.to(device) if os.path.isfile(args.pretrained_weights): state_dict = torch.load(args.pretrained_weights, map_location="cpu")['state_dict'] # remove `module.` prefix state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()} # remove `backbone.` prefix induced by multicrop wrapper state_dict = {k.replace("backbone.", ""): v for k, v in state_dict.items()} msg = network.load_state_dict(state_dict, strict=False) print('Pretrained weights found at {} and loaded with msg: {}'.format(args.pretrained_weights, msg)) if args.sample_type == 'class': augmentation = transforms.Compose([ transforms.Resize((args.img_size, args.img_size)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) else: class RandomResizedCrop(transforms.RandomResizedCrop): def forward(self, img): i, j, h, w = self.get_params(img, self.scale, self.ratio) W, H = TF._get_image_size(img) self.corner = np.array([i / H, j / W, (i + h) / H, (j + w) / W]) return TF.resized_crop(img, i, j, h, w, self.size, self.interpolation) class RandomHorizontalFlip(transforms.RandomHorizontalFlip): def forward(self, img): self.flip = False if torch.rand(1) < self.p: self.flip = True return TF.hflip(img) return img class Augmentation(object): def __init__(self, img_size): color_jitter = transforms.Compose([ transforms.RandomApply( [transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.2, hue=0.1)], p=0.8 ), transforms.RandomGrayscale(p=0.2), ]) normalize = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), ]) # first global crop self.global_transfo1 = transforms.Compose([ RandomResizedCrop(img_size, scale=(0.4, 1.0), interpolation=Image.BICUBIC), RandomHorizontalFlip(p=0.5), color_jitter, normalize, ]) # second global crop self.global_transfo2 = transforms.Compose([ RandomResizedCrop(img_size, scale=(0.4, 1.0), interpolation=Image.BICUBIC), RandomHorizontalFlip(p=0.5), color_jitter, normalize, ]) def __call__(self, image): crops = [] corners = [] # im1 crops.append(self.global_transfo1(image)) corner1 = self.global_transfo1.transforms[0].corner if self.global_transfo1.transforms[1].flip: corner1[1], corner1[3] = corner1[3], corner1[1] corners.append(corner1) # im2 crops.append(self.global_transfo2(image)) corner2 = self.global_transfo2.transforms[0].corner if self.global_transfo2.transforms[1].flip: corner2[1], corner2[3] = corner2[3], corner2[1] corners.append(corner2) return crops + corners augmentation = Augmentation(args.img_size) if args.sample_type == 'class': class CustomSampler(Sampler): def __init__(self, data): self.data = data def __iter__(self): indices = [] for n in range(self.data.num_classes): index = torch.where(self.data.label == n)[0] indices.append(index) indices = torch.cat(indices, dim=0) return iter(indices) def __len__(self): return len(self.data) class CustomBatchSampler: def __init__(self, sampler, batch_size, shuffle, drop_last): self.sampler = sampler self.batch_size = batch_size self.shuffle = shuffle self.drop_last = drop_last def __iter__(self): batch = [] i = 0 sampler_list = list(self.sampler) all_list = [] for idx in sampler_list: batch.append(idx) if len(batch) == self.batch_size: # yield batch all_list.append(batch) batch = [] if ( i < len(sampler_list) - 1 and self.sampler.data.label[idx] != self.sampler.data.label[sampler_list[i + 1]] ): if len(batch) > 0 and not self.drop_last: # yield batch all_list.append(batch) batch = [] else: batch = [] i += 1 if len(batch) > 0 and not self.drop_last: # yield batch all_list.append(batch) if self.shuffle: random.shuffle(all_list) for bs in all_list: yield bs def __len__(self): if self.drop_last: return len(self.sampler) // self.batch_size else: return (len(self.sampler) + self.batch_size - 1) // self.batch_size train_dataset = ImageFolderInstance(args.data_path, transform=lambda x: torch.Tensor(0)) train_dataloader = DataLoader(train_dataset, batch_size=2048, shuffle=False, num_workers=10, pin_memory=True, drop_last=False) labels = np.array([], dtype=np.int) for data in tqdm(train_dataloader): _, cls, idx = data labels = np.concatenate([labels, cls]) train_dataset.label = torch.Tensor(labels) train_dataset.num_classes = labels.max() - labels.min() + 1 batch_sampler = CustomBatchSampler(CustomSampler(train_dataset), batch_size=args.batch_size, shuffle=True, drop_last=True) train_dataset = ImageFolderInstance(args.data_path, transform=augmentation) train_dataloader = DataLoader(train_dataset, batch_sampler=batch_sampler, num_workers=4, pin_memory=True) else: train_dataset = ImageFolderInstance(args.data_path, transform=augmentation) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=4, pin_memory=True) cnt = 0 acc = [] for data in tqdm(train_dataloader): if args.sample_type == 'class': img, cls, idx = data img1 = img.clone() img2 = torch.cat([img[1:].clone(), img[0:1].clone()], dim=0) ovlp = None elif args.sample_type == 'instance': (img1, img2, pos1, pos2), cls, idx = data unit = args.img_size // args.patch_size pos1, pos2 = pos1.cpu().numpy(), pos2.cpu().numpy() pos1 = torch.stack(( torch.from_numpy(np.linspace(pos1[:, 0], pos1[:, 2], num=2*unit+1)[1::2]).unsqueeze(1).expand(-1, unit, -1), torch.from_numpy(np.linspace(pos1[:, 1], pos1[:, 3], num=2*unit+1)[1::2]).unsqueeze(0).expand(unit, -1, -1)) ).flatten(1, 2).permute(2, 1, 0).cuda() pos2 = torch.stack(( torch.from_numpy(np.linspace(pos2[:, 0], pos2[:, 2], num=2*unit+1)[1::2]).unsqueeze(1).expand(-1, unit, -1), torch.from_numpy(np.linspace(pos2[:, 1], pos2[:, 3], num=2*unit+1)[1::2]).unsqueeze(0).expand(unit, -1, -1)) ).flatten(1, 2).permute(2, 1, 0).cuda() eps = args.patch_size // 2 / args.img_size ovlp = ((pos1 + eps) > pos2.min(dim=1, keepdim=True)[0]).all(dim=-1) & \ ((pos1 - eps) < pos2.max(dim=1, keepdim=True)[0]).all(dim=-1) ovlp = ovlp.view(-1, 1, 14, 14) with torch.no_grad(): idx = idx.to(device) img1 = img1.to(device) img2 = img2.to(device) x1 = network(img1)[:, 1:] x2 = network(img2)[:, 1:] attentions = attentioner.get_last_selfattention(img1.to(device)) attentions = attentions[:, :, 0, 1:].view(x1.size(0), -1, args.img_size // 8, args.img_size // 8) attentions1 = nn.functional.interpolate(attentions, scale_factor=0.5, mode="nearest") if ovlp is not None: attentions1 = attentions1 * ovlp.float() attentions = attentions * nn.functional.interpolate(ovlp.float(), scale_factor=2, mode="nearest") attentions = attentions.mean(1, keepdim=True) attentions1 = attentions1.mean(1, keepdim=True) sim_matrix = torch.bmm(x1, x2.permute(0, 2, 1)) value, index = sim_matrix.max(-1) if args.sample_type == "instance": real_sim_matrix = torch.matmul(pos1, pos2.permute(0, 2, 1)) real_dst_matrix = pos1.square().sum(2, keepdim=True) + \ pos2.permute(0, 2, 1).square().sum(1, keepdim=True) - 2 * real_sim_matrix real_index = real_dst_matrix.min(dim=2)[1] index_h, index_w = index // unit, index % unit real_index_h, real_index_w = real_index // unit, real_index % unit accuracy = (((index_h - real_index_h).abs() <= args.eval_radius) & ((index_w - real_index_w).abs() <= args.eval_radius) & ovlp.flatten(1)).sum() / ovlp.sum() acc.append(accuracy) if args.show_pics: for cs, id, val, im1, im2, attention, attention1, in zip(cls, index, value, img1, img2, attentions, attentions1): for nh in range(attention.size(0)): attn = attention[nh] attn1 = attention1[nh].flatten() st = attn1.topk(args.topk)[1] point1 = st point2 = id[st] i1 = torchvision.utils.make_grid(im1, normalize=True, scale_each=True) i1 = Image.fromarray(i1.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()) i2 = torchvision.utils.make_grid(im2, normalize=True, scale_each=True) i2 = Image.fromarray(i2.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()) if args.show_with_attn: img = Image.new('RGB', (args.img_size * 3, args.img_size)) else: img = Image.new('RGB', (args.img_size * 2, args.img_size)) draw = ImageDraw.Draw(img) unit = args.img_size // args.patch_size if args.show_with_attn: attn = nn.functional.interpolate(attn.detach()[None, None], scale_factor=8, mode="nearest")[0, 0].cpu().numpy() plt.imsave(fname=f'{args.output_path}/temp_attn.png', arr=attn, format='png') img.paste(Image.open(f'{args.output_path}/temp_attn.png'), (0, 0)) img.paste(i1, (args.img_size, 0)) img.paste(i2, (args.img_size * 2, 0)) else: img.paste(i1, (0, 0)) img.paste(i2, (args.img_size, 0)) for p1, p2 in zip(point1, point2): p1y, p1x = p1 // unit + 0.5, p1 % unit + 0.5 p2y, p2x = p2 // unit + 0.5, p2 % unit + 0.5 draw.line((p1x * args.patch_size + args.img_size * (1 if args.show_with_attn else 0), p1y * args.patch_size, p2x * args.patch_size + args.img_size * (2 if args.show_with_attn else 1), p2y * args.patch_size), width=1, fill='red') img.save(f'{args.output_path}/{args.sample_type}_corresp{cnt}_cls{cs}_nh{nh}.png') cnt += 1 if cnt >= args.show_nums: exit() if args.sample_type == "instance": print(sum(acc) / len(acc)) if __name__ == '__main__': main()
8,116
356
#include "ply.h" #include <candle.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #define MAX_WORD 4095 enum value_type { PLY_NONE, PLY_FLOAT, PLY_DOUBLE, PLY_UCHAR, PLY_CHAR, PLY_INT8, PLY_INT, PLY_UINT8, PLY_UINT, PLY_LONG, PLY_ULONG, PLY_LIST }; struct type_info { char name[32]; enum value_type type; char format[16]; }; static struct type_info g_types[] = { {"float", PLY_FLOAT, " %lf"}, {"float32", PLY_FLOAT, " %lf"}, {"float64", PLY_DOUBLE, " %lf"}, {"double", PLY_DOUBLE, " %lf"}, {"uchar", PLY_UCHAR, " %c"}, {"char", PLY_CHAR, " %c"}, {"int8", PLY_INT8, " %ld"}, {"int32", PLY_INT, " %ld"}, {"int", PLY_INT, " %ld"}, {"int64", PLY_LONG, " %ld"}, {"uint8", PLY_UINT8, " %ld"}, {"uint32", PLY_UINT, " %ld"}, {"uint", PLY_UINT, " %ld"}, {"uint64", PLY_ULONG, " %ld"}, {"list", PLY_LIST}, {"", PLY_NONE} }; typedef struct { char chars[MAX_WORD + 1]; } ply_word_t; /* ////////////////////////////////////////////////////////////////////////// */ /* .PLY LOADER */ /* ////////////////////////////////////////////////////////////////////////// */ static ply_word_t *get_words(FILE *fp, int *nwords) { #define _WORD_FORMAT(mx) " %" #mx "s" #define WORD_FORMAT(mx) _WORD_FORMAT(mx) unsigned int i; ply_word_t *words; int num_words = 0; char word[MAX_WORD + 1]; while(fscanf(fp, WORD_FORMAT(MAX_WORD), word) == 1) { num_words++; } rewind(fp); words = malloc(sizeof(ply_word_t) * num_words); for(i = 0; i < num_words; i++) { if(fscanf(fp, WORD_FORMAT(MAX_WORD), words[i].chars) == -1) { words[i].chars[0] = '\0'; } } *nwords = num_words; return words; } static int get_type(const char *name) { unsigned int i; for(i = 0;; i++) { struct type_info type = g_types[i]; if(type.type == PLY_NONE) return -1; if(!strncmp(g_types[i].name, name, sizeof(g_types[i].name))) return i; } return -1; } void mesh_load_ply(mesh_t *self, const char *filename) { unsigned int i; int nwords; ply_word_t *words; ply_word_t *word; FILE *fp; struct property { char name[32]; int type, list_count_type, list_element_type; }; struct element_type { char name[32]; struct property props[10]; int props_num; int num; }; struct element_type *elements = NULL; int elements_num = 0; int file_type = 0; strncpy(self->name, filename, sizeof(self->name) - 1); fp = fopen(filename, "r"); if (!fp) { printf("Could not find object '%s'\n", filename); return; } #define FORMAT_ASCII 0x01 #define FORMAT_BINARY_BE 0x02 #define FORMAT_BINARY_LE 0x03 words = get_words(fp, &nwords); if(!words || !!strcmp(words[0].chars, "ply")) { printf("Couldn't parse words in ply %s.\n", filename); exit(1); } /* READ HEADER */ for(word = words; word->chars[0];) { if(!strcmp(word[0].chars, "format")) { word++; if(!strcmp(word->chars, "ascii")) { file_type = FORMAT_ASCII; } else if(!strcmp(word->chars, "binary_big_endian")) { file_type = FORMAT_BINARY_BE; } else if(!strcmp(word->chars, "binary_little_endian")) { file_type = FORMAT_BINARY_LE; } else { printf("Unknown ply format.\n"); exit(1); } /* word[1] is version */ word++; } else if(!strcmp(word->chars, "element")) { struct element_type *el; word++; i = elements_num++; elements = realloc(elements, sizeof(*elements) * elements_num); el = &elements[i]; el->props_num = 0; strncpy(el->name, word->chars, sizeof(el->name) - 1); word++; if(sscanf(word->chars, "%d", &el->num) < 0) { printf("Failed to parse ply.\n"); exit(1); } word++; while(!strcmp(word->chars, "property")) { struct property *props; word++; props = &el->props[el->props_num]; el->props_num++; props->type = get_type(word->chars); word++; if(g_types[props->type].type == PLY_LIST) { props->list_count_type = get_type(word->chars); word++; props->list_element_type = get_type(word->chars); word++; } strncpy(props->name, word->chars, sizeof(props->name) - 1); word++; } } else if(!strcmp(word->chars, "end_header")) { word++; break; } else word++; } /* READ DATA */ if(file_type != FORMAT_ASCII) { printf("Format not yet supported.\n"); exit(1); } for(i = 0; i < elements_num; i++) { struct element_type *el = &elements[i]; int vertex = !strcmp(el->name, "vertex"); int face = !strcmp(el->name, "face"); unsigned int j, k; for(j = 0; j < el->num; j++) { double x, y, z; unsigned long count; unsigned long id[4]; for(k = 0; k < el->props_num; k++) { struct property *prop = &el->props[k]; struct type_info *type = &g_types[prop->type]; if(type->type == PLY_LIST) { if(face) { unsigned long c; struct type_info *count_type = &g_types[prop->list_count_type]; struct type_info *list_type = &g_types[prop->list_element_type]; sscanf((word++)->chars, count_type->format, &count); for(c = 0; c < count; c++) { sscanf((word++)->chars, list_type->format, &id[c]); } } } else { if(vertex) { if(!strcmp(prop->name, "x")) { sscanf(word->chars, type->format, &x); } if(!strcmp(prop->name, "y")) { sscanf(word->chars, type->format, &y); } if(!strcmp(prop->name, "z")) { sscanf(word->chars, type->format, &z); } word++; } } } if(vertex) mesh_add_vert(self, VEC3((float)x, (float)y, (float)z)); if(face) { vec3_t z3 = vec3(0.0f, 0.0f, 0.0f); vec2_t z2 = vec2(0.0f, 0.0f); if(count == 4) { mesh_add_quad(self, id[0], z3, z2, id[1], z3, z2, id[2], z3, z2, id[3], z3, z2); } else { mesh_add_triangle(self, id[0], z3, z2, id[1], z3, z2, id[2], z3, z2); } } } } self->has_texcoords = 0; free(elements); free(words); fclose(fp); }
3,111
5,169
{ "name": "SwiftFunnyAnimations", "version": "0.1.0", "summary": "For now only 2 simple animations set.", "description": "Its simple set of particle animations for iOS in swift 4.0", "homepage": "https://github.com/mmachado53/SwiftFunnyAnimations", "screenshots": "https://raw.githubusercontent.com/mmachado53/SwiftFunnyAnimations/develop/readmefiles/1.gif", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "mmachado53": "<EMAIL>" }, "source": { "git": "https://github.com/mmachado53/SwiftFunnyAnimations.git", "tag": "0.1.0" }, "platforms": { "ios": "8.0" }, "swift_versions": "4.0", "source_files": "SwiftFunnyAnimations/Classes/**/*", "swift_version": "4.0" }
300
2,291
<reponame>M-i-k-e-l/osmdroid<filename>issues/osmdroid_issue187.json { "id" : 187, "status" : "Invalid", "summary" : "DefaultResourceProxyImpl is broken?", "labels" : [ "Type-Defect", "Priority-Medium" ], "stars" : 0, "commentCount" : 3, "comments" : [ { "id" : 0, "commenterId" : 7646092065249173135, "content" : "I can't get DefaultResourceProxyImpl to work for me. It always says that the resource is not found. This includes when I try to use it in the samples (instead of the ResourceProxyImpl).\r\n\r\nI tried a few things to get it to work, but it always can't find the resource in the JAR. Anyone else have this issue? or a solution?", "timestamp" : 1300678483, "attachments" : [ ] }, { "id" : 1, "commenterId" : 7646092065249173135, "content" : "I'm sorry, I should be more specific. What doesn't work is loading Bitmaps. Specifically, this line (106):\r\n\r\nis = getClass().getResourceAsStream(resName);\r\n\r\nIn the debugger I've tried:\r\ngetClass().getResourceAsStream(\"center.png\");\r\ngetClass().getResourceAsStream(\"/center.png\");\r\ngetClass().getResourceAsStream(\"\\\\center.png\");\r\n\r\nand they all return null.", "timestamp" : 1300678888, "attachments" : [ ] }, { "id" : 2, "commenterId" : 7646092065249173135, "content" : "Never mind - this is because the OpenStreetMapViewer project doesn't use the JAR file, so it fails. When you use the JAR proper, it works.", "timestamp" : 1300679970, "attachments" : [ ] } ] }
562
407
<gh_stars>100-1000 import sys si = sys.stdin.readline n = int(si()) a= [0] * n for i in range(n): a[i] = int(si()) dy = [[0, 0] for _ in range(n + 2)] # 초기값 채우기 dy[0][0], dy[0][1] = 0, a[0] if n >= 2: dy[1][0], dy[1][1] = a[1], a[0] + a[1] # 점화식을 토대로 dy 배열 채우기 for i in range(2, n): dy[i][0] = max(dy[i - 2][0] + a[i], dy[i - 2][1] + a[i]) dy[i][1] = dy[i - 1][0] + a[i] print(max(dy[n - 1][0], dy[n - 1][1]))
291
312
//----------------------------------------------------------------------------- // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include <plugins/plugins_shared.h> #include "Foliage.h" #include <sim/simObject.h> #include <3d/rendering/common.h> #include <graphics/core.h> #include <bx/fpumath.h> F32 mTransformMatrix[16]; bgfx::ProgramHandle mShader; Rendering::RenderData* mRenderData = NULL; bgfx::TextureHandle mTexture = BGFX_INVALID_HANDLE; Vector<Rendering::InstanceData> mInstanceData; Vector<Rendering::TextureData> mTextureData; using namespace Plugins; // Called when the plugin is loaded. void create(PluginLink _link) { bx::mtxIdentity(mTransformMatrix); Link.Con.addCommand("Foliage", "load", loadModel, "", 2, 2); } void destroy() { } void loadModel(SimObject *obj, S32 argc, const char *argv[]) { // Load skybox texture. MeshAsset* mesh = Link.Scene.getMeshAsset(argv[1]); if ( mesh ) { Link.Con.printf("Found Mesh Successfully!"); // Load Shader Graphics::ShaderAsset* particleShaderAsset = Plugins::Link.Graphics.getShaderAsset("Foliage:grassShader"); if ( particleShaderAsset ) mShader = particleShaderAsset->getProgram(); // Load Texture TextureObject* texture_obj = Plugins::Link.Graphics.loadTexture("grass01_diffuse.png", TextureHandle::BitmapKeepTexture, false, false, false); if ( texture_obj ) mTexture = texture_obj->getBGFXTexture(); if ( mRenderData == NULL ) mRenderData = Plugins::Link.Rendering.createRenderData(); mRenderData->indexBuffer = mesh->getIndexBuffer(0); mRenderData->vertexBuffer = mesh->getVertexBuffer(0); // Render in Forward (for now) with our custom terrain shader. mRenderData->shader = mShader; mRenderData->view = Plugins::Link.Graphics.getView("TransparencyBuffer", "", false); mRenderData->state = 0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE) | BGFX_STATE_BLEND_INDEPENDENT; mRenderData->stateRGBA = 0 | BGFX_STATE_BLEND_FUNC_RT_1(BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_INV_SRC_ALPHA); // Transform of emitter. mRenderData->transformTable = &mTransformMatrix[0]; mRenderData->transformCount = 1; // Instances mInstanceData.clear(); for(S32 x = -100; x < 100; ++x) { for(S32 y = -100; y < 100; ++y) { Rendering::InstanceData grassInstance; F32 instScale = mRandF(0.5f, 1.5f); F32 instRot = mRandF(0.0f, 3.14f); F32 instMat[16]; bx::mtxSRT(instMat, instScale, instScale, instScale, 1.57f, instRot, 0.0f, x * 20.0f, 0.0f, y * 20.0f); grassInstance.i_data0.set(instMat[0], instMat[1], instMat[2], instMat[3]); grassInstance.i_data1.set(instMat[4], instMat[5], instMat[6], instMat[7]); grassInstance.i_data2.set(instMat[8], instMat[9], instMat[10], instMat[11]); grassInstance.i_data3.set(instMat[12], instMat[13], instMat[14], instMat[15]); mInstanceData.push_back(grassInstance); } } mRenderData->instances = &mInstanceData; // Textures mTextureData.clear(); mRenderData->textures = &mTextureData; Rendering::TextureData* texture = mRenderData->addTexture(); texture->handle = mTexture; texture->uniform = Plugins::Link.Graphics.getTextureUniform(0); } }
1,849
1,738
<reponame>jeikabu/lumberyard<filename>dev/Code/Sandbox/Plugins/MaglevControlPanel/QBackgroundLambda.h /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <QObject> #include <QThread> #include <QWidget> #include <functional> class AwsResultWrapper { public: AwsResultWrapper() = default; AwsResultWrapper(const QString& objectName, std::function<void()> applyResult) : m_objectName(objectName) , m_applyLambda(applyResult) {} AwsResultWrapper(const AwsResultWrapper& rhs) = default; ~AwsResultWrapper() = default; void Apply(const QString& currentObjectName) { if (currentObjectName == m_objectName) { m_applyLambda(); } } const QString& GetObjectName() const { return m_objectName; } private: QString m_objectName; std::function<void()> m_applyLambda; }; class QBackgroundLambdaBase : public QObject { Q_OBJECT public: QBackgroundLambdaBase() {} virtual ~QBackgroundLambdaBase() {} public slots: void Run() { Execute(); } signals: void finished(); void OnError(const QString& objectName, const QString& error); void OnSuccess(const QString& objectName); void OnSuccessApply(AwsResultWrapper result); protected: virtual void Execute() = 0; }; class QAwsObjectBackgroundLambda : public QBackgroundLambdaBase { public: QAwsObjectBackgroundLambda(const QString& objectName, std::function<void(QString&)> lambda) : m_objectName(objectName) , m_lambda(lambda) {} virtual ~QAwsObjectBackgroundLambda() {} protected: virtual void Execute() { QString errorMessage; m_lambda(errorMessage); if (!errorMessage.isEmpty()) { OnError(m_objectName, errorMessage); } else { OnSuccess(m_objectName); } finished(); } private: QString m_objectName; std::function<void(QString&)> m_lambda; }; template< typename T > class QAwsApplyResultBackgroundLambda : public QBackgroundLambdaBase { public: using GetLambdaType = std::function<T (QString&)>; using ApplyLambdaType = std::function<void(const T&)>; QAwsApplyResultBackgroundLambda(const QString& objectName, GetLambdaType getLambda, ApplyLambdaType applyLambda) : m_objectName(objectName) , m_getLambda(getLambda) , m_applyLambda(applyLambda) {} virtual ~QAwsApplyResultBackgroundLambda() {} protected: virtual void Execute() { QString errorMessage; T result = m_getLambda(errorMessage); if (!errorMessage.isEmpty()) { OnError(m_objectName, errorMessage); } else { auto lambdaCopy = m_applyLambda; auto signalLambda = [=](){lambdaCopy(result); }; AwsResultWrapper wrapper(m_objectName, signalLambda); OnSuccessApply(wrapper); } finished(); } private: QString m_objectName; GetLambdaType m_getLambda; ApplyLambdaType m_applyLambda; }; void RunBackgroundLambda(QBackgroundLambdaBase* backgroundTask);
1,467
875
<reponame>christeoh/sqoop<filename>src/java/org/apache/sqoop/manager/SqlServerManagerContextConfigurator.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 * <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 org.apache.sqoop.manager; import org.apache.hadoop.conf.Configuration; import org.apache.sqoop.SqoopOptions; import org.apache.sqoop.mapreduce.SQLServerResilientExportOutputFormat; import org.apache.sqoop.mapreduce.SQLServerResilientUpdateOutputFormat; import org.apache.sqoop.mapreduce.db.SQLServerConnectionFailureHandler; import org.apache.sqoop.mapreduce.db.SQLServerDBInputFormat; import org.apache.sqoop.mapreduce.sqlserver.SqlServerExportBatchOutputFormat; public class SqlServerManagerContextConfigurator { public static final String RESILIENT_OPTION = "resilient"; /** * Check if the user has requested the operation to be resilient. */ private boolean isResilientOperation(SqoopOptions options) { String [] extraArgs = options.getExtraArgs(); if (extraArgs != null) { // Traverse the extra options for (int iArg = 0; iArg < extraArgs.length; ++iArg) { String currentArg = extraArgs[iArg]; if (currentArg.startsWith("--") && currentArg.substring(2).equalsIgnoreCase(RESILIENT_OPTION)) { // User has explicitly requested the operation to be resilient return true; } } } return false; } public void configureContextForExport(ExportJobContext context) { if (isResilientOperation(context.getOptions())) { context.setOutputFormatClass(SQLServerResilientExportOutputFormat.class); configureConnectionRecoveryForExport(context); } else { context.setOutputFormatClass(SqlServerExportBatchOutputFormat.class); } } /** * Configure SQLServer Sqoop export Jobs to recover failed connections by * using {@link SQLServerConnectionFailureHandler}. This can be overridden by setting the * {@link SQLServerResilientExportOutputFormat#EXPORT_FAILURE_HANDLER_CLASS} in the configuration. */ private void configureConnectionRecoveryForExport( ExportJobContext context) { Configuration conf = context.getOptions().getConf(); // Set connection failure handler and recovery settings // Can be overridden if provided as Configuration // properties by the user String clsFailureHandler = conf.get( SQLServerResilientExportOutputFormat.EXPORT_FAILURE_HANDLER_CLASS); if (clsFailureHandler == null) { conf.set( SQLServerResilientExportOutputFormat.EXPORT_FAILURE_HANDLER_CLASS, SQLServerConnectionFailureHandler.class.getName()); } } /** * Configure SQLServer Sqoop Jobs to recover failed connections by using * {@link SQLServerConnectionFailureHandler}. This can be overridden by setting the * {@link SQLServerDBInputFormat#IMPORT_FAILURE_HANDLER_CLASS} in the configuration. */ private void configureConnectionRecoveryForImport( ImportJobContext context) { Configuration conf = context.getOptions().getConf(); // Configure input format class context.setInputFormat(SQLServerDBInputFormat.class); // Set connection failure handler and recovery settings // Can be overridden if provided as Configuration // properties by the user if (conf.get(SQLServerDBInputFormat.IMPORT_FAILURE_HANDLER_CLASS) == null) { conf.set(SQLServerDBInputFormat.IMPORT_FAILURE_HANDLER_CLASS, SQLServerConnectionFailureHandler.class.getName()); } } public void configureContextForImport(ImportJobContext context, String splitCol) { if (isResilientOperation(context.getOptions())) { // Enable connection recovery only if split column is provided if (splitCol != null) { // Configure SQLServer table import jobs for connection recovery configureConnectionRecoveryForImport(context); } } } /** * * @param context * @param manager * @return whether the job should be executed as an exportjob */ public boolean configureContextForUpdate(ExportJobContext context, SQLServerManager manager) { boolean runAsExportJob = isResilientOperation(context.getOptions()); if (runAsExportJob) { context.setConnManager(manager); context.setOutputFormatClass(SQLServerResilientUpdateOutputFormat.class); configureConnectionRecoveryForExport(context); } return runAsExportJob; } }
1,626
372
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.driveactivity.v2.model; /** * A known user. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Drive Activity API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class KnownUser extends com.google.api.client.json.GenericJson { /** * True if this is the user making the request. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean isCurrentUser; /** * The identifier for this user that can be used with the People API to get more information. The * format is `people/ACCOUNT_ID`. See https://developers.google.com/people/. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String personName; /** * True if this is the user making the request. * @return value or {@code null} for none */ public java.lang.Boolean getIsCurrentUser() { return isCurrentUser; } /** * True if this is the user making the request. * @param isCurrentUser isCurrentUser or {@code null} for none */ public KnownUser setIsCurrentUser(java.lang.Boolean isCurrentUser) { this.isCurrentUser = isCurrentUser; return this; } /** * The identifier for this user that can be used with the People API to get more information. The * format is `people/ACCOUNT_ID`. See https://developers.google.com/people/. * @return value or {@code null} for none */ public java.lang.String getPersonName() { return personName; } /** * The identifier for this user that can be used with the People API to get more information. The * format is `people/ACCOUNT_ID`. See https://developers.google.com/people/. * @param personName personName or {@code null} for none */ public KnownUser setPersonName(java.lang.String personName) { this.personName = personName; return this; } @Override public KnownUser set(String fieldName, Object value) { return (KnownUser) super.set(fieldName, value); } @Override public KnownUser clone() { return (KnownUser) super.clone(); } }
947
1,870
# model settings model = dict( type='Recognizer2D', backbone=dict( type='MobileNetV2TSM', shift_div=8, num_segments=8, is_shift=True, pretrained='mmcls://mobilenet_v2'), cls_head=dict( type='TSMHead', num_segments=8, num_classes=400, in_channels=1280, spatial_type='avg', consensus=dict(type='AvgConsensus', dim=1), dropout_ratio=0.5, init_std=0.001, is_shift=True), # model training and testing settings train_cfg=None, test_cfg=dict(average_clips='prob'))
305
2,291
<reponame>elkuku/osmdroid<gh_stars>1000+ package org.osmdroid.views.overlay.milestones; import org.osmdroid.util.Distance; import org.osmdroid.views.util.constants.MathConstants; /** * Listing every given meters of the `Path` * Created by Fabrice on 28/12/2017. * * @since 6.0.0 */ public class MilestoneMeterDistanceLister extends MilestoneLister { private final double mNbMetersRecurrence; private double mDistance; private int mIndex; /** * @since 6.0.3 */ private final double[] mMilestoneMeters; private int mMilestoneMetersIndex; private double mNeededForNext; // handling last milestone's side effect (with all the roundings and double/float conversions) private boolean mSideEffectLastFlag; private double mSideEffectLastEpsilon = 1E-5; private long mSideEffectLastX; private long mSideEffectLastY; private double mSideEffectLastOrientation; /** * Use it if you want a milestone every x meters */ public MilestoneMeterDistanceLister(final double pNbMetersRecurrence) { mNbMetersRecurrence = pNbMetersRecurrence; mMilestoneMeters = null; } /** * @since 6.0.3 * Use it if you want milestones separated by different length (in meters) * All the distances are from the origin and must be increasing. * E.g for a marathon: [0, 10000, 20000, 21097, 30000, 40000, 42195] */ public MilestoneMeterDistanceLister(final double[] pMilestoneMeters) { mNbMetersRecurrence = 0; mMilestoneMeters = pMilestoneMeters; } @Override public void init() { super.init(); mDistance = 0; mIndex = 0; if (mMilestoneMeters != null) { mMilestoneMetersIndex = 0; } mNeededForNext = getNewNeededForNext(); mSideEffectLastFlag = false; } @Override protected void add(final long x0, final long y0, final long x1, final long y1) { mSideEffectLastFlag = false; if (mNeededForNext == -1) { return; } double currentDistance = getDistance(++mIndex); if (currentDistance == 0) { return; } final double pixelDistance = Math.sqrt(Distance.getSquaredDistanceToPoint(x0, y0, x1, y1)); final double metersToPixels = pixelDistance / currentDistance; final double orientation = getOrientation(x0, y0, x1, y1); double x = x0; double y = y0; while (true) { if (currentDistance < mNeededForNext) { mDistance += currentDistance; mNeededForNext -= currentDistance; mSideEffectLastFlag = true; mSideEffectLastX = x1; mSideEffectLastY = y1; mSideEffectLastOrientation = orientation; return; } mDistance += mNeededForNext; currentDistance -= mNeededForNext; x += mNeededForNext * Math.cos(MathConstants.DEG2RAD * orientation) * metersToPixels; y += mNeededForNext * Math.sin(MathConstants.DEG2RAD * orientation) * metersToPixels; add((long) x, (long) y, orientation); mNeededForNext = getNewNeededForNext(); if (mNeededForNext == -1) { return; } } } /** * @since 6.0.3 */ private double getNewNeededForNext() { if (mMilestoneMeters == null) { return mNbMetersRecurrence; } if (mMilestoneMetersIndex >= mMilestoneMeters.length) { return -1; } final double before = mMilestoneMetersIndex == 0 ? 0 : mMilestoneMeters[mMilestoneMetersIndex - 1]; final double needed = mMilestoneMeters[mMilestoneMetersIndex++] - before; if (needed < 0) { throw new IllegalArgumentException(); } return needed; } /** * @since 6.0.3 */ @Override public void end() { if (mSideEffectLastFlag && mNeededForNext < mSideEffectLastEpsilon) { add(mSideEffectLastX, mSideEffectLastY, mSideEffectLastOrientation); } super.end(); } /** * @since 6.0.3 */ public void setSideEffectLastEpsilon(final double pSideEffectLastEpsilon) { mSideEffectLastEpsilon = pSideEffectLastEpsilon; } /** * @since 6.0.3 */ private void add(final long pX, final long pY, final double pOrientation) { add(new MilestoneStep(pX, pY, pOrientation, mDistance)); } }
2,002
1,553
from __future__ import unicode_literals, print_function import argparse import codecs import os import re import os.path as op import io from io import open import sys from textwrap import dedent from .formats import get_file_extension from .time import make_time from .ssafile import SSAFile from .common import PY3, VERSION def positive_float(s): x = float(s) if not x > 0: raise argparse.ArgumentTypeError("%r is not a positive number" % s) return x def character_encoding(s): try: codecs.lookup(s) return s except LookupError: raise argparse.ArgumentError def time(s): d = {} for v, k in re.findall(r"(\d*\.?\d*)(ms|m|s|h)", s): d[k] = float(v) return make_time(**d) def change_ext(path, ext): base, _ = op.splitext(path) return base + ext class Pysubs2CLI(object): def __init__(self): parser = self.parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, prog="pysubs2", description=dedent(""" The pysubs2 CLI for processing subtitle files. https://github.com/tkarabela/pysubs2 """), epilog=dedent(""" usage examples: python -m pysubs2 --to srt *.ass python -m pysubs2 --to microdvd --fps 23.976 *.ass python -m pysubs2 --shift 0.3s *.srt python -m pysubs2 --shift 0.3s <my_file.srt >retimed_file.srt python -m pysubs2 --shift-back 0.3s --output-dir retimed *.srt python -m pysubs2 --transform-framerate 25 23.976 *.srt""")) parser.add_argument("files", nargs="*", metavar="FILE", help="Input subtitle files. Can be in SubStation Alpha (*.ass, *.ssa), SubRip (*.srt) or " "MicroDVD (*.sub) formats. When no files are specified, pysubs2 will work as a pipe, " "reading from standard input and writing to standard output.") parser.add_argument("-v", "--version", action="version", version="pysubs2 %s" % VERSION) parser.add_argument("-f", "--from", choices=["ass", "ssa", "srt", "microdvd", "json"], dest="input_format", help="By default, subtitle format is detected from the file. This option can be used to " "skip autodetection and force specific format. Generally, it should never be needed.") parser.add_argument("-t", "--to", choices=["ass", "ssa", "srt", "microdvd", "json"], dest="output_format", help="Convert subtitle files to given format. By default, each file is saved in its " "original format.") parser.add_argument("--input-enc", metavar="ENCODING", default="iso-8859-1", type=character_encoding, help="Character encoding for input files. By default, ISO-8859-1 is used for both " "input and output, which should generally work (for 8-bit encodings).") parser.add_argument("--output-enc", metavar="ENCODING", type=character_encoding, help="Character encoding for output files. By default, it is the same as input encoding. " "If you wish to convert between encodings, make sure --input-enc is set correctly! " "Otherwise, your output files will probably be corrupted. It's a good idea to " "back up your files or use the -o option.") parser.add_argument("--fps", metavar="FPS", type=positive_float, help="This argument specifies framerate for MicroDVD files. By default, framerate " "is detected from the file. Use this when framerate specification is missing " "or to force different framerate.") parser.add_argument("-o", "--output-dir", metavar="DIR", help="Use this to save all files to given directory. By default, every file is saved to its parent directory, " "ie. unless it's being saved in different subtitle format (and thus with different file extension), " "it overwrites the original file.") group = parser.add_mutually_exclusive_group() group.add_argument("--shift", metavar="TIME", type=time, help="Delay all subtitles by given time amount. Time is specified like this: '1m30s', '0.5s', ...") group.add_argument("--shift-back", metavar="TIME", type=time, help="The opposite of --shift (subtitles will appear sooner).") group.add_argument("--transform-framerate", nargs=2, metavar=("FPS1", "FPS2"), type=positive_float, help="Multiply all timestamps by FPS1/FPS2 ratio.") def __call__(self, argv): try: self.main(argv) except KeyboardInterrupt: exit("\nAborted by user.") def main(self, argv): args = self.parser.parse_args(argv) errors = 0 if args.output_dir and not op.exists(args.output_dir): os.makedirs(args.output_dir) if args.output_enc is None: args.output_enc = args.input_enc if args.files: for path in args.files: if not op.exists(path): print("Skipping", path, "(does not exist)") errors += 1 elif not op.isfile(path): print("Skipping", path, "(not a file)") errors += 1 else: with open(path, encoding=args.input_enc) as infile: subs = SSAFile.from_file(infile, args.input_format, args.fps) self.process(subs, args) if args.output_format is None: outpath = path output_format = subs.format else: ext = get_file_extension(args.output_format) outpath = change_ext(path, ext) output_format = args.output_format if args.output_dir is not None: _, filename = op.split(outpath) outpath = op.join(args.output_dir, filename) with open(outpath, "w", encoding=args.output_enc) as outfile: subs.to_file(outfile, output_format, args.fps) else: if PY3: infile = io.TextIOWrapper(sys.stdin.buffer, args.input_enc) outfile = io.TextIOWrapper(sys.stdout.buffer, args.output_enc) else: infile = io.TextIOWrapper(sys.stdin, args.input_enc) outfile = io.TextIOWrapper(sys.stdout, args.output_enc) subs = SSAFile.from_file(infile, args.input_format, args.fps) self.process(subs, args) output_format = args.output_format or subs.format subs.to_file(outfile, output_format, args.fps) return (0 if errors == 0 else 1) @staticmethod def process(subs, args): if args.shift is not None: subs.shift(ms=args.shift) elif args.shift_back is not None: subs.shift(ms=-args.shift_back) elif args.transform_framerate is not None: in_fps, out_fps = args.transform_framerate subs.transform_framerate(in_fps, out_fps) def __main__(): cli = Pysubs2CLI() rv = cli(sys.argv[1:]) sys.exit(rv) if __name__ == "__main__": __main__()
4,306
4,879
#include "drape/texture.hpp" #include "drape/gl_functions.hpp" #include "drape/glsl_func.hpp" #include "drape/utils/gpu_mem_tracker.hpp" #include "base/math.hpp" #include "3party/glm/glm/gtx/bit.hpp" namespace dp { Texture::ResourceInfo::ResourceInfo(m2::RectF const & texRect) : m_texRect(texRect) {} m2::RectF const & Texture::ResourceInfo::GetTexRect() const { return m_texRect; } Texture::~Texture() { Destroy(); } void Texture::Create(ref_ptr<dp::GraphicsContext> context, Params const & params) { if (AllocateTexture(context, params.m_allocator)) m_hwTexture->Create(context, params); } void Texture::Create(ref_ptr<dp::GraphicsContext> context, Params const & params, ref_ptr<void> data) { if (AllocateTexture(context, params.m_allocator)) m_hwTexture->Create(context, params, data); } void Texture::UploadData(ref_ptr<dp::GraphicsContext> context, uint32_t x, uint32_t y, uint32_t width, uint32_t height, ref_ptr<void> data) { ASSERT(m_hwTexture != nullptr, ()); m_hwTexture->UploadData(context, x, y, width, height, data); } TextureFormat Texture::GetFormat() const { ASSERT(m_hwTexture != nullptr, ()); return m_hwTexture->GetFormat(); } uint32_t Texture::GetWidth() const { ASSERT(m_hwTexture != nullptr, ()); return m_hwTexture->GetWidth(); } uint32_t Texture::GetHeight() const { ASSERT(m_hwTexture != nullptr, ()); return m_hwTexture->GetHeight(); } float Texture::GetS(uint32_t x) const { ASSERT(m_hwTexture != nullptr, ()); return m_hwTexture->GetS(x); } float Texture::GetT(uint32_t y) const { ASSERT(m_hwTexture != nullptr, ()); return m_hwTexture->GetT(y); } uint32_t Texture::GetID() const { ASSERT(m_hwTexture != nullptr, ()); return m_hwTexture->GetID(); } void Texture::Bind(ref_ptr<dp::GraphicsContext> context) const { ASSERT(m_hwTexture != nullptr, ()); m_hwTexture->Bind(context); } void Texture::SetFilter(TextureFilter filter) { ASSERT(m_hwTexture != nullptr, ()); m_hwTexture->SetFilter(filter); } // static bool Texture::IsPowerOfTwo(uint32_t width, uint32_t height) { return glm::isPowerOfTwo(static_cast<int>(width)) && glm::isPowerOfTwo(static_cast<int>(height)); } void Texture::Destroy() { m_hwTexture.reset(); } bool Texture::AllocateTexture(ref_ptr<dp::GraphicsContext> context, ref_ptr<HWTextureAllocator> allocator) { if (allocator != nullptr) { m_hwTexture = allocator->CreateTexture(context); return true; } return false; } ref_ptr<HWTexture> Texture::GetHardwareTexture() const { return make_ref(m_hwTexture); } } // namespace dp
1,018
2,027
<filename>util/registry/replication.py import features import json from contextlib import contextmanager from data import model from app import image_replication_queue DEFAULT_BATCH_SIZE = 1000 @contextmanager def queue_replication_batch(namespace, batch_size=DEFAULT_BATCH_SIZE): """ Context manager implementation which returns a target callable that takes the storage to queue for replication. When the the context block exits the items generated by the callable will be bulk inserted into the queue with the specified batch size. """ namespace_user = model.user.get_namespace_user(namespace) with image_replication_queue.batch_insert(batch_size) as queue_put: def queue_storage_replication_batch(storage): if features.STORAGE_REPLICATION: queue_put( [storage.uuid], json.dumps( { "namespace_user_id": namespace_user.id, "storage_id": storage.uuid, } ), ) yield queue_storage_replication_batch def queue_storage_replication(namespace, storage): """ Queues replication for the given image storage under the given namespace (if enabled). """ with queue_replication_batch(namespace, 1) as batch_spawn: batch_spawn(storage)
580
3,227
<filename>Segment_Delaunay_graph_2/test/Segment_Delaunay_graph_2/include/sdg_hierarchy_main.h #ifndef SDG_MAIN_HIERARCHY_H #define SDG_MAIN_HIERARCHY_H #include <CGAL/basic.h> #include <iostream> #include <cassert> #include "test.h" int main(int, char**) { CGAL::test_hierarchy_x(std::cin, "bizarre"); CGAL::test_hierarchy_no_x(std::cin, "bizarre"); CGAL::test_hierarchy_x(std::cin, "sitesx", false); CGAL::test_hierarchy_no_x(std::cin, "sitesx", false); CGAL::test_hierarchy_x(std::cin, "sitesxx", false); CGAL::test_hierarchy_no_x(std::cin, "sitesxx", false); CGAL::test_hierarchy_x(std::cin, "MartinHeldBugreport", false); CGAL::test_hierarchy_no_x(std::cin, "MartiHeldBugreport", false); return 0; } #endif // SDG_MAIN_HIERARCHY_H
339
14,668
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_IMAGE_IMAGE_UTIL_H_ #define UI_GFX_IMAGE_IMAGE_UTIL_H_ #include <stddef.h> #include <vector> #include "ui/gfx/gfx_export.h" namespace gfx { class Image; class ImageSkia; } namespace gfx { // Creates an image from the given JPEG-encoded input. If there was an error // creating the image, returns an IsEmpty() Image. GFX_EXPORT Image ImageFrom1xJPEGEncodedData(const unsigned char* input, size_t input_size); // Fills the |dst| vector with JPEG-encoded bytes of the 1x representation of // the given image. // Returns true if the image has a 1x representation and the 1x representation // was encoded successfully. // |quality| determines the compression level, 0 == lowest, 100 == highest. // Returns true if the Image was encoded successfully. GFX_EXPORT bool JPEG1xEncodedDataFromImage(const Image& image, int quality, std::vector<unsigned char>* dst); bool JPEG1xEncodedDataFromSkiaRepresentation(const Image& image, int quality, std::vector<unsigned char>* dst); // Fills the |dst| vector with WebP-encoded bytes of the the given image. // Returns true if the image was encoded (lossy) successfully. // |quality| determines the visual quality, 0 == lowest, 100 == highest. // Returns true if the Image was encoded successfully. GFX_EXPORT bool WebpEncodedDataFromImage(const Image& image, int quality, std::vector<unsigned char>* dst); // Computes the width of any nearly-transparent regions at the sides of the // image and returns them in |left| and |right|. This checks each column of // pixels from the outsides in, looking for anything with alpha above a // reasonably small value. For a fully-opaque image, the margins will thus be // (0, 0); for a fully-transparent image, the margins will be // (width / 2, width / 2), with |left| getting the extra pixel for odd widths. GFX_EXPORT void GetVisibleMargins(const ImageSkia& image, int* left, int* right); // Downsizes the image if its area exceeds kSearchByImageMaxImageArea AND // (either its width exceeds kSearchByImageMaxImageWidth OR its height exceeds // kSearchByImageMaxImageHeight) in preparation for searching. GFX_EXPORT Image ResizedImageForSearchByImage(const Image& image); // Downsizes the image if its area exceeds the max_area defined AND (either its // width exceeds the max_width defined OR its height exceeds the max_height // defined). GFX_EXPORT Image ResizedImageForMaxDimensions(const Image& image, int max_width, int max_height, int max_area); Image ResizedImageForSearchByImageSkiaRepresentation(const Image& image); Image ResizedImageForMaxDimensionsSkiaRepresentation(const Image& image, int max_width, int max_height, int max_area); } // namespace gfx #endif // UI_GFX_IMAGE_IMAGE_UTIL_H_
1,505
322
{ "cancelBtn": "Отмена", "saveBtn": "Сохранить", "settings": "Настройки", "language": "Язык" }
71
1,405
<filename>sample4/recompiled_java/sources/QQPIM/TopList.java<gh_stars>1000+ package QQPIM; import com.qq.taf.jce.JceDisplayer; import com.qq.taf.jce.JceInputStream; import com.qq.taf.jce.JceOutputStream; import com.qq.taf.jce.JceStruct; import com.qq.taf.jce.JceUtil; import java.util.ArrayList; import java.util.Collection; public final class TopList extends JceStruct implements Cloneable { static ArrayList<ModelMarkInfo> a; static final /* synthetic */ boolean b = (!TopList.class.desiredAssertionStatus()); public ArrayList<ModelMarkInfo> markinfos; public int modelmarkid; public TopList() { this.modelmarkid = 0; this.markinfos = null; this.modelmarkid = this.modelmarkid; this.markinfos = this.markinfos; } public TopList(int i, ArrayList<ModelMarkInfo> arrayList) { this.modelmarkid = 0; this.markinfos = null; this.modelmarkid = i; this.markinfos = arrayList; } public final String className() { return "QQPIM.TopList"; } @Override // java.lang.Object public final Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { if (b) { return null; } throw new AssertionError(); } } @Override // com.qq.taf.jce.JceStruct public final void display(StringBuilder sb, int i) { JceDisplayer jceDisplayer = new JceDisplayer(sb, i); jceDisplayer.display(this.modelmarkid, "modelmarkid"); jceDisplayer.display((Collection) this.markinfos, "markinfos"); } public final boolean equals(Object obj) { if (obj == null) { return false; } TopList topList = (TopList) obj; return JceUtil.equals(this.modelmarkid, topList.modelmarkid) && JceUtil.equals(this.markinfos, topList.markinfos); } public final String fullClassName() { return "QQPIM.TopList"; } public final ArrayList<ModelMarkInfo> getMarkinfos() { return this.markinfos; } public final int getModelmarkid() { return this.modelmarkid; } public final int hashCode() { try { throw new Exception("Need define key first!"); } catch (Exception e) { e.printStackTrace(); return 0; } } @Override // com.qq.taf.jce.JceStruct public final void readFrom(JceInputStream jceInputStream) { this.modelmarkid = jceInputStream.read(this.modelmarkid, 0, true); if (a == null) { a = new ArrayList<>(); a.add(new ModelMarkInfo()); } setMarkinfos((ArrayList) jceInputStream.read((Object) a, 1, true)); } public final void setMarkinfos(ArrayList<ModelMarkInfo> arrayList) { this.markinfos = arrayList; } public final void setModelmarkid(int i) { this.modelmarkid = i; } @Override // com.qq.taf.jce.JceStruct public final void writeTo(JceOutputStream jceOutputStream) { jceOutputStream.write(this.modelmarkid, 0); jceOutputStream.write((Collection) this.markinfos, 1); } }
1,397
1,799
<reponame>714627034/Paddle-Lite // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/xpu/__xpu__embedding_with_eltwise_add_compute.h" #include "lite/backends/xpu/xpu_header_sitter.h" #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace kernels { namespace xpu { void XPUEmbeddingWithEltwiseAddCompute::PrepareForRun() { auto& param = this->Param<param_t>(); CHECK_GT(param.Tables.size(), 0); auto embed_dim = param.Tables[0]->dims()[1]; for (auto* table : param.Tables) { auto& table_dims = table->dims(); CHECK_EQ(table_dims.size(), 2); /* shape like [table_len, embed_dim] */ CHECK_EQ(table_dims[1], embed_dim); table_lens_cpu_.push_back(table_dims[0]); arg_tables_.push_back(table->data<float>()); } } void XPUEmbeddingWithEltwiseAddCompute::Run() { auto& param = this->Param<param_t>(); auto& ctx = this->ctx_->As<XPUContext>(); auto& id_dims = param.Ids[0]->dims(); int idx_len = id_dims[0] * id_dims[1]; int emb_layer_num = param.Ids.size(); int embed_dim = param.Tables[0]->dims()[1]; std::vector<std::vector<int>> int_idx(emb_layer_num, std::vector<int>(idx_len, 0)); std::vector<xdnn::VectorParam<int>> arg_ids_; if (param.Mask && param.Mask->data<float>()) { auto& mask_dims = param.Mask->dims(); auto batch_size = mask_dims[0]; auto pad_seq_len = mask_dims[1]; param.PadSeqLen->mutable_data<int>()[0] = pad_seq_len; auto* seq_lod = param.SeqLod; seq_lod->Resize({batch_size + 1}); std::vector<int> cpu_seq_lod{0}; auto* mask_ptr = param.Mask->data<float>(); for (auto batch_idx = 0; batch_idx < batch_size; batch_idx++) { int cur_batch_seq_len = 0; for (auto seq_idx = 0; seq_idx < pad_seq_len; seq_idx++) { if (mask_ptr[batch_idx * pad_seq_len + seq_idx] > 1e-7) { cur_batch_seq_len += 1; } else { break; } } cpu_seq_lod.push_back(cpu_seq_lod.back() + cur_batch_seq_len); CHECK_GT(cur_batch_seq_len, 0); } auto* seq_lod_ptr = seq_lod->mutable_data<int>(); memcpy(seq_lod_ptr, cpu_seq_lod.data(), cpu_seq_lod.size() * sizeof(int)); idx_len = cpu_seq_lod.back(); for (size_t i = 0; i < emb_layer_num; ++i) { auto* idx_pad_ptr = param.Ids[i]->data<int64_t>(); for (auto batch_idx = 0; batch_idx < batch_size; batch_idx++) { for (auto j = 0; j < cpu_seq_lod[batch_idx + 1] - cpu_seq_lod[batch_idx]; j++) { int_idx[i][cpu_seq_lod[batch_idx] + j] = static_cast<int>(idx_pad_ptr[batch_idx * pad_seq_len + j]); } } arg_ids_.push_back( xdnn::VectorParam<int>{int_idx[i].data(), idx_len, nullptr}); } param.Out->Resize({1, idx_len, embed_dim}); } else { for (size_t i = 0; i < emb_layer_num; i++) { for (size_t j = 0; j < idx_len; j++) { int_idx[i][j] = static_cast<int>(param.Ids[i]->data<int64_t>()[j]); } arg_ids_.push_back( xdnn::VectorParam<int>{int_idx[i].data(), idx_len, nullptr}); } } int r = xdnn::multi_embedding_fusion<float, float, int>( ctx.GetRawContext(), arg_tables_, /* tables */ param.Out->mutable_data<float>(TARGET(kXPU)), arg_ids_, table_lens_cpu_, embed_dim, std::vector<float>(table_lens_cpu_.size(), 1.0f), std::vector<int>(table_lens_cpu_.size(), static_cast<int>(param.padding_idx))); CHECK_EQ(r, 0); } } // namespace xpu } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL( __xpu__embedding_with_eltwise_add, kXPU, kFloat, kNCHW, paddle::lite::kernels::xpu::XPUEmbeddingWithEltwiseAddCompute, def) .BindInput("Ids", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt64))}) .BindInput("Tables", {LiteType::GetTensorTy(TARGET(kXPU))}) .BindInput("Mask", {LiteType::GetTensorTy(TARGET(kHost))}) .BindOutput("Output", {LiteType::GetTensorTy(TARGET(kXPU))}) .BindOutput("SeqLod", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt32))}) .BindOutput("PadSeqLen", {LiteType::GetTensorTy(TARGET(kHost), PRECISION(kInt32))}) .Finalize();
2,238
11,356
/*============================================================================= Copyright (c) 2006-2007 <NAME> Use modification and distribution are subject to 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). ==============================================================================*/ #if !defined(BOOST_FUSION_FUNCTIONAL_ADAPTER_UNFUSED_HPP_INCLUDED) #if !defined(BOOST_PP_IS_ITERATING) #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/facilities/intercept.hpp> #include <boost/utility/result_of.hpp> #include <boost/config.hpp> #include <boost/fusion/container/vector/vector.hpp> #include <boost/fusion/functional/adapter/limits.hpp> #include <boost/fusion/functional/adapter/detail/access.hpp> #if defined (BOOST_MSVC) # pragma warning(push) # pragma warning (disable: 4512) // assignment operator could not be generated. #endif namespace boost { namespace fusion { template <class Function, bool AllowNullary = true> class unfused; //----- ---- --- -- - - - - template <class Function> class unfused<Function,true> : public unfused<Function,false> { typedef typename detail::qf_c<Function>::type function_c; typedef typename detail::qf<Function>::type function; typedef typename detail::call_param<Function>::type func_const_fwd_t; public: using unfused<Function,false>::operator(); BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline explicit unfused(func_const_fwd_t f = function()) : unfused<Function,false>(f) { } typedef typename boost::result_of< function_c(fusion::vector0<> &) >::type call_const_0_result; BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline call_const_0_result operator()() const { fusion::vector0<> arg; return this->fnc_transformed(arg); } typedef typename boost::result_of< function(fusion::vector0<> &) >::type call_0_result; BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline call_0_result operator()() { fusion::vector0<> arg; return this->fnc_transformed(arg); } }; template <class Function> class unfused<Function,false> { protected: Function fnc_transformed; typedef typename detail::qf_c<Function>::type function_c; typedef typename detail::qf<Function>::type function; typedef typename detail::call_param<Function>::type func_const_fwd_t; public: BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline explicit unfused(func_const_fwd_t f = function()) : fnc_transformed(f) { } template <typename Sig> struct result; #define BOOST_PP_FILENAME_1 \ <boost/fusion/functional/adapter/unfused.hpp> #define BOOST_PP_ITERATION_LIMITS \ (1,BOOST_FUSION_UNFUSED_MAX_ARITY) #include BOOST_PP_ITERATE() }; }} #if defined (BOOST_MSVC) # pragma warning(pop) #endif namespace boost { #if !defined(BOOST_RESULT_OF_USE_DECLTYPE) || defined(BOOST_NO_CXX11_DECLTYPE) template<class F> struct result_of< boost::fusion::unfused<F> const () > { typedef typename boost::fusion::unfused<F>::call_const_0_result type; }; template<class F> struct result_of< boost::fusion::unfused<F>() > { typedef typename boost::fusion::unfused<F>::call_0_result type; }; #endif template<class F> struct tr1_result_of< boost::fusion::unfused<F> const () > { typedef typename boost::fusion::unfused<F>::call_const_0_result type; }; template<class F> struct tr1_result_of< boost::fusion::unfused<F>() > { typedef typename boost::fusion::unfused<F>::call_0_result type; }; } #define BOOST_FUSION_FUNCTIONAL_ADAPTER_UNFUSED_HPP_INCLUDED #else // defined(BOOST_PP_IS_ITERATING) //////////////////////////////////////////////////////////////////////////////// // // Preprocessor vertical repetition code // //////////////////////////////////////////////////////////////////////////////// #define N BOOST_PP_ITERATION() template <class Self, BOOST_PP_ENUM_PARAMS(N,typename T)> struct result< Self const (BOOST_PP_ENUM_PARAMS(N,T)) > : boost::result_of< function_c( BOOST_PP_CAT(fusion::vector,N)< BOOST_PP_ENUM_BINARY_PARAMS(N, typename detail::mref<T,>::type BOOST_PP_INTERCEPT) > & )> { }; template <class Self, BOOST_PP_ENUM_PARAMS(N,typename T)> struct result< Self(BOOST_PP_ENUM_PARAMS(N,T)) > : boost::result_of< function( BOOST_PP_CAT(fusion::vector,N)< BOOST_PP_ENUM_BINARY_PARAMS(N, typename detail::mref<T,>::type BOOST_PP_INTERCEPT) > & )> { }; template <BOOST_PP_ENUM_PARAMS(N,typename T)> BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename boost::result_of<function_c(BOOST_PP_CAT(fusion::vector,N) <BOOST_PP_ENUM_BINARY_PARAMS(N,T,& BOOST_PP_INTERCEPT)> & )>::type operator()(BOOST_PP_ENUM_BINARY_PARAMS(N,T,& a)) const { BOOST_PP_CAT(fusion::vector,N)< BOOST_PP_ENUM_BINARY_PARAMS(N,T,& BOOST_PP_INTERCEPT) > arg(BOOST_PP_ENUM_PARAMS(N,a)); return this->fnc_transformed(arg); } template <BOOST_PP_ENUM_PARAMS(N,typename T)> BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename boost::result_of<function(BOOST_PP_CAT(fusion::vector,N) <BOOST_PP_ENUM_BINARY_PARAMS(N,T,& BOOST_PP_INTERCEPT)> & )>::type operator()(BOOST_PP_ENUM_BINARY_PARAMS(N,T,& a)) { BOOST_PP_CAT(fusion::vector,N)< BOOST_PP_ENUM_BINARY_PARAMS(N,T,& BOOST_PP_INTERCEPT) > arg(BOOST_PP_ENUM_PARAMS(N,a)); return this->fnc_transformed(arg); } #undef N #endif // defined(BOOST_PP_IS_ITERATING) #endif
2,906
4,879
package com.mapswithme.maps.dialog; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentManager; public interface ResolveFragmentManagerStrategy { @NonNull FragmentManager resolve(@NonNull Fragment baseFragment); @NonNull FragmentManager resolve(@NonNull FragmentActivity activity); }
125