max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
22,481
<filename>homeassistant/components/smart_meter_texas/manifest.json { "domain": "smart_meter_texas", "name": "Smart Meter Texas", "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/smart_meter_texas", "requirements": ["smart-meter-texas==0.4.7"], "codeowners": ["@grahamwetzler"], "iot_class": "cloud_polling" }
133
1,144
// Generated Model - DO NOT CHANGE package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; import javax.annotation.Nullable; /** Generated Model for C_TaxCategory * @author metasfresh (generated) */ @SuppressWarnings("unused") public class X_C_TaxCategory extends org.compiere.model.PO implements I_C_TaxCategory, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1076080462L; /** Standard Constructor */ public X_C_TaxCategory (final Properties ctx, final int C_TaxCategory_ID, @Nullable final String trxName) { super (ctx, C_TaxCategory_ID, trxName); } /** Load Constructor */ public X_C_TaxCategory (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setCommodityCode (final @Nullable java.lang.String CommodityCode) { set_Value (COLUMNNAME_CommodityCode, CommodityCode); } @Override public java.lang.String getCommodityCode() { return get_ValueAsString(COLUMNNAME_CommodityCode); } @Override public void setC_TaxCategory_ID (final int C_TaxCategory_ID) { if (C_TaxCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID); } @Override public int getC_TaxCategory_ID() { return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setInternalName (final @Nullable java.lang.String InternalName) { set_Value (COLUMNNAME_InternalName, InternalName); } @Override public java.lang.String getInternalName() { return get_ValueAsString(COLUMNNAME_InternalName); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * VATType AD_Reference_ID=540842 * Reference name: VATType */ public static final int VATTYPE_AD_Reference_ID=540842; /** RegularVAT = N */ public static final String VATTYPE_RegularVAT = "N"; /** ReducedVAT = R */ public static final String VATTYPE_ReducedVAT = "R"; /** TaxExempt = E */ public static final String VATTYPE_TaxExempt = "E"; @Override public void setVATType (final @Nullable java.lang.String VATType) { set_Value (COLUMNNAME_VATType, VATType); } @Override public java.lang.String getVATType() { return get_ValueAsString(COLUMNNAME_VATType); } }
1,064
848
<filename>tensorflow/compiler/tests/variable_ops_test.py # 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. # ============================================================================== """Tests for reading and writing variables.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.compiler.tests import xla_test from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_state_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import googletest from tensorflow.python.training.gradient_descent import GradientDescentOptimizer class VariableOpsTest(xla_test.XLATestCase): """Test cases for resource variable operators.""" def testWriteEmptyShape(self): # Verifies that we can pass an uninitialized variable with an empty shape, # assign it a value, and successfully return it. for dtype in self.numeric_types: with self.session() as sess, self.test_scope(): zeros = np.zeros([3, 0], dtype=dtype) v = resource_variable_ops.ResourceVariable(zeros) p = array_ops.placeholder(dtype) x = v.assign(p) with ops.control_dependencies([x]): y = v.read_value() self.assertAllClose(zeros, sess.run(y, {p: zeros})) def testOneWriteOneOutput(self): # Regression test for a bug where computations with one non-constant # output and one variable update were mishandled. for dtype in self.numeric_types: init = np.array([[1, 2j], [3, 4]]).astype(dtype) with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) sess.run(variables.variables_initializer([v])) p = array_ops.placeholder(dtype) x = v.assign_add(p) with ops.control_dependencies([x]): y = v.read_value() self.assertAllClose( np.array([[2, 1 + 2j], [4, 5]]).astype(dtype), sess.run(y, {p: 1})) def testSparseRead0DIndices(self): for dtype in self.numeric_types: init = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8j, 9, 10, 11]]).astype(dtype) with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) sess.run(variables.variables_initializer([v])) x = v.sparse_read(2) self.assertAllClose( np.array([8j, 9, 10, 11]).astype(dtype), self.evaluate(x)) def testSparseRead1DIndices(self): for dtype in self.numeric_types: init = np.array([[0, 1, 2, 3], [4, 5, 6j, 7], [8, 9, 10, 11]]).astype(dtype) with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) sess.run(variables.variables_initializer([v])) x = v.sparse_read([2, 1]) self.assertAllClose( np.array([[8, 9, 10, 11], [4, 5, 6j, 7]]).astype(dtype), self.evaluate(x)) def testSparseRead2DIndices(self): for dtype in self.numeric_types: init = np.array([[0, 1, 2j, 3], [4, 5, 6, 7], [8, 9, 10, 11]]).astype(dtype) with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) sess.run(variables.variables_initializer([v])) x = v.sparse_read([[2, 1], [0, 2]]) self.assertAllClose( np.array([[[8, 9, 10, 11], [4, 5, 6, 7]], [[0, 1, 2j, 3], [8, 9, 10, 11]]]).astype(dtype), self.evaluate(x)) def testSparseRead2DIndices3DTensor(self): for dtype in self.numeric_types: init = np.array([[[0, 1, 2], [3, 4, 5]], [[10, 11, 12], [13, 14, 15]], [[20, 21, 22], [23, 24j, 25]], [[30, 31, 32], [33, 34, 35]]]).astype(dtype) with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) sess.run(variables.variables_initializer([v])) x = v.sparse_read([[2, 1], [3, 0]]) self.assertAllClose( np.array( [[[[20, 21, 22], [23, 24j, 25]], [[10, 11, 12], [13, 14, 15]]], [[[30, 31, 32], [33, 34, 35]], [[0, 1, 2], [3, 4, 5]]] ],).astype(dtype), self.evaluate(x)) def testShape(self): for dtype in self.numeric_types: init = np.ones([2, 3]).astype(dtype) with self.session() as session, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) session.run(variables.variables_initializer([v])) h = v.handle s32, s64 = session.run([ resource_variable_ops.variable_shape(h), resource_variable_ops.variable_shape(h, out_type=dtypes.int64) ]) self.assertEqual(s32.dtype, np.int32) self.assertEqual(s64.dtype, np.int64) self.assertAllEqual(s32, [2, 3]) self.assertAllEqual(s64, [2, 3]) def testReadWrite(self): """Tests initialization, reading, and writing a resource variable.""" for dtype in self.numeric_types: with self.session() as session: with self.test_scope(): with variable_scope.variable_scope("ascope", use_resource=True): x = variable_scope.get_variable( "x", shape=[], dtype=dtype, initializer=init_ops.constant_initializer(2)) a = x.read_value() with ops.control_dependencies([a]): b = state_ops.assign(x, dtype(47)) with ops.control_dependencies([b]): c = x.read_value() with ops.control_dependencies([c]): d = state_ops.assign_add(x, np.array(6 + 2j).astype(dtype)) with ops.control_dependencies([d]): e = state_ops.assign_sub(x, dtype(3)) with ops.control_dependencies([e]): f = x.read_value() session.run(variables.global_variables_initializer()) v1, v2, v3 = session.run([a, c, f]) self.assertAllClose(dtype(2), v1) self.assertAllClose(dtype(47), v2) self.assertAllClose(np.array(50 + 2j).astype(dtype), v3) def testTraining(self): """Tests a gradient descent step for a simple model.""" with self.session() as session: with self.test_scope(): with variable_scope.variable_scope("ascope", use_resource=True): w = variable_scope.get_variable( "w", shape=[4, 2], dtype=dtypes.float32, initializer=init_ops.constant_initializer( np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.float32))) b = variable_scope.get_variable( "b", shape=[2], dtype=dtypes.float32, initializer=init_ops.constant_initializer( np.array([2, 3], dtype=np.float32))) x = array_ops.placeholder(dtypes.float32, shape=[1, 4]) y = math_ops.matmul(x, w) + b loss = math_ops.reduce_sum(y) optimizer = GradientDescentOptimizer(0.1) train = optimizer.minimize(loss) session.run(variables.global_variables_initializer()) session.run(train, {x: np.array([[7, 3, 5, 9]], dtype=np.float32)}) vw, vb = session.run([w, b]) self.assertAllClose( np.array( [[0.3, 1.3], [2.7, 3.7], [4.5, 5.5], [6.1, 7.1]], dtype=np.float32), vw, rtol=1e-4) self.assertAllClose(np.array([1.9, 2.9], dtype=np.float32), vb, rtol=1e-4) def testWriteOfAliasedTensor(self): for dtype in self.numeric_types: init = np.array([[1, 2j], [3, 4]]).astype(dtype) update = np.array([[7, 1j], [2, 11]]).astype(dtype) with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable(init) sess.run(variables.variables_initializer([v])) p = array_ops.placeholder(dtype) q = array_ops.identity(p) x = v.read_value() # Writes the value of 'p' to 'v', but keeps a reference to the original # value of 'v' so the variable update cannot reuse its buffer. with ops.control_dependencies([x]): y = v.assign(q) result = sess.run([x, y, q], {p: update}) self.assertAllClose(init, result[0]) self.assertAllClose(update, result[1]) self.assertAllClose(update, result[2]) def testScatterAdd(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[2, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1], [7]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_add( handle, [0], constant_op.constant([[2]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertAllEqual(self.evaluate(read), [[3], [7]]) def testScatterSub(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[2, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[4], [1]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_sub( handle, [1], constant_op.constant([[2]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertAllEqual(self.evaluate(read), [[4], [-1]]) def testScatterMul(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_mul( handle, [0], constant_op.constant([[5]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[5]]) def testScatterDiv(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_div( handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertAllEqual(self.evaluate(read), [[2]]) def testScatterMin(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_min( handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) def testScatterMax(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_max( handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[6]]) def testScatterUpdate(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_update( handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) def testScatterAddScalar(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_add( handle, [0], constant_op.constant(2, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) def testScatterSubScalar(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_sub( handle, [0], constant_op.constant(2, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[-1]]) def testScatterMulScalar(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[1]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_mul( handle, [0], constant_op.constant(5, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[5]]) def testScatterDivScalar(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_div( handle, [0], constant_op.constant(3, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[2]]) def testScatterMinScalar(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_min( handle, [0], constant_op.constant(3, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[3]]) def testScatterMaxScalar(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.int32, shape=[1, 1]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([[6]], dtype=dtypes.int32))) sess.run( resource_variable_ops.resource_scatter_max( handle, [0], constant_op.constant(3, dtype=dtypes.int32))) read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) self.assertEqual(self.evaluate(read), [[6]]) def testScatterNdAddOps(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.float32, shape=[8]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([1] * 8, dtype=dtypes.float32))) indices = constant_op.constant([[4], [3], [1], [7]], dtype=dtypes.int32) updates = constant_op.constant([9, 10, 11, 12], dtype=dtypes.float32) expected = np.array([1, 12, 1, 11, 10, 1, 1, 13]) sess.run(gen_state_ops.resource_scatter_nd_add(handle, indices, updates)) read = resource_variable_ops.read_variable_op( handle, dtype=dtypes.float32) self.assertAllClose(expected, self.evaluate(read)) def testScatterNdUpdateAddOps(self): with self.session() as sess, self.test_scope(): handle = resource_variable_ops.var_handle_op( dtype=dtypes.float32, shape=[8]) sess.run( resource_variable_ops.assign_variable_op( handle, constant_op.constant([1] * 8, dtype=dtypes.float32))) indices = constant_op.constant([[4], [3], [1], [7]], dtype=dtypes.int32) updates = constant_op.constant([9, 10, 11, 12], dtype=dtypes.float32) expected = np.array([1, 11, 1, 10, 9, 1, 1, 12]) sess.run( gen_state_ops.resource_scatter_nd_update(handle, indices, updates)) read = resource_variable_ops.read_variable_op( handle, dtype=dtypes.float32) self.assertAllClose(expected, self.evaluate(read)) class StridedSliceAssignChecker(object): """Compares the results of a slice assignment using Tensorflow and numpy.""" def __init__(self, test, x, dtype): self.dtype = dtype self.test = test self.x_np = np.array(x).astype(dtype) # Randomly start on mode 0 or 1. self.which_mode = np.random.randint(2, size=1)[0] def __setitem__(self, index, value): self.which_mode = 1 - self.which_mode value = np.array(value).astype(self.dtype) with self.test.session() as sess, self.test.test_scope(): x = constant_op.constant(self.x_np, dtype=self.dtype) var = resource_variable_ops.ResourceVariable(x) sess.run(variables.variables_initializer([var])) if self.which_mode == 0: val = sess.run(var[index].assign(value)) else: assert self.which_mode == 1 val = sess.run(state_ops.assign(var[index], value)) valnp = np.copy(self.x_np) valnp[index] = np.array(value) self.test.assertAllEqual(val, valnp) class SliceAssignTest(xla_test.XLATestCase): def testSliceAssign(self): for dtype in self.numeric_types: checker = StridedSliceAssignChecker( self, [[1, 2, 3], [4, 5, 6]], dtype=dtype) # No-op assignment checker[:] = [[10, 20, 30], [40, 50, 60]] # Checks trivial (1,1) shape tensor checker[1:2, 1:2] = [[66]] # shrink shape changes checker[1:2, 1] = [66] checker[1, 1:2] = [66] if dtype != dtypes.bfloat16.as_numpy_dtype: # TODO(b/68813416): valnp call above results in an ndarray and not a # number for bfloat16s. checker[1, 1] = 66 # newaxis shape changes checker[:, None, :] = [[[10, 20, 30]], [[40, 50, 50]]] # shrink and newaxis checker[None, None, 0, 0:1] = [[[99]]] # Non unit strides checker[::1, 1::-1] = [[3, 33], [4, 44]] # degenerate interval checker[8:10, 0] = [] checker[8:10, 8:10] = [[]] # Assign vector to scalar (rank-0) using newaxis checker2 = StridedSliceAssignChecker(self, 222, dtype=dtype) if dtype != dtypes.bfloat16.as_numpy_dtype: # TODO(b/68813416): valnp call above results in an ndarray and not a # number for bfloat16s. checker2[()] = 6 # no indices checker2[...] = 6 # ellipsis checker2[None] = [6] # new axis def testUninitialized(self): with self.assertRaisesRegexp(errors.FailedPreconditionError, "uninitialized variable"): with self.session() as sess, self.test_scope(): v = resource_variable_ops.ResourceVariable([1, 2]) sess.run(v[:].assign([1, 2])) if __name__ == "__main__": googletest.main()
9,809
14,668
<filename>components/test/data/payments/kylepay.com/app.json { "name": "Pay with KylePay", "short_name": "KylePay", "icons": [{ "src": "icon.png", "sizes": "48x48", "type": "image/png" }], "serviceworker": { "src": "app.js", "use_cache": false, "scope": "/webpay" }, "payment": { "supported_delegations": ["shippingAddress", "payerName", "payerEmail", "payerPhone"] } }
180
587
<reponame>sw96411/gaffer-tools { "class": "uk.gov.gchq.gaffer.operation.impl.get.GetAllElements", "options": { "gaffer.federatedstore.operation.graphIds": "propertyIndex" } }
78
1,755
<filename>Rendering/External/vtkExternalOpenGLRenderer.h /*========================================================================= Program: Visualization Toolkit Module: vtkExternalOpenGLRenderer.h Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkExternalOpenGLRenderer * @brief OpenGL renderer * * vtkExternalOpenGLRenderer is a secondary implementation of the class * vtkOpenGLRenderer. vtkExternalOpenGLRenderer interfaces to the * OpenGL graphics library. This class provides API to preserve the color and * depth buffers, thereby allowing external applications to manage the OpenGL * buffers. This becomes very useful when there are multiple OpenGL applications * sharing the same OpenGL context. * * vtkExternalOpenGLRenderer makes sure that the camera used in the scene if of * type vtkExternalOpenGLCamera. It manages light and camera transformations for * VTK objects in the OpenGL context. * * \sa vtkExternalOpenGLCamera */ #ifndef vtkExternalOpenGLRenderer_h #define vtkExternalOpenGLRenderer_h #include "vtkOpenGLRenderer.h" #include "vtkRenderingExternalModule.h" // For export macro // Forward declarations class vtkLightCollection; class vtkExternalLight; class VTKRENDERINGEXTERNAL_EXPORT vtkExternalOpenGLRenderer : public vtkOpenGLRenderer { public: static vtkExternalOpenGLRenderer* New(); vtkTypeMacro(vtkExternalOpenGLRenderer, vtkOpenGLRenderer); void PrintSelf(ostream& os, vtkIndent indent) override; /** * Synchronize camera and light parameters */ void Render(void) override; /** * Create a new Camera sutible for use with this type of Renderer. * This function creates the vtkExternalOpenGLCamera. */ vtkCamera* MakeCamera() override; /** * Add an external light to the list of external lights. */ virtual void AddExternalLight(vtkExternalLight*); /** * Remove an external light from the list of external lights. */ virtual void RemoveExternalLight(vtkExternalLight*); /** * Remove all external lights */ virtual void RemoveAllExternalLights(); /** * If PreserveGLCameraMatrices is set to true, VTK camera matrices * are copied from the current context GL_MODELVIEW_MATRIX and * GL_PROJECTION_MATRIX parameters before each render call. * This flag is on by default. */ vtkGetMacro(PreserveGLCameraMatrices, vtkTypeBool); vtkSetMacro(PreserveGLCameraMatrices, vtkTypeBool); vtkBooleanMacro(PreserveGLCameraMatrices, vtkTypeBool); /** * If PreserveGLLights is set to true, existing GL lights are modified before * each render call to match the collection of lights added with * AddExternalLight(). This flag is on by default. */ vtkGetMacro(PreserveGLLights, vtkTypeBool); vtkSetMacro(PreserveGLLights, vtkTypeBool); vtkBooleanMacro(PreserveGLLights, vtkTypeBool); protected: vtkExternalOpenGLRenderer(); ~vtkExternalOpenGLRenderer() override; /** * Copy the current OpenGL GL_MODELVIEW_MATRIX and GL_PROJECTION_MATRIX to * the active VTK camera before each render call if PreserveGLCameraMatrices * is set to true (default behavior). */ void SynchronizeGLCameraMatrices(); /** * Query existing GL lights before each render call and tweak them to match * the external lights collection if PreserveGLLights is set to true (default * behavior). */ void SynchronizeGLLights(); vtkTypeBool PreserveGLCameraMatrices; vtkTypeBool PreserveGLLights; vtkLightCollection* ExternalLights; private: vtkExternalOpenGLRenderer(const vtkExternalOpenGLRenderer&) = delete; void operator=(const vtkExternalOpenGLRenderer&) = delete; }; #endif // vtkExternalOpenGLRenderer_h
1,230
1,141
<filename>EHenTaiViewer/QJTipViewController.h // // QJTipViewController.h // EHenTaiViewer // // Created by QinJ on 2017/11/30. // Copyright © 2017年 kayanouriko. All rights reserved. // #import <UIKit/UIKit.h> @interface QJTipViewController : UIViewController - (void)startAnimateWithTip:(NSString *)tip; - (void)stopAnimateWithTip:(NSString *)tip; @end
136
2,151
<filename>chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler_unittest.cc // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/interventions_internals/interventions_internals_page_handler.h" #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/base_switches.h" #include "base/command_line.h" #include "base/macros.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/run_loop.h" #include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "chrome/browser/flag_descriptions.h" #include "chrome/browser/net/nqe/ui_network_quality_estimator_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/interventions_internals/interventions_internals.mojom.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "components/previews/content/previews_io_data.h" #include "components/previews/content/previews_ui_service.h" #include "components/previews/core/previews_features.h" #include "components/previews/core/previews_logger.h" #include "components/previews/core/previews_logger_observer.h" #include "components/previews/core/previews_switches.h" #include "content/public/test/test_browser_thread_bundle.h" #include "mojo/public/cpp/bindings/binding.h" #include "net/nqe/effective_connection_type.h" #include "net/nqe/network_quality_estimator_params.h" #include "services/network/public/cpp/network_switches.h" #include "testing/gtest/include/gtest/gtest.h" namespace { // The HTML DOM ID used in Javascript. constexpr char kPreviewsAllowedHtmlId[] = "previews-allowed-status"; constexpr char kClientLoFiPreviewsHtmlId[] = "client-lofi-preview-status"; constexpr char kNoScriptPreviewsHtmlId[] = "noscript-preview-status"; constexpr char kOfflinePreviewsHtmlId[] = "offline-preview-status"; // Descriptions for previews. constexpr char kPreviewsAllowedDescription[] = "Previews Allowed"; constexpr char kClientLoFiDescription[] = "Client LoFi Previews"; constexpr char kNoScriptDescription[] = "NoScript Previews"; constexpr char kOfflineDesciption[] = "Offline Previews"; // The HTML DOM ID used in Javascript. constexpr char kEctFlagHtmlId[] = "ect-flag"; constexpr char kIgnorePreviewsBlacklistFlagHtmlId[] = "ignore-previews-blacklist"; constexpr char kNoScriptFlagHtmlId[] = "noscript-flag"; constexpr char kOfflinePageFlagHtmlId[] = "offline-page-flag"; // Links to flags in chrome://flags. constexpr char kNoScriptFlagLink[] = "chrome://flags/#enable-noscript-previews"; constexpr char kEctFlagLink[] = "chrome://flags/#force-effective-connection-type"; constexpr char kIgnorePreviewsBlacklistLink[] = "chrome://flags/#ignore-previews-blacklist"; constexpr char kOfflinePageFlagLink[] = "chrome://flags/#enable-offline-previews"; // Flag features names. constexpr char kNoScriptFeatureName[] = "NoScriptPreviews"; constexpr char kOfflinePageFeatureName[] = "OfflinePreviews"; constexpr char kDefaultFlagValue[] = "Default"; constexpr char kEnabledFlagValue[] = "Enabled"; constexpr char kDisabledFlagValue[] = "Disabled"; // The map that would be passed to the callback in GetPreviewsEnabledCallback. std::unordered_map<std::string, mojom::PreviewsStatusPtr> passed_in_modes; // The map that would be passed to the callback in // GetPreviewsFlagsDetailsCallback. std::unordered_map<std::string, mojom::PreviewsFlagPtr> passed_in_flags; // Mocked call back method to test GetPreviewsEnabledCallback. void MockGetPreviewsEnabledCallback( std::vector<mojom::PreviewsStatusPtr> params) { passed_in_modes.clear(); for (size_t i = 0; i < params.size(); i++) { passed_in_modes[params[i]->htmlId] = std::move(params[i]); } } // Mocked call back method to test GetPreviewsFlagsDetailsCallback. void MockGetPreviewsFlagsCallback(std::vector<mojom::PreviewsFlagPtr> params) { passed_in_flags.clear(); for (size_t i = 0; i < params.size(); i++) { passed_in_flags[params[i]->htmlId] = std::move(params[i]); } } // Dummy method for creating TestPreviewsUIService. bool MockedPreviewsIsEnabled(previews::PreviewsType type) { return true; } // Mock class that would be pass into the InterventionsInternalsPageHandler by // calling its SetClientPage method. Used to test that the PageHandler // actually invokes the page's LogNewMessage method with the correct message. class TestInterventionsInternalsPage : public mojom::InterventionsInternalsPage { public: TestInterventionsInternalsPage( mojom::InterventionsInternalsPageRequest request) : binding_(this, std::move(request)), blacklist_ignored_(false) {} ~TestInterventionsInternalsPage() override {} // mojom::InterventionsInternalsPage: void LogNewMessage(mojom::MessageLogPtr message) override { message_ = std::make_unique<mojom::MessageLogPtr>(std::move(message)); } void OnBlacklistedHost(const std::string& host, int64_t time) override { host_blacklisted_ = host; host_blacklisted_time_ = time; } void OnUserBlacklistedStatusChange(bool blacklisted) override { user_blacklisted_ = blacklisted; } void OnBlacklistCleared(int64_t time) override { blacklist_cleared_time_ = time; } void OnEffectiveConnectionTypeChanged(const std::string& type) override { // Ignore. // TODO(thanhdle): Add integration test to test behavior of the pipeline end // to end. crbug.com/777936 } void OnIgnoreBlacklistDecisionStatusChanged(bool ignored) override { blacklist_ignored_ = ignored; } // Expose passed in message in LogNewMessage for testing. mojom::MessageLogPtr* message() const { return message_.get(); } // Expose passed in blacklist events info for testing. std::string host_blacklisted() const { return host_blacklisted_; } int64_t host_blacklisted_time() const { return host_blacklisted_time_; } bool user_blacklisted() const { return user_blacklisted_; } int64_t blacklist_cleared_time() const { return blacklist_cleared_time_; } // Expose the passed in blacklist ignore status for testing. bool blacklist_ignored() const { return blacklist_ignored_; } private: mojo::Binding<mojom::InterventionsInternalsPage> binding_; // The MessageLogPtr passed in LogNewMessage method. std::unique_ptr<mojom::MessageLogPtr> message_; // Received blacklist events info. std::string host_blacklisted_; int64_t host_blacklisted_time_; int64_t user_blacklisted_; int64_t blacklist_cleared_time_; // Whether to ignore previews blacklist decisions. bool blacklist_ignored_; }; // Mock class to test interaction between the PageHandler and the // PreviewsLogger. class TestPreviewsLogger : public previews::PreviewsLogger { public: TestPreviewsLogger() : PreviewsLogger(), remove_is_called_(false) {} // PreviewsLogger: void RemoveObserver(previews::PreviewsLoggerObserver* obs) override { remove_is_called_ = true; } bool RemovedObserverIsCalled() const { return remove_is_called_; } private: bool remove_is_called_; }; // Mock class to test interaction between PageHandler and the // UINetworkQualityEstimatorService. class TestUINetworkQualityEstimatorService : public UINetworkQualityEstimatorService { public: explicit TestUINetworkQualityEstimatorService(Profile* profile) : UINetworkQualityEstimatorService(profile), remove_is_called_(false) {} // UINetworkQualityEstimatorService: void RemoveEffectiveConnectionTypeObserver( net::EffectiveConnectionTypeObserver* observer) override { remove_is_called_ = true; } bool RemovedObserverIsCalled() const { return remove_is_called_; } private: // Check if the observer removed itself from the observer list. bool remove_is_called_; }; // A dummy class to setup PreviewsUIService. class TestPreviewsIOData : public previews::PreviewsIOData { public: TestPreviewsIOData() : PreviewsIOData(nullptr, nullptr) {} // previews::PreviewsIOData: void Initialize( base::WeakPtr<previews::PreviewsUIService> previews_ui_service, std::unique_ptr<previews::PreviewsOptOutStore> opt_out_store, std::unique_ptr<previews::PreviewsOptimizationGuide> previews_opt_guide, const previews::PreviewsIsEnabledCallback& is_enabled_callback) override { // Do nothing. } }; // Mocked TestPreviewsService for testing InterventionsInternalsPageHandler. class TestPreviewsUIService : public previews::PreviewsUIService { public: TestPreviewsUIService(TestPreviewsIOData* io_data, std::unique_ptr<previews::PreviewsLogger> logger) : PreviewsUIService(io_data, nullptr, /* io_task_runner */ nullptr, /* previews_opt_out_store */ nullptr, /* previews_opt_guide */ base::Bind(&MockedPreviewsIsEnabled), std::move(logger)), blacklist_ignored_(false) {} ~TestPreviewsUIService() override {} // previews::PreviewsUIService: void SetIgnorePreviewsBlacklistDecision(bool ignored) override { blacklist_ignored_ = ignored; } // Exposed blacklist ignored state. bool blacklist_ignored() const { return blacklist_ignored_; } private: // Whether the blacklist decisions are ignored or not. bool blacklist_ignored_; }; class InterventionsInternalsPageHandlerTest : public testing::Test { public: InterventionsInternalsPageHandlerTest() : profile_manager_(TestingBrowserProcess::GetGlobal()) {} ~InterventionsInternalsPageHandlerTest() override {} void SetUp() override { TestPreviewsIOData io_data; std::unique_ptr<TestPreviewsLogger> logger = std::make_unique<TestPreviewsLogger>(); logger_ = logger.get(); previews_ui_service_ = std::make_unique<TestPreviewsUIService>(&io_data, std::move(logger)); ASSERT_TRUE(profile_manager_.SetUp()); TestingProfile* test_profile = profile_manager_.CreateTestingProfile(chrome::kInitialProfile); ui_nqe_service_ = std::make_unique<TestUINetworkQualityEstimatorService>(test_profile); mojom::InterventionsInternalsPageHandlerPtr page_handler_ptr; handler_request_ = mojo::MakeRequest(&page_handler_ptr); page_handler_ = std::make_unique<InterventionsInternalsPageHandler>( std::move(handler_request_), previews_ui_service_.get(), ui_nqe_service_.get()); mojom::InterventionsInternalsPagePtr page_ptr; page_request_ = mojo::MakeRequest(&page_ptr); page_ = std::make_unique<TestInterventionsInternalsPage>( std::move(page_request_)); page_handler_->SetClientPage(std::move(page_ptr)); scoped_feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); } void TearDown() override { profile_manager_.DeleteAllTestingProfiles(); } content::TestBrowserThreadBundle thread_bundle_; protected: TestingProfileManager profile_manager_; TestPreviewsLogger* logger_; std::unique_ptr<TestPreviewsUIService> previews_ui_service_; std::unique_ptr<TestUINetworkQualityEstimatorService> ui_nqe_service_; // InterventionsInternalPageHandler's variables. mojom::InterventionsInternalsPageHandlerRequest handler_request_; std::unique_ptr<InterventionsInternalsPageHandler> page_handler_; // InterventionsInternalPage's variables. mojom::InterventionsInternalsPageRequest page_request_; std::unique_ptr<TestInterventionsInternalsPage> page_; std::unique_ptr<base::test::ScopedFeatureList> scoped_feature_list_; }; TEST_F(InterventionsInternalsPageHandlerTest, GetPreviewsEnabledCount) { page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); constexpr size_t expected = 4; EXPECT_EQ(expected, passed_in_modes.size()); } TEST_F(InterventionsInternalsPageHandlerTest, PreviewsAllowedDisabled) { // Init with kPreviews disabled. scoped_feature_list_->InitWithFeatures({}, {previews::features::kPreviews}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto previews_allowed = passed_in_modes.find(kPreviewsAllowedHtmlId); ASSERT_NE(passed_in_modes.end(), previews_allowed); EXPECT_EQ(kPreviewsAllowedDescription, previews_allowed->second->description); EXPECT_FALSE(previews_allowed->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, PreviewsAllowedEnabled) { // Init with kPreviews enabled. scoped_feature_list_->InitWithFeatures({previews::features::kPreviews}, {}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto previews_allowed = passed_in_modes.find(kPreviewsAllowedHtmlId); ASSERT_NE(passed_in_modes.end(), previews_allowed); EXPECT_EQ(kPreviewsAllowedDescription, previews_allowed->second->description); EXPECT_TRUE(previews_allowed->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, ClientLoFiDisabled) { // Init with kClientLoFi disabled. scoped_feature_list_->InitWithFeatures({}, {previews::features::kClientLoFi}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto client_lofi = passed_in_modes.find(kClientLoFiPreviewsHtmlId); ASSERT_NE(passed_in_modes.end(), client_lofi); EXPECT_EQ(kClientLoFiDescription, client_lofi->second->description); EXPECT_FALSE(client_lofi->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, ClientLoFiEnabled) { // Init with kClientLoFi enabled. scoped_feature_list_->InitWithFeatures({previews::features::kClientLoFi}, {}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto client_lofi = passed_in_modes.find(kClientLoFiPreviewsHtmlId); ASSERT_NE(passed_in_modes.end(), client_lofi); EXPECT_EQ(kClientLoFiDescription, client_lofi->second->description); EXPECT_TRUE(client_lofi->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, NoScriptDisabled) { // Init with kNoScript disabled. scoped_feature_list_->InitWithFeatures( {}, {previews::features::kNoScriptPreviews}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto noscript = passed_in_modes.find(kNoScriptPreviewsHtmlId); ASSERT_NE(passed_in_modes.end(), noscript); EXPECT_EQ(kNoScriptDescription, noscript->second->description); EXPECT_FALSE(noscript->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, NoScriptEnabled) { // Init with kNoScript enabled. scoped_feature_list_->InitWithFeatures( {previews::features::kNoScriptPreviews}, {}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto noscript = passed_in_modes.find(kNoScriptPreviewsHtmlId); ASSERT_NE(passed_in_modes.end(), noscript); EXPECT_EQ(kNoScriptDescription, noscript->second->description); EXPECT_TRUE(noscript->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, OfflinePreviewsDisabled) { // Init with kOfflinePreviews disabled. scoped_feature_list_->InitWithFeatures( {}, {previews::features::kOfflinePreviews}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto offline_previews = passed_in_modes.find(kOfflinePreviewsHtmlId); ASSERT_NE(passed_in_modes.end(), offline_previews); EXPECT_EQ(kOfflineDesciption, offline_previews->second->description); EXPECT_FALSE(offline_previews->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, OfflinePreviewsEnabled) { // Init with kOfflinePreviews enabled. scoped_feature_list_->InitWithFeatures({previews::features::kOfflinePreviews}, {}); page_handler_->GetPreviewsEnabled( base::BindOnce(&MockGetPreviewsEnabledCallback)); auto offline_previews = passed_in_modes.find(kOfflinePreviewsHtmlId); ASSERT_NE(passed_in_modes.end(), offline_previews); EXPECT_TRUE(offline_previews->second); EXPECT_EQ(kOfflineDesciption, offline_previews->second->description); EXPECT_TRUE(offline_previews->second->enabled); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsCount) { page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); constexpr size_t expected = 5; EXPECT_EQ(expected, passed_in_flags.size()); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsEctDefaultValue) { page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto ect_flag = passed_in_flags.find(kEctFlagHtmlId); ASSERT_NE(passed_in_flags.end(), ect_flag); EXPECT_EQ(flag_descriptions::kForceEffectiveConnectionTypeName, ect_flag->second->description); EXPECT_EQ(kDefaultFlagValue, ect_flag->second->value); EXPECT_EQ(kEctFlagLink, ect_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsForceEctValue) { std::string expected_ects[] = { net::kEffectiveConnectionTypeUnknown, net::kEffectiveConnectionTypeOffline, net::kEffectiveConnectionTypeSlow2G, net::kEffectiveConnectionType3G, net::kEffectiveConnectionType4G, }; base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); for (auto expected_ect : expected_ects) { command_line->AppendSwitchASCII( network::switches::kForceEffectiveConnectionType, expected_ect); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto ect_flag = passed_in_flags.find(kEctFlagHtmlId); ASSERT_NE(passed_in_flags.end(), ect_flag); EXPECT_EQ(flag_descriptions::kForceEffectiveConnectionTypeName, ect_flag->second->description); EXPECT_EQ(expected_ect, ect_flag->second->value); EXPECT_EQ(kEctFlagLink, ect_flag->second->link); } } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsEctForceFieldtrialValue) { base::FieldTrialList field_trial_list_(nullptr); const std::string trial_name = "NetworkQualityEstimator"; const std::string group_name = "Enabled"; const std::string expected_ect = "Slow-2G"; std::map<std::string, std::string> params; params[net::kForceEffectiveConnectionType] = expected_ect; ASSERT_TRUE(base::AssociateFieldTrialParams(trial_name, group_name, params)); base::FieldTrialList::CreateFieldTrial(trial_name, group_name); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto ect_flag = passed_in_flags.find(kEctFlagHtmlId); ASSERT_NE(passed_in_flags.end(), ect_flag); EXPECT_EQ(flag_descriptions::kForceEffectiveConnectionTypeName, ect_flag->second->description); EXPECT_EQ("Fieldtrial forced " + expected_ect, ect_flag->second->value); EXPECT_EQ(kEctFlagLink, ect_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsIgnorePreviewsBlacklistDisabledValue) { // Disabled by default. page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto ignore_previews_blacklist = passed_in_flags.find(kIgnorePreviewsBlacklistFlagHtmlId); ASSERT_NE(passed_in_flags.end(), ignore_previews_blacklist); EXPECT_EQ(flag_descriptions::kIgnorePreviewsBlacklistName, ignore_previews_blacklist->second->description); EXPECT_EQ(kDisabledFlagValue, ignore_previews_blacklist->second->value); EXPECT_EQ(kIgnorePreviewsBlacklistLink, ignore_previews_blacklist->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsNoScriptDisabledValue) { page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto ignore_previews_blacklist = passed_in_flags.find(kIgnorePreviewsBlacklistFlagHtmlId); ASSERT_NE(passed_in_flags.end(), ignore_previews_blacklist); EXPECT_EQ(flag_descriptions::kIgnorePreviewsBlacklistName, ignore_previews_blacklist->second->description); EXPECT_EQ(kDisabledFlagValue, ignore_previews_blacklist->second->value); EXPECT_EQ(kIgnorePreviewsBlacklistLink, ignore_previews_blacklist->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsNoScriptDefaultValue) { page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto noscript_flag = passed_in_flags.find(kNoScriptFlagHtmlId); ASSERT_NE(passed_in_flags.end(), noscript_flag); EXPECT_EQ(flag_descriptions::kEnableNoScriptPreviewsName, noscript_flag->second->description); EXPECT_EQ(kDefaultFlagValue, noscript_flag->second->value); EXPECT_EQ(kNoScriptFlagLink, noscript_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsNoScriptEnabled) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->AppendSwitchASCII(switches::kEnableFeatures, kNoScriptFeatureName); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto noscript_flag = passed_in_flags.find(kNoScriptFlagHtmlId); ASSERT_NE(passed_in_flags.end(), noscript_flag); EXPECT_EQ(flag_descriptions::kEnableNoScriptPreviewsName, noscript_flag->second->description); EXPECT_EQ(kEnabledFlagValue, noscript_flag->second->value); EXPECT_EQ(kNoScriptFlagLink, noscript_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, GetFlagsNoScriptDisabled) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->AppendSwitchASCII(switches::kDisableFeatures, kNoScriptFeatureName); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto noscript_flag = passed_in_flags.find(kNoScriptFlagHtmlId); ASSERT_NE(passed_in_flags.end(), noscript_flag); EXPECT_EQ(flag_descriptions::kEnableNoScriptPreviewsName, noscript_flag->second->description); EXPECT_EQ(kDisabledFlagValue, noscript_flag->second->value); EXPECT_EQ(kNoScriptFlagLink, noscript_flag->second->link); } #if defined(OS_ANDROID) #define TestAndroid(x) x #else #define TestAndroid(x) DISABLED_##x #endif // OS_ANDROID TEST_F(InterventionsInternalsPageHandlerTest, TestAndroid(GetFlagsOfflinePageDefaultValue)) { page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto offline_page_flag = passed_in_flags.find(kOfflinePageFlagHtmlId); ASSERT_NE(passed_in_flags.end(), offline_page_flag); #if defined(OS_ANDROID) EXPECT_EQ(flag_descriptions::kEnableOfflinePreviewsName, offline_page_flag->second->description); #endif // OS_ANDROID EXPECT_EQ(kDefaultFlagValue, offline_page_flag->second->value); EXPECT_EQ(kOfflinePageFlagLink, offline_page_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, TestAndroid(GetFlagsOfflinePageEnabled)) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->AppendSwitchASCII(switches::kEnableFeatures, kOfflinePageFeatureName); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto offline_page_flag = passed_in_flags.find(kOfflinePageFlagHtmlId); ASSERT_NE(passed_in_flags.end(), offline_page_flag); #if defined(OS_ANDROID) EXPECT_EQ(flag_descriptions::kEnableOfflinePreviewsName, offline_page_flag->second->description); #endif // OS_ANDROID EXPECT_EQ(kEnabledFlagValue, offline_page_flag->second->value); EXPECT_EQ(kOfflinePageFlagLink, offline_page_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, TestAndroid(GetFlagsOfflinePageDisabled)) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->AppendSwitchASCII(switches::kDisableFeatures, kOfflinePageFeatureName); page_handler_->GetPreviewsFlagsDetails( base::BindOnce(&MockGetPreviewsFlagsCallback)); auto offline_page_flag = passed_in_flags.find(kOfflinePageFlagHtmlId); ASSERT_NE(passed_in_flags.end(), offline_page_flag); #if defined(OS_ANDROID) EXPECT_EQ(flag_descriptions::kEnableOfflinePreviewsName, offline_page_flag->second->description); #endif // OS_ANDROID EXPECT_EQ(kDisabledFlagValue, offline_page_flag->second->value); EXPECT_EQ(kOfflinePageFlagLink, offline_page_flag->second->link); } TEST_F(InterventionsInternalsPageHandlerTest, OnNewMessageLogAddedPostToPage) { const previews::PreviewsLogger::MessageLog expected_messages[] = { previews::PreviewsLogger::MessageLog( "Event_a", "Some description a", GURL("http://www.url_a.com/url_a"), base::Time::Now(), 1234UL /* page_id */), previews::PreviewsLogger::MessageLog( "Event_b", "Some description b", GURL("http://www.url_b.com/url_b"), base::Time::Now(), 4321UL /* page_id */), previews::PreviewsLogger::MessageLog( "Event_c", "Some description c", GURL("http://www.url_c.com/url_c"), base::Time::Now(), 6789UL /* page_id */), }; for (auto message : expected_messages) { page_handler_->OnNewMessageLogAdded(message); base::RunLoop().RunUntilIdle(); mojom::MessageLogPtr* actual = page_->message(); EXPECT_EQ(message.event_type, (*actual)->type); EXPECT_EQ(message.event_description, (*actual)->description); EXPECT_EQ(message.url, (*actual)->url); int64_t expected_time = message.time.ToJavaTime(); EXPECT_EQ(expected_time, (*actual)->time); EXPECT_EQ(message.page_id, (*actual)->page_id); } } TEST_F(InterventionsInternalsPageHandlerTest, ObserverIsRemovedWhenDestroyed) { EXPECT_FALSE(logger_->RemovedObserverIsCalled()); EXPECT_FALSE(ui_nqe_service_->RemovedObserverIsCalled()); page_handler_.reset(); EXPECT_TRUE(logger_->RemovedObserverIsCalled()); EXPECT_TRUE(ui_nqe_service_->RemovedObserverIsCalled()); } TEST_F(InterventionsInternalsPageHandlerTest, OnNewBlacklistedHostPostToPage) { const std::string hosts[] = { "example_0.com", "example_1.com", "example_2.com", }; for (auto expected_host : hosts) { base::Time expected_time = base::Time::Now(); page_handler_->OnNewBlacklistedHost(expected_host, expected_time); base::RunLoop().RunUntilIdle(); EXPECT_EQ(expected_host, page_->host_blacklisted()); EXPECT_EQ(expected_time.ToJavaTime(), page_->host_blacklisted_time()); } } TEST_F(InterventionsInternalsPageHandlerTest, OnUserBlacklistedPostToPage) { page_handler_->OnUserBlacklistedStatusChange(true /* blacklisted */); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(page_->user_blacklisted()); page_handler_->OnUserBlacklistedStatusChange(false /* blacklisted */); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(page_->user_blacklisted()); } TEST_F(InterventionsInternalsPageHandlerTest, OnBlacklistClearedPostToPage) { base::Time times[] = { base::Time::FromJsTime(-413696806000), // Nov 21 1956 20:13:14 UTC base::Time::FromJsTime(758620800000), // Jan 15 1994 08:00:00 UTC base::Time::FromJsTime(1581696550000), // Feb 14 2020 16:09:10 UTC }; for (auto expected_time : times) { page_handler_->OnBlacklistCleared(expected_time); base::RunLoop().RunUntilIdle(); EXPECT_EQ(expected_time.ToJavaTime(), page_->blacklist_cleared_time()); } } TEST_F(InterventionsInternalsPageHandlerTest, SetIgnorePreviewsBlacklistDecisionCallsUIServiceCorrectly) { page_handler_->SetIgnorePreviewsBlacklistDecision(true /* ignored */); EXPECT_TRUE(previews_ui_service_->blacklist_ignored()); page_handler_->SetIgnorePreviewsBlacklistDecision(false /* ignored */); EXPECT_FALSE(previews_ui_service_->blacklist_ignored()); } TEST_F(InterventionsInternalsPageHandlerTest, PageUpdateOnBlacklistIgnoredChange) { page_handler_->OnIgnoreBlacklistDecisionStatusChanged(true /* ignored */); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(page_->blacklist_ignored()); page_handler_->OnIgnoreBlacklistDecisionStatusChanged(false /* ignored */); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(page_->blacklist_ignored()); } TEST_F(InterventionsInternalsPageHandlerTest, IgnoreBlacklistReversedOnLastObserverRemovedCalled) { ASSERT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch( previews::switches::kIgnorePreviewsBlacklist)); page_handler_->OnLastObserverRemove(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(page_->blacklist_ignored()); } TEST_F(InterventionsInternalsPageHandlerTest, IgnoreBlacklistReversedOnLastObserverRemovedCalledIgnoreViaFlag) { base::test::ScopedCommandLine scoped_command_line; base::CommandLine* command_line = scoped_command_line.GetProcessCommandLine(); command_line->AppendSwitch(previews::switches::kIgnorePreviewsBlacklist); ASSERT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch( previews::switches::kIgnorePreviewsBlacklist)); page_handler_->OnLastObserverRemove(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(page_->blacklist_ignored()); } } // namespace
10,402
3,227
namespace CGAL { /*! \ingroup PkgSegmentDelaunayGraph2Ref \cgalModels `SegmentDelaunayGraphFaceBase_2` The class `Segment_Delaunay_graph_face_base_2` provides a model for the `SegmentDelaunayGraphFaceBase_2` concept which is the face base required by the `SegmentDelaunayGraphDataStructure_2` concept. \tparam Gt must be a model of the concept `SegmentDelaunayGraphTraits_2`. This type must be identical to the template parameter used for `CGAL::Segment_Delaunay_graph_2`. \tparam Fb is a face base class from which `Segment_Delaunay_graph_face_base_2` derives. It must be a model of the `TriangulationFaceBase_2` concept. It has the default value `CGAL::Triangulation_face_base_2<Gt>`. */ template< typename Gt, typename Fb > class Segment_Delaunay_graph_face_base_2 { public: }; /* end Segment_Delaunay_graph_face_base_2 */ } /* end namespace CGAL */
330
354
#include<bits/stdc++.h> using namespace std; void leftRotate(int arr[], int d, int n) { d = d % n; //handle if d >=n int g_c_d = __gcd(d, n); // __gcd predefine method in c++.which takes two input and return gcd. for (int i = 0; i < g_c_d; i++) { int temp = arr[i]; // move i-th values of blocks int j = i; while (1) { int k = j + d; if (k >= n) k = k - n; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; } } void printArray(int arr[], int size) // Function to print an array { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout<<endl; } int main() { int n,k; cout<<"Enter size of an array and value of k:\n"; cin>>n>>k; int arr[n]; for(int i=0; i<n; i++) { cin>>arr[i]; } cout<<"Before Rotation:\n"; printArray(arr, n); leftRotate(arr,k, n); // Function calling cout<<"After Rotation:\n"; printArray(arr, n); return 0; } //Time complexity: o(n) and space complexity:o(1)
594
1,306
package io.github.biezhi.java8.growing.jdk8; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; /** * 并行数组 * * @author biezhi * @date 2018/2/8 */ public class ParallelArrays { public static void main(String[] args) { long[] arrayOfLong = new long[20000]; Arrays.parallelSetAll(arrayOfLong, index -> ThreadLocalRandom.current().nextInt(1000000)); Arrays.stream(arrayOfLong).limit(10).forEach( i -> System.out.print(i + " ")); System.out.println(); Arrays.parallelSort(arrayOfLong); Arrays.stream(arrayOfLong).limit(10).forEach( i -> System.out.print(i + " ")); System.out.println(); } }
328
403
package io.craft.atom.nio.api; import io.craft.atom.io.IoHandler; import io.craft.atom.nio.NioAdaptiveBufferSizePredictorFactory; import io.craft.atom.nio.NioConfig; import io.craft.atom.nio.NioOrderedDirectChannelEventDispatcher; import io.craft.atom.nio.spi.NioBufferSizePredictorFactory; import io.craft.atom.nio.spi.NioChannelEventDispatcher; /** * @author mindwind * @version 1.0, Mar 7, 2014 */ public abstract class NioBuilder<T> { protected final IoHandler handler ; protected NioChannelEventDispatcher dispatcher = new NioOrderedDirectChannelEventDispatcher(); protected NioBufferSizePredictorFactory predictorFactory = new NioAdaptiveBufferSizePredictorFactory() ; protected int readBufferSize = 2048 ; protected int minReadBufferSize = 64 ; protected int maxReadBufferSize = 65536 ; protected int ioTimeoutInMillis = 120 * 1000 ; protected int processorPoolSize = Runtime.getRuntime().availableProcessors() ; protected int executorSize = processorPoolSize << 3 ; protected int channelEventSize = Integer.MAX_VALUE ; protected int totalEventSize = Integer.MAX_VALUE ; protected boolean readWriteFair = true ; public NioBuilder(IoHandler handler) { this.handler = handler; } public NioBuilder<T> minReadBufferSize(int size) { this.minReadBufferSize = size ; return this; } public NioBuilder<T> maxReadBufferSize(int size) { this.maxReadBufferSize = size ; return this; } public NioBuilder<T> readBufferSize (int size) { this.readBufferSize = size ; return this; } public NioBuilder<T> processorPoolSize(int size) { this.processorPoolSize = size ; return this; } public NioBuilder<T> executorSize (int size) { this.executorSize = size ; return this; } public NioBuilder<T> channelEventSize (int size) { this.channelEventSize = size ; return this; } public NioBuilder<T> totalEventSize (int size) { this.totalEventSize = size ; return this; } public NioBuilder<T> ioTimeoutInMillis(int timeout) { this.ioTimeoutInMillis = timeout ; return this; } public NioBuilder<T> readWriteFair (boolean fair) { this.readWriteFair = fair ; return this; } public NioBuilder<T> dispatcher (NioChannelEventDispatcher dispatcher) { this.dispatcher = dispatcher; return this; } public NioBuilder<T> predictorFactory (NioBufferSizePredictorFactory factory) { this.predictorFactory = factory ; return this; } protected void set(NioConfig config) { config.setReadWritefair(readWriteFair) ; config.setTotalEventSize(totalEventSize) ; config.setChannelEventSize(channelEventSize) ; config.setExecutorSize(executorSize) ; config.setProcessorPoolSize(processorPoolSize) ; config.setIoTimeoutInMillis(ioTimeoutInMillis) ; config.setDefaultReadBufferSize(readBufferSize); config.setMinReadBufferSize(minReadBufferSize) ; config.setMaxReadBufferSize(maxReadBufferSize) ; } abstract public T build(); }
1,927
982
/* * Copyright (C) 2019-2020 Red Hat, Inc. * * Written By: <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met : * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and / or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of their 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 HOLDERS 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. */ #pragma once extern "C" { #define __CPLUSPLUS #include <stddef.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <initguid.h> #include <ntddk.h> #ifndef FAR #define FAR #endif #include <windef.h> #include <winerror.h> #include <wingdi.h> #include <stdarg.h> #include <winddi.h> #include <ntddvdeo.h> #include <d3dkmddi.h> #include <d3dkmthk.h> #include <ntstrsafe.h> #include <ntintsafe.h> #include <dispmprt.h> #include "trace.h" #include "osdep.h" #include "virtio_pci.h" #include "virtio.h" #include "virtio_ring.h" #include "kdebugprint.h" #include "viogpu_pci.h" #include "viogpu.h" #include "viogpu_queue.h" #include "viogpu_idr.h" #include "viogpum.h" } #define MAX_CHILDREN 1 #define MAX_VIEWS 1 #define BITS_PER_BYTE 8 #define POINTER_SIZE 64 #if NTDDI_VERSION > NTDDI_WINBLUE #define MIN_WIDTH_SIZE 640 #define MIN_HEIGHT_SIZE 480 #else #define MIN_WIDTH_SIZE 1024 #define MIN_HEIGHT_SIZE 768 #endif #define NOM_WIDTH_SIZE 1024 #define NOM_HEIGHT_SIZE 768 #define VIOGPUTAG 'OIVg' extern VirtIOSystemOps VioGpuSystemOps; #define VIOGPU_LOG_ASSERTION0(Msg) NT_ASSERT(FALSE) #define VIOGPU_LOG_ASSERTION1(Msg,Param1) NT_ASSERT(FALSE) #define VIOGPU_ASSERT(exp) {if (!(exp)) {VIOGPU_LOG_ASSERTION0(#exp);}} #if DBG #define VIOGPU_ASSERT_CHK(exp) VIOGPU_ASSERT(exp) #else #define VIOGPU_ASSERT_CHK(exp) {} #endif #define PAGED_CODE_SEG __declspec(code_seg("PAGE")) #define PAGED_CODE_SEG_BEGIN \ __pragma(code_seg(push)) \ __pragma(code_seg("PAGE")) #define PAGED_CODE_SEG_END \ __pragma(code_seg(pop))
1,421
6,989
<gh_stars>1000+ # -*- coding: utf-8 -*- import pickle import random from collections import deque from copy import copy as shallow_copy import pytest from markupsafe import Markup from jinja2._compat import range_type from jinja2._compat import string_types from jinja2.utils import consume from jinja2.utils import generate_lorem_ipsum from jinja2.utils import LRUCache from jinja2.utils import missing from jinja2.utils import object_type_repr from jinja2.utils import select_autoescape from jinja2.utils import urlize class TestLRUCache(object): def test_simple(self): d = LRUCache(3) d["a"] = 1 d["b"] = 2 d["c"] = 3 d["a"] d["d"] = 4 assert len(d) == 3 assert "a" in d and "c" in d and "d" in d and "b" not in d def test_itervalue_deprecated(self): cache = LRUCache(3) cache["a"] = 1 cache["b"] = 2 with pytest.deprecated_call(): cache.itervalue() def test_itervalues(self): cache = LRUCache(3) cache["b"] = 1 cache["a"] = 2 values = [v for v in cache.values()] assert len(values) == 2 assert 1 in values assert 2 in values def test_itervalues_empty(self): cache = LRUCache(2) values = [v for v in cache.values()] assert len(values) == 0 def test_pickleable(self): cache = LRUCache(2) cache["foo"] = 42 cache["bar"] = 23 cache["foo"] for protocol in range(3): copy = pickle.loads(pickle.dumps(cache, protocol)) assert copy.capacity == cache.capacity assert copy._mapping == cache._mapping assert copy._queue == cache._queue @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy]) def test_copy(self, copy_func): cache = LRUCache(2) cache["a"] = 1 cache["b"] = 2 copy = copy_func(cache) assert copy._queue == cache._queue copy["c"] = 3 assert copy._queue != cache._queue assert "a" not in copy and "b" in copy and "c" in copy def test_clear(self): d = LRUCache(3) d["a"] = 1 d["b"] = 2 d["c"] = 3 d.clear() assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])} def test_repr(self): d = LRUCache(3) d["a"] = 1 d["b"] = 2 d["c"] = 3 # Sort the strings - mapping is unordered assert sorted(repr(d)) == sorted(u"<LRUCache {'a': 1, 'b': 2, 'c': 3}>") def test_items(self): """Test various items, keys, values and iterators of LRUCache.""" d = LRUCache(3) d["a"] = 1 d["b"] = 2 d["c"] = 3 assert d.items() == [("c", 3), ("b", 2), ("a", 1)] assert d.keys() == ["c", "b", "a"] assert d.values() == [3, 2, 1] assert list(reversed(d)) == ["a", "b", "c"] # Change the cache a little d["b"] d["a"] = 4 assert d.items() == [("a", 4), ("b", 2), ("c", 3)] assert d.keys() == ["a", "b", "c"] assert d.values() == [4, 2, 3] assert list(reversed(d)) == ["c", "b", "a"] def test_setdefault(self): d = LRUCache(3) assert len(d) == 0 assert d.setdefault("a") is None assert d.setdefault("a", 1) is None assert len(d) == 1 assert d.setdefault("b", 2) == 2 assert len(d) == 2 class TestHelpers(object): def test_object_type_repr(self): class X(object): pass assert object_type_repr(42) == "int object" assert object_type_repr([]) == "list object" assert object_type_repr(X()) == "__tests__.test_utils.X object" assert object_type_repr(None) == "None" assert object_type_repr(Ellipsis) == "Ellipsis" def test_autoescape_select(self): func = select_autoescape( enabled_extensions=("html", ".htm"), disabled_extensions=("txt",), default_for_string="STRING", default="NONE", ) assert func(None) == "STRING" assert func("unknown.foo") == "NONE" assert func("foo.html") assert func("foo.htm") assert not func("foo.txt") assert func("FOO.HTML") assert not func("FOO.TXT") class TestEscapeUrlizeTarget(object): def test_escape_urlize_target(self): url = "http://example.org" target = "<script>" assert urlize(url, target=target) == ( '<a href="http://example.org"' ' target="&lt;script&gt;">' "http://example.org</a>" ) class TestLoremIpsum(object): def test_lorem_ipsum_markup(self): """Test that output of lorem_ipsum is Markup by default.""" assert isinstance(generate_lorem_ipsum(), Markup) def test_lorem_ipsum_html(self): """Test that output of lorem_ipsum is a string_type when not html.""" assert isinstance(generate_lorem_ipsum(html=False), string_types) def test_lorem_ipsum_n(self): """Test that the n (number of lines) works as expected.""" assert generate_lorem_ipsum(n=0, html=False) == u"" for n in range_type(1, 50): assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2 def test_lorem_ipsum_min(self): """Test that at least min words are in the output of each line""" for _ in range_type(5): m = random.randrange(20, 99) for _ in range_type(10): assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1 def test_lorem_ipsum_max(self): """Test that at least max words are in the output of each line""" for _ in range_type(5): m = random.randrange(21, 100) for _ in range_type(10): assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1 def test_missing(): """Test the repr of missing.""" assert repr(missing) == u"missing" def test_consume(): """Test that consume consumes an iterator.""" x = iter([1, 2, 3, 4, 5]) consume(x) with pytest.raises(StopIteration): next(x)
2,924
963
<filename>core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/transaction/spring/jpa/service/ReleaseAfterStatementForumService.java package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.jpa.service; import com.vladmihalcea.book.hpjp.hibernate.forum.dto.PostDTO; import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post; import org.springframework.stereotype.Service; import java.util.List; /** * @author <NAME> */ @Service public interface ReleaseAfterStatementForumService { Post newPost(String title); PostDTO savePostTitle(Long id, String title); }
220
395
<gh_stars>100-1000 /** * Copyright 2017-2019 The OpenTracing Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.opentracing.contrib.spring.cloud.feign; import feign.Client; import feign.opentracing.FeignSpanDecorator; import feign.opentracing.TracingClient; import io.opentracing.Tracer; import java.util.List; /** * @author <NAME> */ class TracingClientBuilder { private Client delegate; private Tracer tracer; private List<FeignSpanDecorator> decorators; TracingClientBuilder(Client delegate, Tracer tracer) { this.delegate = delegate; this.tracer = tracer; } io.opentracing.contrib.spring.cloud.feign.TracingClientBuilder withFeignSpanDecorators(List<FeignSpanDecorator> decorators) { this.decorators = decorators; return this; } TracingClient build() { if (decorators == null || decorators.isEmpty()) { return new TracingClient(delegate, tracer); } return new TracingClient(delegate, tracer, decorators); } }
473
1,334
<gh_stars>1000+ package org.mockserver.model; import java.util.Objects; public class ExpectationId extends ObjectWithJsonToString { private int hashCode; private String id; public String getId() { return id; } public ExpectationId withId(String id) { this.id = id; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (hashCode() != o.hashCode()) { return false; } ExpectationId that = (ExpectationId) o; return Objects.equals(id, that.id); } @Override public int hashCode() { if (hashCode == 0) { hashCode = Objects.hash(id); } return hashCode; } }
408
2,421
<gh_stars>1000+ /* * Copyright 2012-2018 Chronicle Map Contributors * * 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 net.openhft.chronicle.map; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; /** * @author <NAME> */ public class CHMTestIterator1 { public static void main(String[] args) { AtomicLong alValue = new AtomicLong(); AtomicLong alKey = new AtomicLong(); int runs = 3000000; ChronicleMapBuilder<String, Long> builder = ChronicleMapBuilder.of(String.class, Long.class) .entries(runs); try (ChronicleMap<String, Long> chm = builder.create()) { /*chm.put("k1", alValue.incrementAndGet()); chm.put("k2", alValue.incrementAndGet()); chm.put("k3", alValue.incrementAndGet()); chm.put("k4", alValue.incrementAndGet()); chm.put("k5", alValue.incrementAndGet());*/ //chm.keySet(); for (int i = 0; i < runs; i++) { chm.put("k" + alKey.incrementAndGet(), alValue.incrementAndGet()); } long start = System.nanoTime(); for (Map.Entry<String, Long> entry : chm.entrySet()) { entry.getKey(); entry.getValue(); } long time = System.nanoTime() - start; System.out.println("Average iteration time was " + time / runs / 1e3 + "us, for " + runs / 1e6 + "m entries"); } } }
781
1,091
<filename>apps/openstacktelemetry/app/src/test/java/org/onosproject/openstacktelemetry/util/OpenstackTelemetryUtilTest.java /* * Copyright 2018-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.openstacktelemetry.util; import org.junit.Test; import org.onlab.packet.IPv4; import static org.junit.Assert.assertEquals; import static org.onosproject.openstacktelemetry.util.OpenstackTelemetryUtil.getProtocolNameFromType; import static org.onosproject.openstacktelemetry.util.OpenstackTelemetryUtil.getProtocolTypeFromString; public class OpenstackTelemetryUtilTest { private static final String PROTOCOL_TCP_L = "TCP"; private static final String PROTOCOL_TCP_S = "tcp"; private static final String PROTOCOL_UDP_L = "UDP"; private static final String PROTOCOL_UDP_S = "udp"; private static final String PROTOCOL_ANY_L = "ANY"; private static final String PROTOCOL_ANY_S = "any"; /** * Tests getting a protocol type from a protocol name. */ @Test public void testGetProtocolTypeFromString() { assertEquals(IPv4.PROTOCOL_TCP, getProtocolTypeFromString(PROTOCOL_TCP_L)); assertEquals(IPv4.PROTOCOL_TCP, getProtocolTypeFromString(PROTOCOL_TCP_S)); assertEquals(IPv4.PROTOCOL_UDP, getProtocolTypeFromString(PROTOCOL_UDP_L)); assertEquals(IPv4.PROTOCOL_UDP, getProtocolTypeFromString(PROTOCOL_UDP_S)); assertEquals(0, getProtocolTypeFromString(PROTOCOL_ANY_L)); assertEquals(0, getProtocolTypeFromString(PROTOCOL_ANY_S)); } /** * Tests getting a protocol name from a protocol type. */ @Test public void testGetProtocolNameFromType() { assertEquals(PROTOCOL_TCP_S, getProtocolNameFromType(IPv4.PROTOCOL_TCP)); assertEquals(PROTOCOL_UDP_S, getProtocolNameFromType(IPv4.PROTOCOL_UDP)); assertEquals(PROTOCOL_ANY_S, getProtocolNameFromType((byte) 0)); } }
892
799
<gh_stars>100-1000 import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 ALL_OPTION = 'All' NO_CAMPAIGN_INCIDENTS_MSG = 'There is no Campaign Incidents in the Context' NO_ID_IN_CONTEXT = 'There is no \"id\" key in the incidents' def get_campaign_incidents(): """ Get the campaign incidents form the incident's context :rtype: ``list`` :return: list of campaign incidents """ incident_id = demisto.incidents()[0]['id'] res = demisto.executeCommand('getContext', {'id': incident_id}) if isError(res): return_error(f'Error occurred while trying to get the incident context: {get_error(res)}') return demisto.get(res[0], 'Contents.context.EmailCampaign.incidents') def get_incident_ids_as_options(incidents): """ Collect the campaign incidents ids form the context and return them as options for MultiSelect field :type incidents: ``list`` :param incidents: the campaign incidents to collect ids from :rtype: ``dict`` :return: dict with the ids as options for MultiSelect field e.g {"hidden": False, "options": ids} """ try: ids = [str(incident['id']) for incident in incidents] ids.sort(key=lambda incident_id: int(incident_id)) ids.insert(0, ALL_OPTION) return {"hidden": False, "options": ids} except KeyError as e: raise DemistoException(NO_ID_IN_CONTEXT) from e def main(): try: incidents = get_campaign_incidents() if incidents: result = get_incident_ids_as_options(incidents) else: result = NO_CAMPAIGN_INCIDENTS_MSG return_results(result) except Exception as err: return_error(str(err), error=traceback.format_exc()) if __name__ in ('__main__', '__builtin__', 'builtins'): main()
731
973
/*_########################################################################## _## _## Copyright (C) 2016 Pcap4J.org _## _########################################################################## */ package org.pcap4j.packet; import java.util.Arrays; import org.pcap4j.packet.RadiotapPacket.RadiotapData; import org.pcap4j.util.ByteArrays; /** * Pad between Radiotap fields. * * @author <NAME> * @since pcap4j 1.6.5 */ public final class RadiotapDataPad implements RadiotapData { /** */ private static final long serialVersionUID = 2443487622598511815L; private final byte[] pad; /** * A static factory method. This method validates the arguments by {@link * ByteArrays#validateBounds(byte[], int, int)}, which may throw exceptions undocumented here. * * @param pad pad * @param offset offset * @param length length * @return a new RadiotapDataPad object. */ public static RadiotapDataPad newInstance(byte[] pad, int offset, int length) { ByteArrays.validateBounds(pad, offset, length); return new RadiotapDataPad(pad, offset, length); } private RadiotapDataPad(byte[] pad, int offset, int length) { this.pad = ByteArrays.getSubArray(pad, offset, length); } private RadiotapDataPad(Builder builder) { if (builder == null || builder.pad == null) { StringBuilder sb = new StringBuilder(); sb.append("builder: ").append(builder).append(" builder.pad: ").append(builder.pad); throw new NullPointerException(sb.toString()); } this.pad = ByteArrays.clone(builder.pad); } @Override public int length() { return pad.length; } @Override public byte[] getRawData() { return ByteArrays.clone(pad); } /** @return a new Builder object populated with this object's fields. */ public Builder getBuilder() { return new Builder(this); } @Override public String toString() { return toString(""); } @Override public String toString(String indent) { StringBuilder sb = new StringBuilder(); String ls = System.getProperty("line.separator"); sb.append(indent) .append("Pad: ") .append(ls) .append(indent) .append(" data: ") .append(ByteArrays.toHexString(pad, " ")) .append(ls); return sb.toString(); } @Override public int hashCode() { return Arrays.hashCode(pad); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!this.getClass().isInstance(obj)) { return false; } RadiotapDataPad other = (RadiotapDataPad) obj; return Arrays.equals(pad, other.pad); } /** * @author <NAME> * @since pcap4j 1.6.5 */ public static final class Builder { private byte[] pad; /** */ public Builder() {} private Builder(RadiotapDataPad obj) { this.pad = obj.pad; } /** * @param pad pad * @return this Builder object for method chaining. */ public Builder pad(byte[] pad) { this.pad = pad; return this; } /** @return a new RadiotapDataPad object. */ public RadiotapDataPad build() { return new RadiotapDataPad(this); } } }
1,159
7,880
import java.util.Scanner; /** * It provide some kind of BASIC language behaviour simulations. */ final class Basic { public static int randomOf(int base) { return (int)Math.round(Math.floor(base* Math.random() + 1)); } /** * The Console "simulate" the message error when input does not match with the expected type. * Specifically for this game if you enter an String when and int was expected. */ public static class Console { private final Scanner input = new Scanner(System.in); public String readLine() { return input.nextLine(); } public int readInt() { int ret = -1; boolean failedInput = true; do { boolean b = input.hasNextInt(); if (b) { ret = input.nextInt(); failedInput = false; } else { input.next(); // discard read System.out.print("!NUMBER EXPECTED - RETRY INPUT LINE\n? "); } } while (failedInput); return ret; } public void print(String message, Object... args) { System.out.printf(message, args); } } }
576
348
/* * Copyright (c) 2012-2014, <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 ALICE Project-Team 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. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: <NAME> * * <EMAIL> * http://www.loria.fr/~levy * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ #include <geogram_gfx/gui/simple_application.h> #include <geogram_gfx/basic/GLSL.h> #include <geogram/basic/command_line.h> #include <geogram/basic/file_system.h> #include <geogram/basic/stopwatch.h> #include <algorithm> #include <map> extern void register_embedded_glsl_files(GEO::FileSystem::MemoryNode* n); namespace { using namespace GEO; /** * \brief A super-simple shader authoring application. */ class GeoShadeApplication : public SimpleApplication { public: /** * \brief GeoShadeApplication constructor. */ GeoShadeApplication() : SimpleApplication("GeoShade") { builtin_files_ = new FileSystem::MemoryNode(); set_default_filename("hello.glsl"); use_text_editor_ = true; set_region_of_interest(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); register_embedded_glsl_files(builtin_files_); glsl_program_ = 0; three_D_ = false; glsl_frame_ = 0; glsl_start_time_ = SystemStopwatch::now(); object_properties_visible_ = false; new_file(); } /** * \brief GeoShadeApplication destructor. */ ~GeoShadeApplication() override { if(glsl_program_ != 0) { glDeleteProgram(glsl_program_); glsl_program_ = 0; } } /** * \copydoc SimpleApplication::geogram_initialize() */ void geogram_initialize(int argc, char** argv) override { SimpleApplication::geogram_initialize(argc, argv); if(phone_screen_) { viewer_properties_visible_ = false; } } /** * \brief Displays and handles the GUI for object properties. * \details Overloads Application::draw_object_properties(). */ void draw_object_properties() override { // TODO } /** * \brief Draws the scene according to currently set primitive and * drawing modes. */ void draw_scene() override { if(glsl_program_ != 0) { if(animate()) { glUseProgram(glsl_program_); // If shader has an iTime uniform (e.g. a ShaderToy shader), // then update it, and indicate that graphics should be // updated again and again (call update() at each frame). GLint iTime_loc = glGetUniformLocation( glsl_program_, "iTime" ); if(iTime_loc != -1) { glUniform1f( iTime_loc, float(SystemStopwatch::now() - glsl_start_time_) ); } GLint iFrame_loc = glGetUniformLocation( glsl_program_, "iFrame" ); if(iFrame_loc != -1) { glUniform1f( iFrame_loc, float(glsl_frame_) ); } GLint iDate_loc = glGetUniformLocation( glsl_program_, "iDate" ); if(iDate_loc != -1) { time_t t = time(nullptr); struct tm* tm = localtime(&t); float datex = float(tm->tm_year + 1900); float datey = float(tm->tm_mon); float datez = float(tm->tm_mday); float datew = float(tm->tm_sec) + 60.0f * float(tm->tm_min) + 3600.0f * float(tm->tm_hour); glUniform4f(iDate_loc, datex, datey, datez, datew); } glUseProgram(0); ++glsl_frame_; // Of course, there is a much faster way of drawing a // quad, but here we do not care about this (tiny) loss // of performance. glupDisable(GLUP_VERTEX_COLORS); glupEnable(GLUP_TEXTURING); glupUseProgram(glsl_program_); glupBegin(GLUP_TRIANGLES); glupTexCoord2d(0.0, 0.0); glupVertex2d( 0.0, 0.0); glupTexCoord2d(1.0, 1.0); glupVertex2d( 1.0, 1.0); glupTexCoord2d(0.0, 1.0); glupVertex2d( 0.0, 1.0); glupTexCoord2d(1.0, 1.0); glupVertex2d( 1.0, 1.0); glupTexCoord2d(0.0, 0.0); glupVertex2d( 0.0, 0.0); glupTexCoord2d(1.0, 0.0); glupVertex2d( 1.0, 0.0); glupEnd(); glupUseProgram(0); glupDisable(GLUP_TEXTURING); } } } void new_file() { text_editor_.clear(); text_editor_.load_data( "void mainImage(\n" " out vec4 col,in vec2 coord\n" ") {\n" " col.r = coord.x /\n" " iResolution.x;\n" " col.g = coord.y /\n" " iResolution.y;\n" " col.b = 0.5*(col.x+col.y);\n" "}\n" ); text_editor_visible_ = true; } virtual void draw_fileops_menu() override { if(ImGui::MenuItem( (icon_UTF8("play-circle") + " Run program").c_str(), phone_screen_ ? nullptr : "[F5]" )) { run_program(); } if(ImGui::MenuItem( (icon_UTF8("stop-circle") + "Stop program").c_str() )) { stop_program(); } ImGui::Separator(); if(ImGui::MenuItem(icon_UTF8("file")+" New...")) { new_file(); current_file_ = ""; } if(phone_screen_) { draw_load_menu(); draw_save_menu(); } ImGui::Separator(); if(ImGui::MenuItem(icon_UTF8("folder-open")+"Load example...")) { ImGui::OpenFileDialog( "##load_dlg", supported_read_file_extensions().c_str(), filename_, ImGuiExtFileDialogFlags_Load, builtin_files_ ); } } void run_program() { if(glsl_program_ != 0) { glDeleteProgram(glsl_program_); glsl_program_ = 0; } glsl_frame_ = 0; glsl_start_time_ = SystemStopwatch::now(); if(text_editor_.text().find("<GLUP/ShaderToy.h>") != std::string::npos) { glsl_program_ = glupCompileProgram(text_editor_.text().c_str()); } else { std::string source = ( "//stage GL_FRAGMENT_SHADER\n" "//import <GLUP/ShaderToy.h>\n" "#line 1\n" ) + text_editor_.text(); glsl_program_ = glupCompileProgram(source.c_str()); } text_editor_visible_ = (glsl_program_ == 0); start_animation(); } void stop_program() { stop_animation(); text_editor_visible_ = true; } /** * \copydoc SimpleApplication::draw_application_icons() */ void draw_application_icons() override { if(phone_screen_) { if(ImGui::SimpleButton(icon_UTF8("home"))) { home(); } if(ImGui::SimpleButton(icon_UTF8("play-circle"))) { run_program(); } if(ImGui::SimpleButton(icon_UTF8("stop-circle"))) { stop_program(); } } } /** * \copydoc Application::load() */ bool load(const std::string& filename) override { if(FileSystem::is_file(filename)) { text_editor_.load(filename); current_file_ = filename; text_editor_visible_ = true; return true; } else if(builtin_files_->is_file(filename)) { const char* data = builtin_files_->get_file_contents(filename); text_editor_.load_data(data); current_file_ = ""; text_editor_visible_ = true; return true; } return false; } /** * \copydoc Application::save() */ bool save(const std::string& filename) override { text_editor_.save(filename); current_file_ = filename; return true; } /** * \copydoc Application::supported_read_file_extensions() */ std::string supported_read_file_extensions() override { return "glsl"; } /** * \copydoc Application::supported_write_file_extensions() */ std::string supported_write_file_extensions() override { return "glsl"; } protected: void draw_viewer_properties() override { if(ImGui::Button( (icon_UTF8("play-circle")+" run").c_str(), ImVec2(-ImGui::GetContentRegionAvail().x/1.8f,0.0f)) ) { run_program(); } ImGui::SameLine(); if(ImGui::Button( (icon_UTF8("stop-circle")+" stop").c_str(), ImVec2(-1.0f, 0.0f)) ) { stop_program(); } ImGui::Separator(); if(ImGui::Button( (icon_UTF8("home") + " Home").c_str(), ImVec2(-1.0, 0.0)) ) { home(); } } private: GLuint glsl_program_; int glsl_frame_; double glsl_start_time_; SmartPointer<FileSystem::MemoryNode> builtin_files_; }; } int main(int argc, char** argv) { GeoShadeApplication app; app.start(argc, argv); return 0; }
4,361
1,475
<gh_stars>1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.distributed.internal; import static org.apache.geode.distributed.ConfigurationProperties.ARCHIVE_DISK_SPACE_LIMIT; import static org.apache.geode.distributed.ConfigurationProperties.ARCHIVE_FILE_SIZE_LIMIT; import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT; import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_HTTP_PORT; import static org.apache.geode.distributed.ConfigurationProperties.LOG_DISK_SPACE_LIMIT; import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE_SIZE_LIMIT; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_ARCHIVE_FILE; import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLE_RATE; import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED; import java.io.File; import java.util.Arrays; import java.util.List; import org.apache.logging.log4j.Logger; import org.apache.geode.GemFireIOException; import org.apache.geode.internal.ConfigSource; import org.apache.geode.logging.internal.log4j.api.LogService; /** * Provides an implementation of {@code DistributionConfig} that is used at runtime by an * {@link InternalDistributedSystem}. It allows for dynamic reconfiguration of the app that owns it. * * The attribute setter methods in this class all assume that they are being called at runtime. If * they are called from some other ConfigSource then those calls should come through * setAttributeObject and it will set the attSourceMap to the correct source after these methods * return. * * @since GemFire 3.0 */ public class RuntimeDistributionConfigImpl extends DistributionConfigImpl { private static final Logger logger = LogService.getLogger(); private static final long serialVersionUID = -805637520096606113L; private final transient InternalDistributedSystem system; /** * Create a new {@code RuntimeDistributionConfigImpl} from the contents of another * {@code DistributionConfig}. */ public RuntimeDistributionConfigImpl(InternalDistributedSystem system) { super(system.getOriginalConfig()); this.system = system; modifiable = false; } @Override public void setLogLevel(int value) { logLevel = (Integer) checkAttribute(LOG_LEVEL, value); getAttSourceMap().put(LOG_LEVEL, ConfigSource.runtime()); logConfigChanged(); } @Override public void setStatisticSamplingEnabled(boolean newValue) { statisticSamplingEnabled = (Boolean) checkAttribute(STATISTIC_SAMPLING_ENABLED, newValue); getAttSourceMap().put(STATISTIC_SAMPLING_ENABLED, ConfigSource.runtime()); } @Override public void setStatisticSampleRate(int value) { value = (Integer) checkAttribute(STATISTIC_SAMPLE_RATE, value); if (value < DEFAULT_STATISTIC_SAMPLE_RATE) { // fix 48228 logger.info( "Setting statistic-sample-rate to {} instead of the requested {} because VSD does not work with sub-second sampling.", DEFAULT_STATISTIC_SAMPLE_RATE, value); value = DEFAULT_STATISTIC_SAMPLE_RATE; } statisticSampleRate = value; } @Override public void setStatisticArchiveFile(File value) { value = (File) checkAttribute(STATISTIC_ARCHIVE_FILE, value); if (value == null) { value = new File(""); } try { system.getStatSampler().changeArchive(value); } catch (GemFireIOException ex) { throw new IllegalArgumentException(ex.getMessage()); } statisticArchiveFile = value; getAttSourceMap().put(STATISTIC_ARCHIVE_FILE, ConfigSource.runtime()); } @Override public void setArchiveDiskSpaceLimit(int value) { archiveDiskSpaceLimit = (Integer) checkAttribute(ARCHIVE_DISK_SPACE_LIMIT, value); getAttSourceMap().put(ARCHIVE_DISK_SPACE_LIMIT, ConfigSource.runtime()); } @Override public void setArchiveFileSizeLimit(int value) { archiveFileSizeLimit = (Integer) checkAttribute(ARCHIVE_FILE_SIZE_LIMIT, value); getAttSourceMap().put(ARCHIVE_FILE_SIZE_LIMIT, ConfigSource.runtime()); } @Override public void setLogDiskSpaceLimit(int value) { logDiskSpaceLimit = (Integer) checkAttribute(LOG_DISK_SPACE_LIMIT, value); getAttSourceMap().put(LOG_DISK_SPACE_LIMIT, ConfigSource.runtime()); logConfigChanged(); } @Override public void setLogFileSizeLimit(int value) { logFileSizeLimit = (Integer) checkAttribute(LOG_FILE_SIZE_LIMIT, value); getAttSourceMap().put(LOG_FILE_SIZE_LIMIT, ConfigSource.runtime()); logConfigChanged(); } @Override public List<String> getModifiableAttributes() { String[] modifiables = {HTTP_SERVICE_PORT, JMX_MANAGER_HTTP_PORT, ARCHIVE_DISK_SPACE_LIMIT, ARCHIVE_FILE_SIZE_LIMIT, LOG_DISK_SPACE_LIMIT, LOG_FILE_SIZE_LIMIT, LOG_LEVEL, STATISTIC_ARCHIVE_FILE, STATISTIC_SAMPLE_RATE, STATISTIC_SAMPLING_ENABLED}; return Arrays.asList(modifiables); } public DistributionConfig takeSnapshot() { return new DistributionConfigSnapshot(this); } private void logConfigChanged() { system.logConfigChanged(); } }
1,888
348
<filename>docs/data/leg-t2/028/02802096.json {"nom":"<NAME>","circ":"2ème circonscription","dpt":"Eure-et-Loir","inscrits":837,"abs":483,"votants":354,"blancs":23,"nuls":3,"exp":328,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":242},{"nuance":"REM","nom":"Mme <NAME>","voix":86}]}
119
611
<gh_stars>100-1000 // DejaLu // Copyright (c) 2015 <NAME>. All rights reserved. #include "HMIMAPFetchNextSourceSyncStep.h" #include "HMMailDBUIDToFetchOperation.h" #include "HMMailStorage.h" using namespace hermes; using namespace mailcore; IMAPFetchNextSourceSyncStep::IMAPFetchNextSourceSyncStep() { mUidOp = NULL; mFetchOp = NULL; mMessageRowID = -1; mMessageData = NULL; } IMAPFetchNextSourceSyncStep::~IMAPFetchNextSourceSyncStep() { MC_SAFE_RELEASE(mMessageData); MC_SAFE_RELEASE(mUidOp); MC_SAFE_RELEASE(mFetchOp); } void IMAPFetchNextSourceSyncStep::setMessageRowID(int64_t messageRowID) { mMessageRowID = messageRowID; } int64_t IMAPFetchNextSourceSyncStep::messageRowID() { return mMessageRowID; } mailcore::Data * IMAPFetchNextSourceSyncStep::messageData() { return mMessageData; } void IMAPFetchNextSourceSyncStep::start() { retain(); mUidOp = storage()->uidToFetchOperation(mMessageRowID); mUidOp->setCallback(this); MC_SAFE_RETAIN(mUidOp); mUidOp->start(); } void IMAPFetchNextSourceSyncStep::uidFetched() { if (mUidOp->uid() == -1) { setError(hermes::ErrorMessageNotFound); MC_SAFE_RELEASE(mUidOp); notifyDelegateDone(); release(); return; } if ((mUidOp->uid() == 0) && (mUidOp->filename() != NULL)) { Data * data = Data::dataWithContentsOfFile(mUidOp->filename()); MC_SAFE_REPLACE_RETAIN(Data, mMessageData, data); notifyDelegateDone(); release(); return; } mFetchOp = session()->fetchMessageByUIDOperation(folderPath(), mUidOp->uid()); mFetchOp->setCallback(this); MC_SAFE_RETAIN(mFetchOp); mFetchOp->start(); MC_SAFE_RELEASE(mUidOp); } void IMAPFetchNextSourceSyncStep::sourceFetched() { if (mFetchOp->error() != mailcore::ErrorNone) { setError((hermes::ErrorCode) mFetchOp->error()); MC_SAFE_RELEASE(mFetchOp); notifyDelegateDone(); release(); return; } mMessageData = mFetchOp->data(); MC_SAFE_RETAIN(mMessageData); MC_SAFE_RELEASE(mFetchOp); notifyDelegateDone(); release(); } void IMAPFetchNextSourceSyncStep::cancel() { if (mUidOp != NULL) { mUidOp->cancel(); MC_SAFE_RELEASE(mUidOp); release(); } else if (mFetchOp != NULL) { mFetchOp->cancel(); MC_SAFE_RELEASE(mFetchOp); release(); } } void IMAPFetchNextSourceSyncStep::operationFinished(mailcore::Operation * op) { if (op == mUidOp) { uidFetched(); } else if (op == mFetchOp) { sourceFetched(); } }
1,185
6,304
/* * Copyright 2020 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkSVGFeBlend_DEFINED #define SkSVGFeBlend_DEFINED #include "modules/svg/include/SkSVGFe.h" #include "modules/svg/include/SkSVGTypes.h" class SkSVGFeBlend : public SkSVGFe { public: enum class Mode { kNormal, kMultiply, kScreen, kDarken, kLighten, }; static sk_sp<SkSVGFeBlend> Make() { return sk_sp<SkSVGFeBlend>(new SkSVGFeBlend()); } SVG_ATTR(Mode, Mode, Mode::kNormal) SVG_ATTR(In2, SkSVGFeInputType, SkSVGFeInputType()) protected: sk_sp<SkImageFilter> onMakeImageFilter(const SkSVGRenderContext&, const SkSVGFilterContext&) const override; std::vector<SkSVGFeInputType> getInputs() const override { return {this->getIn(), this->getIn2()}; } bool parseAndSetAttribute(const char*, const char*) override; private: SkSVGFeBlend() : INHERITED(SkSVGTag::kFeBlend) {} using INHERITED = SkSVGFe; }; #endif // SkSVGFeBlend_DEFINED
498
338
package com.camnter.newlife.widget; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Xfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.IntDef; import android.util.AttributeSet; import android.util.TypedValue; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.ref.WeakReference; /** * Description:XfermodeRoundImageView * Created by:CaMnter * Time:2016-03-02 16:30 */ public class XfermodeRoundImageView extends android.support.v7.widget.AppCompatImageView { public static final int ROUND = 2601; public static final int CIRCLE = 2602; private static final int DEFAULT_BORDER_RADIUS = 8; // @formatter:on @ImageType private int imageType; private int mBorderRadius; private Paint mBitmapPaint; private Bitmap mMaskBitmap; private Xfermode mXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN); private WeakReference<Bitmap> mWeakReference; public XfermodeRoundImageView(Context context) { super(context); this.init(context, null); } public XfermodeRoundImageView(Context context, AttributeSet attrs) { super(context, attrs); this.init(context, attrs); } public XfermodeRoundImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.init(context, attrs); } private void init(Context context, AttributeSet attrs) { this.mBitmapPaint = new Paint(); this.mBitmapPaint.setAntiAlias(true); if (attrs == null) return; TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.XfermodeRoundImageView); this.imageType = typedArray.getInt(R.styleable.XfermodeRoundImageView_xfermodeImageType, CIRCLE) == CIRCLE ? CIRCLE : ROUND; this.mBorderRadius = typedArray.getDimensionPixelSize( R.styleable.XfermodeRoundImageView_xfermodeBorderRadius, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_BORDER_RADIUS, this.getResources().getDisplayMetrics())); typedArray.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (this.imageType == CIRCLE) { int side = Math.min(this.getMeasuredWidth(), this.getMeasuredHeight()); this.setMeasuredDimension(side, side); } } @Override protected void onDraw(Canvas canvas) { Bitmap bitmap = this.mWeakReference == null ? null : this.mWeakReference.get(); if (bitmap == null || bitmap.isRecycled()) { Drawable drawable = this.getDrawable(); if (drawable == null) { super.onDraw(canvas); return; } bitmap = this.drawableToBitmap(drawable, this.imageType); if (this.mMaskBitmap == null || this.mMaskBitmap.isRecycled()) { this.mMaskBitmap = this.drawBitmapSafely(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888, 1); } this.mWeakReference = new WeakReference<>(bitmap); } if (bitmap != null) { @SuppressLint("WrongConstant") int sc = canvas.saveLayer(0, 0, this.getWidth(), this.getHeight(), null, Canvas.ALL_SAVE_FLAG); this.mBitmapPaint.reset(); this.mBitmapPaint.setFilterBitmap(false); canvas.drawBitmap(this.mMaskBitmap, 0.0f, 0.0f, this.mBitmapPaint); this.mBitmapPaint.setXfermode(this.mXfermode); canvas.drawBitmap(bitmap, 0.0f, 0.0f, this.mBitmapPaint); this.mBitmapPaint.setXfermode(null); canvas.restoreToCount(sc); } else { this.mBitmapPaint.reset(); super.onDraw(canvas); } } @Override public void invalidate() { this.mWeakReference = null; if (this.mMaskBitmap != null) { this.mMaskBitmap.recycle(); this.mMaskBitmap = null; } super.invalidate(); } private Bitmap drawableToBitmap(Drawable drawable, @ImageType int imageType) { if (drawable instanceof BitmapDrawable) ((BitmapDrawable) drawable).getBitmap(); int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); float scale = 1.0f; Bitmap bitmap = this.createBitmapSafely(width, height, Bitmap.Config.ARGB_8888, 1); Canvas canvas = new Canvas(bitmap); switch (imageType) { case ROUND: { scale = Math.max(this.getWidth() * 1.0f / width, getHeight() * 1.0f / height); break; } case CIRCLE: { scale = this.getWidth() * 1.0f / Math.min(width, height); break; } } drawable.setBounds(0, 0, (int) (scale * width), (int) (scale * height)); drawable.draw(canvas); return bitmap; } public Bitmap createBitmapSafely(int width, int height, Bitmap.Config config, int retryCount) { try { return Bitmap.createBitmap(width, height, config); } catch (OutOfMemoryError e) { e.printStackTrace(); if (retryCount > 0) { System.gc(); return createBitmapSafely(width, height, config, retryCount - 1); } return null; } } public Bitmap drawBitmapSafely(int width, int height, Bitmap.Config config, int retryCount) { try { Bitmap bitmap = Bitmap.createBitmap(width, height, config); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLACK); switch (this.imageType) { case ROUND: canvas.drawRoundRect(new RectF(0, 0, this.getWidth(), getHeight()), this.mBorderRadius, this.mBorderRadius, paint); break; case CIRCLE: canvas.drawCircle(this.getWidth() / 2, this.getWidth() / 2, this.getWidth() / 2, paint); break; } return bitmap; } catch (OutOfMemoryError e) { e.printStackTrace(); if (retryCount > 0) { System.gc(); return drawBitmapSafely(width, height, config, retryCount - 1); } return null; } } // @formatter:off @IntDef({ ROUND, CIRCLE }) @Retention(RetentionPolicy.SOURCE) public @interface ImageType {} }
3,283
4,036
class DifferentTypes { SOME_TYPE i1; SOME_TYPE i2; SOME_TYPE i3; SOME_TYPE i4; SOME_TYPE i5; SOME_TYPE i6; SOME_TYPE i7; SOME_TYPE i8; SOME_TYPE i9; }; class DifferentTypes2 { SOME_TYPE i1; SOME_TYPE i2; SOME_TYPE i3; SOME_TYPE i4; SOME_TYPE i5; SOME_TYPE i6; SOME_TYPE i7; SOME_TYPE i8; SOME_TYPE i9; int j1; int j2; int j3; int j4; int j5; int j6; int j7; int j8; int j9; };
269
796
<filename>src/net/zhuoweizhang/mcpelauncher/api/modpe/Enchantment.java package net.zhuoweizhang.mcpelauncher.api.modpe; public final class Enchantment { // These names are taken from SpongeAPI public static final int PROTECTION = 0, FIRE_PROTECTION = 1, FEATHER_FALLING = 2, BLAST_PROTECTION = 3, PROJECTILE_PROTECTION = 4, THORNS = 5, RESPIRATION = 6, AQUA_AFFINITY = 7, DEPTH_STRIDER = 8, SHARPNESS = 9, SMITE = 10, BANE_OF_ARTHROPODS = 11, KNOCKBACK = 12, FIRE_ASPECT = 13, LOOTING = 14, EFFICIENCY = 15, SILK_TOUCH = 16, UNBREAKING = 17, FORTUNE = 18, POWER = 19, PUNCH = 20, FLAME = 21, INFINITY = 22, LUCK_OF_THE_SEA = 23, LURE = 24, FROST_WALKER = 25, MENDING = 26; }
334
1,742
<gh_stars>1000+ ## -*- encoding: utf-8 -*- """ This file (./nonlinear_doctest.sage) was *autogenerated* from ./nonlinear.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./nonlinear_doctest.sage It is always safe to delete this file; it is not used in typesetting your document. Sage example in ./nonlinear.tex, line 102:: sage: R.<x> = PolynomialRing(RealField(prec=10)) sage: p = 2*x^7 - 21*x^6 + 64*x^5 - 67*x^4 + 90*x^3 \ ....: + 265*x^2 - 900*x + 375 sage: p.roots() [(-1.7, 1), (0.50, 1), (1.7, 1), (5.0, 2)] sage: p.roots(ring=ComplexField(10), multiplicities=False) [-1.7, 0.50, 1.7, 5.0, -2.2*I, 2.2*I] sage: p.roots(ring=RationalField()) [(1/2, 1), (5, 2)] Sage example in ./nonlinear.tex, line 246:: sage: R.<x> = PolynomialRing(QQ, 'x') sage: p = x^4 + x^3 + x^2 + x + 1 sage: K.<alpha> = p.root_field() sage: p.roots(ring=K, multiplicities=None) [alpha, alpha^2, alpha^3, -alpha^3 - alpha^2 - alpha - 1] sage: alpha^5 1 Sage example in ./nonlinear.tex, line 309:: sage: R.<x> = PolynomialRing(RR, 'x') sage: d = ZZ.random_element(1, 15) sage: p = R.random_element(d) sage: p.degree() == sum(r[1] for r in p.roots(CC)) True Sage example in ./nonlinear.tex, line 348:: sage: def build_complex_roots(degree): ....: R.<x> = PolynomialRing(CDF, 'x') ....: v = [] ....: for c in cartesian_product([[-1, 1]] * (degree + 1)): ....: v.extend(R(list(c)).roots(multiplicities=False)) ....: return v sage: data = build_complex_roots(12) # long time sage: points(data, pointsize=1, aspect_ratio=1) # long time Graphics object consisting of 1 graphics primitive Sage example in ./nonlinear.tex, line 420:: sage: a, b, c, x = var('a, b, c, x') sage: p = a * x^2 + b * x + c sage: type(p) <... 'sage.symbolic.expression.Expression'> sage: p.parent() Symbolic Ring sage: p.roots(x) [(-1/2*(b + sqrt(b^2 - 4*a*c))/a, 1), (-1/2*(b - sqrt(b^2 - 4*a*c))/a, 1)] Sage example in ./nonlinear.tex, line 450:: sage: a, b, c, d, e, f, x = var('a, b, c, d, e, f, x') sage: p = a*x^5+b*x^4+c*x^3+d*x^2+e*x+f sage: p.roots(x) Traceback (most recent call last): ... RuntimeError: no explicit roots found Sage example in ./nonlinear.tex, line 467:: sage: x, a, b, c, d = var('x, a, b, c, d') sage: P = a * x^3 + b * x^2 + c * x + d sage: alpha = var('alpha') sage: P.subs(x = x + alpha).expand().coefficient(x, 2) 3*a*alpha + b sage: P.subs(x = x - b / (3 * a)).expand().collect(x) a*x^3 - 1/3*(b^2/a - 3*c)*x + 2/27*b^3/a^2 - 1/3*b*c/a + d Sage example in ./nonlinear.tex, line 482:: sage: p, q, u, v = var('p, q, u, v') sage: P = x^3 + p * x + q sage: P.subs(x = u + v).expand() u^3 + 3*u^2*v + 3*u*v^2 + v^3 + p*u + p*v + q Sage example in ./nonlinear.tex, line 498:: sage: P.subs({x: u + v, q: -u^3 - v^3}).factor() (3*u*v + p)*(u + v) sage: P.subs({x: u+v, q: -u^3 - v^3, p: -3 * u * v}).expand() 0 sage: X = var('X') sage: solve([X^2 + q*X - p^3 / 27 == 0], X, solution_dict=True) [{X: -1/2*q - 1/18*sqrt(12*p^3 + 81*q^2)}, {X: -1/2*q + 1/18*sqrt(12*p^3 + 81*q^2)}] Sage example in ./nonlinear.tex, line 539:: sage: e = sin(x) * (x^3 + 1) * (x^5 + x^4 + 1) sage: roots = e.roots(); len(roots) 9 sage: roots [(0, 1), (-1/2*(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)*(I*sqrt(3) + 1) - 1/6*(-I*sqrt(3) + 1)/(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3), 1), (-1/2*(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)*(-I*sqrt(3) + 1) - 1/6*(I*sqrt(3) + 1)/(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3), 1), ((1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3) + 1/3/(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3), 1), (-1/2*I*sqrt(3) - 1/2, 1), (1/2*I*sqrt(3) - 1/2, 1), (1/2*I*sqrt(3)*(-1)^(1/3) - 1/2*(-1)^(1/3), 1), (-1/2*I*sqrt(3)*(-1)^(1/3) - 1/2*(-1)^(1/3), 1), ((-1)^(1/3), 1)] Sage example in ./nonlinear.tex, line 620:: sage: alpha, m, x = var('alpha, m, x'); q = function('q')(x) sage: p = (x - alpha)^m * q sage: p.derivative(x) (-alpha + x)^(m - 1)*m*q(x) + (-alpha + x)^m*diff(q(x), x) sage: simplify(p.derivative(x)(x=alpha)) 0 Sage example in ./nonlinear.tex, line 659:: sage: R.<x> = PolynomialRing(QQ, 'x') sage: p = 128 * x^13 - 1344 * x^12 + 6048 * x^11 - 15632 * x^10 \ ....: + 28056 * x^9 - 44604 * x^8 + 71198 * x^7 - 98283 * x^6 \ ....: + 105840 * x^5 - 101304 * x^4 + 99468 * x^3 - 81648 * x^2 \ ....: + 40824 * x - 8748 sage: d = gcd(p, p.derivative()) sage: (p // d).degree() 4 sage: roots = SR(p // d).roots(multiplicities=False) sage: roots [1/2*I*sqrt(3)*2^(1/3) - 1/2*2^(1/3), -1/2*I*sqrt(3)*2^(1/3) - 1/2*2^(1/3), 2^(1/3), 3/2] sage: [QQbar(p(alpha)).is_zero() for alpha in roots] # long time [True, True, True, True] Sage example in ./nonlinear.tex, line 732:: sage: R.<x> = PolynomialRing(RR, 'x') sage: p = x^7 - 131/3*x^6 + 1070/3*x^5 - 2927/3*x^4 \ ....: + 2435/3*x^3 - 806/3*x^2 + 3188/3*x - 680 sage: l = [c for c in p.coefficients(sparse=False) if not c.is_zero()] sage: sign_changes = [l[i]*l[i+1] < 0 for i in range(len(l)-1)].count(True) sage: real_positive_roots = \ ....: sum([alpha[1] if alpha[0] > 0 else 0 for alpha in p.roots()]) sage: sign_changes, real_positive_roots (7, 5) Sage example in ./nonlinear.tex, line 831:: sage: def count_sign_changes(p): ....: l = [c for c in p if not c.is_zero()] ....: changes = [l[i]*l[i + 1] < 0 for i in range(len(l) - 1)] ....: return changes.count(True) Sage example in ./nonlinear.tex, line 837:: sage: def sturm(p, a, b): ....: assert p.degree() > 2 ....: assert not (p(a) == 0) ....: assert not (p(b) == 0) ....: assert a <= b ....: remains = [p, p.derivative()] ....: for i in range(p.degree() - 1): ....: remains.append(-(remains[i] % remains[i + 1])) ....: evals = [[], []] ....: for q in remains: ....: evals[0].append(q(a)) ....: evals[1].append(q(b)) ....: return count_sign_changes(evals[0]) \ ....: - count_sign_changes(evals[1]) Sage example in ./nonlinear.tex, line 857:: sage: R.<x> = PolynomialRing(QQ, 'x') sage: p = (x - 34) * (x - 5) * (x - 3) * (x - 2) * (x - 2/3) sage: sturm(p, 1, 4) 2 sage: sturm(p, 1, 10) 3 sage: sturm(p, 1, 200) 4 sage: p.roots(multiplicities=False) [34, 5, 3, 2, 2/3] sage: sturm(p, 1/2, 35) 5 Sage example in ./nonlinear.tex, line 949:: sage: f(x) = 4 * sin(x) - exp(x) / 2 + 1 sage: a, b = RR(-pi), RR(pi) sage: bool(f(a) * f(b) < 0) True Sage example in ./nonlinear.tex, line 961:: sage: solve(f(x) == 0, x) [sin(x) == 1/8*e^x - 1/4] Sage example in ./nonlinear.tex, line 966:: sage: f.roots() Traceback (most recent call last): ... RuntimeError: no explicit roots found Sage example in ./nonlinear.tex, line 991:: sage: a, b = RR(-pi), RR(pi) sage: g = plot(f, a, b, rgbcolor='blue') Sage example in ./nonlinear.tex, line 1045:: sage: def phi(s, t): return (s + t) / 2 sage: def intervalgen(f, phi, s, t): ....: msg = 'Wrong arguments: f({0})*f({1})>=0)'.format(s, t) ....: assert (f(s) * f(t) < 0), msg ....: yield s ....: yield t ....: while True: ....: u = phi(s, t) ....: yield u ....: if f(u) * f(s) < 0: ....: t = u ....: else: ....: s = u Sage example in ./nonlinear.tex, line 1152:: sage: a, b (-3.14159265358979, 3.14159265358979) sage: bisection = intervalgen(f, phi, a, b) sage: next(bisection) -3.14159265358979 sage: next(bisection) 3.14159265358979 sage: next(bisection) 0.000000000000000 Sage example in ./nonlinear.tex, line 1178:: sage: from types import GeneratorType, FunctionType sage: def checklength(u, v, w, prec): ....: return abs(v - u) < 2 * prec sage: def iterate(series, check=checklength, prec=10^-5, maxit=100): ....: assert isinstance(series, GeneratorType) ....: assert isinstance(check, FunctionType) ....: niter = 2 ....: v, w = next(series), next(series) ....: while niter <= maxit: ....: niter += 1 ....: u, v, w = v, w, next(series) ....: if check(u, v, w, prec): ....: print('After {0} iterations: {1}'.format(niter, w)) ....: return ....: print('Failed after {0} iterations'.format(maxit)) Sage example in ./nonlinear.tex, line 1221:: sage: bisection = intervalgen(f, phi, a, b) sage: iterate(bisection) After 22 iterations: 2.15847275559132 Sage example in ./nonlinear.tex, line 1313:: sage: phi(s, t) = s - f(s) * (t - s) / (f(t) - f(s)) sage: falsepos = intervalgen(f, phi, a, b) sage: iterate(falsepos) After 8 iterations: -2.89603757331027 Sage example in ./nonlinear.tex, line 1320:: sage: a, b = RR(-pi), RR(pi) sage: g = plot(f, a, b, rgbcolor='blue') sage: phi(s, t) = s - f(s) * (t - s) /(f(t) - f(s)) sage: falsepos = intervalgen(f, phi, a, b) sage: u, v, w = next(falsepos), next(falsepos), next(falsepos) sage: niter = 3 sage: while niter < 9: ....: g += line([(u, 0), (u, f(u))], rgbcolor='red', ....: linestyle=':') ....: g += line([(u, f(u)), (v, f(v))], rgbcolor='red') ....: g += line([(v, 0), (v, f(v))], rgbcolor='red', ....: linestyle=':') ....: g += point((w, 0), rgbcolor='red') ....: if (f(u) * f(w)) < 0: ....: u, v = u, w ....: else: ....: u, v = w, v ....: w = next(falsepos) ....: niter += 1 Sage example in ./nonlinear.tex, line 1361:: sage: a, b = RR(pi/2), RR(pi) sage: phi(s, t) = t - f(t) * (s - t) / (f(s) - f(t)) sage: falsepos = intervalgen(f, phi, a, b) sage: phi(s, t) = (s + t) / 2 sage: bisection = intervalgen(f, phi, a, b) sage: iterate(falsepos) After 15 iterations: 2.15846441170219 sage: iterate(bisection) After 20 iterations: 2.15847275559132 Sage example in ./nonlinear.tex, line 1373:: sage: a, b = RR(pi/2), RR(pi) sage: g = plot(f, a, b, rgbcolor='blue') sage: phi(s, t) = t - f(t) * (s - t) / (f(s) - f(t)) sage: falsepos = intervalgen(f, phi, a, b) sage: u, v, w = next(falsepos), next(falsepos), next(falsepos) sage: niter = 3 sage: while niter < 7: ....: g += line([(u, 0), (u, f(u))], rgbcolor='red', ....: linestyle=':') ....: g += line([(u, f(u)), (v, f(v))], rgbcolor='red') ....: g += line([(v, 0), (v, f(v))], rgbcolor='red', ....: linestyle=':') ....: g += point((w, 0), rgbcolor='red') ....: if (f(u) * f(w)) < 0: ....: u, v = u, w ....: else: ....: u, v = w, v ....: w = next(falsepos) ....: niter += 1 Sage example in ./nonlinear.tex, line 1477:: sage: f.derivative() x |--> 4*cos(x) - 1/2*e^x sage: a, b = RR(pi/2), RR(pi) Sage example in ./nonlinear.tex, line 1501:: sage: def newtongen(f, u): ....: while True: ....: yield u ....: u -= f(u) / f.derivative()(u) sage: def checkconv(u, v, w, prec): ....: return abs(w - v) / abs(w) <= prec Sage example in ./nonlinear.tex, line 1513:: sage: iterate(newtongen(f, a), check=checkconv) After 6 iterations: 2.15846852566756 Sage example in ./nonlinear.tex, line 1518:: sage: generator = newtongen(f, a) sage: g = plot(f, a, b, rgbcolor='blue') sage: u, v = next(generator), next(generator) sage: niter = 2 sage: while niter < 6: ....: g += point((u, 0), rgbcolor='red') ....: g += line([(u, 0), (u, f(u))], rgbcolor='red', ....: linestyle=':') ....: g += line([(u, f(u)), (v, 0)], rgbcolor='red') ....: u, v = v, next(generator) ....: niter += 1 Sage example in ./nonlinear.tex, line 1583:: sage: def secantgen(f, a): ....: yield a ....: estimate = f.derivative()(a) ....: b = a - f(a) / estimate ....: yield b ....: while True: ....: fa, fb = f(a), f(b) ....: if fa == fb: ....: estimate = f.derivative()(a) ....: else: ....: estimate = (fb - fa) / (b - a) ....: a = b ....: b -= fb / estimate ....: yield b Sage example in ./nonlinear.tex, line 1609:: sage: iterate(secantgen(f, a), check=checkconv) After 8 iterations: 2.15846852557553 Sage example in ./nonlinear.tex, line 1621:: sage: g = plot(f, a, b, rgbcolor='blue') sage: sequence = secantgen(f, a) sage: u, v = next(sequence), next(sequence) sage: niter = 2 sage: while niter < 6: ....: g += point((u, 0), rgbcolor='red') ....: g += line([(u, 0), (u, f(u))], rgbcolor='red', ....: linestyle=':') ....: g += line([(u, f(u)), (v, 0)], rgbcolor='red') ....: u, v = v, next(sequence) ....: niter += 1 Sage example in ./nonlinear.tex, line 1697:: sage: from collections import deque sage: basering = PolynomialRing(CC, 'x') sage: def quadraticgen(f, r, s): ....: t = (r + s) / 2 ....: yield t ....: points = deque([(r,f(r)), (s,f(s)), (t,f(t))], maxlen=int(3)) ....: while True: ....: pol = basering.lagrange_polynomial(points) ....: roots = pol.roots(ring=CC, multiplicities=False) ....: u = min(roots, key=lambda x: abs(x - points[2][0])) ....: points.append((u, f(u))) ....: yield points[2][0] Sage example in ./nonlinear.tex, line 1742:: sage: generator = quadraticgen(f, a, b) sage: iterate(generator, check=checkconv) After 5 iterations: 2.15846852554764 Sage example in ./nonlinear.tex, line 1851:: sage: for ring in [ZZ, QQ, QQbar, RDF, RIF, RR, AA, CDF, CIF, CC]: ....: print("{0:50} {1}".format(str(ring), ring.is_exact())) Integer Ring True Rational Field True Algebraic Field True Real Double Field False Real Interval Field with 53 bits of precision False Real Field with 53 bits of precision False Algebraic Real Field True Complex Double Field False Complex Interval Field with 53 bits of precision False Complex Field with 53 bits of precision False Sage example in ./nonlinear.tex, line 2031:: sage: def steffensen(sequence): ....: assert isinstance(sequence, GeneratorType) ....: values = deque(maxlen=int(3)) ....: for i in range(3): ....: values.append(next(sequence)) ....: yield values[i] ....: while True: ....: values.append(next(sequence)) ....: u, v, w = values ....: yield u - (v - u)^2 / (w - 2 * v + u) Sage example in ./nonlinear.tex, line 2047:: sage: g(x) = sin(x^2 - 2) * (x^2 - 2) sage: sequence = newtongen(g, RR(0.7)) sage: accelseq = steffensen(newtongen(g, RR(0.7))) sage: iterate(sequence, check=checkconv) After 17 iterations: 1.41422192763287 sage: iterate(accelseq, check=checkconv) After 10 iterations: 1.41421041980166 Sage example in ./nonlinear.tex, line 2062:: sage: sequence = newtongen(f, RR(a)) sage: accelseq = steffensen(newtongen(f, RR(a))) sage: iterate(sequence, check=checkconv) After 6 iterations: 2.15846852566756 sage: iterate(accelseq, check=checkconv) After 7 iterations: 2.15846852554764 Sage example in ./nonlinear.tex, line 2124:: sage: result = (f == 0).find_root(a, b, full_output=True) sage: result[0], result[1].iterations (2.1584685255476415, 9) Sage example in ./nonlinear.tex, line 2183:: sage: a, b = pi/2, pi sage: generator = newtongen(f, a) sage: next(generator); next(generator) 1/2*pi 1/2*pi - (e^(1/2*pi) - 10)*e^(-1/2*pi) """
7,607
1,521
/** * Copyright 2020 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.maxgraph.compiler.tree; import com.alibaba.maxgraph.Message; import com.alibaba.maxgraph.QueryFlowOuterClass; import com.alibaba.maxgraph.QueryFlowOuterClass.RequirementType; import com.alibaba.maxgraph.compiler.api.schema.GraphSchema; import com.alibaba.maxgraph.compiler.logical.LogicalVertex; import com.alibaba.maxgraph.compiler.tree.source.SourceVertexTreeNode; import com.alibaba.maxgraph.compiler.utils.CompilerUtils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import static com.alibaba.maxgraph.QueryFlowOuterClass.RequirementType.*; import static com.google.common.base.Preconditions.checkNotNull; public abstract class BaseTreeNode implements TreeNode { private static final Logger logger = LoggerFactory.getLogger(BaseTreeNode.class); private TreeNode output = null; protected NodeType nodeType; protected QueryFlowOuterClass.RangeLimit.Builder rangeLimit = null; protected LogicalVertex outputVertex; protected List<HasContainer> hasContainerList = Lists.newArrayList(); boolean globalRangeFlag = true; Map<RequirementType, Object> afterRequirementList = Maps.newHashMap(); Map<RequirementType, Object> beforeRequirementList = Maps.newHashMap(); /** * Early stop related argument */ protected QueryFlowOuterClass.EarlyStopArgument.Builder earlyStopArgument = QueryFlowOuterClass.EarlyStopArgument.newBuilder(); /** * If true, the output of this node can be added to path */ private boolean pathFlag; /** * If ture, it can access edge and property locally after this operator executed */ private boolean propLocalFlag; /** * Label list is used in this tree node */ private Set<String> usedLabelList = Sets.newHashSet(); /** * If this operator open dedup local optimize */ private boolean dedupLocalFlag = false; /** * Describe if this node is a subquery node */ private boolean subqueryNodeFlag = false; protected GraphSchema schema; public BaseTreeNode(NodeType nodeType, GraphSchema schema) { this.nodeType = nodeType; this.schema = schema; this.outputVertex = null; this.pathFlag = false; this.propLocalFlag = false; } @Override public TreeNode getOutputNode() { return output; } @Override public void setOutputNode(TreeNode output) { this.output = output; } @Override public NodeType getNodeType() { return this.nodeType; } @Override public void setFinishVertex(LogicalVertex vertex, TreeNodeLabelManager treeNodeLabelManager) { this.outputVertex = vertex; if (null != treeNodeLabelManager) { hasContainerList.forEach(v -> { Message.LogicalCompare logicalCompare = CompilerUtils.parseLogicalCompare(v, schema, treeNodeLabelManager.getLabelIndexList(), this instanceof SourceVertexTreeNode); vertex.getProcessorFunction().getLogicalCompareList().add(logicalCompare); }); } } @Override public LogicalVertex getOutputVertex() { return checkNotNull(outputVertex); } @Override public void addLabelStartRequirement(String label) { Object labelList = this.afterRequirementList.get(LABEL_START); if (null != labelList) { ((Set<String>) labelList).add(checkNotNull(label)); } else { this.afterRequirementList.put(LABEL_START, Sets.newHashSet(label)); } } @Override public List<QueryFlowOuterClass.RequirementValue.Builder> buildAfterRequirementList(TreeNodeLabelManager nodeLabelManager) { return getRequirementList(afterRequirementList, Arrays.asList(LABEL_START), nodeLabelManager); } @Override public List<QueryFlowOuterClass.RequirementValue.Builder> buildBeforeRequirementList(TreeNodeLabelManager nodeLabelManager) { return getRequirementList(beforeRequirementList, Arrays.asList(PATH_ADD, LABEL_START), nodeLabelManager); } private List<QueryFlowOuterClass.RequirementValue.Builder> getRequirementList(Map<RequirementType, Object> requirementMap, List<RequirementType> requirementTypes, TreeNodeLabelManager nodeLabelManager) { List<QueryFlowOuterClass.RequirementValue.Builder> requirementList = Lists.newArrayList(); for (RequirementType type : requirementTypes) { if (!requirementMap.containsKey(type)) { logger.warn("requirement type {} not exist in map", type); continue; } Object conf = requirementMap.get(type); switch (type) { case LABEL_START: { Set<String> startLabelList = (Set<String>) conf; if (startLabelList == null || startLabelList.isEmpty()) { throw new IllegalArgumentException("There's label start requirement but start label list is empty"); } Message.Value.Builder valueBuilder = Message.Value.newBuilder(); for (String startLabel : startLabelList) { valueBuilder.addIntValueList(nodeLabelManager.getLabelIndex(startLabel)); } requirementList.add(QueryFlowOuterClass.RequirementValue.newBuilder() .setReqArgument(valueBuilder) .setReqType(type)); break; } case PATH_ADD: { Message.Value.Builder valueBuilder = Message.Value.newBuilder(); requirementList.add(QueryFlowOuterClass.RequirementValue.newBuilder() .setReqArgument(valueBuilder) .setReqType(type)); break; } default: { throw new IllegalArgumentException(type + " can't exist in before requirement"); } } } return requirementList; } @Override public Set<String> getUsedLabelList() { return usedLabelList; } @Override public void addPathRequirement() { this.beforeRequirementList.put(PATH_ADD, null); } @Override public boolean isPathFlag() { return pathFlag; } public void setPathFlag(boolean pathFlag) { this.pathFlag = pathFlag; } @Override public boolean isPropLocalFlag() { return propLocalFlag; } public void setPropLocalFlag(boolean propLocalFlag) { this.propLocalFlag = propLocalFlag; } @Override public void setRangeLimit(long low, long high, boolean globalRangeFlag) { this.rangeLimit = QueryFlowOuterClass.RangeLimit.newBuilder() .setRangeStart(low) .setRangeEnd(high); this.globalRangeFlag = globalRangeFlag; } public Map<RequirementType, Object> getAfterRequirementList() { return afterRequirementList; } public Map<RequirementType, Object> getBeforeRequirementList() { return beforeRequirementList; } public void addHasContainer(HasContainer hasContainer) { hasContainerList.add(hasContainer); } public List<HasContainer> getHasContainerList() { return hasContainerList; } @Override public void addHasContainerList(List<HasContainer> hasContainerList) { hasContainerList.forEach(v -> addHasContainer(v)); } @Override public void enableDedupLocal() { this.dedupLocalFlag = true; } @Override public boolean isDedupLocal() { return this.dedupLocalFlag; } /** * Set this node as subquery node */ public void setSubqueryNode() { this.subqueryNodeFlag = true; } /** * Check if this node is subquery node * * @return The subquery node flag */ public boolean isSubqueryNode() { return this.subqueryNodeFlag; } protected Message.Value.Builder createArgumentBuilder() { return Message.Value.newBuilder() .setDedupLocalFlag(dedupLocalFlag) .setSubqueryFlag(subqueryNodeFlag); } /** * Enable global stop by global limit operator */ @Override public void enableGlobalStop() { this.earlyStopArgument.setGlobalStopFlag(true); } /** * Enable global filter by global stop */ @Override public void enableGlobalFilter() { this.earlyStopArgument.setGlobalFilterFlag(true); } public boolean removeBeforeLabel(String label) { Set<String> labelList = (Set<String>) this.beforeRequirementList.get(LABEL_START); if (null != labelList && labelList.contains(label)) { labelList.remove(label); if (labelList.isEmpty()) { this.beforeRequirementList.remove(LABEL_START); } return true; } return false; } }
4,064
695
<reponame>mdiazmel/keops #pragma once #include "core/formulas/maths/Mult.h" #include "core/formulas/maths/Square.h" #include "core/formulas/maths/Sum.h" namespace keops { // Anisotropic (but diagonal) norm, if S::DIM == A::DIM: // SqNormDiag<S,A> = sum_i s_i*a_i*a_i template < class FS, class FA > using SqNormDiag = Sum<Mult<FS,Square<FA>>>; }
155
14,668
<reponame>zealoussnow/chromium<gh_stars>1000+ // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.bookmarkswidget; import org.chromium.chrome.browser.base.SplitCompatRemoteViewsService; import org.chromium.chrome.browser.base.SplitCompatUtils; /** See {@link BookmarkWidgetServiceImpl}. */ public class BookmarkWidgetService extends SplitCompatRemoteViewsService { public BookmarkWidgetService() { super(SplitCompatUtils.getIdentifierName( "org.chromium.chrome.browser.bookmarkswidget.BookmarkWidgetServiceImpl")); } }
220
682
#ifndef SIMULATION_BUFFER_H #define SIMULATION_BUFFER_H #include <atomic> #include <thread> /** * Odin use -1 internally, so we need to go back on forth * TODO: change the default odin value to match both the Blif value and this buffer */ typedef signed char data_t; #define BUFFER_SIZE 12 //use something divisible by 4 since the compact buffer can contain 4 value #define CONCURENCY_LIMIT (BUFFER_SIZE - 1) // access to cycle -1 with an extra pdding cell struct BitFields { uint8_t i0 : 2; uint8_t i1 : 2; uint8_t i2 : 2; uint8_t i3 : 2; }; class AtomicBuffer { private: BitFields bits[BUFFER_SIZE / 4]; std::atomic<bool> lock; int32_t cycle; void lock_it() { std::atomic_thread_fence(std::memory_order_acquire); while (lock.exchange(true, std::memory_order_relaxed)) { std::this_thread::yield(); } } void unlock_it() { lock.exchange(false, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_relaxed); } uint8_t get_bits(uint8_t index) { uint8_t modindex = index % (BUFFER_SIZE); uint8_t address = modindex / 4; uint8_t bit_index = modindex % 4; switch (bit_index) { case 0: return (this->bits[address].i0); case 1: return (this->bits[address].i1); case 2: return (this->bits[address].i2); case 3: return (this->bits[address].i3); default: return 0x3; } } void set_bits(uint8_t index, uint8_t value) { uint8_t modindex = index % (BUFFER_SIZE); uint8_t address = modindex / 4; uint8_t bit_index = modindex % 4; value = value & 0x3; switch (bit_index) { case 0: this->bits[address].i0 = value; break; case 1: this->bits[address].i1 = value; break; case 2: this->bits[address].i2 = value; break; case 3: this->bits[address].i3 = value; break; default: break; } } public: AtomicBuffer(data_t value_in) { this->lock = false; this->cycle = -1; this->init_all_values(value_in); } void print() { for (int i = 0; i < BUFFER_SIZE; i++) { uint8_t value = get_bits(i); printf("%s", (value == 0) ? "0" : (value == 1) ? "1" : "x"); } printf("\n"); } void init_all_values(data_t value) { this->lock = false; for (int i = 0; i < BUFFER_SIZE; i++) set_bits(i, value); } int32_t lock_free_get_cycle() { return this->cycle; } void lock_free_update_cycle(int64_t cycle_in) { //if (cycle_in > this->cycle) this->cycle = cycle_in; } data_t lock_free_get_value(int64_t cycle_in) { return get_bits(cycle_in); } void lock_free_update_value(data_t value_in, int64_t cycle_in) { if (cycle_in > this->cycle) { set_bits(cycle_in, value_in); lock_free_update_cycle(cycle_in); } } void lock_free_copy_foward_one_cycle(int64_t cycle_in) { set_bits(cycle_in + 1, get_bits(cycle_in)); lock_free_update_cycle(cycle_in); } int32_t get_cycle() { lock_it(); int32_t value = lock_free_get_cycle(); unlock_it(); return value; } void update_cycle(int64_t cycle_in) { lock_it(); lock_free_update_cycle(cycle_in); unlock_it(); } data_t get_value(int64_t cycle_in) { lock_it(); data_t value = lock_free_get_value(cycle_in); unlock_it(); return value; } void update_value(data_t value_in, int64_t cycle_in) { lock_it(); lock_free_update_value(value_in, cycle_in); unlock_it(); } void copy_foward_one_cycle(int64_t cycle_in) { lock_it(); lock_free_copy_foward_one_cycle(cycle_in); unlock_it(); } }; #endif
2,149
2,266
/* * File : i2c-bit-ops.h * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Change Logs: * Date Author Notes * 2012-04-25 weety first version */ #ifndef __I2C_BIT_OPS_H__ #define __I2C_BIT_OPS_H__ #ifdef __cplusplus extern "C" { #endif struct rt_i2c_bit_ops { void *data; /* private data for lowlevel routines */ void (*set_sda)(void *data, rt_int32_t state); void (*set_scl)(void *data, rt_int32_t state); rt_int32_t (*get_sda)(void *data); rt_int32_t (*get_scl)(void *data); void (*udelay)(rt_uint32_t us); rt_uint32_t delay_us; /* scl and sda line delay */ rt_uint32_t timeout; /* in tick */ }; rt_err_t rt_i2c_bit_add_bus(struct rt_i2c_bus_device *bus, const char *bus_name); #ifdef __cplusplus } #endif #endif
637
397
<filename>sample-chat-obj-c/sample-chat/Components/ChatScreen/ChatViewController.h // // ChatViewController.h // samplechat // // Created by Injoit on 2/25/19. // Copyright © 2019 Quickblox. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class ChatAttachmentCell; typedef NS_ENUM(NSUInteger, ChatActions) { ChatActionsNone = 0, ChatActionsLeaveChat, ChatActionsChatInfo, ChatActionsEdit, ChatActionsDelete, ChatActionsForward, ChatActionsDeliveredTo, ChatActionsViewedBy, ChatActionsSaveAttachment, }; @interface ChatViewController : UIViewController @property (strong, nonatomic) NSString *dialogID; // metods ChatContextMenuProtocol - (void)forwardAction; - (void)deliveredToAction; - (void)viewedByAction; - (void)saveFileAttachmentFromChatAttachmentCell:(ChatAttachmentCell *)chatAttachmentCell; @end NS_ASSUME_NONNULL_END
328
326
<filename>azure-devops/azext_devops/dev/common/git.py # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import subprocess import sys from knack.log import get_logger from knack.util import CLIError from .uri import uri_parse logger = get_logger(__name__) _GIT_EXE = 'git' def set_config(key, value, local=True): scope = _get_git_config_scope_arg(local) subprocess.check_output([_GIT_EXE, 'config', scope, key, value]) def unset_config(key, local=True): scope = _get_git_config_scope_arg(local) subprocess.check_output([_GIT_EXE, 'config', scope, '--unset', key]) def get_config(key, local=True): scope = _get_git_config_scope_arg(local) return subprocess.check_output([_GIT_EXE, 'config', scope, key]) def _get_git_config_scope_arg(local): if local: return '--local' return '--global' def fetch_remote_and_checkout(refName, remote_name): subprocess.run([_GIT_EXE, 'fetch', remote_name, refName], check=False) subprocess.run([_GIT_EXE, 'checkout', get_branch_name_from_ref(refName)], check=False) subprocess.run([_GIT_EXE, 'pull', remote_name, get_branch_name_from_ref(refName)], check=False) def get_current_branch_name(): try: output = subprocess.check_output([_GIT_EXE, 'symbolic-ref', '--short', '-q', 'HEAD']) except BaseException as ex: # pylint: disable=broad-except logger.info('GitDetect: Could not detect current branch based on current working directory.') logger.debug(ex, exc_info=True) return None if sys.stdout.encoding is not None: result = output.decode(sys.stdout.encoding) else: result = output.decode() return result.strip() def get_remote_url(validation_function=None): remotes = get_git_remotes() if remotes is not None: if _ORIGIN_PUSH_KEY in remotes and (validation_function is None or validation_function(remotes[_ORIGIN_PUSH_KEY])): return remotes[_ORIGIN_PUSH_KEY] for k, value in remotes.items(): if k != _ORIGIN_PUSH_KEY and k.endswith('(push)') and (validation_function is None or validation_function(value)): return value return None def get_git_credentials(organization): parse_result = uri_parse(organization) protocol = parse_result.scheme host = parse_result.netloc standard_in = bytes('protocol={protocol}\nhost={host}'.format(protocol=protocol, host=host), 'utf-8') try: # pylint: disable=unexpected-keyword-arg output = subprocess.check_output([_GIT_EXE, 'credential-manager', 'get'], input=standard_in) except BaseException as ex: # pylint: disable=broad-except logger.info('GitDetect: Could not detect git credentials for current working directory.') logger.debug(ex, exc_info=True) return None if sys.stdout.encoding is not None: lines = output.decode(sys.stdout.encoding).split('\n') else: lines = output.decode().split('\n') properties = {} for line in lines: equal_position = line.find('=') if equal_position >= 0: properties[line[0:equal_position]] = line[equal_position + 1:] return properties def get_git_remotes(): if _git_remotes: return _git_remotes try: # Example output: # git remote - v # full https://mseng.visualstudio.com/DefaultCollection/VSOnline/_git/_full/VSO (fetch) # full https://mseng.visualstudio.com/DefaultCollection/VSOnline/_git/_full/VSO (push) # origin https://mseng.visualstudio.com/defaultcollection/VSOnline/_git/VSO (fetch) # origin https://mseng.visualstudio.com/defaultcollection/VSOnline/_git/VSO (push) output = subprocess.check_output([_GIT_EXE, 'remote', '-v'], stderr=subprocess.STDOUT) except BaseException as ex: # pylint: disable=broad-except logger.info('GitDetect: Could not detect current remotes based on current working directory.') logger.debug(ex, exc_info=True) return None if sys.stdout.encoding is not None: lines = output.decode(sys.stdout.encoding).split('\n') else: lines = output.decode().split('\n') for line in lines: components = line.strip().split() if len(components) == 3: _git_remotes[components[0] + components[2]] = components[1] return _git_remotes def resolve_git_refs(ref): """Prepends 'refs/' prefix to ref str if not already there. :param str ref: The text to validate. :rtype: str """ if ref is not None and not ref.startswith(REFS_PREFIX): ref = REFS_PREFIX + ref return ref def get_ref_name_from_ref(ref): """Removes 'refs/' prefix from ref str if there. :param ref: The text to validate. :type ref: str :rtype: str """ if ref is not None and ref.startswith(REFS_PREFIX): ref = ref[len(REFS_PREFIX):] return ref def resolve_git_ref_heads(ref): """Prepends 'refs/heads/' prefix to ref str if not already there. :param ref: The text to validate. :type ref: str :rtype: str """ if (ref is not None and not ref.startswith(REF_HEADS_PREFIX) and not ref.startswith(REF_PULL_PREFIX) and not ref.startswith(REF_TAGS_PREFIX)): ref = REF_HEADS_PREFIX + ref return ref def get_branch_name_from_ref(ref): """Removes 'refs/heads/' prefix from ref str if there. :param ref: The text to validate. :type ref: str :rtype: str """ if ref is not None and ref.startswith(REF_HEADS_PREFIX): ref = ref[len(REF_HEADS_PREFIX):] return ref def setup_git_alias(alias, command, local=False): try: set_config(key=_get_alias_key(alias), value=_get_alias_value(command), local=local) except OSError: raise CLIError('Setting the git alias failed. Ensure git is installed and in your path.') def clear_git_alias(alias, local=False): unset_config(key=_get_alias_key(alias), local=local) def is_git_alias_setup(alias, command, local=False): try: try: value = get_config(key=_get_alias_key(alias), local=local) except subprocess.CalledProcessError: return False return _get_alias_value(command) == value.decode(sys.stdout.encoding).strip() except OSError: raise CLIError('Checking the git config values failed. Ensure git is installed and in your path.') def _get_alias_key(alias): return 'alias.' + alias def _get_alias_value(command): mime = '.cmd' if sys.platform.lower().startswith('win') else '' return '!f() { exec az' + mime + ' ' + command + ' \"$@\"; }; f' _git_remotes = {} _ORIGIN_PUSH_KEY = 'origin(push)' REFS_PREFIX = 'refs/' REF_HEADS_PREFIX = 'refs/heads/' REF_PULL_PREFIX = 'refs/pull/' REF_TAGS_PREFIX = 'refs/tags/' GIT_CREDENTIALS_USERNAME_KEY = 'username' GIT_CREDENTIALS_PASSWORD_KEY = 'password'
2,992
331
<filename>presentation/src/main/java/com/freedom/lauzy/ticktockmusic/base/IBaseView.java package com.freedom.lauzy.ticktockmusic.base; /** * Desc : IBaseView * Author : Lauzy * Date : 2017/7/3 * Blog : http://www.jianshu.com/u/e76853f863a9 * Email : <EMAIL> */ public interface IBaseView { // Context context(); }
126
7,339
<reponame>schalkventer/htm<filename>test/fixtures/esm/package.json { "name": "htm_dist_test", "type": "module", "private": true, "description": "A package to test importing htm as ES modules in Node", "dependencies": { "htm": "file:htm.tgz", "preact": "^10.4.1" } }
116
623
package me.chanjar.jms.base.sender.disruptor; public class PayloadEvent { private Object payload; public Object getPayload() { return payload; } public void setPayload(Object payload) { this.payload = payload; } }
81
2,133
<reponame>uavosky/uavosky-qgroundcontrol #include "../../../../../src/positioning/qgeocoordinate_p.h"
42
493
<gh_stars>100-1000 """ Version helper updates file version-helper.js which takes care of injecting versions into rtd template. After version-helper.js is updated, script prints paths of old versions to be removed. EXAMPLE docs directory (sceptre.github.io) contains following directories ├── 1.5.0 ├── 2.1.3 ├── 2.1.4 ├── 2.1.5 ├── 2.2.0 ├── 2.2.1 ├── dev └── latest -> 2.2.1 (symlink) Script settings: KEEP_SPECIFIC_VERSIONS = ["1.5.0"] KEEP_ACTIVE_VERSIONS = 3 The content of version-helper.js will be: ['latest', 'dev', '2.2.1', '2.2.0', '2.1.5', '1.5.0'] (where latest points to 2.2.1) Output of versions to remove will be: <path>/2.1.4 <path>/2.1.3 """ import os from operator import attrgetter import sys import re VERSION_REGEX = re.compile(r"\d+.\d+.\d+") KEEP_VERSIONS = ["1.5.0", "1.4.2", "1.3.4"] # these versions won't be removed NUMBER_OF_VERSIONS_TO_KEEP = 3 def main(): try: build_dir = str(sys.argv[1]) except IndexError: sys.exit("Missing build dir path: python /path/docs") documentation_directories = sorted( ( item for item in os.scandir(build_dir) if item.is_dir() and VERSION_REGEX.match(item.name) ), reverse=True, key=attrgetter("name") ) active_versions = ( ["latest", "dev"] + [item.name for item in documentation_directories[:NUMBER_OF_VERSIONS_TO_KEEP]] + KEEP_VERSIONS ) versions_to_remove = ( item.path for item in documentation_directories[NUMBER_OF_VERSIONS_TO_KEEP:] if item.name not in KEEP_VERSIONS ) with open(build_dir + "/version-helper.js", "w+") as outf: outf.write("let versions = {};".format(active_versions)) # print versions_to_remove to stdout for deletion by bash script (github-pages.sh) print(",".join(versions_to_remove)) if __name__ == "__main__": main()
863
471
///////////////////////////////////////////////////////////////////////////// // Name: graphics.cpp // Purpose: Some benchmarks for measuring graphics operations performance // Author: <NAME> // Created: 2008-04-13 // Copyright: (c) 2008 <NAME> <<EMAIL>> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #include "wx/app.h" #include "wx/frame.h" #include "wx/cmdline.h" #include "wx/dcclient.h" #include "wx/dcmemory.h" #include "wx/dcgraph.h" #include "wx/image.h" #include "wx/rawbmp.h" #include "wx/stopwatch.h" #include "wx/crt.h" #if wxUSE_GLCANVAS #include "wx/glcanvas.h" #ifdef _MSC_VER #pragma comment(lib, "opengl32") #endif #endif // wxUSE_GLCANVAS #if wxUSE_GLCANVAS GLuint g_texture; wxImage g_image; void InitializeTexture(int w, int h) { glGenTextures(1, &g_texture); glBindTexture(GL_TEXTURE_2D, g_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); g_image.Create(w, h, false /* don't clear */); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, g_image.GetWidth(), g_image.GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, g_image.GetData()); } #endif // wxUSE_GLCANVAS struct GraphicsBenchmarkOptions { GraphicsBenchmarkOptions() { mapMode = 0; penWidth = 0; width = 800; height = 600; numIters = 1000; testBitmaps = testImages = testLines = testRawBitmaps = testRectangles = false; usePaint = useClient = useMemory = false; useDC = useGC = useGL = false; } long mapMode, penWidth, width, height, numIters; bool testBitmaps, testImages, testLines, testRawBitmaps, testRectangles; bool usePaint, useClient, useMemory; bool useDC, useGC, useGL; } opts; class GraphicsBenchmarkFrame : public wxFrame { public: GraphicsBenchmarkFrame() : wxFrame(NULL, wxID_ANY, "wxWidgets Graphics Benchmark") { SetClientSize(opts.width, opts.height); #if wxUSE_GLCANVAS m_glCanvas = NULL; if ( opts.useGL ) { m_glCanvas = new wxGLCanvas(this, wxID_ANY, NULL, wxPoint(0, 0), wxSize(opts.width, opts.height)); m_glContext = new wxGLContext(m_glCanvas); m_glContext->SetCurrent(*m_glCanvas); glViewport(0, 0, opts.width, opts.height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1, 1, -1, 1, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); InitializeTexture(opts.width, opts.height); m_glCanvas->Connect( wxEVT_PAINT, wxPaintEventHandler(GraphicsBenchmarkFrame::OnGLRender), NULL, this ); } else // Not using OpenGL #endif // wxUSE_GLCANVAS { Connect(wxEVT_PAINT, wxPaintEventHandler(GraphicsBenchmarkFrame::OnPaint)); } Connect(wxEVT_SIZE, wxSizeEventHandler(GraphicsBenchmarkFrame::OnSize)); m_bitmap.Create(64, 64, 32); Show(); } #if wxUSE_GLCANVAS virtual ~GraphicsBenchmarkFrame() { delete m_glContext; } #endif // wxUSE_GLCANVAS private: // Just change the image in some (quick) way to show that it's really being // updated on screen. void UpdateRGB(unsigned char* data, int n) { for ( int y = 0; y < opts.height; ++y ) { memset(data, n % 256, 3*opts.width); data += 3*opts.width; n++; } } #if wxUSE_GLCANVAS void OnGLRender(wxPaintEvent& WXUNUSED(event)) { m_glContext->SetCurrent(*m_glCanvas); glEnable(GL_TEXTURE_2D); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); wxPrintf("Benchmarking %s: ", "OpenGL images"); fflush(stdout); wxStopWatch sw; for ( int n = 0; n < opts.numIters; n++ ) { UpdateRGB(g_image.GetData(), n); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, opts.width, opts.height, GL_RGB, GL_UNSIGNED_BYTE, g_image.GetData()); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(-1.0, -1.0); glTexCoord2f(0, 1); glVertex2f(-1.0, 1.0); glTexCoord2f(1, 1); glVertex2f(1.0, 1.0); glTexCoord2f(1, 0); glVertex2f(1.0, -1.0); glEnd(); m_glCanvas->SwapBuffers(); } const long t = sw.Time(); wxPrintf("%ld images done in %ldms = %gus/image or %ld FPS\n", opts.numIters, t, (1000. * t)/opts.numIters, (1000*opts.numIters + t - 1)/t); wxTheApp->ExitMainLoop(); } #endif // wxUSE_GLCANVAS void OnPaint(wxPaintEvent& WXUNUSED(event)) { if ( opts.usePaint ) { wxPaintDC dc(this); wxGCDC gcdc(dc); BenchmarkDCAndGC("paint", dc, gcdc); } if ( opts.useClient ) { wxClientDC dc(this); wxGCDC gcdc(dc); BenchmarkDCAndGC("client", dc, gcdc); } if ( opts.useMemory ) { wxBitmap bmp(opts.width, opts.height); wxMemoryDC dc(bmp); wxGCDC gcdc(dc); BenchmarkDCAndGC("memory", dc, gcdc); } wxTheApp->ExitMainLoop(); } void BenchmarkDCAndGC(const char* dckind, wxDC& dc, wxGCDC& gcdc) { if ( opts.useDC ) BenchmarkAll(wxString::Format("%6s DC", dckind), dc); if ( opts.useGC ) BenchmarkAll(wxString::Format("%6s GC", dckind), gcdc); } void BenchmarkAll(const wxString& msg, wxDC& dc) { BenchmarkBitmaps(msg, dc); BenchmarkImages(msg, dc); BenchmarkLines(msg, dc); BenchmarkRawBitmaps(msg, dc); BenchmarkRectangles(msg, dc); } void BenchmarkLines(const wxString& msg, wxDC& dc) { if ( !opts.testLines ) return; if ( opts.mapMode != 0 ) dc.SetMapMode((wxMappingMode)opts.mapMode); if ( opts.penWidth != 0 ) dc.SetPen(wxPen(*wxWHITE, opts.penWidth)); wxPrintf("Benchmarking %s: ", msg); fflush(stdout); wxStopWatch sw; int x = 0, y = 0; for ( int n = 0; n < opts.numIters; n++ ) { int x1 = rand() % opts.width, y1 = rand() % opts.height; dc.DrawLine(x, y, x1, y1); x = x1; y = y1; } const long t = sw.Time(); wxPrintf("%ld lines done in %ldms = %gus/line\n", opts.numIters, t, (1000. * t)/opts.numIters); } void BenchmarkRectangles(const wxString& msg, wxDC& dc) { if ( !opts.testRectangles ) return; if ( opts.mapMode != 0 ) dc.SetMapMode((wxMappingMode)opts.mapMode); if ( opts.penWidth != 0 ) dc.SetPen(wxPen(*wxWHITE, opts.penWidth)); dc.SetBrush( *wxRED_BRUSH ); wxPrintf("Benchmarking %s: ", msg); fflush(stdout); wxStopWatch sw; for ( int n = 0; n < opts.numIters; n++ ) { int x = rand() % opts.width, y = rand() % opts.height; dc.DrawRectangle(x, y, 32, 32); } const long t = sw.Time(); wxPrintf("%ld rects done in %ldms = %gus/rect\n", opts.numIters, t, (1000. * t)/opts.numIters); } void BenchmarkBitmaps(const wxString& msg, wxDC& dc) { if ( !opts.testBitmaps ) return; if ( opts.mapMode != 0 ) dc.SetMapMode((wxMappingMode)opts.mapMode); if ( opts.penWidth != 0 ) dc.SetPen(wxPen(*wxWHITE, opts.penWidth)); wxPrintf("Benchmarking %s: ", msg); fflush(stdout); wxStopWatch sw; for ( int n = 0; n < opts.numIters; n++ ) { int x = rand() % opts.width, y = rand() % opts.height; dc.DrawBitmap(m_bitmap, x, y, true); } const long t = sw.Time(); wxPrintf("%ld bitmaps done in %ldms = %gus/bitmap\n", opts.numIters, t, (1000. * t)/opts.numIters); } void BenchmarkImages(const wxString& msg, wxDC& dc) { if ( !opts.testImages ) return; if ( opts.mapMode != 0 ) dc.SetMapMode((wxMappingMode)opts.mapMode); wxPrintf("Benchmarking %s: ", msg); fflush(stdout); wxImage image(wxSize(opts.width, opts.height), false /* don't clear */); wxStopWatch sw; for ( int n = 0; n < opts.numIters; n++ ) { UpdateRGB(image.GetData(), n); dc.DrawBitmap(image, 0, 0); } const long t = sw.Time(); wxPrintf("%ld images done in %ldms = %gus/image or %ld FPS\n", opts.numIters, t, (1000. * t)/opts.numIters, (1000*opts.numIters + t - 1)/t); } void BenchmarkRawBitmaps(const wxString& msg, wxDC& dc) { if ( !opts.testRawBitmaps ) return; if ( opts.mapMode != 0 ) dc.SetMapMode((wxMappingMode)opts.mapMode); wxPrintf("Benchmarking %s: ", msg); fflush(stdout); wxBitmap bitmap(opts.width, opts.height, 24); wxNativePixelData data(bitmap); wxStopWatch sw; for ( int n = 0; n < opts.numIters; n++ ) { unsigned char c = n % 256; { wxNativePixelData::Iterator p(data); for ( int y = 0; y < opts.height; ++y ) { wxNativePixelData::Iterator rowStart = p; for ( int x = 0; x < opts.width; ++x ) { p.Red() = p.Green() = p.Blue() = c; ++p; } p = rowStart; p.OffsetY(data, 1); c++; } } dc.DrawBitmap(bitmap, 0, 0); } const long t = sw.Time(); wxPrintf("%ld raw bitmaps done in %ldms = %gus/bitmap or %ld FPS\n", opts.numIters, t, (1000. * t)/opts.numIters, (1000*opts.numIters + t - 1)/t); } wxBitmap m_bitmap; #if wxUSE_GLCANVAS wxGLCanvas* m_glCanvas; wxGLContext* m_glContext; #endif // wxUSE_GLCANVAS }; class GraphicsBenchmarkApp : public wxApp { public: virtual void OnInitCmdLine(wxCmdLineParser& parser) { static const wxCmdLineEntryDesc desc[] = { { wxCMD_LINE_SWITCH, "", "bitmaps" }, { wxCMD_LINE_SWITCH, "", "images" }, { wxCMD_LINE_SWITCH, "", "lines" }, { wxCMD_LINE_SWITCH, "", "rawbmp" }, { wxCMD_LINE_SWITCH, "", "rectangles" }, { wxCMD_LINE_SWITCH, "", "paint" }, { wxCMD_LINE_SWITCH, "", "client" }, { wxCMD_LINE_SWITCH, "", "memory" }, { wxCMD_LINE_SWITCH, "", "dc" }, { wxCMD_LINE_SWITCH, "", "gc" }, #if wxUSE_GLCANVAS { wxCMD_LINE_SWITCH, "", "gl" }, #endif // wxUSE_GLCANVAS { wxCMD_LINE_OPTION, "m", "map-mode", "", wxCMD_LINE_VAL_NUMBER }, { wxCMD_LINE_OPTION, "p", "pen-width", "", wxCMD_LINE_VAL_NUMBER }, { wxCMD_LINE_OPTION, "w", "width", "", wxCMD_LINE_VAL_NUMBER }, { wxCMD_LINE_OPTION, "h", "height", "", wxCMD_LINE_VAL_NUMBER }, { wxCMD_LINE_OPTION, "I", "images", "", wxCMD_LINE_VAL_NUMBER }, { wxCMD_LINE_OPTION, "N", "number-of-iterations", "", wxCMD_LINE_VAL_NUMBER }, { wxCMD_LINE_NONE }, }; parser.SetDesc(desc); } virtual bool OnCmdLineParsed(wxCmdLineParser& parser) { if ( parser.Found("m", &opts.mapMode) && (opts.mapMode < 1 || opts.mapMode > wxMM_METRIC) ) return false; if ( parser.Found("p", &opts.penWidth) && opts.penWidth < 1 ) return false; if ( parser.Found("w", &opts.width) && opts.width < 1 ) return false; if ( parser.Found("h", &opts.height) && opts.height < 1 ) return false; if ( parser.Found("N", &opts.numIters) && opts.numIters < 1 ) return false; opts.testBitmaps = parser.Found("bitmaps"); opts.testImages = parser.Found("images"); opts.testLines = parser.Found("lines"); opts.testRawBitmaps = parser.Found("rawbmp"); opts.testRectangles = parser.Found("rectangles"); if ( !(opts.testBitmaps || opts.testImages || opts.testLines || opts.testRawBitmaps || opts.testRectangles) ) { // Do everything by default. opts.testBitmaps = opts.testImages = opts.testLines = opts.testRawBitmaps = opts.testRectangles = true; } opts.usePaint = parser.Found("paint"); opts.useClient = parser.Found("client"); opts.useMemory = parser.Found("memory"); if ( !(opts.usePaint || opts.useClient || opts.useMemory) ) { opts.usePaint = opts.useClient = opts.useMemory = true; } opts.useDC = parser.Found("dc"); opts.useGC = parser.Found("gc"); #if wxUSE_GLCANVAS opts.useGL = parser.Found("gl"); if ( opts.useGL ) { if ( opts.useDC || opts.useGC ) { wxLogError("Can't use both OpenGL and normal graphics."); return false; } } else // Not using OpenGL #endif // wxUSE_GLCANVAS { if ( !(opts.useDC || opts.useGC) ) { opts.useDC = opts.useGC = true; } } return true; } virtual bool OnInit() { if ( !wxApp::OnInit() ) return false; new GraphicsBenchmarkFrame; return true; } }; IMPLEMENT_APP_CONSOLE(GraphicsBenchmarkApp)
8,089
777
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/ssl/ssl_platform_key_util.h" #include <stddef.h> #include "base/memory/ref_counted.h" #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_private_key.h" #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/boringssl/src/include/openssl/ecdsa.h" namespace net { namespace { bool GetClientCertInfoFromFile(const char* filename, SSLPrivateKey::Type* out_type, size_t* out_max_length) { scoped_refptr<X509Certificate> cert = ImportCertFromFile(GetTestCertsDirectory(), filename); if (!cert) { ADD_FAILURE() << "Could not read " << filename; return false; } return GetClientCertInfo(cert.get(), out_type, out_max_length); } size_t BitsToBytes(size_t bits) { return (bits + 7) / 8; } } // namespace TEST(SSLPlatformKeyUtil, GetClientCertInfo) { SSLPrivateKey::Type type; size_t max_length; ASSERT_TRUE(GetClientCertInfoFromFile("client_1.pem", &type, &max_length)); EXPECT_EQ(SSLPrivateKey::Type::RSA, type); EXPECT_EQ(2048u / 8u, max_length); ASSERT_TRUE(GetClientCertInfoFromFile("client_4.pem", &type, &max_length)); EXPECT_EQ(SSLPrivateKey::Type::ECDSA_P256, type); EXPECT_EQ(ECDSA_SIG_max_len(BitsToBytes(256)), max_length); ASSERT_TRUE(GetClientCertInfoFromFile("client_5.pem", &type, &max_length)); EXPECT_EQ(SSLPrivateKey::Type::ECDSA_P384, type); EXPECT_EQ(ECDSA_SIG_max_len(BitsToBytes(384)), max_length); ASSERT_TRUE(GetClientCertInfoFromFile("client_6.pem", &type, &max_length)); EXPECT_EQ(SSLPrivateKey::Type::ECDSA_P521, type); EXPECT_EQ(ECDSA_SIG_max_len(BitsToBytes(521)), max_length); } } // namespace net
801
7,137
package io.onedev.server.web.component.watchstatus; import io.onedev.server.web.page.base.BaseDependentCssResourceReference; public class WatchStatusResourceReference extends BaseDependentCssResourceReference { private static final long serialVersionUID = 1L; public WatchStatusResourceReference() { super(WatchStatusResourceReference.class, "watch-status.css"); } }
105
30,023
"""Constants for the KNX integration.""" from __future__ import annotations from enum import Enum from typing import Final, TypedDict from homeassistant.components.climate.const import ( PRESET_AWAY, PRESET_COMFORT, PRESET_ECO, PRESET_NONE, PRESET_SLEEP, HVACAction, HVACMode, ) from homeassistant.const import Platform DOMAIN: Final = "knx" # Address is used for configuration and services by the same functions so the key has to match KNX_ADDRESS: Final = "address" CONF_INVERT: Final = "invert" CONF_KNX_EXPOSE: Final = "expose" CONF_KNX_INDIVIDUAL_ADDRESS: Final = "individual_address" ## # Connection constants ## CONF_KNX_CONNECTION_TYPE: Final = "connection_type" CONF_KNX_AUTOMATIC: Final = "automatic" CONF_KNX_ROUTING: Final = "routing" CONF_KNX_TUNNELING: Final = "tunneling" CONF_KNX_TUNNELING_TCP: Final = "tunneling_tcp" CONF_KNX_TUNNELING_TCP_SECURE: Final = "tunneling_tcp_secure" CONF_KNX_LOCAL_IP: Final = "local_ip" CONF_KNX_MCAST_GRP: Final = "multicast_group" CONF_KNX_MCAST_PORT: Final = "multicast_port" CONF_KNX_RATE_LIMIT: Final = "rate_limit" CONF_KNX_ROUTE_BACK: Final = "route_back" CONF_KNX_STATE_UPDATER: Final = "state_updater" CONF_KNX_DEFAULT_STATE_UPDATER: Final = True CONF_KNX_DEFAULT_RATE_LIMIT: Final = 20 ## # Secure constants ## CONST_KNX_STORAGE_KEY: Final = "knx/" CONF_KNX_KNXKEY_FILENAME: Final = "knxkeys_filename" CONF_KNX_KNXKEY_PASSWORD: Final = "knxkeys_password" CONF_KNX_SECURE_USER_ID: Final = "user_id" CONF_KNX_SECURE_USER_PASSWORD: Final = "<PASSWORD>" CONF_KNX_SECURE_DEVICE_AUTHENTICATION: Final = "device_authentication" CONF_PAYLOAD: Final = "payload" CONF_PAYLOAD_LENGTH: Final = "payload_length" CONF_RESET_AFTER: Final = "reset_after" CONF_RESPOND_TO_READ: Final = "respond_to_read" CONF_STATE_ADDRESS: Final = "state_address" CONF_SYNC_STATE: Final = "sync_state" # yaml config merged with config entry data DATA_KNX_CONFIG: Final = "knx_config" # original hass yaml config DATA_HASS_CONFIG: Final = "knx_hass_config" ATTR_COUNTER: Final = "counter" ATTR_SOURCE: Final = "source" class KNXConfigEntryData(TypedDict, total=False): """Config entry for the KNX integration.""" connection_type: str individual_address: str local_ip: str | None multicast_group: str multicast_port: int route_back: bool state_updater: bool rate_limit: int host: str port: int user_id: int user_password: str device_authentication: str knxkeys_filename: str knxkeys_password: str class ColorTempModes(Enum): """Color temperature modes for config validation.""" ABSOLUTE = "DPT-7.600" RELATIVE = "DPT-5.001" SUPPORTED_PLATFORMS: Final = [ Platform.BINARY_SENSOR, Platform.BUTTON, Platform.CLIMATE, Platform.COVER, Platform.FAN, Platform.LIGHT, Platform.NOTIFY, Platform.NUMBER, Platform.SCENE, Platform.SELECT, Platform.SENSOR, Platform.SWITCH, Platform.WEATHER, ] # Map KNX controller modes to HA modes. This list might not be complete. CONTROLLER_MODES: Final = { # Map DPT 20.105 HVAC control modes "Auto": HVACMode.AUTO, "Heat": HVACMode.HEAT, "Cool": HVACMode.COOL, "Off": HVACMode.OFF, "Fan only": HVACMode.FAN_ONLY, "Dry": HVACMode.DRY, } CURRENT_HVAC_ACTIONS: Final = { HVACMode.HEAT: HVACAction.HEATING, HVACMode.COOL: HVACAction.COOLING, HVACMode.OFF: HVACAction.OFF, HVACMode.FAN_ONLY: HVACAction.FAN, HVACMode.DRY: HVACAction.DRYING, } PRESET_MODES: Final = { # Map DPT 20.102 HVAC operating modes to HA presets "Auto": PRESET_NONE, "Frost Protection": PRESET_ECO, "Night": PRESET_SLEEP, "Standby": PRESET_AWAY, "Comfort": PRESET_COMFORT, }
1,602
6,684
{ "pagination": { "DescribeBackups": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" }, "DescribeDataRepositoryTasks": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" }, "DescribeFileSystemAliases": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" }, "DescribeFileSystems": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" }, "DescribeStorageVirtualMachines": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" }, "DescribeVolumes": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" }, "ListTagsForResource": { "input_token": "NextToken", "output_token": "NextToken", "limit_key": "MaxResults" } } }
450
357
#include <iostream> #include <stdlib.h> #include <string> #define num 8 #define MAXSIZE 100 using namespace std; class coded_char { private: char value; double weight; string code; bool iscoded = false; public: coded_char(char value, double weight) :value(value), weight(weight){} coded_char* left, *right; void setcode(string s){code = s;} string getcode(){return code;} double getweight(){return weight;} bool getiscoded(){return iscoded;} void setiscoded(){iscoded = true;} char getvalue(){return value;} }; coded_char* get_last(coded_char* data[], int end) { double min = 9999.0; coded_char* last = data[0]; for (int i = 0; i < end; i++) { if ((*data[i]).getiscoded() == true) continue; if ((*data[i]).getweight() < min) { min = (*data[i]).getweight(); last = data[i]; } } return last; } coded_char* get_second_last(coded_char* data[], coded_char* last, int end) { double min = 9999.0; coded_char* second_last = data[0]; for (int i = 0; i < end; i++) { if ((*data[i]).getiscoded() == true) continue; if ((*data[i]).getweight() < min && data[i] != last) { min = (*data[i]).getweight(); second_last = data[i]; } } return second_last; } void trace(coded_char* root) { if ((*root).getvalue() != ' ') { return; } else { (*((*root).left)).setcode((*root).getcode() + "0"); (*((*root).right)).setcode((*root).getcode() + "1"); trace((*root).left); trace((*root).right); } } void HUFFMAN_CODE(coded_char* data[]) { for (int i = num; i < 2 * num - 1; i++) { coded_char* last = get_last(data, i); coded_char* second_last = get_second_last(data, last, i); data[i] = new coded_char(' ', (*last).getweight() + (*second_last).getweight()); (*data[i]).left = last; (*data[i]).right = second_last; (*last).setiscoded(); (*second_last).setiscoded(); } (*data[2 * num - 2]).setcode(""); //root trace(data[2 * num - 2]); } void print_code(coded_char* data) { cout << (*data).getvalue() << ":" << (*data).getcode() << endl; } int main() { coded_char* data[2 * num - 1]; data[0] = new coded_char('A', 1); data[1] = new coded_char('B', 1); data[2] = new coded_char('C', 1); data[3] = new coded_char('D', 2); data[4] = new coded_char('E', 3); data[5] = new coded_char('F', 5); data[6] = new coded_char('G', 5); data[7] = new coded_char('H', 10); HUFFMAN_CODE(data); for (int k = 0; k < num; k++) print_code(data[k]); //cout << (*last).getvalue() << ' ' << (*second_last).getvalue() << endl; system("pause"); return 0; }
1,061
2,967
<filename>src/core/os2/geniconv/os2cp.c /* Simple DirectMedia Layer Copyright (C) 1997-2021 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #define INCL_DOSNLS #define INCL_DOSERRORS #include <os2.h> #include "os2cp.h" #ifndef GENICONV_STANDALONE #include "../../../SDL_internal.h" #else #include <string.h> #include <ctype.h> #define SDL_isspace isspace #define SDL_strchr strchr #define SDL_memcpy memcpy #define SDL_strupr strupr #define SDL_strcmp strcmp #endif typedef struct _CP2NAME { ULONG ulCode; PSZ pszName; } CP2NAME; typedef struct _NAME2CP { PSZ pszName; ULONG ulCode; } NAME2CP; static CP2NAME aCP2Name[] = { {367, "ANSI_X3.4-1968"}, {813, "ECMA-118"}, {819, "CP819"}, {850, "850"}, {862, "862"}, {866, "866"}, {874, "ISO-IR-166"}, {878, "KOI8-R"}, {896, "JISX0201-1976"}, {901, "ISO-8859-13"}, {912, "ISO-8859-2"}, {913, "ISO-8859-3"}, {914, "ISO-8859-4"}, {915, "CYRILLIC"}, {920, "ISO-8859-9"}, {923, "ISO-8859-15"}, {943, "MS_KANJI"}, {954, "EUC-JP"}, {964, "EUC-TW"}, {970, "EUC-KR"}, {1051, "HP-ROMAN8"}, {1089, "ARABIC"}, {1129, "VISCII"}, {1168, "KOI8-U"}, {1200, "ISO-10646-UCS-2"}, {1202, "UTF-16LE"}, {1204, "UCS-2BE"}, {1208, "UTF-8"}, {1232, "UTF-32BE"}, {1234, "UTF-32LE"}, {1236, "ISO-10646-UCS-4"}, {1250, "CP1250"}, {1251, "CP1251"}, {1252, "CP1252"}, {1253, "CP1253"}, {1254, "CP1254"}, {1255, "CP1255"}, {1256, "CP1256"}, {1257, "CP1257"}, {1275, "MAC"}, {1383, "CN-GB"}, {1386, "GBK"}, {1392, "GB18030"}, {62210, "HEBREW"} }; static NAME2CP aName2CP[] = { {"850", 850}, {"862", 862}, {"866", 866}, {"ANSI_X3.4-1968", 367}, {"ANSI_X3.4-1986", 367}, {"ARABIC", 1089}, {"ASCII", 367}, {"ASMO-708", 1089}, {"CN-GB", 1383}, {"CP1250", 1250}, {"CP1251", 1251}, {"CP1252", 1252}, {"CP1253", 1253}, {"CP1254", 1254}, {"CP1255", 1255}, {"CP1256", 1256}, {"CP1257", 1257}, {"CP367", 367}, {"CP819", 819}, {"CP850", 850}, {"CP862", 862}, {"CP866", 866}, {"CP936", 1386}, {"CSASCII", 367}, {"CSEUCKR", 970}, {"CSEUCPKDFMTJAPANESE", 954}, {"CSEUCTW", 964}, {"CSGB2312", 1383}, {"CSHALFWIDTHKATAKANA", 896}, {"CSHPROMAN8", 1051}, {"CSIBM866", 866}, {"CSISOLATIN1", 819}, {"CSISOLATIN2", 912}, {"CSISOLATIN3", 913}, {"CSISOLATIN4", 914}, {"CSISOLATIN5", 920}, {"CSISOLATINARABIC", 1089}, {"CSISOLATINCYRILLIC", 915}, {"CSISOLATINGREEK", 813}, {"CSISOLATINHEBREW", 62210}, {"CSKOI8R", 878}, {"CSKSC56011987", 970}, {"CSMACINTOSH", 1275}, {"CSPC850MULTILINGUAL", 850}, {"CSPC862LATINHEBREW", 862}, {"CSSHIFTJIS", 943}, {"CSUCS4", 1236}, {"CSUNICODE", 1200}, {"CSUNICODE11", 1204}, {"CSVISCII", 1129}, {"CYRILLIC", 915}, {"ECMA-114", 1089}, {"ECMA-118", 813}, {"ELOT_928", 813}, {"EUC-CN", 1383}, {"EUC-JP", 954}, {"EUC-KR", 970}, {"EUC-TW", 964}, {"EUCCN", 1383}, {"EUCJP", 954}, {"EUCKR", 970}, {"EUCTW", 964}, {"EXTENDED_UNIX_CODE_PACKED_FORMAT_FOR_JAPANESE", 954}, {"GB18030", 1392}, {"GB2312", 1383}, {"GBK", 1386}, {"GREEK", 813}, {"GREEK8", 813}, {"HEBREW", 62210}, {"HP-ROMAN8", 1051}, {"IBM367", 367}, {"IBM819", 819}, {"IBM850", 850}, {"IBM862", 862}, {"IBM866", 866}, {"ISO-10646-UCS-2", 1200}, {"ISO-10646-UCS-4", 1236}, {"ISO-8859-1", 819}, {"ISO-8859-13", 901}, {"ISO-8859-15", 923}, {"ISO-8859-2", 912}, {"ISO-8859-3", 913}, {"ISO-8859-4", 914}, {"ISO-8859-5", 915}, {"ISO-8859-6", 1089}, {"ISO-8859-7", 813}, {"ISO-8859-8", 62210}, {"ISO-8859-9", 920}, {"ISO-IR-100", 819}, {"ISO-IR-101", 912}, {"ISO-IR-109", 913}, {"ISO-IR-110", 914}, {"ISO-IR-126", 813}, {"ISO-IR-127", 1089}, {"ISO-IR-138", 62210}, {"ISO-IR-144", 915}, {"ISO-IR-148", 920}, {"ISO-IR-149", 970}, {"ISO-IR-166", 874}, {"ISO-IR-179", 901}, {"ISO-IR-203", 923}, {"ISO-IR-6", 367}, {"ISO646-US", 367}, {"ISO8859-1", 819}, {"ISO8859-13", 901}, {"ISO8859-15", 923}, {"ISO8859-2", 912}, {"ISO8859-3", 913}, {"ISO8859-4", 914}, {"ISO8859-5", 915}, {"ISO8859-6", 1089}, {"ISO8859-7", 813}, {"ISO8859-8", 62210}, {"ISO8859-9", 920}, {"ISO_646.IRV:1991", 367}, {"ISO_8859-1", 819}, {"ISO_8859-13", 901}, {"ISO_8859-15", 923}, {"ISO_8859-15:1998", 923}, {"ISO_8859-1:1987", 819}, {"ISO_8859-2", 912}, {"ISO_8859-2:1987", 912}, {"ISO_8859-3", 913}, {"ISO_8859-3:1988", 913}, {"ISO_8859-4", 914}, {"ISO_8859-4:1988", 914}, {"ISO_8859-5", 915}, {"ISO_8859-5:1988", 915}, {"ISO_8859-6", 1089}, {"ISO_8859-6:1987", 1089}, {"ISO_8859-7", 813}, {"ISO_8859-7:1987", 813}, {"ISO_8859-7:2003", 813}, {"ISO_8859-8", 62210}, {"ISO_8859-8:1988", 62210}, {"ISO_8859-9", 920}, {"ISO_8859-9:1989", 920}, {"JISX0201-1976", 896}, {"JIS_X0201", 896}, {"KOI8-R", 878}, {"KOI8-U", 1168}, {"KOREAN", 970}, {"KSC_5601", 970}, {"KS_C_5601-1987", 970}, {"KS_C_5601-1989", 970}, {"L1", 819}, {"L2", 912}, {"L3", 913}, {"L4", 914}, {"L5", 920}, {"L7", 901}, {"LATIN-9", 923}, {"LATIN1", 819}, {"LATIN2", 912}, {"LATIN3", 913}, {"LATIN4", 914}, {"LATIN5", 920}, {"LATIN7", 901}, {"MAC", 1275}, {"MACINTOSH", 1275}, {"MACROMAN", 1275}, {"MS-ANSI", 1252}, {"MS-ARAB", 1256}, {"MS-CYRL", 1251}, {"MS-EE", 1250}, {"MS-GREEK", 1253}, {"MS-HEBR", 1255}, {"MS-TURK", 1254}, {"MS936", 1386}, {"MS_KANJI", 943}, {"R8", 1051}, {"ROMAN8", 1051}, {"SHIFT-JIS", 943}, {"SHIFT_JIS", 943}, {"SJIS", 943}, {"TIS-620", 874}, {"TIS620", 874}, {"TIS620-0", 874}, {"TIS620.2529-1", 874}, {"TIS620.2533-0", 874}, {"TIS620.2533-1", 874}, {"UCS-2", 1200}, {"UCS-2BE", 1204}, {"UCS-4", 1236}, {"UNICODE-1-1", 1204}, {"UNICODEBIG", 1204}, {"US", 367}, {"US-ASCII", 367}, {"UTF-16", 1204}, {"UTF-16BE", 1200}, {"UTF-16LE", 1202}, {"UTF-32", 1236}, {"UTF-32BE", 1232}, {"UTF-32LE", 1234}, {"UTF-8", 1208}, {"VISCII", 1129}, {"VISCII1.1-1", 1129}, {"WINBALTRIM", 1257}, {"WINDOWS-1250", 1250}, {"WINDOWS-1251", 1251}, {"WINDOWS-1252", 1252}, {"WINDOWS-1253", 1253}, {"WINDOWS-1254", 1254}, {"WINDOWS-1255", 1255}, {"WINDOWS-1256", 1256}, {"WINDOWS-1257", 1257}, {"WINDOWS-936", 1386}, {"X0201", 896} }; char *os2cpToName(unsigned long cp) { ULONG ulLo = 0; ULONG ulHi = (sizeof(aCP2Name) / sizeof(struct _CP2NAME)) - 1; ULONG ulNext; LONG lFound = -1; if (cp == SYSTEM_CP) { ULONG aulCP[3]; ULONG cCP; if (DosQueryCp(sizeof(aulCP), aulCP, &cCP) != NO_ERROR) { return NULL; } cp = aulCP[0]; } if (aCP2Name[0].ulCode > cp || aCP2Name[ulHi].ulCode < cp) { return NULL; } if (aCP2Name[0].ulCode == cp) { return aCP2Name[0].pszName; } if (aCP2Name[ulHi].ulCode == cp) { return aCP2Name[ulHi].pszName; } while ((ulHi - ulLo) > 1) { ulNext = (ulLo + ulHi) / 2; if (aCP2Name[ulNext].ulCode < cp) { ulLo = ulNext; } else if (aCP2Name[ulNext].ulCode > cp) { ulHi = ulNext; } else { lFound = ulNext; break; } } return (lFound == -1)? NULL : aCP2Name[lFound].pszName; } unsigned long os2cpFromName(char *cp) { ULONG ulLo = 0; ULONG ulHi = (sizeof(aName2CP) / sizeof(struct _NAME2CP)) - 1; ULONG ulNext; LONG lFound = -1; LONG lCmp; PCHAR pcEnd; CHAR acBuf[64]; if (cp == NULL) { ULONG aulCP[3]; ULONG cCP; return (DosQueryCp(sizeof(aulCP), aulCP, &cCP) != NO_ERROR)? 0 : aulCP[0]; } while (SDL_isspace((unsigned char) *cp)) { cp++; } pcEnd = SDL_strchr(cp, ' '); if (pcEnd == NULL) { pcEnd = SDL_strchr(cp, '\0'); } ulNext = pcEnd - cp; if (ulNext >= sizeof(acBuf)) { return 0; } SDL_memcpy(acBuf, cp, ulNext); acBuf[ulNext] = '\0'; SDL_strupr(acBuf); lCmp = SDL_strcmp(aName2CP[0].pszName, acBuf); if (lCmp > 0) { return 0; } if (lCmp == 0) { return aName2CP[0].ulCode; } lCmp = SDL_strcmp(aName2CP[ulHi].pszName, acBuf); if (lCmp < 0) { return 0; } if (lCmp == 0) { return aName2CP[ulHi].ulCode; } while ((ulHi - ulLo) > 1) { ulNext = (ulLo + ulHi) / 2; lCmp = SDL_strcmp(aName2CP[ulNext].pszName, acBuf); if (lCmp < 0) { ulLo = ulNext; } else if (lCmp > 0) { ulHi = ulNext; } else { lFound = ulNext; break; } } return (lFound == -1)? 0 : aName2CP[lFound].ulCode; } /* vi: set ts=4 sw=4 expandtab: */
4,813
11,094
<filename>基础教程/A1-Python与基础知识/算法第一步/ExampleCodes/chapter16/16-4_16-5.py<gh_stars>1000+ def recursion_test(depth): if depth <1000: recursion_test(depth + 1) return # 下面是 代码16-5 recursion_test(1)
135
412
public class Test_binary3 { public static void main(Boolean b) { String s = Long.toString(Long.MIN_VALUE + 1, 2); if (b) { assert(s.equals("-111111111111111111111111111111111111111111111111111111111111111")); } else { assert(!s.equals("-111111111111111111111111111111111111111111111111111111111111111")); } } }
178
2,430
<reponame>PierreMesure/openaddresses import json import math import sys import logging from esridump.dumper import EsriDumper logging.basicConfig(level=logging.DEBUG) outfile_name = sys.argv[1] if len(sys.argv) > 1 else 'medellin.geojson' d = EsriDumper('https://www.medellin.gov.co/arcgis/rest/services/ServiciosPlaneacion/Pot_base1/MapServer/0') outfile = open(outfile_name, 'w') outfile.write('{"type":"FeatureCollection","features":[\n') features = iter(d) try: feature = next(features) while True: if not feature.get('geometry') or feature['geometry']['coordinates'][0] == 'NaN' or (type(feature['geometry']['coordinates'][0]) is float and math.isnan(feature['geometry']['coordinates'][0])): feature = next(features) continue outfile.write(json.dumps(feature)) feature = next(features) outfile.write(',\n') except StopIteration: outfile.write('\n') outfile.write(']}')
381
577
<filename>examples/generation/docking_generation/guacamol_tdc/guacamol/guacamol/utils/math.py from typing import List import numpy as np def arithmetic_mean(values: List[float]) -> float: """ Computes the arithmetic mean of a list of values. """ return sum(values) / len(values) def geometric_mean(values: List[float]) -> float: """ Computes the geometric mean of a list of values. """ a = np.array(values) return a.prod() ** (1.0 / len(a))
177
347
<reponame>SAristeev/CUDALibrarySamples<filename>cuSPARSE/compression/compression_example.cpp /* * Copyright 1993-2021 NVIDIA Corporation. All rights reserved. * * NOTICE TO LICENSEE: * * This source code and/or documentation ("Licensed Deliverables") are * subject to NVIDIA intellectual property rights under U.S. and * international Copyright laws. * * These Licensed Deliverables contained herein is PROPRIETARY and * CONFIDENTIAL to NVIDIA and is being provided under the terms and * conditions of a form of NVIDIA software license agreement by and * between NVIDIA and Licensee ("License Agreement") or electronically * accepted by Licensee. Notwithstanding any terms or conditions to * the contrary in the License Agreement, reproduction or disclosure * of the Licensed Deliverables to any third party without the express * written consent of NVIDIA is prohibited. * * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THESE LICENSED DELIVERABLES. * * U.S. Government End Users. These Licensed Deliverables are a * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT * 1995), consisting of "commercial computer software" and "commercial * computer software documentation" as such terms are used in 48 * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government * only as a commercial end item. Consistent with 48 C.F.R.12.212 and * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all * U.S. Government End Users acquire the Licensed Deliverables with * only those rights set forth herein. * * Any use of the Licensed Deliverables in individual and commercial * software must include, in the user documentation and internal * comments to the code, the above Disclaimer and U.S. Government End * Users Notice. */ #include <algorithm> // std::fill #include <cstdio> // printf #include <cstdlib> // EXIT_FAILURE #include <cuda.h> // cuMemCreate #include <cuda_runtime_api.h> // cudaMalloc, cudaMemcpy, etc. #include <cusparse.h> // cusparseAxpby #include <numeric> // std::iota #define CHECK_DRV(func) \ { \ CUresult status = (func); \ if (status != CUDA_SUCCESS) { \ const char* error_str; \ cuGetErrorString(status, &error_str); \ std::printf("cuMem API failed at line %d with error: %s (%d)\n", \ __LINE__, error_str, status); \ std::exit(EXIT_FAILURE); \ } \ } #define CHECK_CUDA(func) \ { \ cudaError_t status = (func); \ if (status != cudaSuccess) { \ std::printf("CUDA API failed at line %d with error: %s (%d)\n", \ __LINE__, cudaGetErrorString(status), status); \ std::exit(EXIT_FAILURE); \ } \ } #define CHECK_CUSPARSE(func) \ { \ cusparseStatus_t status = (func); \ if (status != CUSPARSE_STATUS_SUCCESS) { \ std::printf("CUSPARSE API failed at line %d with error: %s (%d)\n", \ __LINE__, cusparseGetErrorString(status), status); \ std::exit(EXIT_FAILURE); \ } \ } size_t round_up(size_t value, size_t div) { return ((value + div - 1) / div) * div; } //------------------------------------------------------------------------------ template<typename T> class drvMemory { public: explicit drvMemory(int64_t num_items, const T* h_values) { // DRIVER CONTEXT auto size_bytes = num_items * sizeof(T); CUdevice dev = 0; // (1) Set allocation properties, enable compression CUmemAllocationProp prop = {}; prop.allocFlags.compressionType = CU_MEM_ALLOCATION_COMP_GENERIC; prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE; prop.location.id = static_cast<int>(dev); prop.win32HandleMetaData = 0; // (2) Retrieve allocation granularity size_t granularity = 0; CHECK_DRV( cuMemGetAllocationGranularity(&granularity, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM) ) _padded_size = round_up(size_bytes, granularity); // (3) Reverse Address range CUdeviceptr d_ptr_raw = 0ULL; CHECK_DRV( cuMemAddressReserve(&d_ptr_raw, _padded_size, 0, 0, 0) ) // (4) Create the Allocation Handle CHECK_DRV( cuMemCreate(&_allocation_handle, _padded_size, &prop, 0) ) // (5) Memory mappping CHECK_DRV( cuMemMap(d_ptr_raw, _padded_size, 0, _allocation_handle, 0) ) // (6) Verify that the allocation properties are supported CHECK_DRV( cuMemGetAllocationPropertiesFromHandle(&prop, _allocation_handle) ) // (7) Set Access Permissions CUmemAccessDesc accessDesc = {}; accessDesc.location = prop.location; accessDesc.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE; CHECK_DRV( cuMemSetAccess(d_ptr_raw, _padded_size, &accessDesc, 1) ) // (7) Convert the raw pointer _d_ptr = reinterpret_cast<T*>(d_ptr_raw); CHECK_CUDA( cudaMemcpy(_d_ptr, h_values, num_items * sizeof(T), cudaMemcpyHostToDevice) ) } T* ptr() const { return static_cast<T*>(_d_ptr); } ~drvMemory() { auto ptr = reinterpret_cast<CUdeviceptr>(_d_ptr); CHECK_DRV( cuMemUnmap(ptr, _padded_size) ) CHECK_DRV( cuMemAddressFree(ptr, _padded_size) ) CHECK_DRV( cuMemRelease(_allocation_handle) ) } private: CUmemGenericAllocationHandle _allocation_handle {}; size_t _padded_size { 0 }; void* _d_ptr { nullptr }; }; //------------------------------------------------------------------------------ template<typename T> class cudaMemory { public: explicit cudaMemory(int64_t num_items, const T* h_values) { CHECK_CUDA( cudaMalloc(reinterpret_cast<void**>(&_d_ptr), num_items * sizeof(T)) ) CHECK_CUDA( cudaMemcpy(_d_ptr, h_values, num_items * sizeof(T), cudaMemcpyHostToDevice) ) } T* ptr() const { return _d_ptr; } ~cudaMemory() { CHECK_CUDA( cudaFree(_d_ptr) ) } private: T* _d_ptr { nullptr }; }; //------------------------------------------------------------------------------ float benchmark(int64_t nnz, int64_t size, void* dX_indices, void* dX_values, void* dY) { float alpha = 1.0f; float beta = 1.0f; // CUSPARSE APIs cusparseHandle_t handle = NULL; cusparseSpVecDescr_t vecX; cusparseDnVecDescr_t vecY; CHECK_CUSPARSE( cusparseCreate(&handle) ) // Create sparse vector X CHECK_CUSPARSE( cusparseCreateSpVec(&vecX, size, nnz, dX_indices, dX_values, CUSPARSE_INDEX_32I, CUSPARSE_INDEX_BASE_ZERO, CUDA_R_32F) ) // Create dense vector y CHECK_CUSPARSE( cusparseCreateDnVec(&vecY, size, dY, CUDA_R_32F) ) // Warmup run CHECK_CUSPARSE( cusparseAxpby(handle, &alpha, vecX, &beta, vecY) ) CHECK_CUDA( cudaDeviceSynchronize() ) // Timer setup float elapsed_ms = 0; cudaEvent_t start_event{}, stop_event{}; CHECK_CUDA( cudaEventCreate(&start_event) ) CHECK_CUDA( cudaEventCreate(&stop_event) ) CHECK_CUDA( cudaEventRecord(start_event, nullptr) ) // Computation for (int i = 0; i < 10; i++) cusparseAxpby(handle, &alpha, vecX, &beta, vecY); CHECK_CUDA( cudaEventRecord(stop_event, nullptr) ) CHECK_CUDA( cudaEventSynchronize(stop_event) ) CHECK_CUDA( cudaEventElapsedTime(&elapsed_ms, start_event, stop_event) ) CHECK_CUDA( cudaEventDestroy(start_event) ) CHECK_CUDA( cudaEventDestroy(stop_event) ) // Destroy matrix/vector descriptors CHECK_CUSPARSE( cusparseDestroySpVec(vecX) ) CHECK_CUSPARSE( cusparseDestroyDnVec(vecY) ) CHECK_CUSPARSE( cusparseDestroy(handle) ) return elapsed_ms; } //------------------------------------------------------------------------------ constexpr int EXIT_UNSUPPORTED = 2; int main() { cudaFree(nullptr); // Without a previous CUDA runtime call (e.g. cudaMalloc) we need to // explicitly initialize the context: // // CUcontext ctx; // CHECK_DRV( cuInit(0) ) // CHECK_DRV( cuDevicePrimaryCtxRetain(&ctx, 0) ) // CHECK_DRV( cuCtxSetCurrent(ctx) ) // CHECK_DRV( cuCtxGetDevice(&dev) ) // Check if Memory Compression and Virtual Address Management is supported CUdevice dev = 0; int supportsCompression = 0; int supportsVMM = 0; CHECK_DRV( cuDeviceGetAttribute( &supportsCompression, CU_DEVICE_ATTRIBUTE_GENERIC_COMPRESSION_SUPPORTED, dev) ) if (supportsCompression == 0) { std::printf("\nL2 compression is not supported on the " "current device\n\n"); return EXIT_UNSUPPORTED; } CHECK_DRV( cuDeviceGetAttribute( &supportsVMM, CU_DEVICE_ATTRIBUTE_VIRTUAL_ADDRESS_MANAGEMENT_SUPPORTED, dev) ) if (supportsVMM == 0) { std::printf("\nVirtual Memory Management is not supported on the " "current device\n\n"); return EXIT_UNSUPPORTED; } //-------------------------------------------------------------------------- // Host problem definition int64_t size = 134217728; // 2^27 int64_t nnz = 134217728; // 2^27 auto hX_indices = new int[nnz]; auto hX_values = new float[nnz]; auto hY = new float[size]; std::iota(hX_indices, hX_indices + nnz, 0); std::fill(hX_values, hX_values + nnz, 1.0f); std::fill(hY, hY + size, 1.0f); //-------------------------------------------------------------------------- // Device memory management float cuda_elapsed_ms = 0.0f; float drv_elapsed_ms = 0.0f; { cudaMemory<int> dX_indices_cuda{nnz, hX_indices}; cudaMemory<float> dX_values_cuda{nnz, hX_values}; cudaMemory<float> dY_cuda{size, hY}; cuda_elapsed_ms = benchmark(nnz, size, dX_indices_cuda.ptr(), dX_values_cuda.ptr(), dY_cuda.ptr()); } { drvMemory<int> dX_indices_drv{nnz, hX_indices}; drvMemory<float> dX_values_drv{nnz, hX_values}; drvMemory<float> dY_drv{size, hY}; drv_elapsed_ms = benchmark(nnz, size, dX_indices_drv.ptr(), dX_values_drv.ptr(), dY_drv.ptr()); } delete[] hX_indices; delete[] hX_values; delete[] hY; auto speedup = ((cuda_elapsed_ms - drv_elapsed_ms) / cuda_elapsed_ms) * 100.0f; std::printf("\nStandard call: %.1f ms" "\nL2 Compression: %.1f ms" "\nPerf improvement: %.1f%%\n\n", cuda_elapsed_ms, drv_elapsed_ms, speedup); return EXIT_SUCCESS; }
6,458
400
/* * NASA Docket No. GSC-18,370-1, and identified as "Operating System Abstraction Layer" * * Copyright (c) 2019 United States Government as represented by * the Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * \file os-impl-queues.c * \ingroup rtems * \author <EMAIL> * * This file contains some of the OS APIs abstraction layer for RTEMS * This has been tested against the current RTEMS 4.11 release branch * * NOTE: This uses only the "Classic" RTEMS API. It is intended to * work on RTEMS targets that do not provide the POSIX API, i.e. * when "--disable-posix" is given during the configuration stage. */ /**************************************************************************************** INCLUDE FILES ***************************************************************************************/ #include "os-rtems.h" #include "os-impl-queues.h" #include "os-shared-queue.h" #include "os-shared-idmap.h" #include "os-shared-timebase.h" /**************************************************************************************** DEFINES ***************************************************************************************/ /**************************************************************************************** GLOBAL DATA ***************************************************************************************/ /* Tables where the OS object information is stored */ OS_impl_queue_internal_record_t OS_impl_queue_table[OS_MAX_QUEUES]; /**************************************************************************************** MESSAGE QUEUE API ***************************************************************************************/ /*---------------------------------------------------------------- * * Function: OS_Rtems_QueueAPI_Impl_Init * * Purpose: Local helper routine, not part of OSAL API. * *-----------------------------------------------------------------*/ int32 OS_Rtems_QueueAPI_Impl_Init(void) { memset(OS_impl_queue_table, 0, sizeof(OS_impl_queue_table)); return (OS_SUCCESS); } /* end OS_Rtems_QueueAPI_Impl_Init */ /*---------------------------------------------------------------- * * Function: OS_QueueCreate_Impl * * Purpose: Implemented per internal OSAL API * See prototype for argument/return detail * *-----------------------------------------------------------------*/ int32 OS_QueueCreate_Impl(const OS_object_token_t *token, uint32 flags) { rtems_status_code status; rtems_name r_name; OS_impl_queue_internal_record_t *impl; OS_queue_internal_record_t * queue; impl = OS_OBJECT_TABLE_GET(OS_impl_queue_table, *token); queue = OS_OBJECT_TABLE_GET(OS_queue_table, *token); /* ** RTEMS task names are 4 byte integers. ** It is convenient to use the OSAL queue ID in here, as we know it is already unique ** and trying to use the real queue name would be less than useful (only 4 chars) */ r_name = OS_ObjectIdToInteger(OS_ObjectIdFromToken(token)); /* ** Create the message queue. ** The queue attributes are set to default values; the waiting order ** (RTEMS_FIFO or RTEMS_PRIORITY) is irrelevant since only one task waits ** on each queue. */ status = rtems_message_queue_create(r_name, /* 32-bit RTEMS object name; not used */ queue->max_depth, /* maximum number of messages in queue (queue depth) */ queue->max_size, /* maximum size in bytes of a message */ RTEMS_FIFO | RTEMS_LOCAL, /* attributes (default) */ &(impl->id) /* object ID returned for queue */ ); /* ** If the operation failed, report the error */ if (status != RTEMS_SUCCESSFUL) { OS_DEBUG("Unhandled queue_create error: %s\n", rtems_status_text(status)); return OS_ERROR; } return OS_SUCCESS; } /* end OS_QueueCreate_Impl */ /*---------------------------------------------------------------- * * Function: OS_QueueDelete_Impl * * Purpose: Implemented per internal OSAL API * See prototype for argument/return detail * *-----------------------------------------------------------------*/ int32 OS_QueueDelete_Impl(const OS_object_token_t *token) { rtems_status_code status; OS_impl_queue_internal_record_t *impl; impl = OS_OBJECT_TABLE_GET(OS_impl_queue_table, *token); /* Try to delete the queue */ status = rtems_message_queue_delete(impl->id); if (status != RTEMS_SUCCESSFUL) { OS_DEBUG("Unhandled queue_delete error: %s\n", rtems_status_text(status)); return OS_ERROR; } return OS_SUCCESS; } /* end OS_QueueDelete_Impl */ /*---------------------------------------------------------------- * * Function: OS_QueueGet_Impl * * Purpose: Implemented per internal OSAL API * See prototype for argument/return detail * *-----------------------------------------------------------------*/ int32 OS_QueueGet_Impl(const OS_object_token_t *token, void *data, size_t size, size_t *size_copied, int32 timeout) { int32 return_code; rtems_status_code status; rtems_interval ticks; int tick_count; rtems_option option_set; size_t rtems_size; rtems_id rtems_queue_id; OS_impl_queue_internal_record_t *impl; impl = OS_OBJECT_TABLE_GET(OS_impl_queue_table, *token); rtems_queue_id = impl->id; /* Get Message From Message Queue */ if (timeout == OS_PEND) { option_set = RTEMS_WAIT; ticks = RTEMS_NO_TIMEOUT; } else if (timeout == OS_CHECK) { option_set = RTEMS_NO_WAIT; ticks = RTEMS_NO_TIMEOUT; } else { option_set = RTEMS_WAIT; /* msecs rounded to the closest system tick count */ if (OS_Milli2Ticks(timeout, &tick_count) != OS_SUCCESS) { return OS_ERROR; } ticks = (rtems_interval)tick_count; } /* ** Pend until a message arrives. */ status = rtems_message_queue_receive(rtems_queue_id, /* message queue descriptor */ data, /* pointer to message buffer */ &rtems_size, /* returned size of message */ option_set, /* wait option */ ticks /* timeout */ ); if (status == RTEMS_SUCCESSFUL) { return_code = OS_SUCCESS; } else if (status == RTEMS_TIMEOUT) { return_code = OS_QUEUE_TIMEOUT; } else if (status == RTEMS_UNSATISFIED) { return_code = OS_QUEUE_EMPTY; } else { /* Something else went wrong */ return_code = OS_ERROR; OS_DEBUG("Unhandled queue_receive error: %s\n", rtems_status_text(status)); } /* ** Check the size of the message. If a valid message was ** obtained, indicate success. */ if (status == RTEMS_SUCCESSFUL) { *size_copied = rtems_size; if (rtems_size != size) { /* Success, but the size was wrong */ return_code = OS_QUEUE_INVALID_SIZE; } } else { *size_copied = 0; } return return_code; } /* end OS_QueueGet_Impl */ /*---------------------------------------------------------------- * * Function: OS_QueuePut_Impl * * Purpose: Implemented per internal OSAL API * See prototype for argument/return detail * *-----------------------------------------------------------------*/ int32 OS_QueuePut_Impl(const OS_object_token_t *token, const void *data, size_t size, uint32 flags) { rtems_status_code status; rtems_id rtems_queue_id; OS_impl_queue_internal_record_t *impl; impl = OS_OBJECT_TABLE_GET(OS_impl_queue_table, *token); rtems_queue_id = impl->id; /* Write the buffer pointer to the queue. If an error occurred, report it ** with the corresponding SB status code. */ status = rtems_message_queue_send(rtems_queue_id, /* message queue descriptor */ data, /* pointer to message */ size /* length of message */ ); if (status == RTEMS_TOO_MANY) { /* ** Queue is full. */ return OS_QUEUE_FULL; } if (status != RTEMS_SUCCESSFUL) { /* ** Unexpected error while writing to queue. */ OS_DEBUG("Unhandled queue_send error: %s\n", rtems_status_text(status)); return OS_ERROR; } return OS_SUCCESS; } /* end OS_QueuePut_Impl */ /*---------------------------------------------------------------- * * Function: OS_QueueGetInfo_Impl * * Purpose: Implemented per internal OSAL API * See prototype for argument/return detail * *-----------------------------------------------------------------*/ int32 OS_QueueGetInfo_Impl(const OS_object_token_t *token, OS_queue_prop_t *queue_prop) { /* No extra info for queues in the OS implementation */ return OS_SUCCESS; } /* end OS_QueueGetInfo_Impl */
4,066
6,700
# TODO Test browse() from unittest import mock import pytest from mopidy.file import backend from mopidy.internal import path from tests import path_to_data_dir @pytest.fixture def config(): return { "proxy": {}, "file": { "show_dotfiles": False, "media_dirs": [str(path_to_data_dir(""))], "excluded_file_extensions": [], "follow_symlinks": False, "metadata_timeout": 1000, }, } @pytest.fixture def audio(): return mock.Mock() @pytest.fixture def track_uri(): return path.path_to_uri(path_to_data_dir("song1.wav")) def test_file_browse(config, audio, track_uri, caplog): provider = backend.FileBackend(audio=audio, config=config).library result = provider.browse(track_uri) assert len(result) == 0 assert any(map(lambda record: record.levelname == "ERROR", caplog.records)) assert any( map(lambda record: "Rejected attempt" in record.message, caplog.records) )
420
3,586
package com.linkedin.metadata.models; import com.linkedin.data.schema.RecordDataSchema; import com.linkedin.data.schema.TyperefDataSchema; import com.linkedin.metadata.models.annotation.EntityAnnotation; import java.util.List; import java.util.Map; public interface EntitySpec { String getName(); EntityAnnotation getEntityAnnotation(); String getKeyAspectName(); AspectSpec getKeyAspectSpec(); List<AspectSpec> getAspectSpecs(); Map<String, AspectSpec> getAspectSpecMap(); Boolean hasAspect(String name); AspectSpec getAspectSpec(String name); RecordDataSchema getSnapshotSchema(); TyperefDataSchema getAspectTyperefSchema(); List<SearchableFieldSpec> getSearchableFieldSpecs(); }
245
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.SubResource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.network.models.IpsecPolicy; import com.azure.resourcemanager.network.models.ProvisioningState; import com.azure.resourcemanager.network.models.VirtualNetworkGatewayConnectionProtocol; import com.azure.resourcemanager.network.models.VpnConnectionStatus; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** VpnConnection Resource. */ @Fluent public final class VpnConnectionInner extends SubResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(VpnConnectionInner.class); /* * Parameters for VpnConnection */ @JsonProperty(value = "properties") private VpnConnectionProperties innerProperties; /* * The name of the resource that is unique within a resource group. This * name can be used to access the resource. */ @JsonProperty(value = "name") private String name; /* * Gets a unique read-only string that changes whenever the resource is * updated. */ @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY) private String etag; /** * Get the innerProperties property: Parameters for VpnConnection. * * @return the innerProperties value. */ private VpnConnectionProperties innerProperties() { return this.innerProperties; } /** * Get the name property: The name of the resource that is unique within a resource group. This name can be used to * access the resource. * * @return the name value. */ public String name() { return this.name; } /** * Set the name property: The name of the resource that is unique within a resource group. This name can be used to * access the resource. * * @param name the name value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withName(String name) { this.name = name; return this; } /** * Get the etag property: Gets a unique read-only string that changes whenever the resource is updated. * * @return the etag value. */ public String etag() { return this.etag; } /** {@inheritDoc} */ @Override public VpnConnectionInner withId(String id) { super.withId(id); return this; } /** * Get the remoteVpnSite property: Id of the connected vpn site. * * @return the remoteVpnSite value. */ public SubResource remoteVpnSite() { return this.innerProperties() == null ? null : this.innerProperties().remoteVpnSite(); } /** * Set the remoteVpnSite property: Id of the connected vpn site. * * @param remoteVpnSite the remoteVpnSite value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withRemoteVpnSite(SubResource remoteVpnSite) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withRemoteVpnSite(remoteVpnSite); return this; } /** * Get the routingWeight property: routing weight for vpn connection. * * @return the routingWeight value. */ public Integer routingWeight() { return this.innerProperties() == null ? null : this.innerProperties().routingWeight(); } /** * Set the routingWeight property: routing weight for vpn connection. * * @param routingWeight the routingWeight value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withRoutingWeight(Integer routingWeight) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withRoutingWeight(routingWeight); return this; } /** * Get the connectionStatus property: The connection status. * * @return the connectionStatus value. */ public VpnConnectionStatus connectionStatus() { return this.innerProperties() == null ? null : this.innerProperties().connectionStatus(); } /** * Get the vpnConnectionProtocolType property: Connection protocol used for this connection. * * @return the vpnConnectionProtocolType value. */ public VirtualNetworkGatewayConnectionProtocol vpnConnectionProtocolType() { return this.innerProperties() == null ? null : this.innerProperties().vpnConnectionProtocolType(); } /** * Set the vpnConnectionProtocolType property: Connection protocol used for this connection. * * @param vpnConnectionProtocolType the vpnConnectionProtocolType value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withVpnConnectionProtocolType( VirtualNetworkGatewayConnectionProtocol vpnConnectionProtocolType) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withVpnConnectionProtocolType(vpnConnectionProtocolType); return this; } /** * Get the ingressBytesTransferred property: Ingress bytes transferred. * * @return the ingressBytesTransferred value. */ public Long ingressBytesTransferred() { return this.innerProperties() == null ? null : this.innerProperties().ingressBytesTransferred(); } /** * Get the egressBytesTransferred property: Egress bytes transferred. * * @return the egressBytesTransferred value. */ public Long egressBytesTransferred() { return this.innerProperties() == null ? null : this.innerProperties().egressBytesTransferred(); } /** * Get the connectionBandwidth property: Expected bandwidth in MBPS. * * @return the connectionBandwidth value. */ public Integer connectionBandwidth() { return this.innerProperties() == null ? null : this.innerProperties().connectionBandwidth(); } /** * Set the connectionBandwidth property: Expected bandwidth in MBPS. * * @param connectionBandwidth the connectionBandwidth value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withConnectionBandwidth(Integer connectionBandwidth) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withConnectionBandwidth(connectionBandwidth); return this; } /** * Get the sharedKey property: SharedKey for the vpn connection. * * @return the sharedKey value. */ public String sharedKey() { return this.innerProperties() == null ? null : this.innerProperties().sharedKey(); } /** * Set the sharedKey property: SharedKey for the vpn connection. * * @param sharedKey the sharedKey value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withSharedKey(String sharedKey) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withSharedKey(sharedKey); return this; } /** * Get the enableBgp property: EnableBgp flag. * * @return the enableBgp value. */ public Boolean enableBgp() { return this.innerProperties() == null ? null : this.innerProperties().enableBgp(); } /** * Set the enableBgp property: EnableBgp flag. * * @param enableBgp the enableBgp value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withEnableBgp(Boolean enableBgp) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withEnableBgp(enableBgp); return this; } /** * Get the ipsecPolicies property: The IPSec Policies to be considered by this connection. * * @return the ipsecPolicies value. */ public List<IpsecPolicy> ipsecPolicies() { return this.innerProperties() == null ? null : this.innerProperties().ipsecPolicies(); } /** * Set the ipsecPolicies property: The IPSec Policies to be considered by this connection. * * @param ipsecPolicies the ipsecPolicies value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withIpsecPolicies(List<IpsecPolicy> ipsecPolicies) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withIpsecPolicies(ipsecPolicies); return this; } /** * Get the enableRateLimiting property: EnableBgp flag. * * @return the enableRateLimiting value. */ public Boolean enableRateLimiting() { return this.innerProperties() == null ? null : this.innerProperties().enableRateLimiting(); } /** * Set the enableRateLimiting property: EnableBgp flag. * * @param enableRateLimiting the enableRateLimiting value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withEnableRateLimiting(Boolean enableRateLimiting) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withEnableRateLimiting(enableRateLimiting); return this; } /** * Get the enableInternetSecurity property: Enable internet security. * * @return the enableInternetSecurity value. */ public Boolean enableInternetSecurity() { return this.innerProperties() == null ? null : this.innerProperties().enableInternetSecurity(); } /** * Set the enableInternetSecurity property: Enable internet security. * * @param enableInternetSecurity the enableInternetSecurity value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withEnableInternetSecurity(Boolean enableInternetSecurity) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withEnableInternetSecurity(enableInternetSecurity); return this; } /** * Get the provisioningState property: The provisioning state of the resource. * * @return the provisioningState value. */ public ProvisioningState provisioningState() { return this.innerProperties() == null ? null : this.innerProperties().provisioningState(); } /** * Set the provisioningState property: The provisioning state of the resource. * * @param provisioningState the provisioningState value to set. * @return the VpnConnectionInner object itself. */ public VpnConnectionInner withProvisioningState(ProvisioningState provisioningState) { if (this.innerProperties() == null) { this.innerProperties = new VpnConnectionProperties(); } this.innerProperties().withProvisioningState(provisioningState); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (innerProperties() != null) { innerProperties().validate(); } } }
4,303
28,056
<filename>src/test/java/com/alibaba/fastjson/deserializer/issue3804/TestIssue3804.java package com.alibaba.fastjson.deserializer.issue3804; import com.alibaba.fastjson.JSONValidator; import org.junit.Test; public class TestIssue3804 { @Test public void testIssue3804() { //String textResponse="{\"error\":false,\"code\":0}"; String textResponse="{\"error\":false,\"code"; JSONValidator validator = JSONValidator.from(textResponse); if (validator.validate() && validator.getType() == JSONValidator.Type.Object) { System.out.println("Yes, it is Object"); } else { System.out.println("No, it is not Object"); } } }
278
558
package io.github.microcks.security; import org.keycloak.KeycloakSecurityContext; import org.keycloak.representations.AccessToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; /** * Simpler mappe for transforming KeyclaokSecurityContext token into UserInfo bean. * @author laurent */ public class KeycloakTokenToUserInfoMapper { /** A simple logger for diagnostic messages. */ private static Logger log = LoggerFactory.getLogger(KeycloakTokenToUserInfoMapper.class); /** The name of token claim that contains the groups information. */ public static final String MICROCKS_GROUPS_TOKEN_CLAIM = "microcks-groups"; /** The name of the token resource that holds roles information. */ public static final String MICROCKS_APP_RESOURCE = "microcks-app"; /** * Maps the information from KeycloakSecurityContext tokens into a UserInfo instance. * @param context The current security context provided by Keycloak server adapter. * @return A new UserInfo with info coming from Keycloak tokens. */ public static UserInfo map(KeycloakSecurityContext context) { AccessToken token = context.getToken(); // Build groups string array if any. String[] microcksGroups = null; Object groups = context.getToken().getOtherClaims().get(MICROCKS_GROUPS_TOKEN_CLAIM); if (groups instanceof List) { Object[] objGroups = ((List) groups).toArray(); microcksGroups = Arrays.copyOf(objGroups, objGroups.length, String[].class); } // Create and return UserInfo. UserInfo userInfo = new UserInfo(token.getName(), token.getPreferredUsername(), token.getGivenName(), token.getFamilyName(), token.getEmail(), token.getResourceAccess(MICROCKS_APP_RESOURCE).getRoles().stream().toArray(String[] ::new), microcksGroups); log.debug("Current user is: " + userInfo); return userInfo; } }
636
12,252
<filename>testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractRoleMapperTest.java package org.keycloak.testsuite.broker; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot; import static org.keycloak.testsuite.util.WaitUtils.pause; import java.util.Collections; import java.util.List; import java.util.Map; import org.keycloak.admin.client.resource.UserResource; import org.keycloak.models.IdentityProviderMapperSyncMode; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.openqa.selenium.firefox.FirefoxDriver; /** * @author hmlnarik, * <a href="mailto:<EMAIL>"><NAME></a>, * <a href="mailto:<EMAIL>"><NAME></a>, */ public abstract class AbstractRoleMapperTest extends AbstractIdentityProviderMapperTest { private static final String CLIENT = "realm-management"; private static final String CLIENT_ROLE = "view-realm"; public static final String ROLE_USER = "user"; public static final String CLIENT_ROLE_MAPPER_REPRESENTATION = CLIENT + "." + CLIENT_ROLE; protected abstract void createMapperInIdp(IdentityProviderRepresentation idp, IdentityProviderMapperSyncMode syncMode); protected void updateUser() { } protected UserRepresentation loginAsUserTwiceWithMapper( IdentityProviderMapperSyncMode syncMode, boolean createAfterFirstLogin, Map<String, List<String>> userConfig) { final IdentityProviderRepresentation idp = setupIdentityProvider(); if (!createAfterFirstLogin) { createMapperInIdp(idp, syncMode); } createUserInProviderRealm(userConfig); createUserRoleAndGrantToUserInProviderRealm(); logInAsUserInIDPForFirstTime(); UserRepresentation user = findUser(bc.consumerRealmName(), bc.getUserLogin(), bc.getUserEmail()); if (!createAfterFirstLogin) { assertThatRoleHasBeenAssignedInConsumerRealmTo(user); } else { assertThatRoleHasNotBeenAssignedInConsumerRealmTo(user); } if (createAfterFirstLogin) { createMapperInIdp(idp, syncMode); } logoutFromRealm(getConsumerRoot(), bc.consumerRealmName()); updateUser(); logInAsUserInIDP(); user = findUser(bc.consumerRealmName(), bc.getUserLogin(), bc.getUserEmail()); return user; } protected void createUserRoleAndGrantToUserInProviderRealm() { RoleRepresentation userRole = new RoleRepresentation(ROLE_USER,null, false); adminClient.realm(bc.providerRealmName()).roles().create(userRole); RoleRepresentation role = adminClient.realm(bc.providerRealmName()).roles().get(ROLE_USER).toRepresentation(); UserResource userResource = adminClient.realm(bc.providerRealmName()).users().get(userId); userResource.roles().realmLevel().add(Collections.singletonList(role)); } protected void assertThatRoleHasBeenAssignedInConsumerRealmTo(UserRepresentation user) { assertThat(user.getClientRoles().get(CLIENT), contains(CLIENT_ROLE)); } protected void assertThatRoleHasNotBeenAssignedInConsumerRealmTo(UserRepresentation user) { assertThat(user.getClientRoles().get(CLIENT), not(contains(CLIENT_ROLE))); } }
1,259
351
<gh_stars>100-1000 package org.springframework.boot.loader.thin; import java.io.File; import java.util.List; import java.util.Properties; import org.assertj.core.api.Condition; import org.eclipse.aether.graph.Dependency; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.util.FileSystemUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class DependencyResolverTests { private DependencyResolver resolver = DependencyResolver.instance(); @AfterEach public void clear() { System.clearProperty("maven.home"); } @Test @Disabled("Some issues with reactor build here when top level version changes") public void localPom() throws Exception { Resource resource = new FileSystemResource(new File("pom.xml")); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies).filteredOn("artifact.artifactId", "maven-settings") .hasSize(1); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-test") .isEmpty(); } @Test public void emptyPom() throws Exception { Resource resource = new ClassPathResource("META-INF/thin/empty-pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isEqualTo(0); } @Test public void petclinic() throws Exception { Resource resource = new ClassPathResource("apps/petclinic/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); // System.err.println(dependencies); assertThat(dependencies.size()).isGreaterThan(20); // Resolved from a placeholder version assertThat(dependencies).filteredOn("artifact.artifactId", "bootstrap").first() .is(version("3.3.6")); // Transitive from a starter assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot-starter") .first().is(version("1.4.2.RELEASE")); // Test scope assertThat(dependencies) .filteredOn("artifact.artifactId", "spring-boot-starter-test").isEmpty(); } @Test public void launcher() throws Exception { Resource resource = new ClassPathResource("apps/launcher/pom.xml"); // Resource resource = new // UrlResource("jar:file:/home/dsyer/.m2/repository/org/springframework/cloud/launcher/spring-cloud-launcher-deployer/2.2.1.RELEASE/spring-cloud-launcher-deployer-2.2.1.RELEASE.jar!/META-INF/maven/org.springframework.cloud.launcher/spring-cloud-launcher-deployer/pom.xml"); Properties properties = new Properties(); properties.setProperty(ThinJarLauncher.THIN_PROFILE, "thin"); List<Dependency> dependencies = resolver.dependencies(resource, properties); // System.err.println(dependencies); assertThat(dependencies.size()).isGreaterThan(1); } @Test public void mavenProfiles() throws Exception { Resource resource = new ClassPathResource("apps/profiles/pom.xml"); Properties props = new Properties(); props.setProperty("thin.profile", "secure"); List<Dependency> dependencies = resolver.dependencies(resource, props); assertThat(dependencies.size()).isGreaterThan(4); // Transitive from a starter assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot-starter") .first().is(version("2.1.0.RELEASE")); assertThat(dependencies) .filteredOn("artifact.artifactId", "spring-boot-starter-security") .isNotEmpty(); // Test scope assertThat(dependencies) .filteredOn("artifact.artifactId", "spring-boot-starter-test").isEmpty(); } @Test public void preresolved() throws Exception { Resource resource = new ClassPathResource("apps/petclinic-preresolved/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties(new ClassPathResource( "apps/petclinic-preresolved/META-INF/thin.properties"))); // System.err.println(dependencies); assertThat(dependencies.size()).isGreaterThan(20); // Resolved from a placeholder version assertThat(dependencies).filteredOn("artifact.artifactId", "bootstrap").first() .is(version("3.3.6")); // Transitive from a starter assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot-starter") .first().is(version("1.4.2.RELEASE")); assertThat(dependencies).filteredOn("artifact.artifactId", "bootstrap").first() .is(resolved()); } @Test public void preresolvedClassifier() throws Exception { Resource resource = new ClassPathResource("apps/preresolved-classifier/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties(new ClassPathResource( "apps/preresolved-classifier/META-INF/thin.properties"))); // System.err.println(dependencies); assertThat(dependencies.size()).isEqualTo(2); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot-test") .first().is(version("2.1.0.RELEASE")); assertThat(dependencies).filteredOn("artifact.classifier", "tests").first() .is(resolved()); } @Test public void pomWithBom() throws Exception { Resource resource = new ClassPathResource("apps/cloud/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(20); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-cloud-context") .first().is(version("1.1.7.RELEASE")); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-test") .isEmpty(); } @Test public void exclusions() throws Exception { Resource resource = new ClassPathResource("apps/exclusions/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties(new ClassPathResource( "apps/exclusions/META-INF/thin.properties"))); assertThat(dependencies.size()).isGreaterThan(20); assertThat(dependencies).filteredOn("artifact.artifactId", "jetty-server").first() .is(version("9.3.11.v20160721")); assertThat(dependencies).filteredOn("artifact.artifactId", "tomcat-embed-core") .isEmpty(); } @Test public void inclusions() throws Exception { Resource resource = new ClassPathResource("apps/inclusions/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties(new ClassPathResource( "apps/inclusions/META-INF/thin.properties"))); assertThat(dependencies.size()).isGreaterThan(20); assertThat(dependencies).filteredOn("artifact.artifactId", "jackson-core") .isNotEmpty(); } @Test public void classifier() throws Exception { Resource resource = new ClassPathResource("apps/classifier/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(2); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot-test") .hasSize(2); } @Test public void excludeLast() throws Exception { Resource resource = new ClassPathResource("apps/excludelast/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties(new ClassPathResource( "apps/excludelast/META-INF/thin.properties"))); assertThat(dependencies.size()).isGreaterThan(20); assertThat(dependencies).filteredOn("artifact.artifactId", "amqp-client").first() .is(version("3.6.3")); assertThat(dependencies).filteredOn("artifact.artifactId", "http-client") .isEmpty(); } @Test public void provided() throws Exception { Resource resource = new ClassPathResource("apps/provided/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties( new ClassPathResource("apps/provided/META-INF/thin.properties"))); assertThat(dependencies.size()).isGreaterThan(15); assertThat(dependencies).filteredOn("artifact.artifactId", "tomcat-embed-core") .first().is(version("8.5.5")); } @Test public void testOverride() throws Exception { Resource resource = new ClassPathResource("apps/test/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties( new ClassPathResource("apps/test/META-INF/thin.properties"))); assertThat(dependencies.size()).isGreaterThan(15); assertThat(dependencies) .filteredOn("artifact.artifactId", "spring-boot-starter-web").first() .is(version("1.5.3.RELEASE")); } @Test public void excluded() throws Exception { Resource resource = new ClassPathResource("apps/excluded/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties( new ClassPathResource("apps/excluded/META-INF/thin.properties"))); assertThat(dependencies).filteredOn("artifact.artifactId", "tomcat-embed-core") .isEmpty(); } @Test public void pomInJar() throws Exception { Resource resource = new UrlResource( "jar:file:src/test/resources/app-with-web-in-lib-properties.jar!/META-INF/maven/com.example/app/pom.xml"); assertThat(resource.exists()).isTrue(); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(10); } @Test public void propertiesWithDatabase() throws Exception { Resource resource = new UrlResource(ArchiveUtils .getArchive("src/test/resources/app-with-web-and-cloud-config.jar") .getUrl()).createRelative("META-INF/maven/com.example/app/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties( new ClassPathResource("apps/db/META-INF/thin.properties"))); assertThat(dependencies).size().isGreaterThan(3); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-jdbc").first() .is(version("4.2.8.RELEASE")); // thin.properties changes bom version assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot").first() .is(version("1.3.8.RELEASE")); ; } @Test public void propertiesInline() throws Exception { Resource resource = new ClassPathResource("apps/inline/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource, PropertiesLoaderUtils.loadProperties( new ClassPathResource("apps/inline/META-INF/thin.properties"))); assertThat(dependencies).size().isGreaterThan(3); // thin.properties has placeholder for bom version assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot").first() .is(version("1.3.8.RELEASE")); } @Test public void libsWithProfile() throws Exception { Resource resource = new UrlResource(ArchiveUtils .getArchive("src/test/resources/app-with-web-and-cloud-config.jar") .getUrl()).createRelative("META-INF/maven/com.example/app/pom.xml"); Properties properties = PropertiesLoaderUtils.loadProperties( new ClassPathResource("apps/eureka/META-INF/thin.properties")); PropertiesLoaderUtils.fillProperties(properties, new ClassPathResource("apps/eureka/META-INF/thin-extra.properties")); List<Dependency> dependencies = resolver.dependencies(resource, properties); assertThat(dependencies).size().isGreaterThan(3); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot").first() .is(version("1.4.1.RELEASE")); } @Test public void dependenciesWithPlaceholders() throws Exception { Resource resource = new ClassPathResource("apps/placeholders/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(10); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot").first() .is(version("1.3.8.RELEASE")); } @Test public void dependenciesWithParent() throws Exception { Resource resource = new ClassPathResource("apps/parent-properties/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(10); // Weird combo of spring version picked from the wrong property (but it resolves, // which is the test) assertThat(dependencies).filteredOn("artifact.artifactId", "spring-core").first() .is(version("4.1.3.RELEASE")); } @Test public void dependenciesWithProjectVariables() throws Exception { Resource resource = new ClassPathResource("apps/projectvariables/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(10); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-boot").first() .is(version("1.3.8.RELEASE")); } @Test public void dependenciesWithParentOverride() throws Exception { Resource resource = new ClassPathResource( "apps/parent-properties-override/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(10); assertThat(dependencies).filteredOn("artifact.artifactId", "spring-core").first() .is(version("4.3.5.RELEASE")); } @Test public void dependencyManagementPom() throws Exception { Resource resource = new ClassPathResource("apps/dep-man/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(3); // pom changes spring-context assertThat(dependencies).filteredOn("artifact.artifactId", "spring-context") .first().is(version("4.3.5.RELEASE")); } @Test public void missing() throws Exception { // LogUtils.setLogLevel(Level.DEBUG); Resource resource = new ClassPathResource("apps/missing/pom.xml"); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> { List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(0); }); } @Test @Disabled("Set up a secure server and declare it in your settings.xml to run this test. Point it at your .m2/repository so it can resolve the app sample from this project.") public void authentication() throws Exception { FileSystemUtils.deleteRecursively(new File("target/root")); System.setProperty("maven.home", "target/root"); Resource resource = new ClassPathResource("apps/authentication/pom.xml"); List<Dependency> dependencies = resolver.dependencies(resource); assertThat(dependencies.size()).isGreaterThan(16); } static Condition<Dependency> version(final String version) { return new Condition<Dependency>("artifact matches " + version) { @Override public boolean matches(Dependency value) { return value.getArtifact().getVersion().equals(version); } }; } static Condition<Dependency> resolved() { return new Condition<Dependency>("artifact is resolved") { @Override public boolean matches(Dependency value) { return value.getArtifact().getFile() != null; } }; } }
5,129
2,056
from qira_log import * import json from qira_memory import * regs = Memory() mem = Memory() def init(): dat = read_log("/tmp/qira_log") for (address, data, clnum, flags) in dat: if flags & IS_WRITE and flags & IS_MEM: size = flags & SIZE_MASK # support big endian for i in range(0, size/8): mem.commit(clnum, address+i, data & 0xFF) data >>= 8 elif flags & IS_WRITE: size = flags & SIZE_MASK # support big endian regs.commit(clnum, address, data) if __name__ == '__main__': init() print "init done" dat = {"regs": regs.dump(), "mem": mem.dump()} open("/tmp/qira_memdb", "wb").write(json.dumps(dat)) print "json extracted"
300
1,139
<filename>Android/ProgressDialog/app/src/main/java/com/journaldev/progressdialog/MainActivity.java package com.journaldev.progressdialog; import android.app.ProgressDialog; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button button; ProgressDialog progressDoalog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressDoalog = new ProgressDialog(MainActivity.this); progressDoalog.setMax(100); progressDoalog.setMessage("Its loading...."); progressDoalog.setTitle("ProgressDialog bar example"); progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDoalog.show(); new Thread(new Runnable() { @Override public void run() { try { while (progressDoalog.getProgress() <= progressDoalog .getMax()) { Thread.sleep(200); handle.sendMessage(handle.obtainMessage()); if (progressDoalog.getProgress() == progressDoalog .getMax()) { progressDoalog.dismiss(); } } } catch (Exception e) { e.printStackTrace(); } } }).start(); } Handler handle = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); progressDoalog.incrementProgressBy(1); } }; }); } }
1,233
3,282
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.tabmodel.document; import android.app.Activity; import android.content.Context; import android.util.SparseArray; import org.chromium.base.ApplicationStatus; import org.chromium.base.ThreadUtils; import org.chromium.chrome.browser.document.DocumentActivity; import org.chromium.chrome.browser.document.DocumentUtils; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabCreatorManager; import org.chromium.chrome.browser.tabmodel.TabList; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelJniBridge; import org.chromium.chrome.browser.tabmodel.TabModelObserver; import org.chromium.content_public.browser.WebContents; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; /** * Maintains a list of Tabs displayed when Chrome is running in document-mode. */ public class DocumentTabModelImpl extends TabModelJniBridge implements DocumentTabModel { private static final String TAG = "DocumentTabModel"; public static final String PREF_PACKAGE = "com.google.android.apps.chrome.document"; public static final String PREF_LAST_SHOWN_TAB_ID_REGULAR = "last_shown_tab_id.regular"; public static final String PREF_LAST_SHOWN_TAB_ID_INCOGNITO = "last_shown_tab_id.incognito"; /** TabModel is uninitialized. */ public static final int STATE_UNINITIALIZED = 0; /** Begin parsing the tasks from Recents and loading persisted state. */ public static final int STATE_READ_RECENT_TASKS_START = 1; /** Done parsing the tasks from Recents and loading persisted state. */ public static final int STATE_READ_RECENT_TASKS_END = 2; /** Begin loading the current/prioritized tab state synchronously. */ public static final int STATE_LOAD_CURRENT_TAB_STATE_START = 3; /** Finish loading the current/prioritized tab state synchronously. */ public static final int STATE_LOAD_CURRENT_TAB_STATE_END = 4; /** Begin reading TabStates from storage for background tabs. */ public static final int STATE_LOAD_TAB_STATE_BG_START = 5; /** Done reading TabStates from storage for background tabs. */ public static final int STATE_LOAD_TAB_STATE_BG_END = 6; /** Begin deserializing the TabState. Requires the native library. */ public static final int STATE_DESERIALIZE_START = 7; /** Done deserializing the TabState. */ public static final int STATE_DESERIALIZE_END = 8; /** Begin parsing the historical tabs. */ public static final int STATE_DETERMINE_HISTORICAL_TABS_START = 9; /** Done parsing the historical tabs. */ public static final int STATE_DETERMINE_HISTORICAL_TABS_END = 10; /** Clean out old TabState files. */ public static final int STATE_CLEAN_UP_OBSOLETE_TABS = 11; /** TabModel is fully ready to use. */ public static final int STATE_FULLY_LOADED = 12; /** List of known tabs. */ private final ArrayList<Integer> mTabIdList; /** Stores an entry for each DocumentActivity that is alive. Keys are document IDs. */ private final SparseArray<Entry> mEntryMap; /** * Stores tabIds which have been removed from the ActivityManager while Chrome was not alive. * It is cleared after restoration has been finished. */ private final List<Integer> mHistoricalTabs; /** Delegate for working with the ActivityManager. */ private final ActivityDelegate mActivityDelegate; /** Delegate for working with the filesystem. */ private final StorageDelegate mStorageDelegate; /** Context to use. */ private final Context mContext; /** Current loading status. */ private int mCurrentState; /** ID of the last tab that was shown to the user. */ private int mLastShownTabId = Tab.INVALID_TAB_ID; /** * Pre-load shared prefs to avoid being blocked on the * disk access async task in the future. */ public static void warmUpSharedPrefs(Context context) { context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE); } /** * Construct a DocumentTabModel. * @param activityDelegate Delegate to use for accessing the ActivityManager. * @param storageDelegate Delegate to use for accessing persistent storage. * @param tabCreatorManager Used to create Tabs. * @param isIncognito Whether or not the TabList is managing incognito tabs. * @param prioritizedTabId ID of the tab to prioritize when loading. * @param context Context to use for accessing SharedPreferences. */ public DocumentTabModelImpl(ActivityDelegate activityDelegate, StorageDelegate storageDelegate, TabCreatorManager tabCreatorManager, boolean isIncognito, int prioritizedTabId, Context context) { super(isIncognito, false); mActivityDelegate = activityDelegate; mStorageDelegate = storageDelegate; mContext = context; mCurrentState = STATE_UNINITIALIZED; mTabIdList = new ArrayList<Integer>(); mEntryMap = new SparseArray<Entry>(); mHistoricalTabs = new ArrayList<Integer>(); mLastShownTabId = DocumentUtils.getLastShownTabIdFromPrefs(mContext, isIncognito()); // Restore the tab list. setCurrentState(STATE_READ_RECENT_TASKS_START); mStorageDelegate.restoreTabEntries( isIncognito, activityDelegate, mEntryMap, mTabIdList, mHistoricalTabs); setCurrentState(STATE_READ_RECENT_TASKS_END); } public StorageDelegate getStorageDelegate() { return mStorageDelegate; } /** * Finds the index of the given Tab ID. * @param tabId ID of the Tab to find. * @return Index of the tab, or -1 if it couldn't be found. */ private int indexOf(int tabId) { return mTabIdList.indexOf(tabId); } @Override public int index() { if (getCount() == 0) return TabList.INVALID_TAB_INDEX; int indexOfLastId = indexOf(mLastShownTabId); if (indexOfLastId != -1) return indexOfLastId; // The previous Tab is gone; select a Tab based on MRU ordering. List<Entry> tasks = mActivityDelegate.getTasksFromRecents(isIncognito()); if (tasks.size() == 0) return TabList.INVALID_TAB_INDEX; for (int i = 0; i < tasks.size(); i++) { int lastKnownId = tasks.get(i).tabId; int indexOfMostRecentlyUsedId = indexOf(lastKnownId); if (indexOfMostRecentlyUsedId != -1) return indexOfMostRecentlyUsedId; } return TabList.INVALID_TAB_INDEX; } @Override public int indexOf(Tab tab) { if (tab == null) return Tab.INVALID_TAB_ID; return indexOf(tab.getId()); } @Override public int getCount() { return mTabIdList.size(); } @Override public boolean isClosurePending(int tabId) { return false; } @Override public Tab getTabAt(int index) { if (index < 0 || index >= getCount()) return null; // Return a live tab if the corresponding DocumentActivity is currently alive. int tabId = mTabIdList.get(index); List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities(); for (WeakReference<Activity> activityRef : activities) { Activity activity = activityRef.get(); if (!(activity instanceof DocumentActivity) || !mActivityDelegate.isValidActivity(isIncognito(), activity.getIntent())) { continue; } Tab tab = ((DocumentActivity) activity).getActivityTab(); int documentId = tab == null ? Tab.INVALID_TAB_ID : tab.getId(); if (documentId == tabId) return tab; } // Try to create a Tab that will hold the Tab's info. Entry entry = mEntryMap.get(tabId); assert entry != null; // If a tab has already been initialized, use that. if (entry.placeholderTab != null && entry.placeholderTab.isInitialized()) { return entry.placeholderTab; } // Create a frozen Tab if we are capable, or if the previous Tab is just a placeholder. if (entry.getTabState() != null && isNativeInitialized() && (entry.placeholderTab == null || !entry.placeholderTab.isInitialized())) { entry.placeholderTab = getTabCreator(isIncognito()).createFrozenTab( entry.getTabState(), entry.tabId, TabModel.INVALID_TAB_INDEX); entry.placeholderTab.initializeNative(); } // Create a placeholder Tab that just has the ID. if (entry.placeholderTab == null) { entry.placeholderTab = new Tab(tabId, isIncognito(), null); } return entry.placeholderTab; } @Override public void setIndex(int index, TabSelectionType type) { } @Override protected boolean closeTabAt(int index) { return false; } @Override public boolean closeTab(Tab tab) { return false; } @Override public boolean closeTab(Tab tabToClose, boolean animate, boolean uponExit, boolean canUndo) { return false; } @Override protected TabDelegate getTabCreator(boolean incognito) { return null; } @Override protected boolean createTabWithWebContents(Tab parent, boolean isIncognito, WebContents webContents, int parentTabId) { return false; } @Override protected boolean isSessionRestoreInProgress() { return mCurrentState < STATE_FULLY_LOADED; } @Override public String getInitialUrlForDocument(int tabId) { Entry entry = mEntryMap.get(tabId); return entry == null ? null : entry.initialUrl; } private void setCurrentState(int newState) { ThreadUtils.assertOnUiThread(); assert mCurrentState == newState - 1; mCurrentState = newState; } @Override public Tab getNextTabIfClosed(int id) { // Tab may not necessarily exist. return null; } @Override public void closeAllTabs() { closeAllTabs(true, false); } @Override public void closeAllTabs(boolean allowDelegation, boolean uponExit) { } @Override public void moveTab(int id, int newIndex) { assert false; } @Override public void addTab(Tab tab, int index, TabLaunchType type) { assert false; } @Override public void removeTab(Tab tab) { assert false; } @Override public boolean supportsPendingClosures() { return false; } @Override public void commitAllTabClosures() { } @Override public void commitTabClosure(int tabId) { } @Override public void cancelTabClosure(int tabId) { } @Override public TabList getComprehensiveModel() { return this; } @Override public void addObserver(TabModelObserver observer) { } @Override public void removeObserver(TabModelObserver observer) { } @Override public void openMostRecentlyClosedTab() { } }
4,155
417
<gh_stars>100-1000 #! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020-2021 Alibaba Group Holding Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import numpy as np import pandas as pd import pyarrow as pa import pytest import tensorflow as tf from vineyard.core.builder import builder_context from vineyard.core.resolver import resolver_context from vineyard.contrib.ml.tensorflow import register_tf_types @pytest.fixture(scope="module", autouse=True) def vineyard_for_tensorflow(): with builder_context() as builder: with resolver_context() as resolver: register_tf_types(builder, resolver) yield builder, resolver def test_tf_tensor(vineyard_client): data = [np.random.rand(2, 3) for i in range(10)] label = [np.random.rand(2, 3) for i in range(10)] dataset = tf.data.Dataset.from_tensor_slices((data, label)) object_id = vineyard_client.put(dataset) dtrain = vineyard_client.get(object_id) for x, y in dataset.take(1): xdata = x.shape ydata = y.shape for x, y in dtrain.take(1): xdtrain = x.shape ydtrain = y.shape assert xdata == xdtrain assert ydata == ydtrain assert len(dataset) == len(dtrain) def test_tf_dataframe(vineyard_client): df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], 'target': [1.0, 2.0, 3.0, 4.0]}) labels = df.pop('target') dataset = tf.data.Dataset.from_tensor_slices((dict(df), labels)) object_id = vineyard_client.put(dataset) dtrain = vineyard_client.get(object_id) for x, y in dataset.take(1): data_ncols = len(list(x.keys())) for x, y in dtrain.take(1): dtrain_ncols = len(list(x.keys())) assert len(dataset) == len(dtrain) assert data_ncols == dtrain_ncols def test_tf_record_batch(vineyard_client): arrays = [pa.array([1, 2, 3, 4]), pa.array([3.0, 4.0, 5.0, 6.0]), pa.array([0, 1, 0, 1])] batch = pa.RecordBatch.from_arrays(arrays, ['f0', 'f1', 'label']) object_id = vineyard_client.put(batch) dtrain = vineyard_client.get(object_id) for x, y in dtrain.take(1): ncols = len(list(x.keys())) assert ncols == 2 assert len(dtrain) == 4 def test_tf_table(vineyard_client): arrays = [pa.array([1, 2]), pa.array([0, 1]), pa.array([0.1, 0.2])] batch = pa.RecordBatch.from_arrays(arrays, ['f0', 'f1', 'label']) batches = [batch] * 4 table = pa.Table.from_batches(batches) object_id = vineyard_client.put(table) dtrain = vineyard_client.get(object_id) for x, y in dtrain.take(1): ncols = len(list(x.keys())) assert ncols == 2 assert len(dtrain) == 8
1,285
349
/* * initsync.h - Initial replica synchronization. */ #ifndef SIRIDB_INITSYNC_H_ #define SIRIDB_INITSYNC_H_ typedef struct siridb_initsync_s siridb_initsync_t; #include <stdio.h> #include <uv.h> #include <inttypes.h> #include <siri/db/db.h> #include <siri/db/series.h> #include <siri/net/pkg.h> siridb_initsync_t * siridb_initsync_open(siridb_t * siridb, int create_new); void siridb_initsync_free(siridb_initsync_t ** initsync); void siridb_initsync_run(uv_timer_t * timer); void siridb_initsync_fopen(siridb_initsync_t * initsync, const char * opentype); const char * siridb_initsync_sync_progress(siridb_t * siridb); struct siridb_initsync_s { FILE * fp; char * fn; int fd; long int size; uint32_t * next_series_id; sirinet_pkg_t * pkg_points; sirinet_pkg_t * pkg_tags; }; #endif /* SIRIDB_INITSYNC_H_ */
402
463
<reponame>pblew/jmockit1 package mockit; import org.junit.*; import static org.junit.Assert.*; public final class TestedAbstractClassTest { public abstract static class AbstractClass implements Runnable { private final int value; protected String name; protected AbstractClass(int value) { this.value = value; } public final boolean doSomeOperation() { run(); return doSomething() > 0; } protected abstract int doSomething(); public int getValue() { return value; } } // A subclass is generated with the *same* constructors as the tested class, and with *mocked* implementations // for all abstract methods in the tested base class, its super-classes and its implemented interfaces. @Tested AbstractClass tested; @Injectable("123") int value; @Test public void exerciseTestedObject(@Injectable("Test") String name) { assertThatGeneratedSubclassIsAlwaysTheSame(); assertEquals(123, tested.getValue()); assertEquals("Test", tested.name); new Expectations() {{ tested.doSomething(); result = 23; times = 1; }}; assertTrue(tested.doSomeOperation()); new Verifications() {{ tested.run(); }}; } @Test public void exerciseDynamicallyMockedTestedObject() { assertThatGeneratedSubclassIsAlwaysTheSame(); assertEquals(123, tested.getValue()); new Expectations(tested) {{ tested.getValue(); result = 45; tested.doSomething(); result = 7; }}; assertEquals(45, tested.getValue()); assertTrue(tested.doSomeOperation()); new Verifications() {{ tested.run(); times = 1; }}; } @Test public void exerciseTestedObjectAgain(@Injectable("Another test") String text) { assertThatGeneratedSubclassIsAlwaysTheSame(); assertEquals(123, tested.getValue()); assertEquals("Another test", tested.name); assertFalse(tested.doSomeOperation()); new VerificationsInOrder() {{ tested.run(); tested.doSomething(); }}; } Class<?> generatedSubclass; void assertThatGeneratedSubclassIsAlwaysTheSame() { Class<?> testedClass = tested.getClass(); if (generatedSubclass == null) { generatedSubclass = testedClass; } else { assertSame(generatedSubclass, testedClass); } } }
851
7,158
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Itseez Inc, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Itseez Inc 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. // //M*/ #include "opencv2/datasets/gr_chalearn.hpp" #include <opencv2/core.hpp> #include <cstdio> #include <string> #include <vector> using namespace std; using namespace cv; using namespace cv::datasets; int main(int argc, char *argv[]) { const char *keys = "{ help h usage ? | | show this message }" "{ path p |true| path to dataset folder }"; CommandLineParser parser(argc, argv, keys); string path(parser.get<string>("path")); if (parser.has("help") || path=="true") { parser.printMessage(); return -1; } Ptr<GR_chalearn> dataset = GR_chalearn::create(); dataset->load(path); // *************** // dataset contains information for each sample. // For example, let output dataset size and first element. printf("train size: %u\n", (unsigned int)dataset->getTrain().size()); printf("validation size: %u\n", (unsigned int)dataset->getValidation().size()); GR_chalearnObj *example = static_cast<GR_chalearnObj *>(dataset->getTrain()[0].get()); printf("first dataset sample:\n%s\n", example->name.c_str()); printf("color video:\n%s\n", example->nameColor.c_str()); printf("depth video:\n%s\n", example->nameDepth.c_str()); printf("user video:\n%s\n", example->nameUser.c_str()); printf("video:\nnumber of frames: %u\nfps: %u\nmaximum depth: %u\n", example->numFrames, example->fps, example->depth); for (vector<groundTruth>::iterator it=example->groundTruths.begin(); it!=example->groundTruths.end(); ++it) { printf("gestureID: %u, initial frame: %u, last frame: %u\n", (*it).gestureID, (*it).initialFrame, (*it).lastFrame); } printf("skeletons number: %u\n", (unsigned int)example->skeletons.size()); skeleton &last = example->skeletons.back(); printf("last skeleton:\n"); for (unsigned int i=0; i<20; ++i) { printf("Wx: %f, Wy: %f, Wz: %f, Rx: %f, Ry: %f, Rz: %f, Rw: %f, Px: %f, Py: %f\n", last.s[i].Wx, last.s[i].Wy, last.s[i].Wz, last.s[i].Rx, last.s[i].Ry, last.s[i].Rz, last.s[i].Rw, last.s[i].Px, last.s[i].Py); } return 0; }
1,421
14,668
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_SERVICES_DEVICE_SYNC_CRYPTAUTH_TASK_METRICS_LOGGER_H_ #define CHROMEOS_SERVICES_DEVICE_SYNC_CRYPTAUTH_TASK_METRICS_LOGGER_H_ #include <string> #include "chromeos/services/device_sync/network_request_error.h" namespace chromeos { namespace device_sync { // A group of functions and enums used to log success metrics for individual // tasks in the CryptAuth v2 Enrollment and v2 DeviceSync flows. // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. If entries are added, kMaxValue should // be updated. enum class CryptAuthAsyncTaskResult { kSuccess = 0, kTimeout = 1, kError = 2, kMaxValue = kError }; // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. If entries are added, kMaxValue should // be updated. enum class CryptAuthApiCallResult { kSuccess = 0, kTimeout = 1, kNetworkRequestErrorOffline = 2, kNetworkRequestErrorEndpointNotFound = 3, kNetworkRequestErrorAuthenticationError = 4, kNetworkRequestErrorBadRequest = 5, kNetworkRequestErrorResponseMalformed = 6, kNetworkRequestErrorInternalServerError = 7, kNetworkRequestErrorUnknown = 8, kMaxValue = kNetworkRequestErrorUnknown }; CryptAuthApiCallResult CryptAuthApiCallResultFromNetworkRequestError( NetworkRequestError network_request_error); void LogCryptAuthAsyncTaskSuccessMetric(const std::string& metric_name, CryptAuthAsyncTaskResult result); void LogCryptAuthApiCallSuccessMetric(const std::string& metric_name, CryptAuthApiCallResult result); } // namespace device_sync } // namespace chromeos #endif // CHROMEOS_SERVICES_DEVICE_SYNC_CRYPTAUTH_TASK_METRICS_LOGGER_H_
655
611
<filename>src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/doctrine/metadata/driver/DoctrinePhpAttributeMappingDriverTest.java package fr.adrienbrault.idea.symfony2plugin.tests.doctrine.metadata.driver; import com.jetbrains.php.lang.psi.PhpPsiElementFactory; import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.dict.DoctrineMetadataModel; import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.driver.DoctrineMappingDriverArguments; import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.driver.DoctrinePhpAttributeMappingDriver; import fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.driver.DoctrinePhpMappingDriver; import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase; /** * @author <NAME> <<EMAIL>> * * @see fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.driver.DoctrinePhpAttributeMappingDriver */ public class DoctrinePhpAttributeMappingDriverTest extends SymfonyLightCodeInsightFixtureTestCase { public void setUp() throws Exception { super.setUp(); myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("attributes.php")); } public String getTestDataPath() { return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/doctrine/metadata/driver/fixtures"; } /** * @see DoctrinePhpMappingDriver#getMetadata(fr.adrienbrault.idea.symfony2plugin.doctrine.metadata.driver.DoctrineMappingDriverArguments) */ public void testPhpAttributesMetadata() { DoctrineMetadataModel metadata = createOrmMetadata(); assertEquals("table_name", metadata.getTable()); assertEquals("string", metadata.getField("email").getTypeName()); assertEquals("string", metadata.getField("emailTrait").getTypeName()); assertEquals("\\ORM\\Foobar\\Egg", metadata.getField("apple").getRelation()); assertEquals("ManyToOne", metadata.getField("apple").getRelationType()); assertEquals("\\ORM\\Foobar\\Egg", metadata.getField("egg").getRelation()); assertEquals("ManyToMany", metadata.getField("egg").getRelationType()); assertEquals("\\ORM\\Foobar\\Egg", metadata.getField("address").getRelation()); assertEquals("OneToOne", metadata.getField("address").getRelationType()); assertEquals("\\ORM\\Foobar\\Egg", metadata.getField("phonenumbers").getRelation()); assertEquals("OneToMany", metadata.getField("phonenumbers").getRelationType()); assertEquals("\\Doctrine\\Orm\\MyTrait\\Egg", metadata.getField("appleTrait").getRelation()); assertEquals("ManyToOne", metadata.getField("appleTrait").getRelationType()); } private DoctrineMetadataModel createOrmMetadata() { return new DoctrinePhpAttributeMappingDriver().getMetadata( new DoctrineMappingDriverArguments(getProject(), PhpPsiElementFactory.createPsiFileFromText(getProject(), "<?php $foo = null;"), "\\ORM\\Attributes\\AttributeEntity") ); } }
1,086
3,755
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe def execute(): frappe.delete_doc_if_exists("DocType", "User Permission for Page and Report")
69
1,351
<filename>tests/gold_tests/logging/log-filter.test.py ''' ''' # 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. import os Test.Summary = ''' Test log filter. ''' ts = Test.MakeATSProcess("ts", enable_cache=False) replay_file = "log-filter.replays.yaml" server = Test.MakeVerifierServerProcess("server", replay_file) nameserver = Test.MakeDNServer("dns", default='127.0.0.1') ts.Disk.records_config.update({ 'proxy.config.diags.debug.enabled': 1, 'proxy.config.diags.debug.tags': 'log', 'proxy.config.net.connections_throttle': 100, 'proxy.config.dns.nameservers': f"127.0.0.1:{nameserver.Variables.Port}", 'proxy.config.dns.resolv_conf': 'NULL' }) # setup some config file for this server ts.Disk.remap_config.AddLine( 'map / http://localhost:{}/'.format(server.Variables.http_port) ) ts.Disk.logging_yaml.AddLines( ''' logging: filters: - name: only_localhost action: accept condition: chi MATCH 127.0.0.1 - name: not_localhost action: accept condition: chi MATCH 172.16.17.32 - name: queryparamescaper_cquuc action: WIPE_FIELD_VALUE condition: cquuc CASE_INSENSITIVE_CONTAIN password,secret,access_token,session_redirect,cardNumber,code,query,search-query,prefix,keywords,email,handle formats: - name: custom format: '%<cquuc>' logs: - filename: filter-test format: custom filters: - queryparamescaper_cquuc - only_localhost - filename: should-not-be-written format: custom filters: - queryparamescaper_cquuc - not_localhost '''.split("\n") ) # ######################################################################### # at the end of the different test run a custom log file should exist # Because of this we expect the testruns to pass the real test is if the # customlog file exists and passes the format check Test.Disk.File(os.path.join(ts.Variables.LOGDIR, 'filter-test.log'), exists=True, content='gold/filter-test.gold') tr = Test.AddTestRun() tr.Processes.Default.StartBefore(server) tr.Processes.Default.StartBefore(nameserver) tr.Processes.Default.StartBefore(ts) tr.AddVerifierClientProcess("client-1", replay_file, http_ports=[ts.Variables.port]) # Wait for log file to appear, then wait one extra second to make sure TS is done writing it. test_run = Test.AddTestRun() test_run.Processes.Default.Command = ( os.path.join(Test.Variables.AtsTestToolsDir, 'condwait') + ' 60 1 -f ' + os.path.join(ts.Variables.LOGDIR, 'filter-test.log') ) test_run.Processes.Default.ReturnCode = 0 # We already waited for the above, so we don't have to wait for this one. test_run = Test.AddTestRun() test_run.Processes.Default.Command = ( os.path.join(Test.Variables.AtsTestToolsDir, 'condwait') + ' 1 1 -f ' + os.path.join(ts.Variables.LOGDIR, 'should-not-be-written.log') ) test_run.Processes.Default.ReturnCode = 1
1,272
357
<reponame>wfu8/lightwave<filename>vmidentity/platform/src/main/java/com/vmware/identity/interop/ldap/certContext/CertInfoNative.java /* * Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ package com.vmware.identity.interop.ldap.certContext; import java.util.Arrays; import java.util.List; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.platform.win32.WinBase.FILETIME; /** typedef struct _CERT_INFO { DWORD dwVersion; CRYPT_INTEGER_BLOB SerialNumber; CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; CERT_NAME_BLOB Issuer; FILETIME NotBefore; FILETIME NotAfter; CERT_NAME_BLOB Subject; CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; CRYPT_BIT_BLOB IssuerUniqueId; CRYPT_BIT_BLOB SubjectUniqueId; DWORD cExtension; PCERT_EXTENSION rgExtension; } CERT_INFO, *PCERT_INFO; */ public class CertInfoNative extends Structure { public int dwVersion; public CryptBlobNative SerialNumber; public CryptAlgorithmIdentifierNative SignatureAlgorithm; /** * CERT_NAME_BLOB is same typedef as CRYPT_INTEGER_BLOB {@link CryptBlobNative} */ public CryptBlobNative Issuer; public FILETIME NotBefore; public FILETIME NotAfter; /** * CERT_NAME_BLOB is same typedef as CRYPT_INTEGER_BLOB {@link CryptBlobNative} */ public CryptBlobNative Subject; public CryptPublicKeyInfoNative SubjectPublicKeyInfo; public CryptBitBlobNative IssuerUniqueId; public CryptBitBlobNative SubjectUniqueId; public int cExtension; public Pointer rgExtension; public CertInfoNative(Pointer p) { super(); useMemory(p); read(); } public String getSerialNumberStr() { byte[] serialNumberBuf = new byte[SerialNumber.cbData]; SerialNumber.pbData.read(0, serialNumberBuf, 0, SerialNumber.cbData); StringBuilder sb = new StringBuilder(); for (int i = serialNumberBuf.length -1; i >=0; i--) { sb.append(String.format("%02x",serialNumberBuf[i])); } return sb.toString(); } @Override protected List<String> getFieldOrder() { return Arrays.asList("dwVersion", "SerialNumber", "SignatureAlgorithm", "Issuer", "NotBefore", "NotAfter", "Subject", "SubjectPublicKeyInfo", "IssuerUniqueId", "SubjectUniqueId", "cExtension", "rgExtension"); } }
1,249
348
{"nom":"Milhac","circ":"1ère circonscription","dpt":"Lot","inscrits":178,"abs":72,"votants":106,"blancs":9,"nuls":9,"exp":88,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":57},{"nuance":"REM","nom":"M. <NAME>","voix":31}]}
90
877
<filename>framework-test/src/main/java/org/checkerframework/framework/test/ImmutableTestConfiguration.java package org.checkerframework.framework.test; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.signature.qual.BinaryName; import org.plumelib.util.StringsPlume; /** * Represents all of the information needed to execute the Javac compiler for a given set of test * files. */ public class ImmutableTestConfiguration implements TestConfiguration { /** * Options that should be passed to the compiler. This a {@code Map(optionName => * optionArgumentIfAny)}. E.g., * * <pre>{@code * Map( * "-AprintAllQualifiers" => null * "-classpath" => "myDir1:myDir2" * ) * }</pre> */ private final Map<String, @Nullable String> options; /** * These files contain diagnostics that should be returned by Javac. If this list is empty, the * diagnostics are instead read from comments in the Java file itself */ private final List<File> diagnosticFiles; /** * The source files to compile. If the file is expected to emit errors on compilation, the file * should contain expected error diagnostics OR should have a companion file with the same * path/name but with the extension .out instead of .java if they */ private final List<File> testSourceFiles; /** A list of AnnotationProcessors (usually checkers) to pass to the compiler for this test. */ private final List<@BinaryName String> processors; /** The value of system property "emit.test.debug". */ private final boolean shouldEmitDebugInfo; /** * Create a new ImmutableTestConfiguration. * * @param diagnosticFiles files containing diagnostics that should be returned by javac * @param testSourceFiles the source files to compile * @param processors the annotation processors (usually checkers) to run * @param options options that should be passed to the compiler * @param shouldEmitDebugInfo the value of system property "emit.test.debug" */ public ImmutableTestConfiguration( List<File> diagnosticFiles, List<File> testSourceFiles, List<@BinaryName String> processors, Map<String, @Nullable String> options, boolean shouldEmitDebugInfo) { this.diagnosticFiles = Collections.unmodifiableList(diagnosticFiles); this.testSourceFiles = Collections.unmodifiableList(new ArrayList<>(testSourceFiles)); this.processors = new ArrayList<>(processors); this.options = Collections.unmodifiableMap(new LinkedHashMap<String, @Nullable String>(options)); this.shouldEmitDebugInfo = shouldEmitDebugInfo; } @Override public List<File> getTestSourceFiles() { return testSourceFiles; } @Override public List<File> getDiagnosticFiles() { return diagnosticFiles; } @Override public List<@BinaryName String> getProcessors() { return processors; } @Override public Map<String, @Nullable String> getOptions() { return options; } @Override public List<String> getFlatOptions() { return TestUtilities.optionMapToList(options); } @Override public boolean shouldEmitDebugInfo() { return shouldEmitDebugInfo; } @Override public String toString() { return StringsPlume.joinLines( "TestConfigurationBuilder:", "testSourceFiles=" + StringsPlume.join(" ", testSourceFiles), "processors=" + String.join(", ", processors), "options=" + String.join(", ", getFlatOptions()), "shouldEmitDebugInfo=" + shouldEmitDebugInfo); } }
1,165
543
<filename>core/src/com/riiablo/math/Fixed.java package com.riiablo.math; public final class Fixed { private static final int[] DIVISOR = new int[Integer.SIZE]; static { for (int i = 0; i < Integer.SIZE; i++) { DIVISOR[i] = 1 << i; } } public static int floatToIntBits(final float value, final int precision) { return (int) (value * DIVISOR[precision]); } public static float intBitsToFloat(final int value, final int precision) { final int pow2 = DIVISOR[precision]; final int mask = pow2 - 1; return ((value >> precision) + ((value & mask) / (float) pow2)); } public static int intBitsToFloatFloor(final int value, final int precision) { return value >> precision; } private Fixed() {} }
265
1,531
/* * 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.ngrinder.common.constant; /** * Web related Constants. * * @since 3.0 */ @SuppressWarnings("unused") public interface WebConstants { String JSON_SUCCESS = "success"; String JSON_MESSAGE = "message"; // parameter constant, for parameter from page, and for key in map String PARAM_TPS = "tps"; String PARAM_STATUS_AGENT_PORT = "port"; String PARAM_TEST = "test"; String PARAM_LOG_LIST = "logs"; String PARAM_TEST_CHART_INTERVAL = "chartInterval"; String PARAM_TIMEZONE_OFFSET = "timezoneOffset"; String PARAM_REGION_LIST = "regions"; String PARAM_REGION_AGENT_COUNT_MAP = "regionAgentCountMap"; String PARAM_QUICK_SCRIPT = "quickScript"; String PARAM_QUICK_SCRIPT_REVISION = "quickScriptRevision"; String PARAM_PROCESS_THREAD_POLICY_SCRIPT = "vuserCalcScript"; String PARAM_AVAILABLE_RAMP_UP_TYPE = "rampUpTypes"; String PARAM_MAX_VUSER_PER_AGENT = "maxVuserPerAgent"; String PARAM_MAX_RUN_COUNT = "maxRunCount"; String PARAM_MAX_RUN_HOUR = "maxRunHour"; String PARAM_SAFE_FILE_DISTRIBUTION = "safeFileDistribution"; String PARAM_SECURITY_LEVEL = "securityLevel"; }
562
505
#include <string> #include <iostream> #include <sstream> using namespace std; #include "BlockDataManagerConfig.h" #include "BDM_mainthread.h" #include "BDM_Server.h" int main(int argc, char* argv[]) { ScrAddrFilter::init(); #ifdef _WIN32 WSADATA wsaData; WORD wVersion = MAKEWORD(2, 0); WSAStartup(wVersion, &wsaData); #endif BlockDataManagerConfig bdmConfig; bdmConfig.parseArgs(argc, argv); cout << "logging in " << bdmConfig.logFilePath_ << endl; STARTLOGGING(bdmConfig.logFilePath_, LogLvlDebug); if (!bdmConfig.useCookie_) LOGENABLESTDOUT(); else LOGDISABLESTDOUT(); LOGINFO << "Running on " << bdmConfig.threadCount_ << " threads"; LOGINFO << "Ram usage level: " << bdmConfig.ramUsage_; if (FCGX_Init()) throw runtime_error("failed to initialize FCGI engine"); //init db BlockDataManagerThread bdmThread(bdmConfig); bdmThread.start(bdmConfig.initMode_); //init listen loop FCGI_Server server(&bdmThread, bdmConfig.fcgiPort_, bdmConfig.listen_all_); if (!bdmConfig.checkChain_) { //start listening server.checkSocket(); server.init(); } //create cookie file if applicable bdmConfig.createCookie(); if (!bdmConfig.checkChain_) { //process incoming connections server.enterLoop(); } else { bdmThread.join(); } //stop all threads and clean up server.shutdown(); return 0; }
588
416
<reponame>benhunter/owasp-pysec """Various utilities fot sequences manipulation""" from pysec.utils import xrange def ioc(seq, shift=1): """Return the index of coincidence""" match = 0 seq_len = len(seq) for i in xrange(0, seq_len): j = (i + shift) % seq_len if seq[i] == seq[j]: match += 1 return float(match) / float(seq_len) def contains_only(seq, *values): return all(el in values for el in seq)
185
442
#include <Bindings/obe/obe.hpp> #include <Exception.hpp> #include <ObEngineCore.hpp> #include <Bindings/Config.hpp> namespace obe::Bindings { void LoadClassBaseException(sol::state_view state) { sol::table obeNamespace = state["obe"].get<sol::table>(); sol::usertype<obe::BaseException> bindBaseException = obeNamespace.new_usertype<obe::BaseException>("BaseException", sol::call_constructor, sol::constructors<obe::BaseException(), obe::BaseException(const std::exception&)>()); bindBaseException["what"] = &obe::BaseException::what; bindBaseException["traceback"] = &obe::BaseException::traceback; } void LoadClassDebugInfo(sol::state_view state) { sol::table obeNamespace = state["obe"].get<sol::table>(); sol::usertype<obe::DebugInfo> bindDebugInfo = obeNamespace.new_usertype<obe::DebugInfo>("DebugInfo", sol::call_constructor, sol::constructors<obe::DebugInfo(std::string_view, int, std::string_view)>()); bindDebugInfo["file"] = &obe::DebugInfo::file; bindDebugInfo["line"] = &obe::DebugInfo::line; bindDebugInfo["function"] = &obe::DebugInfo::function; } void LoadFunctionGetTypeName(sol::state_view state) { } void LoadFunctionInitEngine(sol::state_view state) { sol::table obeNamespace = state["obe"].get<sol::table>(); obeNamespace.set_function("InitEngine", obe::InitEngine); } };
647
14,668
// Copyright 2014 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 <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <stdint.h> #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/tests/gl_manager.h" #include "gpu/command_buffer/tests/gl_test_utils.h" #include "gpu/command_buffer/tests/texture_image_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace gpu { namespace { // Blits texture bound to active texture unit to currently bound framebuffer. // Viewport must be set by caller. void BlitTexture() { const GLuint kVertexPositionAttrib = 0; const GLfloat kQuadVertices[] = {-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f}; GLuint buffer_id = 0; glGenBuffers(1, &buffer_id); glBindBuffer(GL_ARRAY_BUFFER, buffer_id); glBufferData(GL_ARRAY_BUFFER, sizeof(kQuadVertices), kQuadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(kVertexPositionAttrib); glVertexAttribPointer(kVertexPositionAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); GLuint shader_program = glCreateProgram(); static const char* kBlitTextureVertexShader = "precision mediump float;\n" "attribute vec2 a_position;\n" "varying mediump vec2 v_uv;\n" "void main(void) {\n" " gl_Position = vec4(a_position, 0, 1);\n" " v_uv = 0.5 * (a_position + vec2(1, 1));\n" "}\n"; GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &kBlitTextureVertexShader, 0); glCompileShader(vertex_shader); glAttachShader(shader_program, vertex_shader); static const char* kBlitTextureFragmentShader = "uniform sampler2D u_sampler;\n" "varying mediump vec2 v_uv;\n" "void main(void) {\n" " gl_FragColor = texture2D(u_sampler, v_uv);\n" "}\n"; GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &kBlitTextureFragmentShader, 0); glCompileShader(fragment_shader); glAttachShader(shader_program, fragment_shader); glBindAttribLocation(shader_program, kVertexPositionAttrib, "a_position"); glLinkProgram(shader_program); glUseProgram(shader_program); GLuint sampler_handle = glGetUniformLocation(shader_program, "u_sampler"); glUniform1i(sampler_handle, 0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); ASSERT_TRUE(glGetError() == GL_NONE); } } // namespace class TextureStorageTest : public testing::Test { protected: static const GLsizei kResolution = 64; void SetUp() override { GLManager::Options options; image_factory_.SetRequiredTextureType(GL_TEXTURE_2D); options.size = gfx::Size(kResolution, kResolution); options.image_factory = &image_factory_; gl_.Initialize(options); gl_.MakeCurrent(); glGenTextures(1, &tex_); glBindTexture(GL_TEXTURE_2D, tex_); glGenFramebuffers(1, &fbo_); glBindFramebuffer(GL_FRAMEBUFFER, fbo_); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0); const GLubyte* extensions = glGetString(GL_EXTENSIONS); ext_texture_storage_available_ = strstr( reinterpret_cast<const char*>(extensions), "GL_EXT_texture_storage"); chromium_texture_storage_image_available_ = strstr(reinterpret_cast<const char*>(extensions), "GL_CHROMIUM_texture_storage_image"); } void TearDown() override { gl_.Destroy(); } TextureImageFactory image_factory_; GLManager gl_; GLuint tex_ = 0; GLuint fbo_ = 0; bool ext_texture_storage_available_ = false; bool chromium_texture_storage_image_available_ = false; }; TEST_F(TextureStorageTest, CorrectPixels) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 2, 2); // Mesa drivers crash without rebinding to FBO. It's why // DISABLE_TEXTURE_STORAGE workaround is introduced. crbug.com/521904 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0); uint8_t source_pixels[16] = {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}; glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_TRUE(GLTestHelper::CheckPixels(0, 0, 2, 2, 0, source_pixels, nullptr)); } TEST_F(TextureStorageTest, IsImmutable) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 4, 4); GLint param = 0; glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_IMMUTABLE_FORMAT_EXT, &param); EXPECT_TRUE(param); } TEST_F(TextureStorageTest, OneLevel) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 4, 4); uint8_t source_pixels[64] = {0}; EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_EQ(static_cast<GLenum>(GL_INVALID_OPERATION), glGetError()); } TEST_F(TextureStorageTest, MultipleLevels) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 2, GL_RGBA8_OES, 2, 2); uint8_t source_pixels[16] = {0}; EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexSubImage2D(GL_TEXTURE_2D, 2, 0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_EQ(static_cast<GLenum>(GL_INVALID_OPERATION), glGetError()); } TEST_F(TextureStorageTest, BadTarget) { if (!ext_texture_storage_available_) return; EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexStorage2DEXT(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 1, GL_RGBA8_OES, 4, 4); EXPECT_EQ(static_cast<GLenum>(GL_INVALID_ENUM), glGetError()); } TEST_F(TextureStorageTest, InvalidId) { if (!ext_texture_storage_available_) return; glDeleteTextures(1, &tex_); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 4, 4); EXPECT_EQ(static_cast<GLenum>(GL_INVALID_OPERATION), glGetError()); } TEST_F(TextureStorageTest, CannotRedefine) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 4, 4); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 4, 4); EXPECT_EQ(static_cast<GLenum>(GL_INVALID_OPERATION), glGetError()); EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); EXPECT_EQ(static_cast<GLenum>(GL_INVALID_OPERATION), glGetError()); } TEST_F(TextureStorageTest, InternalFormatBleedingToTexImage) { if (!ext_texture_storage_available_) return; EXPECT_EQ(static_cast<GLenum>(GL_NO_ERROR), glGetError()); // The context is ES2 context. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8_OES, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); EXPECT_NE(static_cast<GLenum>(GL_NO_ERROR), glGetError()); } TEST_F(TextureStorageTest, CorrectImagePixels) { if (!chromium_texture_storage_image_available_) return; glTexStorage2DImageCHROMIUM(GL_TEXTURE_2D, GL_RGBA8_OES, GL_SCANOUT_CHROMIUM, 2, 2); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0); uint8_t source_pixels[16] = {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}; glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, source_pixels); EXPECT_TRUE(GLTestHelper::CheckPixels(0, 0, 2, 2, 0, source_pixels, nullptr)); } TEST_F(TextureStorageTest, LuminanceEmulation) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 2, 2); // Mesa drivers crash without rebinding to FBO. It's why // DISABLE_TEXTURE_STORAGE workaround is introduced. crbug.com/521904 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0); ASSERT_TRUE(glGetError() == GL_NONE); GLuint luminance_tex = 0; glGenTextures(1, &luminance_tex); glBindTexture(GL_TEXTURE_2D, luminance_tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_LUMINANCE8_EXT, 2, 2); ASSERT_TRUE(glGetError() == GL_NONE); const uint8_t source_data[4] = {1, 1, 1, 1}; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, source_data); ASSERT_TRUE(glGetError() == GL_NONE); BlitTexture(); const uint8_t swizzled_pixel[4] = {1, 1, 1, 255}; EXPECT_TRUE( GLTestHelper::CheckPixels(0, 0, 2, 2, 0, swizzled_pixel, nullptr)); } TEST_F(TextureStorageTest, AlphaEmulation) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 2, 2); // Mesa drivers crash without rebinding to FBO. It's why // DISABLE_TEXTURE_STORAGE workaround is introduced. crbug.com/521904 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0); ASSERT_TRUE(glGetError() == GL_NONE); GLuint alpha_tex = 0; glGenTextures(1, &alpha_tex); glBindTexture(GL_TEXTURE_2D, alpha_tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_ALPHA8_EXT, 2, 2); ASSERT_TRUE(glGetError() == GL_NONE); const uint8_t source_data[4] = {1, 1, 1, 1}; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_ALPHA, GL_UNSIGNED_BYTE, source_data); ASSERT_TRUE(glGetError() == GL_NONE); BlitTexture(); const uint8_t swizzled_pixel[4] = {0, 0, 0, 1}; EXPECT_TRUE( GLTestHelper::CheckPixels(0, 0, 2, 2, 0, swizzled_pixel, nullptr)); } TEST_F(TextureStorageTest, LuminanceAlphaEmulation) { if (!ext_texture_storage_available_) return; glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_RGBA8_OES, 2, 2); // Mesa drivers crash without rebinding to FBO. It's why // DISABLE_TEXTURE_STORAGE workaround is introduced. crbug.com/521904 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_, 0); ASSERT_TRUE(glGetError() == GL_NONE); GLuint luminance_alpha_tex = 0; glGenTextures(1, &luminance_alpha_tex); glBindTexture(GL_TEXTURE_2D, luminance_alpha_tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexStorage2DEXT(GL_TEXTURE_2D, 1, GL_LUMINANCE8_ALPHA8_EXT, 2, 2); ASSERT_TRUE(glGetError() == GL_NONE); const uint8_t source_data[8] = {1, 2, 1, 2, 1, 2, 1, 2}; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 2, 2, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, source_data); ASSERT_TRUE(glGetError() == GL_NONE); BlitTexture(); const uint8_t swizzled_pixel[4] = {1, 1, 1, 2}; EXPECT_TRUE( GLTestHelper::CheckPixels(0, 0, 2, 2, 0, swizzled_pixel, nullptr)); } } // namespace gpu
5,559
12,718
<reponame>Bhuvanesh1208/ruby2.6.1 /** * This file has no copyright assigned and is placed in the Public Domain. * This file is part of the mingw-w64 runtime package. * No warranty is given; refer to the file DISCLAIMER.PD within this package. */ #ifndef _STICOM_ #define _STICOM_ #include <pshpack8.h> #define STI_UNICODE 1 #ifndef _NO_COM #include <objbase.h> #endif #include <stireg.h> #include <stierr.h> #define DLLEXP __declspec(dllexport) #ifdef __cplusplus extern "C" { #endif #ifndef _NO_COM DEFINE_GUID(CLSID_Sti,0xB323F8E0,0x2E68,0x11D0,0x90,0xEA,0x00,0xAA,0x00,0x60,0xF8,0x6C); DEFINE_GUID(IID_IStillImageW,0x641BD880,0x2DC8,0x11D0,0x90,0xEA,0x00,0xAA,0x00,0x60,0xF8,0x6C); DEFINE_GUID(IID_IStillImageA,0xA7B1F740,0x1D7F,0x11D1,0xAC,0xA9,0x00,0xA0,0x24,0x38,0xAD,0x48); DEFINE_GUID(IID_IStiDevice,0x6CFA5A80,0x2DC8,0x11D0,0x90,0xEA,0x00,0xAA,0x00,0x60,0xF8,0x6C); DEFINE_GUID(GUID_DeviceArrivedLaunch,0x740d9ee6,0x70f1,0x11d1,0xad,0x10,0x0,0xa0,0x24,0x38,0xad,0x48); DEFINE_GUID(GUID_ScanImage,0xa6c5a715,0x8c6e,0x11d2,0x97,0x7a,0x0,0x0,0xf8,0x7a,0x92,0x6f); DEFINE_GUID(GUID_ScanPrintImage,0xb441f425,0x8c6e,0x11d2,0x97,0x7a,0x0,0x0,0xf8,0x7a,0x92,0x6f); DEFINE_GUID(GUID_ScanFaxImage,0xc00eb793,0x8c6e,0x11d2,0x97,0x7a,0x0,0x0,0xf8,0x7a,0x92,0x6f); DEFINE_GUID(GUID_STIUserDefined1,0xc00eb795,0x8c6e,0x11d2,0x97,0x7a,0x0,0x0,0xf8,0x7a,0x92,0x6f); DEFINE_GUID(GUID_STIUserDefined2,0xc77ae9c5,0x8c6e,0x11d2,0x97,0x7a,0x0,0x0,0xf8,0x7a,0x92,0x6f); DEFINE_GUID(GUID_STIUserDefined3,0xc77ae9c6,0x8c6e,0x11d2,0x97,0x7a,0x0,0x0,0xf8,0x7a,0x92,0x6f); #endif #define STI_VERSION_FLAG_MASK 0xff000000 #define STI_VERSION_FLAG_UNICODE 0x01000000 #define GET_STIVER_MAJOR(dwVersion) (HIWORD(dwVersion) & ~STI_VERSION_FLAG_MASK) #define GET_STIVER_MINOR(dwVersion) LOWORD(dwVersion) #define STI_VERSION_REAL 0x00000002 #define STI_VERSION_MIN_ALLOWED 0x00000002 #if defined(UNICODE) #define STI_VERSION (STI_VERSION_REAL | STI_VERSION_FLAG_UNICODE) #else #define STI_VERSION (STI_VERSION_REAL) #endif #define STI_MAX_INTERNAL_NAME_LENGTH 128 typedef enum _STI_DEVICE_MJ_TYPE { StiDeviceTypeDefault = 0,StiDeviceTypeScanner = 1,StiDeviceTypeDigitalCamera = 2,StiDeviceTypeStreamingVideo = 3 } STI_DEVICE_MJ_TYPE; typedef DWORD STI_DEVICE_TYPE; #define GET_STIDEVICE_TYPE(dwDevType) HIWORD(dwDevType) #define GET_STIDEVICE_SUBTYPE(dwDevType) LOWORD(dwDevType) typedef struct _STI_DEV_CAPS { DWORD dwGeneric; } STI_DEV_CAPS,*PSTI_DEV_CAPS; #define GET_STIDCOMMON_CAPS(dwGenericCaps) LOWORD(dwGenericCaps) #define GET_STIVENDOR_CAPS(dwGenericCaps) HIWORD(dwGenericCaps) #define STI_GENCAP_COMMON_MASK (DWORD)0x00ff #define STI_GENCAP_NOTIFICATIONS 0x00000001 #define STI_GENCAP_POLLING_NEEDED 0x00000002 #define STI_GENCAP_GENERATE_ARRIVALEVENT 0x00000004 #define STI_GENCAP_AUTO_PORTSELECT 0x00000008 #define STI_GENCAP_WIA 0x00000010 #define STI_GENCAP_SUBSET 0x00000020 #define STI_HW_CONFIG_UNKNOWN 0x0001 #define STI_HW_CONFIG_SCSI 0x0002 #define STI_HW_CONFIG_USB 0x0004 #define STI_HW_CONFIG_SERIAL 0x0008 #define STI_HW_CONFIG_PARALLEL 0x0010 typedef struct _STI_DEVICE_INFORMATIONW { DWORD dwSize; STI_DEVICE_TYPE DeviceType; WCHAR szDeviceInternalName[STI_MAX_INTERNAL_NAME_LENGTH]; STI_DEV_CAPS DeviceCapabilities; DWORD dwHardwareConfiguration; LPWSTR pszVendorDescription; LPWSTR pszDeviceDescription; LPWSTR pszPortName; LPWSTR pszPropProvider; LPWSTR pszLocalName; } STI_DEVICE_INFORMATIONW,*PSTI_DEVICE_INFORMATIONW; typedef struct _STI_DEVICE_INFORMATIONA { DWORD dwSize; STI_DEVICE_TYPE DeviceType; CHAR szDeviceInternalName[STI_MAX_INTERNAL_NAME_LENGTH]; STI_DEV_CAPS DeviceCapabilities; DWORD dwHardwareConfiguration; LPCSTR pszVendorDescription; LPCSTR pszDeviceDescription; LPCSTR pszPortName; LPCSTR pszPropProvider; LPCSTR pszLocalName; } STI_DEVICE_INFORMATIONA,*PSTI_DEVICE_INFORMATIONA; #if defined(UNICODE) || defined(STI_UNICODE) typedef STI_DEVICE_INFORMATIONW STI_DEVICE_INFORMATION; typedef PSTI_DEVICE_INFORMATIONW PSTI_DEVICE_INFORMATION; #else typedef STI_DEVICE_INFORMATIONA STI_DEVICE_INFORMATION; typedef PSTI_DEVICE_INFORMATIONA PSTI_DEVICE_INFORMATION; #endif typedef struct _STI_WIA_DEVICE_INFORMATIONW { DWORD dwSize; STI_DEVICE_TYPE DeviceType; WCHAR szDeviceInternalName[STI_MAX_INTERNAL_NAME_LENGTH]; STI_DEV_CAPS DeviceCapabilities; DWORD dwHardwareConfiguration; LPWSTR pszVendorDescription; LPWSTR pszDeviceDescription; LPWSTR pszPortName; LPWSTR pszPropProvider; LPWSTR pszLocalName; LPWSTR pszUiDll; LPWSTR pszServer; } STI_WIA_DEVICE_INFORMATIONW,*PSTI_WIA_DEVICE_INFORMATIONW; typedef struct _STI_WIA_DEVICE_INFORMATIONA { DWORD dwSize; STI_DEVICE_TYPE DeviceType; CHAR szDeviceInternalName[STI_MAX_INTERNAL_NAME_LENGTH]; STI_DEV_CAPS DeviceCapabilities; DWORD dwHardwareConfiguration; LPCSTR pszVendorDescription; LPCSTR pszDeviceDescription; LPCSTR pszPortName; LPCSTR pszPropProvider; LPCSTR pszLocalName; LPCSTR pszUiDll; LPCSTR pszServer; } STI_WIA_DEVICE_INFORMATIONA,*PSTI_WIA_DEVICE_INFORMATIONA; #if defined(UNICODE) || defined(STI_UNICODE) typedef STI_WIA_DEVICE_INFORMATIONW STI_WIA_DEVICE_INFORMATION; typedef PSTI_WIA_DEVICE_INFORMATIONW PSTI_WIA_DEVICE_INFORMATION; #else typedef STI_WIA_DEVICE_INFORMATIONA STI_WIA_DEVICE_INFORMATION; typedef PSTI_WIA_DEVICE_INFORMATIONA PSTI_WIA_DEVICE_INFORMATION; #endif #define STI_DEVSTATUS_ONLINE_STATE 0x0001 #define STI_DEVSTATUS_EVENTS_STATE 0x0002 #define STI_ONLINESTATE_OPERATIONAL 0x00000001 #define STI_ONLINESTATE_PENDING 0x00000002 #define STI_ONLINESTATE_ERROR 0x00000004 #define STI_ONLINESTATE_PAUSED 0x00000008 #define STI_ONLINESTATE_PAPER_JAM 0x00000010 #define STI_ONLINESTATE_PAPER_PROBLEM 0x00000020 #define STI_ONLINESTATE_OFFLINE 0x00000040 #define STI_ONLINESTATE_IO_ACTIVE 0x00000080 #define STI_ONLINESTATE_BUSY 0x00000100 #define STI_ONLINESTATE_TRANSFERRING 0x00000200 #define STI_ONLINESTATE_INITIALIZING 0x00000400 #define STI_ONLINESTATE_WARMING_UP 0x00000800 #define STI_ONLINESTATE_USER_INTERVENTION 0x00001000 #define STI_ONLINESTATE_POWER_SAVE 0x00002000 #define STI_EVENTHANDLING_ENABLED 0x00000001 #define STI_EVENTHANDLING_POLLING 0x00000002 #define STI_EVENTHANDLING_PENDING 0x00000004 typedef struct _STI_DEVICE_STATUS { DWORD dwSize; DWORD StatusMask; DWORD dwOnlineState; DWORD dwHardwareStatusCode; DWORD dwEventHandlingState; DWORD dwPollingInterval; } STI_DEVICE_STATUS,*PSTI_DEVICE_STATUS; #define STI_DIAGCODE_HWPRESENCE 0x00000001 typedef struct _ERROR_INFOW { DWORD dwSize; DWORD dwGenericError; DWORD dwVendorError; WCHAR szExtendedErrorText[255]; } STI_ERROR_INFOW,*PSTI_ERROR_INFOW; typedef struct _ERROR_INFOA { DWORD dwSize; DWORD dwGenericError; DWORD dwVendorError; CHAR szExtendedErrorText[255]; } STI_ERROR_INFOA,*PSTI_ERROR_INFOA; #if defined(UNICODE) || defined(STI_UNICODE) typedef STI_ERROR_INFOW STI_ERROR_INFO; #else typedef STI_ERROR_INFOA STI_ERROR_INFO; #endif typedef STI_ERROR_INFO *PSTI_ERROR_INFO; typedef struct _STI_DIAG { DWORD dwSize; DWORD dwBasicDiagCode; DWORD dwVendorDiagCode; DWORD dwStatusMask; STI_ERROR_INFO sErrorInfo; } STI_DIAG,*LPSTI_DIAG; typedef STI_DIAG DIAG; typedef LPSTI_DIAG LPDIAG; #define STI_TRACE_INFORMATION 0x00000001 #define STI_TRACE_WARNING 0x00000002 #define STI_TRACE_ERROR 0x00000004 #define STI_SUBSCRIBE_FLAG_WINDOW 0x0001 #define STI_SUBSCRIBE_FLAG_EVENT 0x0002 typedef struct _STISUBSCRIBE { DWORD dwSize; DWORD dwFlags; DWORD dwFilter; HWND hWndNotify; HANDLE hEvent; UINT uiNotificationMessage; } STISUBSCRIBE,*LPSTISUBSCRIBE; #define MAX_NOTIFICATION_DATA 64 typedef struct _STINOTIFY { DWORD dwSize; GUID guidNotificationCode; BYTE abNotificationData[MAX_NOTIFICATION_DATA]; } STINOTIFY,*LPSTINOTIFY; #define STI_ADD_DEVICE_BROADCAST_ACTION "Arrival" #define STI_REMOVE_DEVICE_BROADCAST_ACTION "Removal" #define STI_ADD_DEVICE_BROADCAST_STRING "STI\\" STI_ADD_DEVICE_BROADCAST_ACTION "\\%s" #define STI_REMOVE_DEVICE_BROADCAST_STRING "STI\\" STI_REMOVE_DEVICE_BROADCAST_ACTION "\\%s" #define STI_DEVICE_CREATE_STATUS 0x00000001 #define STI_DEVICE_CREATE_DATA 0x00000002 #define STI_DEVICE_CREATE_BOTH 0x00000003 #define STI_DEVICE_CREATE_MASK 0x0000FFFF #define STIEDFL_ALLDEVICES 0x00000000 #define STIEDFL_ATTACHEDONLY 0x00000001 typedef DWORD STI_RAW_CONTROL_CODE; #define STI_RAW_RESERVED 0x1000 struct IStillImageW; struct IStillImageA; struct IStiDevice; STDMETHODIMP StiCreateInstanceW(HINSTANCE hinst,DWORD dwVer,struct IStillImageW **ppSti,LPUNKNOWN punkOuter); STDMETHODIMP StiCreateInstanceA(HINSTANCE hinst,DWORD dwVer,struct IStillImageA **ppSti,LPUNKNOWN punkOuter); #if defined(UNICODE) || defined(STI_UNICODE) #define IID_IStillImage IID_IStillImageW #define IStillImage IStillImageW #define StiCreateInstance StiCreateInstanceW #else #define IID_IStillImage IID_IStillImageA #define IStillImage IStillImageA #define StiCreateInstance StiCreateInstanceA #endif typedef struct IStiDevice *LPSTILLIMAGEDEVICE; typedef struct IStillImage *PSTI; typedef struct IStiDevice *PSTIDEVICE; typedef struct IStillImageA *PSTIA; typedef struct IStiDeviceA *PSTIDEVICEA; typedef struct IStillImageW *PSTIW; typedef struct IStiDeviceW *PSTIDEVICEW; #undef INTERFACE #define INTERFACE IStillImageW DECLARE_INTERFACE_(IStillImageW,IUnknown) { STDMETHOD(QueryInterface) (THIS_ REFIID riid,LPVOID *ppvObj) PURE; STDMETHOD_(ULONG,AddRef) (THIS) PURE; STDMETHOD_(ULONG,Release) (THIS) PURE; STDMETHOD(Initialize) (THIS_ HINSTANCE hinst,DWORD dwVersion) PURE; STDMETHOD(GetDeviceList)(THIS_ DWORD dwType,DWORD dwFlags,DWORD *pdwItemsReturned,LPVOID *ppBuffer) PURE; STDMETHOD(GetDeviceInfo)(THIS_ LPWSTR pwszDeviceName,LPVOID *ppBuffer) PURE; STDMETHOD(CreateDevice) (THIS_ LPWSTR pwszDeviceName,DWORD dwMode,PSTIDEVICE *pDevice,LPUNKNOWN punkOuter) PURE; STDMETHOD(GetDeviceValue)(THIS_ LPWSTR pwszDeviceName,LPWSTR pValueName,LPDWORD pType,LPBYTE pData,LPDWORD cbData); STDMETHOD(SetDeviceValue)(THIS_ LPWSTR pwszDeviceName,LPWSTR pValueName,DWORD Type,LPBYTE pData,DWORD cbData); STDMETHOD(GetSTILaunchInformation)(THIS_ LPWSTR pwszDeviceName,DWORD *pdwEventCode,LPWSTR pwszEventName) PURE; STDMETHOD(RegisterLaunchApplication)(THIS_ LPWSTR pwszAppName,LPWSTR pwszCommandLine) PURE; STDMETHOD(UnregisterLaunchApplication)(THIS_ LPWSTR pwszAppName) PURE; STDMETHOD(EnableHwNotifications)(THIS_ LPCWSTR pwszDeviceName,WINBOOL bNewState) PURE; STDMETHOD(GetHwNotificationState)(THIS_ LPCWSTR pwszDeviceName,WINBOOL *pbCurrentState) PURE; STDMETHOD(RefreshDeviceBus)(THIS_ LPCWSTR pwszDeviceName) PURE; STDMETHOD(LaunchApplicationForDevice)(THIS_ LPWSTR pwszDeviceName,LPWSTR pwszAppName,LPSTINOTIFY pStiNotify); STDMETHOD(SetupDeviceParameters)(THIS_ PSTI_DEVICE_INFORMATIONW); STDMETHOD(WriteToErrorLog)(THIS_ DWORD dwMessageType,LPCWSTR pszMessage) PURE; #ifdef NOT_IMPLEMENTED STIMETHOD(RegisterDeviceNotification(THIS_ LPWSTR pwszAppName,LPSUBSCRIBE lpSubscribe) PURE; STIMETHOD(UnregisterDeviceNotification(THIS_) PURE; #endif }; typedef struct IStillImageW *LPSTILLIMAGEW; #undef INTERFACE #define INTERFACE IStillImageA DECLARE_INTERFACE_(IStillImageA,IUnknown) { STDMETHOD(QueryInterface) (THIS_ REFIID riid,LPVOID *ppvObj) PURE; STDMETHOD_(ULONG,AddRef) (THIS) PURE; STDMETHOD_(ULONG,Release) (THIS) PURE; STDMETHOD(Initialize) (THIS_ HINSTANCE hinst,DWORD dwVersion) PURE; STDMETHOD(GetDeviceList)(THIS_ DWORD dwType,DWORD dwFlags,DWORD *pdwItemsReturned,LPVOID *ppBuffer) PURE; STDMETHOD(GetDeviceInfo)(THIS_ LPCSTR pwszDeviceName,LPVOID *ppBuffer) PURE; STDMETHOD(CreateDevice) (THIS_ LPCSTR pwszDeviceName,DWORD dwMode,PSTIDEVICE *pDevice,LPUNKNOWN punkOuter) PURE; STDMETHOD(GetDeviceValue)(THIS_ LPCSTR pwszDeviceName,LPCSTR pValueName,LPDWORD pType,LPBYTE pData,LPDWORD cbData); STDMETHOD(SetDeviceValue)(THIS_ LPCSTR pwszDeviceName,LPCSTR pValueName,DWORD Type,LPBYTE pData,DWORD cbData); STDMETHOD(GetSTILaunchInformation)(THIS_ LPSTR pwszDeviceName,DWORD *pdwEventCode,LPSTR pwszEventName) PURE; STDMETHOD(RegisterLaunchApplication)(THIS_ LPCSTR pwszAppName,LPCSTR pwszCommandLine) PURE; STDMETHOD(UnregisterLaunchApplication)(THIS_ LPCSTR pwszAppName) PURE; STDMETHOD(EnableHwNotifications)(THIS_ LPCSTR pwszDeviceName,WINBOOL bNewState) PURE; STDMETHOD(GetHwNotificationState)(THIS_ LPCSTR pwszDeviceName,WINBOOL *pbCurrentState) PURE; STDMETHOD(RefreshDeviceBus)(THIS_ LPCSTR pwszDeviceName) PURE; STDMETHOD(LaunchApplicationForDevice)(THIS_ LPCSTR pwszDeviceName,LPCSTR pwszAppName,LPSTINOTIFY pStiNotify); STDMETHOD(SetupDeviceParameters)(THIS_ PSTI_DEVICE_INFORMATIONA); STDMETHOD(WriteToErrorLog)(THIS_ DWORD dwMessageType,LPCSTR pszMessage) PURE; #ifdef NOT_IMPLEMENTED STIMETHOD(RegisterDeviceNotification(THIS_ LPWSTR pwszAppName,LPSUBSCRIBE lpSubscribe) PURE; STIMETHOD(UnregisterDeviceNotification(THIS_) PURE; #endif }; typedef struct IStillImageA *LPSTILLIMAGEA; #if defined(UNICODE) || defined(STI_UNICODE) #define IStillImageVtbl IStillImageWVtbl #else #define IStillImageVtbl IStillImageAVtbl #endif typedef struct IStillImage *LPSTILLIMAGE; #if !defined(__cplusplus) || defined(CINTERFACE) #define IStillImage_QueryInterface(p,a,b) (p)->lpVtbl->QueryInterface(p,a,b) #define IStillImage_AddRef(p) (p)->lpVtbl->AddRef(p) #define IStillImage_Release(p) (p)->lpVtbl->Release(p) #define IStillImage_Initialize(p,a,b) (p)->lpVtbl->Initialize(p,a,b) #define IStillImage_GetDeviceList(p,a,b,c,d) (p)->lpVtbl->GetDeviceList(p,a,b,c,d) #define IStillImage_GetDeviceInfo(p,a,b) (p)->lpVtbl->GetDeviceInfo(p,a,b) #define IStillImage_CreateDevice(p,a,b,c,d) (p)->lpVtbl->CreateDevice(p,a,b,c,d) #define IStillImage_GetDeviceValue(p,a,b,c,d,e) (p)->lpVtbl->GetDeviceValue(p,a,b,c,d,e) #define IStillImage_SetDeviceValue(p,a,b,c,d,e) (p)->lpVtbl->SetDeviceValue(p,a,b,c,d,e) #define IStillImage_GetSTILaunchInformation(p,a,b,c) (p)->lpVtbl->GetSTILaunchInformation(p,a,b,c) #define IStillImage_RegisterLaunchApplication(p,a,b) (p)->lpVtbl->RegisterLaunchApplication(p,a,b) #define IStillImage_UnregisterLaunchApplication(p,a) (p)->lpVtbl->UnregisterLaunchApplication(p,a) #define IStillImage_EnableHwNotifications(p,a,b) (p)->lpVtbl->EnableHwNotifications(p,a,b) #define IStillImage_GetHwNotificationState(p,a,b) (p)->lpVtbl->GetHwNotificationState(p,a,b) #define IStillImage_RefreshDeviceBus(p,a) (p)->lpVtbl->RefreshDeviceBus(p,a) #endif #undef INTERFACE #define INTERFACE IStiDevice DECLARE_INTERFACE_(IStiDevice,IUnknown) { STDMETHOD(QueryInterface) (THIS_ REFIID riid,LPVOID *ppvObj) PURE; STDMETHOD_(ULONG,AddRef) (THIS) PURE; STDMETHOD_(ULONG,Release) (THIS) PURE; STDMETHOD(Initialize) (THIS_ HINSTANCE hinst,LPCWSTR pwszDeviceName,DWORD dwVersion,DWORD dwMode) PURE; STDMETHOD(GetCapabilities) (THIS_ PSTI_DEV_CAPS pDevCaps) PURE; STDMETHOD(GetStatus) (THIS_ PSTI_DEVICE_STATUS pDevStatus) PURE; STDMETHOD(DeviceReset)(THIS) PURE; STDMETHOD(Diagnostic)(THIS_ LPSTI_DIAG pBuffer) PURE; STDMETHOD(Escape)(THIS_ STI_RAW_CONTROL_CODE EscapeFunction,LPVOID lpInData,DWORD cbInDataSize,LPVOID pOutData,DWORD dwOutDataSize,LPDWORD pdwActualData) PURE; STDMETHOD(GetLastError) (THIS_ LPDWORD pdwLastDeviceError) PURE; STDMETHOD(LockDevice) (THIS_ DWORD dwTimeOut) PURE; STDMETHOD(UnLockDevice) (THIS) PURE; STDMETHOD(RawReadData)(THIS_ LPVOID lpBuffer,LPDWORD lpdwNumberOfBytes,LPOVERLAPPED lpOverlapped) PURE; STDMETHOD(RawWriteData)(THIS_ LPVOID lpBuffer,DWORD nNumberOfBytes,LPOVERLAPPED lpOverlapped) PURE; STDMETHOD(RawReadCommand)(THIS_ LPVOID lpBuffer,LPDWORD lpdwNumberOfBytes,LPOVERLAPPED lpOverlapped) PURE; STDMETHOD(RawWriteCommand)(THIS_ LPVOID lpBuffer,DWORD nNumberOfBytes,LPOVERLAPPED lpOverlapped) PURE; STDMETHOD(Subscribe)(THIS_ LPSTISUBSCRIBE lpSubsribe) PURE; STDMETHOD(GetLastNotificationData)(THIS_ LPSTINOTIFY lpNotify) PURE; STDMETHOD(UnSubscribe)(THIS) PURE; STDMETHOD(GetLastErrorInfo) (THIS_ STI_ERROR_INFO *pLastErrorInfo) PURE; }; #if !defined(__cplusplus) || defined(CINTERFACE) #define IStiDevice_QueryInterface(p,a,b) (p)->lpVtbl->QueryInterface(p,a,b) #define IStiDevice_AddRef(p) (p)->lpVtbl->AddRef(p) #define IStiDevice_Release(p) (p)->lpVtbl->Release(p) #define IStiDevice_Initialize(p,a,b,c,d) (p)->lpVtbl->Initialize(p,a,b,c,d) #define IStiDevice_GetCapabilities(p,a) (p)->lpVtbl->GetCapabilities(p,a) #define IStiDevice_GetStatus(p,a) (p)->lpVtbl->GetStatus(p,a) #define IStiDevice_DeviceReset(p) (p)->lpVtbl->DeviceReset(p) #define IStiDevice_LockDevice(p,a) (p)->lpVtbl->LockDevice(p,a) #define IStiDevice_UnLockDevice(p) (p)->lpVtbl->UnLockDevice(p) #define IStiDevice_Diagnostic(p,a) (p)->lpVtbl->Diagnostic(p,a) #define IStiDevice_Escape(p,a,b,c,d,e,f) (p)->lpVtbl->Escape(p,a,b,c,d,e,f) #define IStiDevice_GetLastError(p,a) (p)->lpVtbl->GetLastError(p,a) #define IStiDevice_RawReadData(p,a,b,c) (p)->lpVtbl->RawReadData(p,a,b,c) #define IStiDevice_RawWriteData(p,a,b,c) (p)->lpVtbl->RawWriteData(p,a,b,c) #define IStiDevice_RawReadCommand(p,a,b,c) (p)->lpVtbl->RawReadCommand(p,a,b,c) #define IStiDevice_RawWriteCommand(p,a,b,c) (p)->lpVtbl->RawWriteCommand(p,a,b,c) #define IStiDevice_Subscribe(p,a) (p)->lpVtbl->Subscribe(p,a) #define IStiDevice_GetNotificationData(p,a) (p)->lpVtbl->GetNotificationData(p,a) #define IStiDevice_UnSubscribe(p) (p)->lpVtbl->UnSubscribe(p) #define IStiDevice_GetLastErrorInfo(p,a) (p)->lpVtbl->GetLastErrorInfo(p,a) #endif #ifdef __cplusplus }; #endif #include <poppack.h> #endif
7,938
190,993
/* 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. ==============================================================================*/ #ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_AUTO_MIXED_PRECISION_H_ #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_AUTO_MIXED_PRECISION_H_ #include "tensorflow/core/grappler/optimizers/graph_optimizer.h" #include "tensorflow/core/platform/cpu_info.h" #include "tensorflow/core/protobuf/rewriter_config.pb.h" namespace tensorflow { namespace grappler { // CUDA: convert to float16 on GPU // MKL: convert to bfloat16 on CPU // CPU: emulate float16 on CPU without changing operator kernel enum class AutoMixedPrecisionMode { CUDA, MKL, CPU }; // Convert data types to float16 or bfloat16 where appropriate to improve // performance on GPUs or CPUs. class AutoMixedPrecision : public GraphOptimizer { public: // If 'mode' is CUDA, converts nodes to float16 on Nvidia GPUs. If MKL, // converts nodes to bfloat16 on CPUs in order to take advantage of MKL // performance improvements with bfloat16. explicit AutoMixedPrecision( AutoMixedPrecisionMode mode = AutoMixedPrecisionMode::CUDA) : mode_(mode) {} ~AutoMixedPrecision() override {} string name() const override { switch (mode_) { case AutoMixedPrecisionMode::CUDA: return "auto_mixed_precision"; case AutoMixedPrecisionMode::MKL: return "auto_mixed_precision_mkl"; case AutoMixedPrecisionMode::CPU: return "auto_mixed_precision_cpu"; default: LOG(FATAL) << "Invalid value for AutoMixedPrecisionMode: " // Crash Ok << static_cast<int>(mode_); } }; bool UsesFunctionLibrary() const override { return false; } Status Optimize(Cluster* cluster, const GrapplerItem& item, GraphDef* output) override; private: const AutoMixedPrecisionMode mode_; }; } // end namespace grappler } // end namespace tensorflow #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_AUTO_MIXED_PRECISION_H_
848
307
#include "TestUtil.h" #include "scripting/lua/LuaValue.h" using namespace luacpp; class LuaValueTest: public LuaStateTest {}; TEST_F(LuaValueTest, SetReference) { ScopedLuaStackTest stackTest(L); LuaValue val = LuaValue::createValue(L, "TestTest"); lua_pushnumber(L, 42.0); val.setReference(UniqueLuaReference::create(L)); lua_pop(L, 1); ASSERT_EQ(ValueType::NUMBER, val.getValueType()); ASSERT_DOUBLE_EQ(42.0, val.getValue<double>()); }
177
16,483
/* * Copyright 1999-2019 Seata.io Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.seata.sqlparser.druid.postgresql; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.dialect.postgresql.ast.stmt.PGSelectQueryBlock; import io.seata.common.loader.LoadLevel; import io.seata.sqlparser.SQLRecognizer; import io.seata.sqlparser.druid.SQLOperateRecognizerHolder; import io.seata.sqlparser.util.JdbcConstants; /** * The type PostgresqlOperateRecognizerHolder * * @author will.zjw */ @LoadLevel(name = JdbcConstants.POSTGRESQL) public class PostgresqlOperateRecognizerHolder implements SQLOperateRecognizerHolder { @Override public SQLRecognizer getDeleteRecognizer(String sql, SQLStatement ast) { return new PostgresqlDeleteRecognizer(sql, ast); } @Override public SQLRecognizer getInsertRecognizer(String sql, SQLStatement ast) { return new PostgresqlInsertRecognizer(sql, ast); } @Override public SQLRecognizer getUpdateRecognizer(String sql, SQLStatement ast) { return new PostgresqlUpdateRecognizer(sql, ast); } @Override public SQLRecognizer getSelectForUpdateRecognizer(String sql, SQLStatement ast) { PGSelectQueryBlock selectQueryBlock = (PGSelectQueryBlock) ((SQLSelectStatement) ast).getSelect().getFirstQueryBlock(); if (selectQueryBlock.getForClause() != null && selectQueryBlock.getForClause().getOption().equals(PGSelectQueryBlock.ForClause.Option.UPDATE)) { return new PostgresqlSelectForUpdateRecognizer(sql, ast); } return null; } }
740
409
""" # -*- coding: utf-8 -*- ----------------------------------------------------------------------------------- # Author: <NAME> # DoC: 2020.08.17 # email: <EMAIL> ----------------------------------------------------------------------------------- # Description: This script for the KITTI dataset """ import sys import os from builtins import int from glob import glob import numpy as np from torch.utils.data import Dataset import cv2 import torch src_dir = os.path.dirname(os.path.realpath(__file__)) while not src_dir.endswith("sfa"): src_dir = os.path.dirname(src_dir) if src_dir not in sys.path: sys.path.append(src_dir) from data_process.kitti_data_utils import get_filtered_lidar from data_process.kitti_bev_utils import makeBEVMap import config.kitti_config as cnf class Demo_KittiDataset(Dataset): def __init__(self, configs): self.dataset_dir = os.path.join(configs.dataset_dir, configs.foldername, configs.foldername[:10], configs.foldername) self.input_size = configs.input_size self.hm_size = configs.hm_size self.num_classes = configs.num_classes self.max_objects = configs.max_objects self.image_dir = os.path.join(self.dataset_dir, "image_02", "data") self.lidar_dir = os.path.join(self.dataset_dir, "velodyne_points", "data") self.label_dir = os.path.join(self.dataset_dir, "label_2", "data") self.sample_id_list = sorted(glob(os.path.join(self.lidar_dir, '*.bin'))) self.sample_id_list = [float(os.path.basename(fn)[:-4]) for fn in self.sample_id_list] self.num_samples = len(self.sample_id_list) def __len__(self): return len(self.sample_id_list) def __getitem__(self, index): pass def load_bevmap_front(self, index): """Load only image for the testing phase""" sample_id = int(self.sample_id_list[index]) img_path, img_rgb = self.get_image(sample_id) lidarData = self.get_lidar(sample_id) front_lidar = get_filtered_lidar(lidarData, cnf.boundary) front_bevmap = makeBEVMap(front_lidar, cnf.boundary) front_bevmap = torch.from_numpy(front_bevmap) metadatas = { 'img_path': img_path, } return metadatas, front_bevmap, img_rgb def load_bevmap_front_vs_back(self, index): """Load only image for the testing phase""" sample_id = int(self.sample_id_list[index]) img_path, img_rgb = self.get_image(sample_id) lidarData = self.get_lidar(sample_id) front_lidar = get_filtered_lidar(lidarData, cnf.boundary) front_bevmap = makeBEVMap(front_lidar, cnf.boundary) front_bevmap = torch.from_numpy(front_bevmap) back_lidar = get_filtered_lidar(lidarData, cnf.boundary_back) back_bevmap = makeBEVMap(back_lidar, cnf.boundary_back) back_bevmap = torch.from_numpy(back_bevmap) metadatas = { 'img_path': img_path, } return metadatas, front_bevmap, back_bevmap, img_rgb def get_image(self, idx): img_path = os.path.join(self.image_dir, '{:010d}.png'.format(idx)) img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB) return img_path, img def get_lidar(self, idx): lidar_file = os.path.join(self.lidar_dir, '{:010d}.bin'.format(idx)) # assert os.path.isfile(lidar_file) return np.fromfile(lidar_file, dtype=np.float32).reshape(-1, 4)
1,587
407
<reponame>iuskye/SREWorks #!/usr/bin/env python # encoding: utf-8 """ """ import types import web from web import Storage from teslafaas.common.trace_id import get_upstream_trace from teslafaas.container.webpy.bcc_factory import BCCFactory, BCCFactoryBase from teslafaas.container.webpy.common.hooks import tesla_loadhook from teslafaas.container.webpy.middleware.mysql_manager import create_db_pool from teslafaas.container.webpy.middleware.redis_manager import create_redis_pool from teslafaas.container.webpy.middleware.domain_model import DomainModel import logging __author__ = 'adonis' def context_hook(context_manager): tesla_dict = { 'config': context_manager.config, 'db': context_manager.db, 'dbs': context_manager.dbs, 'dm': DomainModel, 'logger': context_manager.logger, 'tesla_sdk_client': context_manager.tesla_sdk, 'tesla_sdk': context_manager.tesla_sdk, "tesla_sdk_by_gateway": context_manager.tesla_sdk_by_gateway, 'tesla_sdk_channel': context_manager.tesla_sdk_channel, 'redis_pool': context_manager.redis_pool, 'factory': context_manager.factory, # 兼容老的代码 'clusterinfo_source': '', 'http_opts': { 'cors_wl': '*' }, 'db_opts': {}, 'request_id': web.ctx.get('trace_id', None), 'trace_id': web.ctx.get('trace_id', None), } web.ctx.tesla = Storage(tesla_dict) # 兼容老的bcc中的使用方式 web.ctx.factory = context_manager.factory # 兼容老的代码 web.ctx.server = '' web.ctx.db = web.ctx.tesla.db class ContextManager(object): """ # FIXME: dynamic resource and static resource dynamic resource: db, redis, sdk, logger etc. need to be loaded refresh every worker process static resource: conf, hooks, may be shared across workers """ def __init__(self, app, config, raw_mod=None): self.app = app self.raw_mod = raw_mod self.config = config self.db = None self.redis_pool = None self.logger = None self.tesla_sdk = None self.tesla_sdk_channel = None self.tesla_sdk_by_gateway = None self.factory = None def load_middle_ware(self): self.db = self.load_db() self.dbs = self.load_dbs() self.logger = self.load_logger() self.redis_pool = self.load_redis_pool() self.factory = self.load_factory() def load_logger(self): # TODO: container log isolation pass def generate_trace_id(self): # TODO: get from http header pass def load_factory(self): factory = BCCFactory(self.config) self._load_sub_factory(factory) return factory def _load_sub_factory(self, factory): if not self.raw_mod: return sub_factory_mod = getattr(self.raw_mod, 'factory', None) if not sub_factory_mod: return for file_mod in dir(sub_factory_mod): if file_mod.startswith("__"): continue file_mod = getattr(sub_factory_mod, file_mod) if not isinstance(file_mod, types.ModuleType): continue for class_obj in dir(file_mod): if class_obj.startswith("__"): continue class_obj = getattr(file_mod, class_obj) if not isinstance(class_obj, (types.ClassType, types.TypeType)): continue if not issubclass(class_obj, BCCFactoryBase) or class_obj is BCCFactoryBase: continue if hasattr(class_obj, 'register'): factory_instance = class_obj() setattr(factory, factory_instance.register(), factory_instance) def load_db(self, db_conf=None): if not db_conf: db_conf = self.config.get('database', None) if not db_conf: return None db_name = db_conf.get('db', '') db_name = db_conf.get('dbname', '') if not db_name else db_name db_name = db_conf.get('database', '') if not db_name else db_name if not db_name: raise Exception("no db name specified in config file") db_type = db_conf.get('db_type', 'mysql') pool = create_db_pool( db_conf['host'], db_conf['port'], db_conf['user'], db_conf['passwd'], db_name, db_conf.get('pool_size', 20), dbn=db_type, params=db_conf.get('params') ) return pool def load_dbs(self): dbs = Storage({}) db_conf = self.config.get('databases', None) if db_conf is None: db_conf = self.config.get('rds', None) if db_conf is None: db_conf = self.config.get('dbs', None) if not db_conf: return dbs if not isinstance(db_conf, dict): raise Exception("invalid multiple database config: " "not dict format") for k, v in db_conf.iteritems(): if not isinstance(v, dict): raise Exception("invalid multiple database config: " "data source config '%s' not dict format" % k) dbs[k] = self.load_db(db_conf=v) return dbs def load_redis_pool(self): redis_conf = self.config.get('redis', None) if not redis_conf: return None pool = create_redis_pool( redis_conf['host'], redis_conf['port'], redis_conf['passwd'], 50, redis_conf['db'], mode=redis_conf['mode'] ) return pool def trace_id_hook(self): trace_id = get_upstream_trace() if trace_id: web.ctx.trace_id = trace_id else: wsgi_env = web.ctx['environ'] try: remote = wsgi_env['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except KeyError: remote = wsgi_env['REMOTE_ADDR'] # trace_id = generate_trace_id(remote) trace_id = 'xxxx' web.ctx.trace_id = trace_id def set_context_hook(self): self.app.add_processor(web.loadhook(self.trace_id_hook)) self.app.add_processor(tesla_loadhook(context_hook, self))
3,167
3,508
<filename>src/test/java/com/fishercoder/_1746Test.java<gh_stars>1000+ package com.fishercoder; import com.fishercoder.solutions._1746; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; public class _1746Test { private static _1746.Solution1 solution1; @BeforeClass public static void setup() { solution1 = new _1746.Solution1(); } @Test public void test1() { assertEquals(17, solution1.maxSumAfterOperation(new int[]{2, -1, -4, -3})); } @Test public void test2() { assertEquals(4, solution1.maxSumAfterOperation(new int[]{1, -1, 1, 1, -1, -1, 1})); } @Test public void test3() { assertEquals(1936, solution1.maxSumAfterOperation(new int[]{-44})); } @Test public void test4() { assertEquals(10954, solution1.maxSumAfterOperation(new int[]{29, 71, -52, -23, -28, 50, 27, 29, 0, 50, -92, 22, -38, 90, 3, 6, 70, -56, -7, 40, 79, 98, 72, 88, -5, -78, 12, 69, 30, -73, 99, -59, 33, 0, -6, 25, 87, -93, 20, -89, -22, 80, 57, 51, 48, 0, 65, -57, -57, 28, -42, -97, 97, -49, 38, 40, -41, 3, 31, -12, 47, -10, 17, -32, 68, 40, 55, 86, -99, -2, 100, 89, 31, -67})); } }
653
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_DETAILS_PASSWORD_DETAILS_H_ #define IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_DETAILS_PASSWORD_DETAILS_H_ #import <Foundation/Foundation.h> #include "url/gurl.h" namespace password_manager { struct PasswordForm; } // namespace password_manager // Object which is used by |PasswordDetailsViewController| to show // information about password. @interface PasswordDetails : NSObject // Short version of website. @property(nonatomic, copy, readonly) NSString* origin; // Associated website. @property(nonatomic, copy, readonly) NSString* website; // Associated username. @property(nonatomic, copy) NSString* username; // The federation providing this credential, if any. @property(nonatomic, copy, readonly) NSString* federation; // Associated password. @property(nonatomic, copy) NSString* password; // Whether password is compromised or not. @property(nonatomic, assign, getter=isCompromised) BOOL compromised; // URL which allows to change the password of compromised credential. @property(nonatomic, readonly) GURL changePasswordURL; - (instancetype)initWithPasswordForm:(const password_manager::PasswordForm&)form NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_PASSWORD_PASSWORD_DETAILS_PASSWORD_DETAILS_H_
486
645
<reponame>AlexShypula/stoke // Copyright 2013-2016 Stanford University // // Licensed under the Apache License, Version 2.0 (the License); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an AS IS BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _STOKE_TEST_X64ASM_ASSEMBLER_H #define _STOKE_TEST_X64ASM_ASSEMBLER_H namespace x64asm { TEST(X64AsmInstructionInfo, FunctionSize) { Code c; std::stringstream ss; ss << "pushq %rax" << std::endl; ss >> c; ASSERT_FALSE(cpputil::failed(ss)) << cpputil::fail_msg(ss); Assembler assm; auto result = assm.assemble(c); auto fxn = result.second; Function gxn = fxn; //testing copy constructor EXPECT_EQ(2ul, fxn.size()); EXPECT_EQ(2ul, gxn.size()); } TEST(X64AsmInstructionInfo, FunctionSize2) { Code c; std::stringstream ss; ss << "pushq %rdi" << std::endl; ss << "pushq %rsi" << std::endl; ss << "popq %rcx" << std::endl; ss << "popq %r8" << std::endl; ss << "xorl %r9d,%r9d" << std::endl; ss << "movq $0x3,%r11" << std::endl; ss << "pushq %r11" << std::endl; ss << "addw $0x0,(%rcx,%r9,1)" << std::endl; ss << "je .L1" << std::endl; ss << "bsfl %r11d,%r14d" << std::endl; ss << "testb $0xfe,(%rbx)" << std::endl; ss << "setg %cl" << std::endl; ss << "popq %rsi" << std::endl; ss << "pushq %r11" << std::endl; ss << "je .L2" << std::endl; ss << ".L5:" << std::endl; ss << "movzbl 0x10(%rdi),%edx" << std::endl; ss << "movq (%rbx),%rax" << std::endl; ss << "testl %esi,%r9d" << std::endl; ss << "sarq %cl,%rsi" << std::endl; ss << ".L4:" << std::endl; ss << "movq (%r11,%rax,8),%rcx" << std::endl; ss << "movq (%rcx,%r9,1),%rcx" << std::endl; ss << "imulq (%rdx,%rax,8),%rcx" << std::endl; ss << "subw $0xffff,%ax" << std::endl; ss << "xaddq %rcx,%r8" << std::endl; ss << "andb $0xfb,%al" << std::endl; ss << "jne .L4" << std::endl; ss << "xchgq %r8,0x0(%rbp,%r9,1)" << std::endl; ss << "ja .L4" << std::endl; ss << ".L2:" << std::endl; ss << "sbbw $0xfff8,%r9w" << std::endl; ss << "cmpb %r9b,%r8b" << std::endl; ss << "ja .L5" << std::endl; ss << "adcq $0xfc,%r8" << std::endl; ss << ".L1:" << std::endl; ss << "xchgl %r11d,%r8d" << std::endl; ss << "popq %r14" << std::endl; ss << "sarw $0x1, %r9w" << std::endl; ss << "pushq %rdi" << std::endl; ss << "popq %rbp" << std::endl; ss << "sarb $0x1, %dil" << std::endl; ss << "retq " << std::endl; ss >> c; ASSERT_FALSE(cpputil::failed(ss)) << cpputil::fail_msg(ss); Assembler assm; auto fxn = assm.assemble(c).second; EXPECT_EQ(147U, fxn.size()); } } //namespace x64asm #endif
1,438
960
/* * Copyright (c) 2010 Google Inc.J * * 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.google.api.client.json; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * Abstract low-level JSON factory. * * <p>Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency, * applications should use a single globally-shared instance of the JSON factory. * * @since 1.3 * @author <NAME> */ public abstract class JsonFactory { /** * Returns a new instance of a low-level JSON parser for the given input stream. The parser tries * to detect the charset of the input stream by itself. * * @param in input stream * @return new instance of a low-level JSON parser */ public abstract JsonParser createJsonParser(InputStream in) throws IOException; /** * Returns a new instance of a low-level JSON parser for the given input stream. * * @param in input stream * @param charset charset in which the input stream is encoded or {@code null} to let the parser * detect the charset * @return new instance of a low-level JSON parser * @since 1.10 */ public abstract JsonParser createJsonParser(InputStream in, Charset charset) throws IOException; /** * Returns a new instance of a low-level JSON parser for the given string value. * * @param value string value * @return new instance of a low-level JSON parser */ public abstract JsonParser createJsonParser(String value) throws IOException; /** * Returns a new instance of a low-level JSON parser for the given reader. * * @param reader reader * @return new instance of a low-level JSON parser */ public abstract JsonParser createJsonParser(Reader reader) throws IOException; /** * Returns a new instance of a low-level JSON serializer for the given output stream and encoding. * * @param out output stream * @param enc encoding * @return new instance of a low-level JSON serializer * @since 1.10 */ public abstract JsonGenerator createJsonGenerator(OutputStream out, Charset enc) throws IOException; /** * Returns a new instance of a low-level JSON serializer for the given writer. * * @param writer writer * @return new instance of a low-level JSON serializer */ public abstract JsonGenerator createJsonGenerator(Writer writer) throws IOException; /** * Creates an object parser which uses this factory to parse JSON data. * * @since 1.10 */ public final JsonObjectParser createJsonObjectParser() { return new JsonObjectParser(this); } /** * Returns a serialized JSON string representation for the given item using {@link * JsonGenerator#serialize(Object)}. * * @param item data key/value pairs * @return serialized JSON string representation */ public final String toString(Object item) throws IOException { return toString(item, false); } /** * Returns a pretty-printed serialized JSON string representation for the given item using {@link * JsonGenerator#serialize(Object)} with {@link JsonGenerator#enablePrettyPrint()}. * * <p>The specifics of how the JSON representation is made pretty is implementation dependent, and * should not be relied on. However, it is assumed to be legal, and in fact differs from {@link * #toString(Object)} only by adding whitespace that does not change its meaning. * * @param item data key/value pairs * @return serialized JSON string representation * @since 1.6 */ public final String toPrettyString(Object item) throws IOException { return toString(item, true); } /** * Returns a UTF-8 encoded byte array of the serialized JSON representation for the given item * using {@link JsonGenerator#serialize(Object)}. * * @param item data key/value pairs * @return byte array of the serialized JSON representation * @since 1.7 */ public final byte[] toByteArray(Object item) throws IOException { return toByteStream(item, false).toByteArray(); } /** * Returns a serialized JSON string representation for the given item using {@link * JsonGenerator#serialize(Object)}. * * @param item data key/value pairs * @param pretty whether to return a pretty representation * @return serialized JSON string representation */ private String toString(Object item, boolean pretty) throws IOException { return toByteStream(item, pretty).toString("UTF-8"); } /** * Returns a UTF-8 byte array output stream of the serialized JSON representation for the given * item using {@link JsonGenerator#serialize(Object)}. * * @param item data key/value pairs * @param pretty whether to return a pretty representation * @return serialized JSON string representation */ private ByteArrayOutputStream toByteStream(Object item, boolean pretty) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); JsonGenerator generator = createJsonGenerator(byteStream, StandardCharsets.UTF_8); if (pretty) { generator.enablePrettyPrint(); } generator.serialize(item); generator.flush(); return byteStream; } /** * Parses a string value as a JSON object, array, or value into a new instance of the given * destination class using {@link JsonParser#parse(Class)}. * * @param value JSON string value * @param destinationClass destination class that has an accessible default constructor to use to * create a new instance * @return new instance of the parsed destination class * @since 1.4 */ public final <T> T fromString(String value, Class<T> destinationClass) throws IOException { return createJsonParser(value).parse(destinationClass); } /** * Parse and close an input stream as a JSON object, array, or value into a new instance of the * given destination class using {@link JsonParser#parseAndClose(Class)}. * * <p>Tries to detect the charset of the input stream automatically. * * @param inputStream JSON value in an input stream * @param destinationClass destination class that has an accessible default constructor to use to * create a new instance * @return new instance of the parsed destination class * @since 1.7 */ public final <T> T fromInputStream(InputStream inputStream, Class<T> destinationClass) throws IOException { return createJsonParser(inputStream).parseAndClose(destinationClass); } /** * Parse and close an input stream as a JSON object, array, or value into a new instance of the * given destination class using {@link JsonParser#parseAndClose(Class)}. * * @param inputStream JSON value in an input stream * @param charset Charset in which the stream is encoded * @param destinationClass destination class that has an accessible default constructor to use to * create a new instance * @return new instance of the parsed destination class * @since 1.10 */ public final <T> T fromInputStream( InputStream inputStream, Charset charset, Class<T> destinationClass) throws IOException { return createJsonParser(inputStream, charset).parseAndClose(destinationClass); } /** * Parse and close a reader as a JSON object, array, or value into a new instance of the given * destination class using {@link JsonParser#parseAndClose(Class)}. * * @param reader JSON value in a reader * @param destinationClass destination class that has an accessible default constructor to use to * create a new instance * @return new instance of the parsed destination class * @since 1.7 */ public final <T> T fromReader(Reader reader, Class<T> destinationClass) throws IOException { return createJsonParser(reader).parseAndClose(destinationClass); } }
2,467
389
package gw.specContrib.interfaceMethods.defaultMethods.javaInteraction; import java.util.List; public interface JavaInterface1 { public default List foo() { return null; } }
63
612
package com.mtcarpenter.mall.domain; import com.mtcarpenter.mall.model.SmsCoupon; import com.mtcarpenter.mall.model.SmsCouponHistory; import com.mtcarpenter.mall.model.SmsCouponProductCategoryRelation; import com.mtcarpenter.mall.model.SmsCouponProductRelation; import lombok.Data; import java.util.List; /** * @author mtcarpenter * @github https://github.com/mtcarpenter/mall-cloud-alibaba * @desc 微信公众号:山间木匠 */ @Data public class SmsCouponHistoryDetail extends SmsCouponHistory { /** * 相关优惠券信息 */ private SmsCoupon coupon; /** * 优惠券关联商品 */ private List<SmsCouponProductRelation> productRelationList; /** * 优惠券关联商品分类 */ private List<SmsCouponProductCategoryRelation> categoryRelationList; }
370
5,169
{ "name": "AdGem", "version": "1.3.5", "summary": "Maximize ROI with engaging, reward-based ads using AdGem’s lightweight SDK.", "homepage": "http://adgem.com", "authors": { "<NAME>": "<EMAIL>" }, "license": { "type": "Commerical", "text": "LICENSE © 2019 AdGem. All rights reserved. LICENSE" }, "platforms": { "ios": "8.0" }, "source": { "http": "https://adgem-framework.s3.amazonaws.com/iOS-1.3.5.zip" }, "ios": { "vendored_frameworks": "AdGem.framework" } }
225
997
#ifndef PQCLEAN_SNTRUP761_CLEAN_CRYPTO_CORE_INV3SNTRUP761_H #define PQCLEAN_SNTRUP761_CLEAN_CRYPTO_CORE_INV3SNTRUP761_H #include <stdint.h> #define PQCLEAN_SNTRUP761_CLEAN_crypto_core_inv3sntrup761_OUTPUTBYTES 762 #define PQCLEAN_SNTRUP761_CLEAN_crypto_core_inv3sntrup761_INPUTBYTES 761 #define PQCLEAN_SNTRUP761_CLEAN_crypto_core_inv3sntrup761_KEYBYTES 0 #define PQCLEAN_SNTRUP761_CLEAN_crypto_core_inv3sntrup761_CONSTBYTES 0 int PQCLEAN_SNTRUP761_CLEAN_crypto_core_inv3sntrup761(unsigned char *outbytes, const unsigned char *inbytes); #endif
272
417
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.metrics.reporter.file; import com.alibaba.metrics.common.MetricObject; import org.apache.commons.lang3.time.StopWatch; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; public class FormatBenchmark { static Random random = new Random(); public static void main(String[] args) throws InterruptedException { SimpleTextMetricFormat simpleTextMetricFormat = new SimpleTextMetricFormat(); JsonMetricFormat jsonMetricFormat = new JsonMetricFormat(); // 代码预热 for(int i = 0; i < 2; ++i) { // FormatBenchmark.test(simpleTextMetricFormat); // FormatBenchmark.test(jsonMetricFormat); FormatBenchmark.testBytes(jsonMetricFormat); FormatBenchmark.testBytes(simpleTextMetricFormat); } TimeUnit.SECONDS.sleep(5); // 正式测试 System.err.println("===== start ========"); // for(int i = 0; i < 5; ++i) { // FormatBenchmark.test(simpleTextMetricFormat); // TimeUnit.SECONDS.sleep(5); // FormatBenchmark.test(jsonMetricFormat); // TimeUnit.SECONDS.sleep(5); // } for(int i = 0; i < 5; ++i) { FormatBenchmark.testBytes(jsonMetricFormat); TimeUnit.SECONDS.sleep(5); FormatBenchmark.testBytes(simpleTextMetricFormat); TimeUnit.SECONDS.sleep(5); } } private static void test(MetricFormat format) { System.out.println("====== test toString========="); System.out.println("format:" + format.getClass().getSimpleName()); RollingFileAppender appender = RollingFileAppender.builder() .name("metrics/metrics.log") .fileSize(1024 * 1024 * 300) .build(); Map<String, String> tags = new HashMap<String, String>(); tags.put("host", "127.0.0.1"); tags.put("appName", "hello" + random.nextInt()); tags.put("oooooooooooo", "pppppppppp" + random.nextInt()); tags.put("level" + random.nextInt(), "aaaaaaaa"); // MetricObject metricObject = MetricObject.named("abc" + random.nextInt()).withTimestamp(System.currentTimeMillis()) // .withValue("1321lkj12kl4jsdklfjdsf" + random.nextInt()).withTags(tags ).build(); int counter = 1000000; long lengthCounter = 0; StopWatch watch = new StopWatch(); watch.start(); for(int i = 0; i < counter; ++i) { MetricObject metricObject = MetricObject.named("abc" + random.nextInt()).withTimestamp(random.nextLong()) .withValue("1321lkj12kl4jsdklfjdsf" + random.nextInt()).withTags(tags ).build(); String string = format.format(metricObject); lengthCounter += string.length(); // appender.append(string); } watch.stop(); System.out.println(watch); System.out.println("length:" + lengthCounter/counter); System.out.println("qps:" + counter/(watch.getTime()/1000.0)); } private static void testBytes(MetricFormat format) { System.out.println("====test toBytes ==========="); System.out.println("format:" + format.getClass().getSimpleName()); RollingFileAppender appender = RollingFileAppender.builder() .name("metrics/metrics.log") .fileSize(1024 * 1024 * 300) .build(); Map<String, String> tags = new HashMap<String, String>(); tags.put("host", "127.0.0.1"); tags.put("appName", "hello" + random.nextInt()); tags.put("oooooooooooo", "pppppppppp" + random.nextInt()); tags.put("level" + random.nextInt(), "aaaaaaaa"); // MetricObject metricObject = MetricObject.named("abc" + random.nextInt()).withTimestamp(System.currentTimeMillis()) // .withValue("1321lkj12kl4jsdklfjdsf" + random.nextInt()).withTags(tags ).build(); int counter = 1000000; long lengthCounter = 0; StopWatch watch = new StopWatch(); watch.start(); for(int i = 0; i < counter; ++i) { MetricObject metricObject = MetricObject.named("abc" + random.nextInt()).withTimestamp(random.nextLong()) .withValue("1321lkj12kl4jsdklfjdsf" + random.nextInt()).withTags(tags ).build(); byte[] data = format.formatToBytes(metricObject); lengthCounter += data.length; // appender.append(data); } watch.stop(); System.out.println(watch); System.out.println("length:" + lengthCounter/counter); System.out.println("qps:" + counter/(watch.getTime()/1000.0)); } }
2,257
310
{ "name": "MailChimp", "description": "A templated mailing list system.", "url": "https://mailchimp.com/" }
41
375
<reponame>alex729/RED /* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.services.event; import org.osgi.service.event.Event; public class Events { public static <T> T get(final Event event, final String key, final Class<T> expectedDataClass) { final Object data = event.getProperty(key); if (data != null && expectedDataClass.isAssignableFrom(data.getClass())) { return expectedDataClass.cast(data); } return null; } }
227