max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
3,631
<reponame>kostola/drools /* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.kie.dmn.feel.runtime; import java.math.BigDecimal; import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.kie.dmn.feel.FEEL; import org.kie.dmn.feel.lang.ast.InfixOpNode.InfixOperator; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.kie.dmn.feel.util.EvalHelper.getBigDecimalOrNull; public class FEELNumberCoercionTest { private final FEEL feel = FEEL.newInstance(); private Object evaluateInfix(final Object x, final InfixOperator op, final Object y) { final Map<String, Object> inputVariables = new HashMap<>(); inputVariables.put("x", x); inputVariables.put("y", y); final String expression = "x " + op.symbol + " y"; System.out.println(expression); return feel.evaluate(expression, inputVariables); } @Test public void test() { assertThat( evaluateInfix( 1 , InfixOperator.LT , 2d ), is( true ) ); assertThat( evaluateInfix( 2d , InfixOperator.LT , 1 ), is( false ) ); assertThat( evaluateInfix( 1 , InfixOperator.LTE , 2d ), is( true ) ); assertThat( evaluateInfix( 2d , InfixOperator.LTE , 1 ), is( false ) ); assertThat( evaluateInfix( 1 , InfixOperator.GT , 2d ), is( false ) ); assertThat( evaluateInfix( 2d , InfixOperator.GT , 1 ), is( true ) ); assertThat( evaluateInfix( 1 , InfixOperator.GTE , 2d ), is( false ) ); assertThat( evaluateInfix( 2d , InfixOperator.GTE , 1 ), is( true ) ); } @SafeVarargs private final Object evaluate(final String expression, final Map.Entry<String, ?>... vars) { final HashMap<String, Object> inputVariables = new HashMap<>(); for (final Map.Entry<String, ?> v : vars) { inputVariables.put(v.getKey(), v.getValue()); } return feel.evaluate(expression, inputVariables); } private static Map.Entry<String, Object> var(final String name, final Object value) { return new SimpleEntry<>(name, value); } @Test public void testOthers() { assertThat( evaluate("ceiling( 1.01 )") , is( getBigDecimalOrNull( 2d ) ) ); assertThat( evaluate("ceiling( x )", var("x", 1.01d )) , is( getBigDecimalOrNull( 2d ) ) ); assertThat( ((Map) evaluate("{ myf : function( v1, v2 ) ceiling(v1), invoked: myf(v2: false, v1: x) }", var("x", 1.01d) )).get("invoked"), is( getBigDecimalOrNull( 2d ) ) ); assertThat( ((Map) evaluate("{ myf : function( v1, v2 ) v1, invoked: myf(v2: false, v1: x) }", var("x", 1.01d) )).get("invoked"), is( getBigDecimalOrNull( 1.01d ) ) ); assertThat( evaluate(" x.y ", var("x", new HashMap<String, Object>(){{ put("y", 1.01d); }} )), is( getBigDecimalOrNull( 1.01d ) ) ); assertThat( evaluate("ceiling( x.y )", var("x", new HashMap<String, Object>(){{ put("y", 1.01d); }} )), is( getBigDecimalOrNull( 2d ) ) ); } @Test public void testMethodGetBigDecimalOrNull() { assertThat( getBigDecimalOrNull((short) 1), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull((byte) 1), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull(1), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull(1L), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull(1f), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull(1.1f), is(BigDecimal.valueOf(1.1)) ); assertThat( getBigDecimalOrNull(1d), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull(1.1d), is(BigDecimal.valueOf(1.1)) ); assertThat( getBigDecimalOrNull("1"), is(BigDecimal.ONE) ); assertThat( getBigDecimalOrNull("1.1"), is(BigDecimal.valueOf(1.1)) ); assertThat( getBigDecimalOrNull("1.1000000"), is(BigDecimal.valueOf(1.1).setScale(7, BigDecimal.ROUND_HALF_EVEN)) ); assertThat( getBigDecimalOrNull(Double.POSITIVE_INFINITY), is(nullValue()) ); assertThat( getBigDecimalOrNull(Double.NEGATIVE_INFINITY), is(nullValue()) ); assertThat( getBigDecimalOrNull(Double.NaN), is(nullValue()) ); } }
1,943
6,036
<gh_stars>1000+ // Copyright(C) 2021 Intel Corporation // Licensed under the MIT License #include "dnnl_gemm.h" #include "dnnl_subgraph.h" #include "dnnl_subgraph_primitive.h" namespace onnxruntime { namespace ort_dnnl { DnnlGemm::DnnlGemm() {} /* Gemm implementation: Gemm: Inputs: 0) A - Input Tensor 1) B - Input Tensor 2) C - Input Tensor (optional if Opset is 11 or later) Outputs: 0) Y - Output Tensor +-----------+ (A) | | ---------->+ | AB +------+ (B) | MatMul +--------------------->+ | alphaAB ---------->+ | (alpha) | Mul +---+ | | *--------------->+ | | +------+ +-----------+ +------+ +---->+ | (Y) alphaAB + betaC | Add +----------------------> (C) +------+ +---->+ | --------------------------------------------->+ | | +------+ (beta) | Mul +---+ *--------------->+ | betaC +------+ Attributes (alpha, beta, transA, transB) To compose Gemm: (algorithm) (1) perform `MatMul` on input tensors A and B result (AB) (2) if `Mul` the result of (1) by alpha attribute (alphaAB) (3) if C is optional return result from (2) and end (4) if C is avalible `Mul` input C tensor by beta attribute (betaC) (5) `Add` result from (2) to result from (4) (alphaAB + betaC) (6) Return output from (5) and end OneDNN algorithm: (1) perform `MatMul` of tensor A and tensor B with `Output scales` set to alpha (0) (2) if C is optional return output from (1) and end (3) if C is avalible perform binary `Add` of output from (0) and input C with input C's `scale` attribute set to beta (4) return output from (4) and end */ void DnnlGemm::CreatePrimitive(DnnlSubgraphPrimitive& sp, DnnlNode& node) { auto eng = sp.GetEngine(); auto a_dims = sp.GetMemory(node.Input(IN_A)).get_desc().dims(); auto b_dims = sp.GetMemory(node.Input(IN_B)).get_desc().dims(); bool input_c_exists = node.Input(IN_C).Exists(); if (a_dims.size() != b_dims.size()) { while (a_dims.size() < b_dims.size()) { a_dims.insert(a_dims.begin(), 1); } while (a_dims.size() > b_dims.size()) { b_dims.insert(b_dims.begin(), 1); } } dnnl::memory::desc a_md; dnnl::memory::desc b_md; bool transA = GetTransA(node); bool transB = GetTransB(node); dnnl::memory::dim M = (transA) ? a_dims[1] : a_dims[0]; dnnl::memory::dim K = (transA) ? a_dims[0] : a_dims[1]; dnnl::memory::dim N = (transB) ? b_dims[0] : b_dims[1]; dnnl::memory::dims a_strides = (transA) ? dnnl::memory::dims{dnnl::memory::dim(1), M} : dnnl::memory::dims{K, dnnl::memory::dim(1)}; dnnl::memory::dims b_strides = (transB) ? dnnl::memory::dims{dnnl::memory::dim(1), K} : dnnl::memory::dims{N, dnnl::memory::dim(1)}; a_md = dnnl::memory::desc({M, K}, node.Input(IN_A).Type(), a_strides); b_md = dnnl::memory::desc({K, N}, node.Input(IN_B).Type(), b_strides); dnnl::memory::dims output_shape{M, N}; dnnl::primitive_attr matmul_attr; // scale the output from MatMul to alpha float alpha = GetAlpha(node); std::vector<float> alphaScale({alpha}); matmul_attr.set_output_scales(0, alphaScale); auto matmul_dst_md = dnnl::memory::desc(output_shape, node.Output(OUT_Y).Type(), {N, 1}); auto matmul_d = dnnl::matmul::desc(a_md, b_md, matmul_dst_md); dnnl::matmul::primitive_desc matmul_pd; matmul_pd = dnnl::matmul::primitive_desc(matmul_d, matmul_attr, eng); auto matmul_a_mem = sp.GetMemoryAndReshape(node.Input(IN_A), matmul_pd.src_desc(), eng, transA); auto matmul_b_mem = sp.GetMemoryAndReshape(node.Input(IN_B), matmul_pd.weights_desc(), eng, transB); auto gemm_dst_mem = dnnl::memory(matmul_pd.dst_desc(), eng); auto matmul_op = dnnl::matmul(matmul_pd); std::unordered_map<int, dnnl::memory> args; args.insert({DNNL_ARG_SRC, matmul_a_mem}); args.insert({DNNL_ARG_WEIGHTS, matmul_b_mem}); args.insert({DNNL_ARG_DST, gemm_dst_mem}); sp.AddPrimitive(matmul_op, args); if (input_c_exists) { auto c_original_md = sp.GetMemory(node.Input(IN_C)).get_desc(); auto c_dims = c_original_md.dims(); if (c_dims.size() != a_dims.size()) { while (c_dims.size() < a_dims.size()) { c_dims.insert(c_dims.begin(), 1); } } auto c_md = c_original_md.reshape(c_dims); auto y_md = dnnl::memory::desc(output_shape, node.Output(OUT_Y).Type(), dnnl::memory::format_tag::any); auto binary_d = dnnl::binary::desc(dnnl::algorithm::binary_add, matmul_pd.dst_desc(), c_md, y_md); // Scale input C by beta before adding it to the MatMul output. dnnl::primitive_attr binary_attr; float beta = GetBeta(node); binary_attr.set_scales(DNNL_ARG_SRC_1, 0, {beta}); auto binary_pd = dnnl::binary::primitive_desc(binary_d, binary_attr,eng); auto binary_c_mem = sp.GetMemoryAndReshape(node.Input(IN_C), binary_pd.src1_desc(), eng); auto binary_op = dnnl::binary(binary_pd); sp.AddPrimitive(binary_op, {{DNNL_ARG_SRC_0, gemm_dst_mem}, {DNNL_ARG_SRC_1, binary_c_mem}, {DNNL_ARG_DST, gemm_dst_mem}}); } sp.SetMemory(node.Output(OUT_Y), gemm_dst_mem); } float DnnlGemm::GetAlpha(DnnlNode& node) { auto attr = node.Attributes().find("alpha"); if (attr != node.Attributes().end()) { return attr->second().f(); } return 1.0; } float DnnlGemm::GetBeta(DnnlNode& node) { auto attr = node.Attributes().find("beta"); if (attr != node.Attributes().end()) { return attr->second().f(); } return 1.0; } bool DnnlGemm::GetTransA(DnnlNode& node) { auto attr = node.Attributes().find("transA"); if (attr != node.Attributes().end()) { return (attr->second().i() != 0); } return false; } bool DnnlGemm::GetTransB(DnnlNode& node) { auto attr = node.Attributes().find("transB"); if (attr != node.Attributes().end()) { return (attr->second().i() != 0); } return false; } } // namespace ort_dnnl } // namespace onnxruntime
2,954
1,444
<reponame>amc8391/mage<filename>Mage.Tests/src/test/java/org/mage/test/mulligan/VancouverMulliganTest.java package org.mage.test.mulligan; import mage.game.mulligan.MulliganType; import org.junit.Test; import java.util.HashSet; import java.util.Set; import java.util.UUID; import static org.junit.Assert.assertEquals; public class VancouverMulliganTest extends MulliganTestBase { @Test public void testVancouverMulligan_NoMulligan() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 0); Set<UUID> hand1 = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return false; }); scenario.run(() -> { scenario.assertSizes(7, 33); assertEquals(hand1, scenario.getHand()); }); } @Test public void testVancouverMulligan_OneMulligan() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 0); Set<UUID> hand1 = new HashSet<>(); Set<UUID> hand2 = new HashSet<>(); Set<UUID> scry = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); hand2.addAll(scenario.getHand()); return false; }); scenario.scry(() -> { assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); assertEquals(hand2, new HashSet<>(scenario.getHand())); scry.add(scenario.getLibraryTopCard()); return false; }); scenario.run(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); assertEquals(hand2, new HashSet<>(scenario.getHand())); assertEquals(scry, new HashSet<>(scenario.getNTopOfLibrary(1))); }); } @Test public void testVancouverMulligan_OneMulligan_Scry() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 0); Set<UUID> hand1 = new HashSet<>(); Set<UUID> hand2 = new HashSet<>(); Set<UUID> scry = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); hand2.addAll(scenario.getHand()); return false; }); scenario.scry(() -> { assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); assertEquals(hand2, new HashSet<>(scenario.getHand())); scry.add(scenario.getLibraryTopCard()); return true; }); scenario.run(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(26, 7))); assertEquals(hand2, new HashSet<>(scenario.getHand())); assertEquals(scry, new HashSet<>(scenario.getNBottomOfLibrary(1))); }); } @Test public void testVancouverMulligan_FreeMulligan_NoMulligan() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 1); Set<UUID> hand1 = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return false; }); scenario.run(() -> { scenario.assertSizes(7, 33); assertEquals(hand1, scenario.getHand()); }); } @Test public void testVancouverMulligan_FreeMulligan_OneMulligan() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 1); Set<UUID> hand1 = new HashSet<>(); Set<UUID> hand2 = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand2.addAll(scenario.getHand()); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(26, 7))); return false; }); scenario.run(() -> { scenario.assertSizes(7, 33); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(26, 7))); assertEquals(hand2, new HashSet<>(scenario.getHand())); }); } @Test public void testVancouverMulligan_FreeMulligan_TwoMulligan() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 1); Set<UUID> hand1 = new HashSet<>(); Set<UUID> hand2 = new HashSet<>(); Set<UUID> hand3 = new HashSet<>(); Set<UUID> scry = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(7, 33); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(26, 7))); hand2.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(20, 7))); assertEquals(hand2, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); hand3.addAll(scenario.getHand()); return false; }); scenario.scry(() -> { assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(20, 7))); assertEquals(hand2, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); assertEquals(hand3, new HashSet<>(scenario.getHand())); scry.add(scenario.getLibraryTopCard()); return false; }); scenario.run(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(20, 7))); assertEquals(hand2, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); assertEquals(hand3, new HashSet<>(scenario.getHand())); assertEquals(scry, new HashSet<>(scenario.getNTopOfLibrary(1))); }); } @Test public void testVancouverMulligan_FreeMulligan_TwoMulligan_Scry() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 1); Set<UUID> hand1 = new HashSet<>(); Set<UUID> hand2 = new HashSet<>(); Set<UUID> hand3 = new HashSet<>(); Set<UUID> scry = new HashSet<>(); scenario.mulligan(() -> { scenario.assertSizes(7, 33); hand1.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(7, 33); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(26, 7))); hand2.addAll(scenario.getHand()); return true; }); scenario.mulligan(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(20, 7))); assertEquals(hand2, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); hand3.addAll(scenario.getHand()); return false; }); scenario.scry(() -> { assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(20, 7))); assertEquals(hand2, new HashSet<>(scenario.getLibraryRangeSize(27, 7))); assertEquals(hand3, new HashSet<>(scenario.getHand())); scry.add(scenario.getLibraryTopCard()); return true; }); scenario.run(() -> { scenario.assertSizes(6, 34); assertEquals(hand1, new HashSet<>(scenario.getLibraryRangeSize(19, 7))); assertEquals(hand2, new HashSet<>(scenario.getLibraryRangeSize(26, 7))); assertEquals(hand3, new HashSet<>(scenario.getHand())); assertEquals(scry, new HashSet<>(scenario.getNBottomOfLibrary(1))); }); } @Test public void testVancouverMulligan_AlwaysMulligan() { MulliganScenarioTest scenario = new MulliganScenarioTest(MulliganType.VANCOUVER, 0); scenario.mulligan(() -> { scenario.assertSizes(7, 33); return true; }); scenario.mulligan(() -> { scenario.assertSizes(6, 34); return true; }); scenario.mulligan(() -> { scenario.assertSizes(5, 35); return true; }); scenario.mulligan(() -> { scenario.assertSizes(4, 36); return true; }); scenario.mulligan(() -> { scenario.assertSizes(3, 37); return true; }); scenario.mulligan(() -> { scenario.assertSizes(2, 38); return true; }); scenario.mulligan(() -> { scenario.assertSizes(1, 39); return true; }); scenario.scry(() -> { scenario.assertSizes(0, 40); return false; }); scenario.run(() -> { scenario.assertSizes(0, 40); }); } }
4,711
416
// // NFCNDEFReaderSession.h // CoreNFC // // Copyright © 2017 Apple. All rights reserved. // #ifndef NFCNDEFReaderSession_h #define NFCNDEFReaderSession_h #ifndef CoreNFC_H #error Please import <CoreNFC/CoreNFC.h> from your source file #endif #import <Foundation/Foundation.h> @class NFCReaderSession; @class NFCNDEFReaderSession; NS_ASSUME_NONNULL_BEGIN /*! * @discussion Type Name Format value defined by NFC Data Exchange Format (NDEF) Technical Specification * from NFC Forum. */ typedef NS_ENUM(uint8_t, NFCTypeNameFormat) { NFCTypeNameFormatEmpty = 0x00, NFCTypeNameFormatNFCWellKnown = 0x01, NFCTypeNameFormatMedia = 0x02, NFCTypeNameFormatAbsoluteURI = 0x03, NFCTypeNameFormatNFCExternal = 0x04, NFCTypeNameFormatUnknown = 0x05, NFCTypeNameFormatUnchanged = 0x06 }; /*! * @class NFCNDEFPayload * * @discussion A NDEF message payload consists of Type Name Format, Type, Payload Identifier, and Payload data. */ API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, macos, tvos) @interface NFCNDEFPayload : NSObject<NSSecureCoding> @property (nonatomic, assign) NFCTypeNameFormat typeNameFormat; @property (nonatomic, copy) NSData *type; @property (nonatomic, copy) NSData *identifier; @property (nonatomic, copy) NSData *payload; - (instancetype)init NS_UNAVAILABLE; @end /*! * @class NFCNDEFMessage * * @discussion A NDEF message consists of payload records. */ API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, macos, tvos) @interface NFCNDEFMessage : NSObject<NSSecureCoding> @property (nonatomic, copy) NSArray<NFCNDEFPayload *>* records; - (instancetype)init NS_UNAVAILABLE; @end /*! * @protocol NFCNDEFReaderSessionDelegate * * @discussion NDEF reader session callbacks. */ API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, macos, tvos) @protocol NFCNDEFReaderSessionDelegate <NSObject> @required /*! * @method readerSession:didInvalidateWithError: * * @param session The session object that is invalidated. * @param error The error indicates the invalidation reason. * * @discussion Gets called when a session becomes invalid. At this point the client is expected to discard * the returned session object. */ - (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error; /*! * @method readerSession:didDetectNDEFs: * * @param session The session object used for tag detection. * @param messages Array of @link NFCNDEFMessage @link/ objects. The order of the discovery on the tag is maintained. * * @discussion Gets called when the reader detects NFC tag(s) with NDEF messages in the polling sequence. Polling * is automatically restarted once the detected tag is removed from the reader's read range. */ - (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray<NFCNDEFMessage *> *)messages; @end #pragma mark - NDEF reader session /*! * @class NFCNDEFReaderSession * * @discussion Reader session for processing NFC Data Exchange Format (NDEF) tags. This session requires the "com.apple.developer.nfc.readersession.formats" * entitlement in your process. In addition your application's Info.plist must contain a non-empty usage description string. * * NOTE: * Only one NFCReaderSession can be active at any time in the system. Subsequent opened sessions will get queued up and processed by the system in FIFO order. */ API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, macos, tvos) @interface NFCNDEFReaderSession : NFCReaderSession /*! * @property readingAvailable * * @discussion YES if device supports NFC tag reading. */ @property (class, nonatomic, readonly) BOOL readingAvailable; - (instancetype)init NS_UNAVAILABLE; /*! * @method initWithDelegate:queue: * * @param delegate The session will hold a weak ARC reference to this @link NFCNDEFReaderSessionDelegate @link/ object. * @param queue A dispatch queue where NFCNDEFReaderSessionDelegate delegate callbacks will be dispatched to. A <i>nil</i> value will * cause the creation of a serial dispatch queue internally for the session. The session object will retain the provided dispatch queue. * @param invalidateAfterFirstRead Session will automatically invalidate after the first NDEF tag is read successfully when this is set to YES, and -readerSession:didInvalidateWithError: * will return NFCReaderSessionInvalidationErrorFirstNDEFTagRead in this case. * * @return A new NFCNDEFReaderSession instance. * * @discussion A NDEF reader session will automatically scan and detect NFC Forum tags that contain a valid NDEF message. NFC Forum Tag type 1 to 5 that * is NDEF formatted are supported. A modal system UI will present once -beginSession is called to inform the start of the session; the UI sheet * is automatically dismissed when the session is invalidated either by the user or by calling -invalidateSession. The alertMessage property shall be set * prior to -beginSession to display a message on the action sheet UI for the tag scanning operation. * * The reader session has the following properties: * + An opened session has a 60 seconds time limit restriction after -beginSession is called; -readerSession:didInvalidateWithError: will return * NFCReaderSessionInvalidationErrorSessionTimeout error when the time limit is reached. * + Only 1 active reader session is allowed in the system; -readerSession:didInvalidateWithError: will return NFCReaderSessionInvalidationErrorSystemIsBusy * when a new reader session is initiated by -beginSession when there is an active reader session. * + -readerSession:didInvalidateWithError: will return NFCReaderSessionInvalidationErrorUserCanceled when user clicks on the done button on the UI. * + -readerSession:didInvalidateWithError: will return NFCReaderSessionInvalidationErrorSessionTerminatedUnexpectedly when the client application enters * the background state. * + -readerSession:didInvalidateWithError: will return NFCReaderErrorUnsupportedFeature when 1) reader mode feature is not available on the hardware, * 2) client application does not have the required entitlement. */ - (instancetype)initWithDelegate:(id<NFCNDEFReaderSessionDelegate>)delegate queue:(nullable dispatch_queue_t)queue invalidateAfterFirstRead:(BOOL)invalidateAfterFirstRead NS_DESIGNATED_INITIALIZER; NS_ASSUME_NONNULL_END @end #endif
2,263
678
<reponame>bzxy/cydia /** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/PhotoLibrary.framework/PhotoLibrary */ #import <PhotoLibrary/PhotoLibrary-Structs.h> #import <PhotoLibrary/XXUnknownSuperclass.h> @interface PLReorientingButton : XXUnknownSuperclass { BOOL _autorotationEnabled; // 139 = 0x8b BOOL _watchingOrientationChanges; // 140 = 0x8c int _orientation; // 144 = 0x90 float _hitRectExtension; // 148 = 0x94 BOOL _animatingOrientationChange; // 152 = 0x98 float _endCapRadius; // 156 = 0x9c CGPoint _defaultAnchorCenter; // 160 = 0xa0 CGAffineTransform _defaultAnchorTransform; // 168 = 0xa8 } @property(assign, nonatomic) BOOL autorotationEnabled; // G=0xb8525; S=0xb8535; @synthesize=_autorotationEnabled @property(assign, nonatomic) float endCapRadius; // G=0xb9421; S=0xb9431; @synthesize=_endCapRadius @property(assign, nonatomic) float hitRectExtension; // G=0xb9401; S=0xb9411; @synthesize=_hitRectExtension // declared property setter: - (void)setEndCapRadius:(float)radius; // 0xb9431 // declared property getter: - (float)endCapRadius; // 0xb9421 // declared property setter: - (void)setHitRectExtension:(float)extension; // 0xb9411 // declared property getter: - (float)hitRectExtension; // 0xb9401 - (int)_modeForRotationFromOrientation:(int)orientation toOrientation:(int)orientation2; // 0xb9345 - (void)setButtonOrientation:(int)orientation animated:(BOOL)animated; // 0xb90bd - (void)rotationAnimationDidStop; // 0xb906d - (void)_setAnchorPoint:(CGPoint)point rotationMode:(int)mode; // 0xb8e55 - (CGAffineTransform)transformForOrientation:(int)orientation; // 0xb8e25 - (CGAffineTransform)_transformForOrientation:(int)orientation rotationMode:(int)mode; // 0xb8a95 - (void)_deviceOrientationChanged:(id)changed; // 0xb8775 - (void)stopWatchingDeviceOrientationChanges; // 0xb86e9 - (void)startWatchingDeviceOrientationChanges; // 0xb8625 - (BOOL)pointInside:(CGPoint)inside withEvent:(id)event; // 0xb85e9 - (CGRect)hitRect; // 0xb8589 // declared property setter: - (void)setAutorotationEnabled:(BOOL)enabled; // 0xb8535 // declared property getter: - (BOOL)autorotationEnabled; // 0xb8525 - (id)initWithFrame:(CGRect)frame; // 0xb8225 @end
828
2,267
// SPDX-License-Identifier: MPL-2.0 // Copyright (c) <NAME> <<EMAIL>> #pragma once #include <stdbool.h> // Older version of glx.h defines function prototypes for these extensions... // Rename them to avoid conflicts #define glXSwapIntervalMESA glXSwapIntervalMESA_ #define glXBindTexImageEXT glXBindTexImageEXT_ #define glXReleaseTexImageEXT glXReleaseTexImageEXT #include <GL/glx.h> #undef glXSwapIntervalMESA #undef glXBindTexImageEXT #undef glXReleaseTexImageEXT #include <X11/Xlib.h> #include <xcb/xcb.h> #include <xcb/render.h> #include "log.h" #include "compiler.h" #include "utils.h" #include "x.h" struct glx_fbconfig_info { GLXFBConfig cfg; int texture_tgts; int texture_fmt; int y_inverted; }; /// The search criteria for glx_find_fbconfig struct glx_fbconfig_criteria { /// Bit width of the red component int red_size; /// Bit width of the green component int green_size; /// Bit width of the blue component int blue_size; /// Bit width of the alpha component int alpha_size; /// The depth of X visual int visual_depth; }; struct glx_fbconfig_info *glx_find_fbconfig(Display *, int screen, struct xvisual_info); struct glxext_info { bool initialized; bool has_GLX_SGI_video_sync; bool has_GLX_SGI_swap_control; bool has_GLX_OML_sync_control; bool has_GLX_MESA_swap_control; bool has_GLX_EXT_swap_control; bool has_GLX_EXT_texture_from_pixmap; bool has_GLX_ARB_create_context; bool has_GLX_EXT_buffer_age; bool has_GLX_MESA_query_renderer; }; extern struct glxext_info glxext; extern PFNGLXGETVIDEOSYNCSGIPROC glXGetVideoSyncSGI; extern PFNGLXWAITVIDEOSYNCSGIPROC glXWaitVideoSyncSGI; extern PFNGLXGETSYNCVALUESOMLPROC glXGetSyncValuesOML; extern PFNGLXWAITFORMSCOMLPROC glXWaitForMscOML; extern PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT; extern PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI; extern PFNGLXSWAPINTERVALMESAPROC glXSwapIntervalMESA; extern PFNGLXBINDTEXIMAGEEXTPROC glXBindTexImageEXT; extern PFNGLXRELEASETEXIMAGEEXTPROC glXReleaseTexImageEXT; extern PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB; #ifdef GLX_MESA_query_renderer extern PFNGLXQUERYCURRENTRENDERERINTEGERMESAPROC glXQueryCurrentRendererIntegerMESA; #endif void glxext_init(Display *, int screen);
900
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_CELLBINDINGHANDLER_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_CELLBINDINGHANDLER_HXX #include "propertyhandler.hxx" /** === begin UNO includes === **/ #include <com/sun/star/lang/XMultiServiceFactory.hpp> /** === end UNO includes === **/ #include <rtl/ref.hxx> #include <memory> //........................................................................ namespace pcr { //........................................................................ class CellBindingHelper; class IPropertyEnumRepresentation; //==================================================================== //= CellBindingPropertyHandler //==================================================================== class CellBindingPropertyHandler; typedef HandlerComponentBase< CellBindingPropertyHandler > CellBindingPropertyHandler_Base; class CellBindingPropertyHandler : public CellBindingPropertyHandler_Base { private: ::std::auto_ptr< CellBindingHelper > m_pHelper; ::rtl::Reference< IPropertyEnumRepresentation > m_pCellExchangeConverter; public: CellBindingPropertyHandler( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext ); static ::rtl::OUString SAL_CALL getImplementationName_static( ) throw (::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_static( ) throw (::com::sun::star::uno::RuntimeException); protected: ~CellBindingPropertyHandler(); protected: // XPropertyHandler overriables virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& _rPropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL convertToPropertyValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rControlValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL convertToControlValue( const ::rtl::OUString& _rPropertyName, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getActuatingProperties( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL actuatingPropertyChanged( const ::rtl::OUString& _rActuatingPropertyName, const ::com::sun::star::uno::Any& _rNewValue, const ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI, sal_Bool _bFirstTimeInit ) throw (::com::sun::star::lang::NullPointerException, ::com::sun::star::uno::RuntimeException); // PropertyHandler overridables virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL doDescribeSupportedProperties() const; virtual void onNewComponent(); private: /** updates a property (UI) whose state depends on more than one other property ->actuatingPropertyChanged is called for certain properties in whose changes we expressed interes (->getActuatingProperty). Now such a property change can result in simple UI updates, for instance another property being enabled or disabled. However, it can also result in a more complex change: The current (UI) state might depend on the value of more than one other property. Those dependent properties (their UI, more precisely) are updated in this method. @param _nPropid the ->PropertyId of the dependent property whose UI state is to be updated @param _rxInspectorUI provides access to the property browser UI. Must not be <NULL/>. */ void impl_updateDependentProperty_nothrow( PropertyId _nPropId, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XObjectInspectorUI >& _rxInspectorUI ) const; }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_CELLBINDINGHANDLER_HXX
1,912
2,801
<gh_stars>1000+ from __future__ import print_function, unicode_literals import mock from zope.interface import alsoProvides from ..._interfaces import IDilationManager, IWormhole def mock_manager(): m = mock.Mock() alsoProvides(m, IDilationManager) return m def mock_wormhole(): m = mock.Mock() alsoProvides(m, IWormhole) return m def clear_mock_calls(*args): for a in args: a.mock_calls[:] = []
170
416
<reponame>Zi0P4tch0/sdks // // HKQuantityAggregationStyle.h // HealthKit // // Copyright (c) 2013-2018 Apple Inc. All rights reserved. // #import <Foundation/Foundation.h> /*! @enum HKQuantityAggregationStyle @discussion Describes how quantities can be aggregated over time. @constant HKQuantityAggregationStyleCumulative Samples may be summed over a time interval. @constant HKQuantityAggregationStyleDiscreteArithmetic Samples may be averaged over a time interval using the arithmetic mean @constant HKQuantityAggregationStyleDiscreteTemporallyWeighted Samples may be averaged over a time interval using a temporally weighted integration function @constant HKQuantityAggregationStyleDiscreteEquivalentContinuousLevel Samples may be combined over a time interval by computing the equivalent continuous sound level; see IEC 61672-1 */ typedef NS_ENUM(NSInteger, HKQuantityAggregationStyle) { HKQuantityAggregationStyleCumulative = 0, HKQuantityAggregationStyleDiscreteArithmetic API_AVAILABLE(ios(13.0), watchos(6.0)), HKQuantityAggregationStyleDiscrete API_DEPRECATED_WITH_REPLACEMENT("HKQuantityAggregationStyleDiscreteArithmetic", ios(8.0, 13.0), watchos(2.0, 6.0)) = HKQuantityAggregationStyleDiscreteArithmetic, HKQuantityAggregationStyleDiscreteTemporallyWeighted API_AVAILABLE(ios(13.0), watchos(6.0)), HKQuantityAggregationStyleDiscreteEquivalentContinuousLevel API_AVAILABLE(ios(13.0), watchos(6.0)), } API_AVAILABLE(ios(8.0), watchos(2.0));
525
3,428
{"id":"00483","group":"spam-2","checksum":{"type":"MD5","value":"e583ffb0efd3958cdef2e9f3b043ef0d"},"text":"From <EMAIL> Mon Jun 24 17:06:50 2002\nReturn-Path: [email protected]\nDelivery-Date: Mon May 27 18:16:38 2002\nReceived: from mandark.labs.netnoteinc.com ([213.105.180.140]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g4RHGUe22985 for\n <<EMAIL>>; Mon, 27 May 2002 18:16:30 +0100\nReceived: from newperseus.play.tld ([194.145.22.211]) by\n mandark.labs.netnoteinc.com (8.11.2/8.11.2) with ESMTP id g4RHGR726106 for\n <<EMAIL>>; Mon, 27 May 2002 18:16:28 +0100\nReceived: from mx08.hotmail.com ([172.140.253.253]) by newperseus.play.tld\n with Microsoft SMTPSVC(5.0.2195.4453); Mon, 27 May 2002 17:52:50 +0100\nMessage-Id: <<EMAIL>>\nTo: <<EMAIL>>\nCc: <<EMAIL>>, <<EMAIL>>, <<EMAIL>>, <<EMAIL>>,\n <<EMAIL>>, <<EMAIL>>, <<EMAIL>>\nFrom: \"Sarah\" <<EMAIL>>\nSubject: Herbal Viagra 30 day trial... ONCXBV\nDate: Mon, 27 May 2002 09:58:57 -1900\nMIME-Version: 1.0\nReply-To: <EMAIL>\nX-Originalarrivaltime: 27 May 2002 16:52:51.0320 (UTC) FILETIME=[F03B8780:01C2059E]\nX-Keywords: \nContent-Type: text/html; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: quoted-printable\n\n<HTML>\n<HEAD>\n<TITLE>ViaPro</TITLE>\n</HEAD>\n<BODY BGCOLOR=3D\"#FFFFFF\">\n<CENTER><TABLE BORDER=3D\"0\" CELLPADDING=3D\"0\"\nCELLSPACING=3D\"0\" WIDTH=3D\"502\">\n<TR>\n<TD VALIGN=3DTOP>\n<a href=3D\"http://www.thepill4u.com/v609.html\">\n<IMG SRC=3D\"http://www.thepill4u.com/mail/1_1.jpg\"\nWIDTH=3D\"226\" HEIGHT=3D\"183\" BORDER=3D\"0\"></a></TD>\n<TD VALIGN=3DTOP>\n<a href=3D\"http://www.thepill4u.com/v609.html\">\n<IMG SRC=3D\"http://www.thepill4u.com/mail/2_1.gif\"\nWIDTH=3D\"276\" HEIGHT=3D\"183\" BORDER=3D\"0\"></a></TD>\n</TR>\n<TR>\n<TD COLSPAN=3D\"2\" VALIGN=3DTOP>\n<a href=3D\"http://www.thepill4u.com/v609.html\">\n<IMG SRC=3D\"http://www.thepill4u.com/mail/1_1-2.gif\"\nWIDTH=3D\"502\" HEIGHT=3D\"126\" BORDER=3D\"0\"></a></TD>\n</TR></TABLE></CENTER><br><br>\n<font face=3D\"arial,verdana\" size=3D1.5 color=3D\"#8182AB\"><p\nalign=3D\"center\">\n<a href=3D\"http://www.herbs4you.net/service.html\">exit\nlist instructions</a></p></font>\n\n</BODY>\n</HTML>\npmoney\n\n\n\n\n\n"}
1,090
918
/* * 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.gobblin.source.extractor.hadoop; import java.io.IOException; import java.util.List; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import lombok.extern.slf4j.Slf4j; import org.apache.gobblin.configuration.ConfigurationKeys; import org.apache.gobblin.configuration.State; import org.apache.gobblin.configuration.WorkUnitState; import org.apache.gobblin.source.extractor.Extractor; import org.apache.gobblin.source.extractor.filebased.FileBasedHelperException; import org.apache.gobblin.source.extractor.filebased.FileBasedSource; @Slf4j public class AvroFileSource extends FileBasedSource<Schema, GenericRecord> { @Override public Extractor<Schema, GenericRecord> getExtractor(WorkUnitState state) throws IOException { return new AvroFileExtractor(state); } @Override public void initFileSystemHelper(State state) throws FileBasedHelperException { this.fsHelper = new AvroFsHelper(state); this.fsHelper.connect(); } @Override public List<String> getcurrentFsSnapshot(State state) { List<String> results; String path = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY); try { log.info("Running ls command with input " + path); results = this.fsHelper.ls(path); } catch (FileBasedHelperException e) { String errMsg = String.format( "Not able to run ls command due to %s. Will not pull any files", e.getMessage()); log.error(errMsg, e); throw new RuntimeException(errMsg, e); } return results; } }
722
852
#ifndef GlobalGridWrapper_h #define GlobalGridWrapper_h /** \class GlobalGridWrapper * * Generic interpolator that is a wrapper of MagneticFieldGrid, i.e. * non-specialized/optimized for each kind of grid. * * \author <NAME> */ #include "FWCore/Utilities/interface/Visibility.h" #include "MagneticField/Interpolation/interface/MFGrid.h" #include <string> class binary_ifstream; class MagneticFieldGrid; class dso_internal GlobalGridWrapper : public MFGrid { public: GlobalGridWrapper(const GloballyPositioned<float>& vol, const std::string& fileName); LocalVector valueInTesla(const LocalPoint& p) const override; void dump() const override; void toGridFrame(const LocalPoint& p, double& a, double& b, double& c) const override; LocalPoint fromGridFrame(double a, double b, double c) const override; Dimensions dimensions() const override; LocalPoint nodePosition(int i, int j, int k) const override; LocalVector nodeValue(int i, int j, int k) const override; private: MagneticFieldGrid* theRealOne; }; #endif
322
1,092
<gh_stars>1000+ /* * Copyright 2014-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.restdocs.payload; import java.io.IOException; import java.util.Map; import org.springframework.http.MediaType; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.snippet.Snippet; /** * A {@link Snippet} that documents the body of a response. * * @author <NAME> */ public class ResponseBodySnippet extends AbstractBodySnippet { /** * Creates a new {@code ResponseBodySnippet}. */ public ResponseBodySnippet() { this(null, null); } /** * Creates a new {@code ResponseBodySnippet} that will document the subsection of the * response body extracted by the given {@code subsectionExtractor}. * @param subsectionExtractor the subsection extractor */ public ResponseBodySnippet(PayloadSubsectionExtractor<?> subsectionExtractor) { this(subsectionExtractor, null); } /** * Creates a new {@code ResponseBodySnippet} with the given additional * {@code attributes} that will be included in the model during template rendering. * @param attributes the additional attributes */ public ResponseBodySnippet(Map<String, Object> attributes) { this(null, attributes); } /** * Creates a new {@code ResponseBodySnippet} that will document the subsection of the * response body extracted by the given {@code subsectionExtractor}. The given * additional {@code attributes} that will be included in the model during template * rendering. * @param subsectionExtractor the subsection extractor * @param attributes the additional attributes */ public ResponseBodySnippet(PayloadSubsectionExtractor<?> subsectionExtractor, Map<String, Object> attributes) { super("response", subsectionExtractor, attributes); } @Override protected byte[] getContent(Operation operation) throws IOException { return operation.getResponse().getContent(); } @Override protected MediaType getContentType(Operation operation) { return operation.getResponse().getHeaders().getContentType(); } }
724
327
/* <NAME> `gentilkiwi` https://blog.gentilkiwi.com <EMAIL> Licence : https://creativecommons.org/licenses/by/4.0/ */ #pragma once #include "globals.h" #define MIMILOVE L"mimilove" #define MIMILOVE_VERSION L"1.0" #define MIMILOVE_CODENAME L"Love edition <3" #define MIMILOVE_FULL MIMILOVE L" " MIMILOVE_VERSION L" built on " TEXT(__DATE__) L" " TEXT(__TIME__) #define MIMILOVE_SECOND L"\"" MIMILOVE_CODENAME L"\"" #define MIMILOVE_SPECIAL L"Windows 2000 only! " #include "../modules/kull_m_output.h" #include "../modules/kull_m_memory.h" #include "../modules/kull_m_process.h" #include "../modules/kull_m_crypto_system.h" typedef struct _KULL_M_MINI_PATTERN { DWORD Length; BYTE *Pattern; LONG offset; } KULL_M_MINI_PATTERN, *PKULL_M_MINI_PATTERN; typedef struct _MSV1_0_PRIMARY_CREDENTIAL_50 { LSA_UNICODE_STRING LogonDomainName; LSA_UNICODE_STRING UserName; BYTE NtOwfPassword[LM_NTLM_HASH_LENGTH]; BYTE LmOwfPassword[LM_NTLM_HASH_LENGTH]; BOOLEAN isNtOwfPassword; BOOLEAN isLmOwfPassword; /* buffer */ } MSV1_0_PRIMARY_CREDENTIAL_50, *PMSV1_0_PRIMARY_CREDENTIAL_50; typedef struct _KIWI_MSV1_0_PRIMARY_CREDENTIALS { struct _KIWI_MSV1_0_PRIMARY_CREDENTIALS *next; ANSI_STRING Primary; LSA_UNICODE_STRING Credentials; } KIWI_MSV1_0_PRIMARY_CREDENTIALS, *PKIWI_MSV1_0_PRIMARY_CREDENTIALS; typedef struct _KIWI_MSV1_0_CREDENTIALS { struct _KIWI_MSV1_0_CREDENTIALS *next; DWORD AuthenticationPackageId; PKIWI_MSV1_0_PRIMARY_CREDENTIALS PrimaryCredentials; } KIWI_MSV1_0_CREDENTIALS, *PKIWI_MSV1_0_CREDENTIALS; typedef struct _KIWI_MSV1_0_ENTRY_50 { LUID LocallyUniqueIdentifier; LSA_UNICODE_STRING UserName; LSA_UNICODE_STRING Domaine; PVOID unk0; PVOID unk1; PSID pSid; ULONG LogonType; ULONG Session; DWORD align; FILETIME LogonTime; PKIWI_MSV1_0_CREDENTIALS Credentials; ULONG unk19; PVOID unk20; PVOID unk21; PVOID unk22; } KIWI_MSV1_0_ENTRY_50, *PKIWI_MSV1_0_ENTRY_50; typedef struct _KIWI_MSV1_0_LIST_50 { struct _KIWI_MSV1_0_LIST_50 *Flink; struct _KIWI_MSV1_0_LIST_50 *Blink; DWORD unk0; DWORD lowLuid; PKIWI_MSV1_0_ENTRY_50 entry; } KIWI_MSV1_0_LIST_50, *PKIWI_MSV1_0_LIST_50; typedef struct _KIWI_MSV1_0_LOGON_SESSION_TABLE_50 { // small DWORD tag; DWORD unk0; DWORD count; DWORD unk1; LIST_ENTRY list; // PKIWI_MSV1_0_LIST_50 PVOID unkDelete; DWORD unk2; DWORD unk3; DWORD unk4; DWORD unk5; DWORD unk6; DWORD unk7; } KIWI_MSV1_0_LOGON_SESSION_TABLE_50, *PKIWI_MSV1_0_LOGON_SESSION_TABLE_50; typedef struct _KERB_HASHPASSWORD_GENERIC { DWORD Type; SIZE_T Size; PBYTE Checksump; } KERB_HASHPASSWORD_GENERIC, *PKERB_HASHPASSWORD_GENERIC; typedef struct _KERB_HASHPASSWORD_5 { LSA_UNICODE_STRING salt; // http://tools.ietf.org/html/rfc3962 KERB_HASHPASSWORD_GENERIC generic; } KERB_HASHPASSWORD_5, *PKERB_HASHPASSWORD_5; typedef struct _KIWI_KERBEROS_KEYS_LIST_5 { DWORD unk0; // dword_1233EC8 dd 4 DWORD cbItem; // debug048:01233ECC dd 5 PVOID unk1; PVOID unk2; //KERB_HASHPASSWORD_5 KeysEntries[ANYSIZE_ARRAY]; } KIWI_KERBEROS_KEYS_LIST_5, *PKIWI_KERBEROS_KEYS_LIST_5; typedef struct _KIWI_KERBEROS_LOGON_SESSION_50 { LIST_ENTRY Entry; ULONG unk0; LUID LocallyUniqueIdentifier; ULONG unk6; ULONG unk7; ULONG unk8; PVOID unk9; ULONG unk10; PVOID unk11; PVOID unk12; PVOID unk13; PVOID unk14; LSA_UNICODE_STRING UserName; LSA_UNICODE_STRING Domaine; LSA_UNICODE_STRING Password; ULONG unk15; ULONG unk16; ULONG unk17; ULONG unk18; PVOID unk19; PVOID unk20; PVOID unk21; PVOID unk22; PKIWI_KERBEROS_KEYS_LIST_5 pKeyList; PVOID unk24; LIST_ENTRY Tickets_1; // for coders, they're here =) LIST_ENTRY Tickets_2; ULONG unk23; LIST_ENTRY Tickets_3; } KIWI_KERBEROS_LOGON_SESSION_50, *PKIWI_KERBEROS_LOGON_SESSION_50; int wmain(int argc, wchar_t *argv[]); BOOL kuhl_m_sekurlsa_utils_love_search(PKULL_M_PROCESS_VERY_BASIC_MODULE_INFORMATION mi, PKULL_M_MINI_PATTERN pa, PVOID * genericPtr); void mimilove_lsasrv(PKULL_M_MEMORY_HANDLE hMemory); void mimilove_kerberos(PKULL_M_MEMORY_HANDLE hMemory); PCWCHAR mimilove_kerberos_etype(LONG eType);
2,126
5,964
<gh_stars>1000+ // 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8ErrorEventInit.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/V8EventInit.h" namespace blink { void V8ErrorEventInit::toImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, ErrorEventInit& impl, ExceptionState& exceptionState) { if (isUndefinedOrNull(v8Value)) return; if (!v8Value->IsObject()) { exceptionState.throwTypeError("cannot convert to dictionary."); return; } V8EventInit::toImpl(isolate, v8Value, impl, exceptionState); if (exceptionState.hadException()) return; v8::TryCatch block(isolate); v8::Local<v8::Object> v8Object; if (!v8Call(v8Value->ToObject(isolate->GetCurrentContext()), v8Object, block)) { exceptionState.rethrowV8Exception(block.Exception()); return; } { v8::Local<v8::Value> colnoValue; if (!v8Object->Get(isolate->GetCurrentContext(), v8String(isolate, "colno")).ToLocal(&colnoValue)) { exceptionState.rethrowV8Exception(block.Exception()); return; } if (colnoValue.IsEmpty() || colnoValue->IsUndefined()) { // Do nothing. } else { unsigned colno = toUInt32(isolate, colnoValue, NormalConversion, exceptionState); if (exceptionState.hadException()) return; impl.setColno(colno); } } { v8::Local<v8::Value> errorValue; if (!v8Object->Get(isolate->GetCurrentContext(), v8String(isolate, "error")).ToLocal(&errorValue)) { exceptionState.rethrowV8Exception(block.Exception()); return; } if (errorValue.IsEmpty() || errorValue->IsUndefined()) { // Do nothing. } else { ScriptValue error = ScriptValue(ScriptState::current(isolate), errorValue); impl.setError(error); } } { v8::Local<v8::Value> filenameValue; if (!v8Object->Get(isolate->GetCurrentContext(), v8String(isolate, "filename")).ToLocal(&filenameValue)) { exceptionState.rethrowV8Exception(block.Exception()); return; } if (filenameValue.IsEmpty() || filenameValue->IsUndefined()) { // Do nothing. } else { V8StringResource<> filename = filenameValue; if (!filename.prepare(exceptionState)) return; impl.setFilename(filename); } } { v8::Local<v8::Value> linenoValue; if (!v8Object->Get(isolate->GetCurrentContext(), v8String(isolate, "lineno")).ToLocal(&linenoValue)) { exceptionState.rethrowV8Exception(block.Exception()); return; } if (linenoValue.IsEmpty() || linenoValue->IsUndefined()) { // Do nothing. } else { unsigned lineno = toUInt32(isolate, linenoValue, NormalConversion, exceptionState); if (exceptionState.hadException()) return; impl.setLineno(lineno); } } { v8::Local<v8::Value> messageValue; if (!v8Object->Get(isolate->GetCurrentContext(), v8String(isolate, "message")).ToLocal(&messageValue)) { exceptionState.rethrowV8Exception(block.Exception()); return; } if (messageValue.IsEmpty() || messageValue->IsUndefined()) { // Do nothing. } else { V8StringResource<> message = messageValue; if (!message.prepare(exceptionState)) return; impl.setMessage(message); } } } v8::Local<v8::Value> toV8(const ErrorEventInit& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) { v8::Local<v8::Object> v8Object = v8::Object::New(isolate); if (!toV8EventInit(impl, v8Object, creationContext, isolate)) return v8::Local<v8::Value>(); if (!toV8ErrorEventInit(impl, v8Object, creationContext, isolate)) return v8::Local<v8::Value>(); return v8Object; } bool toV8ErrorEventInit(const ErrorEventInit& impl, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) { if (impl.hasColno()) { if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "colno"), v8::Integer::NewFromUnsigned(isolate, impl.colno())))) return false; } if (impl.hasError()) { if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "error"), impl.error().v8Value()))) return false; } if (impl.hasFilename()) { if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "filename"), v8String(isolate, impl.filename())))) return false; } if (impl.hasLineno()) { if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "lineno"), v8::Integer::NewFromUnsigned(isolate, impl.lineno())))) return false; } if (impl.hasMessage()) { if (!v8CallBoolean(dictionary->CreateDataProperty(isolate->GetCurrentContext(), v8String(isolate, "message"), v8String(isolate, impl.message())))) return false; } return true; } ErrorEventInit NativeValueTraits<ErrorEventInit>::nativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { ErrorEventInit impl; V8ErrorEventInit::toImpl(isolate, value, impl, exceptionState); return impl; } } // namespace blink
2,687
2,329
/* * 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.shenyu.web.configuration; import org.apache.shenyu.web.handler.GlobalErrorHandler; import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.lang.NonNull; import org.springframework.web.filter.reactive.HiddenHttpMethodFilter; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; /** * The type Error handler configuration. */ public class ErrorHandlerConfiguration { /** * Error web exception handler error web exception handler. * * @return the error web exception handler */ @Bean @Order(Ordered.HIGHEST_PRECEDENCE + 1) public ErrorWebExceptionHandler errorWebExceptionHandler() { return new GlobalErrorHandler(); } /** * Hidden http method filter hidden http method filter. * * @see <a href="https://github.com/spring-cloud/spring-cloud-gateway/issues/541">issues-541</a> * @return the hidden http method filter */ @Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter() { return new HiddenHttpMethodFilter() { @Override @NonNull public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) { return chain.filter(exchange); } }; } }
736
821
<filename>packages/arb-avm-cpp/fuzz_target/manualtest.cpp<gh_stars>100-1000 /* * Copyright 2019, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "utils.hpp" #include <avm/machine.hpp> #include <fstream> #include <iomanip> #include <iostream> int main(int argc, char** argv) { if (argc < 2) { std::cerr << "Usage: ./manual_test [inputs...]" << std::endl; return -1; } ProofTester tester(true); for (size_t i = 1; i < argc; i++) { std::cerr << "Testing " << argv[i] << std::endl; std::ifstream file(argv[i], std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector<unsigned char> buffer(size); if (!file.read(reinterpret_cast<char*>(buffer.data()), size)) { std::cerr << "Failed to read input file" << std::endl; return -1; } auto machine = parseFuzzInput(buffer.data(), buffer.size()); { std::cerr << "Static value: " << machine.machine_state.static_val << std::endl; auto segment = machine.machine_state.code->loadCodeSegment(0); for (size_t i = 0; i < segment.op_count; i++) { auto code_point = segment.segment->loadCodePoint(segment.op_count - i - 1); std::cerr << std::setw(3) << i << std::setw(0) << " " << code_point.op << std::endl; } } tester.testMachine(machine); std::cerr << "Success" << std::endl; } return 0; }
917
643
# coding=utf-8 # Copyright 2021 The Meta-Dataset 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. # Lint as: python3 # pyformat: disable """Implementation of the criticality measures from [Chatterji et al. (2020)][1]. #### References [1]: Chatterji, <NAME>., <NAME>, and <NAME>. The intriguing role of module criticality in the generalization of deep networks. In _Proceedings of 8th International Conference on Learning Representations_, 2020. https://arxiv.org/abs/1912.00528 """ # pyformat: enable from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools from typing import Callable, Iterable import gin.tf import numpy as np import tensorflow as tf ModuleCriticalityAnalysis = collections.namedtuple( 'ModuleCriticalityAnalysis', ( 'criticality_score', 'alpha', 'sigma', 'loss_value', 'num_samples_per_iteration', 'alpha_grid_size', 'sigma_grid_size', 'sigma_ratio', 'initial_objective_value', 'final_objective_value', )) def relative_error_condition(error, reference_error, rtol = 1.01): return tf.reduce_mean(error) <= rtol * reference_error def _squared_frobenius_norm(t): return tf.reduce_sum(tf.square(t)) def _interpolate_and_perturb( alpha, sigma, params_init, params_final, objective_fn, num_samples_per_iteration, loss_threshold_condition, normalize_error, ): """Interpolate `params_init` and `params_final`, perturb, then evaluate. Args: alpha: The linear interpolation coefficient. sigma: The standard deviation of the Gaussian perturbations. params_init: The initial parameter settings, activated when `alpha` is zero. params_final: The final parameter settings, activated when `alpha` is one. objective_fn: A function that returns the objective value when passed an (interpolated) parameter value. num_samples_per_iteration: Number of perturbations to sample each iteration. loss_threshold_condition: A function that takes in a reference objective value and a candidate objective value and produces a thresholding decision. normalize_error: Whether to normalize the error that is minimized over in the definition of criticality by the Frobenius norm of the distance between initial and final parameters. Returns: The average loss of the interpolation across perturbations. """ # Linearly interpolate. params = ((1 - alpha) * param_init + alpha * param_final for param_init, param_final in zip(params_init, params_final)) # Resample perturbations and evaluate the objective. perturbed_losses = [] for _ in range(num_samples_per_iteration): perturbed_losses += [ objective_fn( (param + tf.random.normal(tf.shape(param), mean=0.0, stddev=sigma) for param in params)) ] # Compute the Frobenius norm between the final and initial parameter values. squared_distance_norm = tf.reduce_sum( tuple( _squared_frobenius_norm(param_final - param_init) for param_init, param_final in zip(params_init, params_final))) # Estimate the expected loss over perturbations. mean_perturbed_loss = tf.reduce_mean(perturbed_losses) # Note: This error normalization was not included in the final paper, but # was discussed as a variant that accounts for large differences in norms # between different parameter tensors. if normalize_error: # Normalize by the Frobenius norm of the parameter distance. mean_perturbed_loss /= tf.math.sqrt(squared_distance_norm) # Compute the weighted norm in the definition of criticality. weighted_squared_distance_norm = ((alpha / sigma)**2 * squared_distance_norm) return ( loss_threshold_condition(mean_perturbed_loss), mean_perturbed_loss, weighted_squared_distance_norm, ) @gin.configurable( allowlist=( 'num_samples_per_iteration', 'alpha_grid_size', 'sigma_grid_size', 'sigma_ratio', 'loss_threshold_condition', 'normalize_error', )) def compute_module_criticality( objective_fn, module_variables_init, module_variables_final, num_samples_per_iteration=10, alpha_grid_size=10, sigma_grid_size=10, sigma_ratio=1.0, loss_threshold_condition=relative_error_condition, normalize_error=False, ): """Compute the criticality of a module parameterized by `module_variables`. Args: objective_fn: A callable that takes in an iterable of the module-specific variables and produces the value of the objective function. module_variables_init: A list of tf.Tensors; the variables of the module at initialization. module_variables_final: A list of tf.Tensors; the variables of the module at convergence. num_samples_per_iteration: Number of perturbations to sample each iteration. alpha_grid_size: The number of values to test for alpha, the interpolation coefficient. sigma_grid_size: The number of values to test for sigma, the standard deviation of the perturbation. sigma_ratio: Positive scalar multiplier k for values of sigma, to enforce that the tested values of sigma lie in [k * 1e-16, k]; the default is 1.0, implying that the tested values of sigma lie in the interval [1e-16, 1]. loss_threshold_condition: A callable that takes in a reference objective value and a candidate objective value and produces a thresholding decision. normalize_error: Whether to normalize the error that is minimized over in the definition of criticality by the Frobenius norm of the distance between initial and final parameters. Returns: A `collections.NamedTuple` that contains the results of the criticality analysis. """ initial_objective_value = objective_fn(module_variables_init) final_objective_value = objective_fn(module_variables_final) # Test a 2D grid of alpha and sigma values. float_zero = tf.cast(0, tf.float32) alphas, sigmas = tf.meshgrid( tf.linspace(float_zero, 1, alpha_grid_size + 1), tf.linspace(float_zero + 1e-16, 1, sigma_grid_size + 1) * sigma_ratio, ) alphas, sigmas = tf.reshape(alphas, [-1]), tf.reshape(sigmas, [-1]) def _evaluate_alpha_sigma(alpha_sigma): alpha, sigma = alpha_sigma return _interpolate_and_perturb( alpha=alpha, sigma=sigma, params_init=module_variables_init, params_final=module_variables_final, objective_fn=objective_fn, loss_threshold_condition=functools.partial( loss_threshold_condition, reference_error=final_objective_value), normalize_error=normalize_error, num_samples_per_iteration=num_samples_per_iteration, ) (threshold_conditions, interpolated_and_perturbed_losses, interpolated_and_perturbed_norms) = tf.map_fn( _evaluate_alpha_sigma, elems=(alphas, sigmas), dtype=(tf.bool, tf.float32, tf.float32), ) masked_interpolated_and_perturbed_norms = tf.where( threshold_conditions, interpolated_and_perturbed_norms, tf.ones_like(interpolated_and_perturbed_norms) * np.inf) idx_min = tf.math.argmin(masked_interpolated_and_perturbed_norms) (loss_final, norm_final, alpha_final, sigma_final) = (interpolated_and_perturbed_losses[idx_min], interpolated_and_perturbed_norms[idx_min], alphas[idx_min], sigmas[idx_min]) return ModuleCriticalityAnalysis( criticality_score=norm_final, alpha=alpha_final, sigma=sigma_final, loss_value=loss_final, num_samples_per_iteration=num_samples_per_iteration, alpha_grid_size=alpha_grid_size, sigma_grid_size=sigma_grid_size, sigma_ratio=sigma_ratio, initial_objective_value=initial_objective_value, final_objective_value=final_objective_value, ) NetworkCriticalityAnalysis = collections.namedtuple( 'NetworkCriticalityAnalysis', ( 'network_criticality_score', 'module_criticality_analyses', )) def compute_network_criticality( parameters, module_objective_fn, init_loop_variables_mapping, final_loop_variables_mapping, ): """Compute the criticality of a network parameterized by `parameters`.""" def _module_criticality_by_ref(layer_ref): return compute_module_criticality( functools.partial( module_objective_fn, module_variable_refs_=(layer_ref,), ), (init_loop_variables_mapping[layer_ref],), (final_loop_variables_mapping[layer_ref],), ) layer_refs = tuple(layer.experimental_ref() for layer in parameters) module_criticality_analyses = map(_module_criticality_by_ref, layer_refs) network_criticality = sum( module_criticality_analysis.criticality_score for module_criticality_analysis in module_criticality_analyses) return NetworkCriticalityAnalysis( network_criticality_score=network_criticality, module_criticality_analyses=dict( zip( (layer.name for layer in parameters), module_criticality_analyses, )))
3,615
1,262
<gh_stars>1000+ /* * Copyright 2013 <NAME> <<EMAIL>> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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, see <http://www.gnu.org/licenses/>. */ #include "languagemenu.h" #include <spellchecker/dictionary.h> #include "hunspell/spellchecker.h" LanguageMenu::LanguageMenu(QWidget *parent) : QMenu(tr("Languages"), parent), dictionariesGroup(new QActionGroup(this)) { } void LanguageMenu::loadDictionaries(const QString &currentLanguage) { QMap<QString, Dictionary> dictionaries = hunspell::SpellChecker::availableDictionaries(); QMapIterator<QString, Dictionary> it(dictionaries); while (it.hasNext()) { it.next(); Dictionary dictionary = it.value(); // create an action for the dictionary QAction *action = createAction(dictionary); if (dictionary.language() == currentLanguage) { action->setChecked(true); action->trigger(); } } } void LanguageMenu::languageTriggered() { QAction *action = qobject_cast<QAction*>(sender()); emit languageTriggered(action->data().value<Dictionary>()); } QAction *LanguageMenu::createAction(const Dictionary &dictionary) { QAction *action = this->addAction(QString("%1 / %2").arg(dictionary.languageName()).arg(dictionary.countryName()), this, SLOT(languageTriggered())); action->setCheckable(true); action->setActionGroup(dictionariesGroup); QVariant data; data.setValue(dictionary); action->setData(data); return action; }
678
4,879
#import "MWMAlert.h" @interface MWMEditorViralAlert : MWMAlert + (nonnull instancetype)alert; @end
41
4,071
<filename>xdl/xdl/python/training/hash_filter.py # Copyright 2018 Alibaba Group. 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. # ============================================================================== from xdl.python.lib import internal_ops import inspect def hash_filter(var_name, fdef, func_name, payload={}): func_def = open(fdef).read() exec(func_def) f = locals()[func_name] f_args = inspect.getargspec(f) if f_args.keywords is not None or f_args.varargs is not None: raise ValueError("function should not have varargs or keywords") f_args = f_args.args payload_name = payload.keys() payload_value = [payload[i] for i in payload_name] return internal_ops.ps_filter_op(payload_value, var_name, func_def, func_name, ";".join(f_args), ";".join(payload_name)) def hash_slot_filter(var_name, fdef, func_name, slot_name, slot_size, payload={}): func_def = open(fdef).read() exec(func_def) f = locals()[func_name] f_args = inspect.getargspec(f) if f_args.keywords is not None or f_args.varargs is not None: raise ValueError("function should not have varargs or keywords") f_args = f_args.args payload_name = payload.keys() payload_value = [payload[i] for i in payload_name] return internal_ops.ps_slot_filter_op(payload_value, var_name, func_def, func_name, ";".join(f_args), ";".join(payload_name), slot_name, slot_size)
607
410
<filename>defibus-client/src/main/java/com/webank/defibus/client/impl/producer/RRResponseFuture.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.defibus.client.impl.producer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.rocketmq.common.message.Message; public class RRResponseFuture { private CountDownLatch countDownLatch = new CountDownLatch(1); private volatile Message respMsg = null; private final RRCallback rrCallback; private long expiredTime = System.currentTimeMillis(); private AtomicBoolean release = new AtomicBoolean(false); public RRResponseFuture() { this.rrCallback = null; } public RRResponseFuture(RRCallback rrCallback) { this.rrCallback = rrCallback; } public RRResponseFuture(RRCallback rrCallback, long timeout) { this.rrCallback = rrCallback; this.expiredTime += timeout; } public void putResponse(final Message respMsg) { this.respMsg = respMsg; this.countDownLatch.countDown(); } public Message waitResponse(long timeout) throws InterruptedException { this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS); return this.respMsg; } public RRCallback getRrCallback() { return rrCallback; } public long getExpiredTime() { return expiredTime; } public boolean release() { return release.getAndSet(true); } }
737
3,428
{"id":"02136","group":"easy-ham-1","checksum":{"type":"MD5","value":"e5c8edd8057c6d595eb368cde9a8aa41"},"text":"From <EMAIL> Tue Oct 1 10:37:15 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>ass<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 2C51016F17\n\tfor <jm@localhost>; Tue, 1 Oct 2002 10:37:14 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 01 Oct 2002 10:37:14 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g9181aK15673 for\n <<EMAIL>>; Tue, 1 Oct 2002 09:01:36 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy<EMAIL>int.org\nFrom: gamasutra <<EMAIL>>\nSubject: Pensioners and housebuyers suffer\nDate: Tue, 01 Oct 2002 08:01:36 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://www.newsisfree.com/click/-2,8418831,215/\nDate: 2002-10-01T04:33:53+01:00\n\n*Business:* Standard Life finally capitulates and cuts payouts on millions of \npolicies.\n\n\n"}
470
2,792
// Copyright 2017,2018,2019,2020,2021 Sony Corporation. // Copyright 2021 Sony Group Corporation. // // 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. /** Slice */ #ifndef __NBLA_FUNCTION_SLICE_HPP__ #define __NBLA_FUNCTION_SLICE_HPP__ #include <nbla/cpu.hpp> #include <nbla/function.hpp> #include <nbla/function_registry.hpp> namespace nbla { NBLA_REGISTER_FUNCTION_HEADER(Slice, const vector<int> &, // start const vector<int> &, // stop const vector<int> &); // step /** Slice arrays along specified axis. Inputs: - N-D array. Outputs: - M-D array. Slice input tensor. y = x[start[0]:stop[0]:step[0], start[1]:stop[1]:step[1], ...] @tparam T Data type for computation. \ingroup FunctionImplGrp */ template <typename T> class Slice : public BaseFunction<const vector<int> &, const vector<int> &, const vector<int> &> { protected: // These settings are array to realize different slice amount for each data. vector<vector<int>> start_; vector<vector<int>> stop_; vector<vector<int>> step_; int base_axis_; // SPECIAL condition enum { SLICE_NONE = 0x7fffffff }; public: Slice(const Context &ctx, const vector<int> &start, const vector<int> &stop, const vector<int> &step) : BaseFunction(ctx, start, stop, step), start_(1), stop_(1), step_(1), base_axis_(0) { start_[0] = start; stop_[0] = stop; step_[0] = step; } virtual ~Slice() {} virtual shared_ptr<Function> copy() const { return create_Slice(ctx_, start_[0], stop_[0], step_[0]); } virtual vector<dtypes> in_types() { return vector<dtypes>{get_dtype<T>(), get_dtype<T>()}; } virtual vector<dtypes> out_types() { return vector<dtypes>{get_dtype<T>()}; } virtual int min_inputs() { return 1; } virtual int min_outputs() { return 1; } virtual string name() { return "Slice"; } virtual vector<string> allowed_array_classes() { return SingletonManager::get<Cpu>()->array_classes(); } virtual bool grad_depends_output_data(int i, int o) const { return false; } protected: NBLA_API virtual void setup_impl(const Variables &inputs, const Variables &outputs); NBLA_API virtual void forward_impl(const Variables &inputs, const Variables &outputs); NBLA_API virtual void backward_impl(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); virtual bool grad_depends_input_data_impl(int i, int j) const { return false; } NBLA_API bool skip_check(const Variables &outputs); private: NBLA_API void slice_forward_recursive(const Variable *inp, Variable *outp, const T *x, T *y, int x_offset, int y_offset, int dim, int &slice_index); NBLA_API void slice_backward_recursive(Variable *outp, const Variable *inp, T *dx, const T *dy, int x_offset, int y_offset, int dim, int &slice_index); }; } #endif
1,694
632
<reponame>wgzhao/bahir-flink<filename>flink-connector-pinot/src/test/java/org/apache/flink/streaming/connectors/pinot/LocalFileSystemAdapter.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.connectors.pinot; import org.apache.flink.streaming.connectors.pinot.filesystem.FileSystemAdapter; import org.apache.flink.streaming.connectors.pinot.filesystem.FileSystemUtils; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.List; import static org.apache.flink.util.Preconditions.checkNotNull; /** * The LocalFileSystemAdapter is used when sharing files via the local filesystem. * Keep in mind that using this FileSystemAdapter requires running the Flink app on a single node. */ public class LocalFileSystemAdapter implements FileSystemAdapter { private final String tempDirPrefix; public LocalFileSystemAdapter(String tempDirPrefix) { this.tempDirPrefix = checkNotNull(tempDirPrefix); } /** * Writes a list of serialized elements to the local filesystem. * * @param elements List of serialized elements * @return Path identifying the written file * @throws IOException */ @Override public String writeToSharedFileSystem(List<String> elements) throws IOException { File tempDir = Files.createTempDirectory(tempDirPrefix).toFile(); return FileSystemUtils.writeToLocalFile(elements, tempDir).getAbsolutePath(); } /** * Reads a previously written list of serialized elements from the local filesystem. * * @param path Path returned by {@link #writeToSharedFileSystem} * @return List of serialized elements read from the local filesystem * @throws IOException */ @Override public List<String> readFromSharedFileSystem(String path) throws IOException { File dataFile = new File(path); return Files.readAllLines(dataFile.toPath(), Charset.defaultCharset()); } /** * Deletes a file from the local filesystem * * @param path Path returned by {@link #writeToSharedFileSystem} * @throws IOException */ @Override public void deleteFromSharedFileSystem(String path) { new File(path).delete(); } }
950
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.history; import android.os.Bundle; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.IntentHandler; import org.chromium.chrome.browser.SnackbarActivity; import org.chromium.chrome.browser.util.IntentUtils; /** * Activity for displaying the browsing history manager. */ public class HistoryActivity extends SnackbarActivity { private HistoryManager mHistoryManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean isIncognito = IntentUtils.safeGetBooleanExtra( getIntent(), IntentHandler.EXTRA_INCOGNITO_MODE, false); mHistoryManager = new HistoryManager(this, true, getSnackbarManager(), isIncognito); setContentView(mHistoryManager.getView()); } @Override protected void onDestroy() { mHistoryManager.onDestroyed(); mHistoryManager = null; super.onDestroy(); } @VisibleForTesting HistoryManager getHistoryManagerForTests() { return mHistoryManager; } }
428
375
from .ClassA import ClassA from .OtherClassA import OtherClassA class mod_a(ClassA, OtherClassA): def __init__(self): pass
51
574
/* * Copyright (C) 2012 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.swift.codec; import com.facebook.swift.codec.internal.TProtocolReader; import com.facebook.swift.codec.internal.TProtocolWriter; import com.facebook.swift.codec.metadata.ThriftType; import org.apache.thrift.protocol.TProtocol; public class OneOfEverythingThriftCodec implements ThriftCodec<OneOfEverything> { private final ThriftType type; private final ThriftCodec<BonkField> aStructCodec; private final ThriftCodec<UnionField> aUnionCodec; private final ThriftCodec<Fruit> aFruitCodec; public OneOfEverythingThriftCodec(ThriftType type, ThriftCodec<BonkField> aStructCodec, ThriftCodec<UnionField> aUnionCodec, ThriftCodec<Fruit> aFruitCodec) { this.type = type; this.aStructCodec = aStructCodec; this.aUnionCodec = aUnionCodec; this.aFruitCodec = aFruitCodec; } @Override public ThriftType getType() { return type; } @Override public OneOfEverything read(TProtocol protocol) throws Exception { TProtocolReader reader = new TProtocolReader(protocol); boolean aBoolean = false; byte aByte = 0; short aShort = 0; int aInt = 0; long aLong = 0; double aDouble = 0; String aString = null; BonkField aStruct = null; Fruit aEnum = null; UnionField aUnion = null; reader.readStructBegin(); while (reader.nextField()) { switch (reader.getFieldId()) { case 1: aBoolean = reader.readBoolField(); break; case 2: aByte = reader.readByteField(); break; case 3: aShort = reader.readI16Field(); break; case 4: aInt = reader.readI32Field(); break; case 5: aLong = reader.readI64Field(); break; case 6: aDouble = reader.readDoubleField(); break; case 7: aString = reader.readStringField(); break; case 8: aStruct = reader.readStructField(aStructCodec); break; case 9: aEnum = reader.readEnumField(aFruitCodec); break; case 60: aUnion = reader.readStructField(aUnionCodec); default: reader.skipFieldData(); } } reader.readStructEnd(); OneOfEverything oneOfEverything = new OneOfEverything(); oneOfEverything.aBoolean = aBoolean; oneOfEverything.aByte = aByte; oneOfEverything.aShort = aShort; oneOfEverything.aInt = aInt; oneOfEverything.aLong = aLong; oneOfEverything.aDouble = aDouble; oneOfEverything.aString = aString; oneOfEverything.aStruct = aStruct; oneOfEverything.aEnum = aEnum; oneOfEverything.aUnion = aUnion; return oneOfEverything; } @Override public void write(OneOfEverything oneOfEverything, TProtocol protocol) throws Exception { TProtocolWriter writer = new TProtocolWriter(protocol); writer.writeStructBegin("OneOfEverything"); writer.writeBoolField("aBoolean", (short) 1, oneOfEverything.aBoolean); writer.writeByteField("aByte", (short) 2, oneOfEverything.aByte); writer.writeI16Field("aShort", (short) 3, oneOfEverything.aShort); writer.writeI32Field("aInt", (short) 4, oneOfEverything.aInt); writer.writeI64Field("aLong", (short) 5, oneOfEverything.aLong); writer.writeDoubleField("aDouble", (short) 6, oneOfEverything.aDouble); writer.writeStringField("aString", (short) 7, oneOfEverything.aString); writer.writeStructField("aStruct", (short) 8, aStructCodec, oneOfEverything.aStruct); writer.writeEnumField("aEnum", (short) 9, aFruitCodec, oneOfEverything.aEnum); writer.writeStructField("aUnion", (short) 61, aUnionCodec, oneOfEverything.aUnion); writer.writeStructEnd(); } }
2,317
435
<filename>pydata-paris-2015/videos/industrial-uses-of-scikit-learn-business-roundta.json { "alias": "video/3527/industrial-uses-of-scikit-learn-business-roundta", "category": "PyData Paris 2015", "copyright_text": "youtube", "description": "Industrial uses of scikit-learn (business roundtable)\n\n::\n\n Bio: <NAME> is Project manager at PriceMinister.\n\n <NAME>\u00e8re is technical evangelist at Microsoft. Benjamin works with startups and companies of different sizes to help them technically adopt Microsoft Azure cloud, should they use Big Data, Machine Learning or other technologies. He also speaks at conferences, writes (blogs, \u2026) and takes feedback.\n\n Combining a strong background in webmining and big data technologies with a deep interest in machine learning, <NAME> has earned the title of Big Data Sergeant at Data Publica, where he alternates between contributions to the development of the infrastructure of the C-Radar product and stints of rapid prototyping with Python data science libs (such as pandas, sklearn). In particular, he works on NLP related problems using unstructured web-scraped data to enrich corporate information.\n\n Thomas is Dataiku\u2019s Chief Data Scientist. Thomas started his career in data mining for large retail and telecommunications companies. Then he lead the data mining team and geo-marketing initiatives at Apple Europe. He was lead data scientist at qunb, a data visualization startup. He spent most of his career deriving value from large datasets using cutting-edge innovations. He is fluent in all the data scientists linguas: R, Python, SAS\u2026\n\n", "duration": null, "id": 3527, "language": "eng", "quality_notes": "", "recorded": "2015-04-21", "slug": "industrial-uses-of-scikit-learn-business-roundta", "speakers": [ "<NAME>\u00e8re", "<NAME>", "<NAME>", "<NAME>" ], "summary": "", "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/XROaMMHhVDc/hqdefault.jpg", "title": "Industrial uses of Scikit-Learn (business roundtable)", "videos": [ { "length": 0, "type": "youtube", "url": "https://www.youtube.com/watch?v=XROaMMHhVDc" } ] }
672
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/WebCore.framework/WebCore */ #import <WebCore/DOMObject.h> __attribute__((visibility("hidden"))) @interface DOMXPathExpression : DOMObject { } - (void)dealloc; // 0x357981 - (void)finalize; // 0x357ce5 - (id)evaluate:(id)evaluate type:(unsigned short)type inResult:(id)result; // 0x357b71 - (id)evaluate:(id)evaluate :(unsigned short)arg2 :(id)arg3; // 0x3579fd @end
173
14,668
<filename>chrome/android/features/start_surface/public/java/src/org/chromium/chrome/features/start_surface/StartSurfaceUserData.java // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.features.start_surface; import androidx.annotation.Nullable; import org.chromium.base.UserData; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tab.TabLaunchType; /** * Helper class for Tabs created from the Start surface. */ public class StartSurfaceUserData implements UserData { private static final Class<StartSurfaceUserData> USER_DATA_KEY = StartSurfaceUserData.class; private boolean mKeepTab; private boolean mFocusOnOmnibox; private boolean mCreatedAsNtp; private boolean mOpenedFromStart; // Saves the Feeds instance state. private String mFeedsInstanceState; /** * Static class that implements the initialization-on-demand holder idiom. */ private static class LazyHolder { static final StartSurfaceUserData INSTANCE = new StartSurfaceUserData(); } /** * Gets the singleton instance for the StartSurfaceUserData. */ public static StartSurfaceUserData getInstance() { return LazyHolder.INSTANCE; } /** * Sets the flag of whether to keep the given tab in the TabModel without auto deleting when * tapping the back button. This flag is for a tab with launchType * {@link org.chromium.chrome.browser.tab.TabLaunchType.FROM_START_SURFACE}. */ public static void setKeepTab(Tab tab, boolean keepTab) { if (tab == null || tab.getLaunchType() != TabLaunchType.FROM_START_SURFACE) return; StartSurfaceUserData startSurfaceUserData = get(tab); if (startSurfaceUserData == null) { startSurfaceUserData = new StartSurfaceUserData(); } startSurfaceUserData.mKeepTab = keepTab; tab.getUserDataHost().setUserData(USER_DATA_KEY, startSurfaceUserData); } /** * @return Whether to keep the given tab in the TabModel without auto deleting when tapping the * back button. Returns false if the UserData isn't set. */ public static boolean getKeepTab(Tab tab) { StartSurfaceUserData startSurfaceUserData = get(tab); return startSurfaceUserData == null ? false : startSurfaceUserData.mKeepTab; } /** * Sets the flag of whether the given tab is opened from the Start surface. Note: should only * call this function in the code path that Start surface is enabled, otherwise may cause the * StartSurfaceUserData is created without Start surface. */ public static void setOpenedFromStart(Tab tab) { if (tab == null || !StartSurfaceConfiguration.isStartSurfaceFlagEnabled()) return; StartSurfaceUserData startSurfaceUserData = get(tab); if (startSurfaceUserData == null) { startSurfaceUserData = new StartSurfaceUserData(); } if (startSurfaceUserData.mOpenedFromStart) return; startSurfaceUserData.mOpenedFromStart = true; tab.getUserDataHost().setUserData(USER_DATA_KEY, startSurfaceUserData); } /** * @return Whether the given tab is opened from the Start surface. */ public static boolean isOpenedFromStart(Tab tab) { StartSurfaceUserData startSurfaceUserData = get(tab); return startSurfaceUserData == null ? false : startSurfaceUserData.mOpenedFromStart; } /** * Sets whether to focus on omnibox when the given tab is shown. Prefer to call * {@link StartSurfaceConfiguration#maySetUserDataForEmptyTab(Tab, String)} instead this * function, since it doesn't have complete checks for the given tab and may cause the * StartSurfaceUserData is created without Start surface enabled. */ public static void setFocusOnOmnibox(Tab tab, boolean focusOnOmnibox) { StartSurfaceUserData startSurfaceUserData = get(tab); if (startSurfaceUserData == null) { startSurfaceUserData = new StartSurfaceUserData(); tab.getUserDataHost().setUserData(USER_DATA_KEY, startSurfaceUserData); } startSurfaceUserData.mFocusOnOmnibox = focusOnOmnibox; } /** * @return Whether to focus on omnibox when the given tab is shown. The focusing on omnibox will * only shown when the tab is created as a new Tab. */ public static boolean getFocusOnOmnibox(Tab tab) { StartSurfaceUserData startSurfaceUserData = get(tab); return startSurfaceUserData == null ? false : startSurfaceUserData.mFocusOnOmnibox; } private static StartSurfaceUserData get(Tab tab) { return tab.getUserDataHost().getUserData(USER_DATA_KEY); } /** * Sets whether the tab is created as chrome://newTab. A tab can only be created in this way * when {@link StartSurfaceConfiguration.OMNIBOX_FOCUSED_ON_NEW_TAB} is enabled. The URL of the * newly created tab is empty, but should be treated as NTP for features like autocomplete. */ public static void setCreatedAsNtp(Tab tab) { if (!StartSurfaceConfiguration.OMNIBOX_FOCUSED_ON_NEW_TAB.getValue()) return; StartSurfaceUserData startSurfaceUserData = get(tab); if (startSurfaceUserData == null) { startSurfaceUserData = new StartSurfaceUserData(); tab.getUserDataHost().setUserData(USER_DATA_KEY, startSurfaceUserData); } startSurfaceUserData.mCreatedAsNtp = true; } /** * @return Whether the tab is created as chrome://newTab. A tab can only be created in this way * when {@link StartSurfaceConfiguration.OMNIBOX_FOCUSED_ON_NEW_TAB} is enabled. The URL of the * newly created tab is empty, but should be treated as NTP for features like autocomplete. */ public static boolean getCreatedAsNtp(Tab tab) { StartSurfaceUserData startSurfaceUserData = get(tab); return startSurfaceUserData == null ? false : startSurfaceUserData.mCreatedAsNtp; } /** Save the feed instance state if necessary. */ public void saveFeedInstanceState(String state) { mFeedsInstanceState = state; } /** * @return The saved feed instance state, or null if it is not previously saved. */ @Nullable protected String restoreFeedInstanceState() { return mFeedsInstanceState; } }
2,277
776
/* * Copyright 2019-present HiveMQ GmbH * * 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.hivemq.persistence.clientqueue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.ImmutableIntArray; import com.hivemq.bootstrap.ClientConnection; import com.hivemq.configuration.service.MqttConfigurationService; import com.hivemq.mqtt.message.MessageWithID; import com.hivemq.mqtt.message.QoS; import com.hivemq.mqtt.message.dropping.MessageDroppedService; import com.hivemq.mqtt.message.publish.PUBLISH; import com.hivemq.mqtt.message.publish.PUBLISHFactory; import com.hivemq.mqtt.services.PublishPollService; import com.hivemq.mqtt.topic.tree.LocalTopicTree; import com.hivemq.persistence.ChannelPersistence; import com.hivemq.persistence.SingleWriterService; import com.hivemq.persistence.clientsession.ClientSession; import com.hivemq.persistence.local.ClientSessionLocalPersistence; import com.hivemq.persistence.local.xodus.bucket.BucketUtils; import com.hivemq.persistence.payload.PublishPayloadPersistence; import com.hivemq.util.ChannelAttributes; import io.netty.channel.Channel; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import util.InitFutureUtilsExecutorRule; import util.TestSingleWriterFactory; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static com.hivemq.configuration.service.MqttConfigurationService.QueuedMessagesStrategy; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; /** * @author <NAME> */ @SuppressWarnings("NullabilityAnnotations") public class ClientQueuePersistenceImplTest { private AutoCloseable closeableMock; @Rule public InitFutureUtilsExecutorRule initFutureUtilsExecutorRule = new InitFutureUtilsExecutorRule(); @Mock ClientQueueXodusLocalPersistence localPersistence; @Mock PublishPayloadPersistence payloadPersistence; @Mock MqttConfigurationService mqttConfigurationService; @Mock ClientSessionLocalPersistence clientSessionLocalPersistence; @Mock MessageDroppedService messageDroppedService; @Mock LocalTopicTree topicTree; @Mock private ChannelPersistence channelPersistence; @Mock private PublishPollService publishPollService; private ClientQueuePersistenceImpl clientQueuePersistence; final int bucketSize = 64; private SingleWriterService singleWriterService; @Before public void setUp() throws Exception { closeableMock = MockitoAnnotations.openMocks(this); singleWriterService = TestSingleWriterFactory.defaultSingleWriter(); when(mqttConfigurationService.maxQueuedMessages()).thenReturn(1000L); when(mqttConfigurationService.getQueuedMessagesStrategy()).thenReturn(QueuedMessagesStrategy.DISCARD); clientQueuePersistence = new ClientQueuePersistenceImpl(localPersistence, singleWriterService, mqttConfigurationService, clientSessionLocalPersistence, messageDroppedService, topicTree, channelPersistence, publishPollService); } @After public void tearDown() throws Exception { clientQueuePersistence.closeDB(); singleWriterService.stop(); closeableMock.close(); } @Test(timeout = 5000) public void test_add() throws ExecutionException, InterruptedException { clientQueuePersistence.add("client", false, createPublish(1, QoS.AT_LEAST_ONCE, "topic"), false, 1000L).get(); verify(localPersistence).add( eq("client"), eq(false), any(PUBLISH.class), eq(1000L), eq(QueuedMessagesStrategy.DISCARD), anyBoolean(), anyInt()); verify(messageDroppedService, never()).queueFull("client", "topic", 1); } @Test(timeout = 5000) public void test_add_shared() throws ExecutionException, InterruptedException { clientQueuePersistence.add("name/topic", true, createPublish(1, QoS.AT_LEAST_ONCE, "topic"), false, 1000L).get(); verify(localPersistence).add( eq("name/topic"), eq(true), any(PUBLISH.class), eq(1000L), eq(QueuedMessagesStrategy.DISCARD), anyBoolean(), anyInt()); } @Test(timeout = 5000) public void test_publish_avaliable() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.attr(ChannelAttributes.CLIENT_CONNECTION).set(new ClientConnection(channel, null)); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessagesSent(true); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessages(new AtomicInteger(0)); when(clientSessionLocalPersistence.getSession("client")).thenReturn(new ClientSession(true, 1000L)); when(channelPersistence.get("client")).thenReturn(channel); clientQueuePersistence.publishAvailable("client"); channel.runPendingTasks(); verify(publishPollService, timeout(2000)).pollNewMessages("client", channel); } @Test(timeout = 5000) public void test_publish_avaliable_channel_inactive() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.attr(ChannelAttributes.CLIENT_CONNECTION).set(new ClientConnection(channel, null)); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessagesSent(true); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessages(new AtomicInteger(0)); channel.close(); when(clientSessionLocalPersistence.getSession("client")).thenReturn(new ClientSession(true, 1000L)); when(channelPersistence.get("client")).thenReturn(channel); clientQueuePersistence.publishAvailable("client"); channel.runPendingTasks(); verify(publishPollService, never()).pollNewMessages("client", channel); } @Test(timeout = 5000) public void test_publish_avaliable_inflight_messages_not_sent() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.attr(ChannelAttributes.CLIENT_CONNECTION).set(new ClientConnection(channel, null)); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessages(new AtomicInteger(0)); when(clientSessionLocalPersistence.getSession("client")).thenReturn(new ClientSession(true, 1000L)); when(channelPersistence.get("client")).thenReturn(channel); clientQueuePersistence.publishAvailable("client"); channel.runPendingTasks(); verify(publishPollService, never()).pollNewMessages("client", channel); } @Test(timeout = 5000) public void test_publish_avaliable_inflight_messages_sending() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.attr(ChannelAttributes.CLIENT_CONNECTION).set(new ClientConnection(channel, null)); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessagesSent(true); channel.attr(ChannelAttributes.CLIENT_CONNECTION).get().setInFlightMessages(new AtomicInteger(10)); when(clientSessionLocalPersistence.getSession("client")).thenReturn(new ClientSession(true, 1000L)); when(channelPersistence.get("client")).thenReturn(channel); clientQueuePersistence.publishAvailable("client"); channel.runPendingTasks(); verify(publishPollService, never()).pollNewMessages("client", channel); } @Test(timeout = 5000) public void test_publish_avaliable_channel_null() { when(clientSessionLocalPersistence.getSession("client")).thenReturn(new ClientSession(true, 1000L)); when(channelPersistence.get("client")).thenReturn(null); clientQueuePersistence.publishAvailable("client"); verify(publishPollService, never()).pollNewMessages(eq("client"), any(Channel.class)); } @Test(timeout = 5000) public void test_publish_avaliable_not_connected() { when(clientSessionLocalPersistence.getSession("client")).thenReturn(new ClientSession(false, 1000L)); clientQueuePersistence.publishAvailable("client"); verify(publishPollService, never()).pollNewMessages(eq("client"), any(Channel.class)); } @Test(timeout = 5000) public void test_read_new() throws ExecutionException, InterruptedException { when(localPersistence.readNew( anyString(), anyBoolean(), any(ImmutableIntArray.class), anyLong(), anyInt())).thenReturn( ImmutableList.of( createPublish(1, QoS.AT_MOST_ONCE, "topic"), createPublish(2, QoS.AT_LEAST_ONCE, "topic"))); final ImmutableList<PUBLISH> publishes = clientQueuePersistence.readNew("client", false, ImmutableIntArray.of(1, 2), 1000).get(); assertEquals(2, publishes.size()); } @Test(timeout = 5000) public void test_clear() throws ExecutionException, InterruptedException { clientQueuePersistence.clear("client", false).get(); verify(localPersistence).clear("client", false, BucketUtils.getBucket("client", bucketSize)); } @Test(timeout = 5000) public void test_read_inflight() throws ExecutionException, InterruptedException { when(localPersistence.readInflight(anyString(), anyBoolean(), anyInt(), anyLong(), anyInt())).thenReturn( ImmutableList.of(createPublish(1, QoS.AT_LEAST_ONCE, "topic"))); final ImmutableList<MessageWithID> messages = clientQueuePersistence.readInflight("client", 10, 11).get(); assertEquals(1, messages.size()); verify(localPersistence).readInflight(eq("client"), eq(false), eq(11), eq(10L), anyInt()); } @Test(timeout = 5000) public void test_clean_up() throws ExecutionException, InterruptedException { when(localPersistence.cleanUp(eq(0))).thenReturn(ImmutableSet.of("group/topic")); when(topicTree.getSharedSubscriber(anyString(), anyString())).thenReturn(ImmutableSet.of()); clientQueuePersistence.cleanUp(0).get(); verify(topicTree).getSharedSubscriber(anyString(), anyString()); } @Test(timeout = 50000) public void test_shared_publish_available() { clientQueuePersistence.sharedPublishAvailable("group/topic"); verify(publishPollService).pollSharedPublishes("group/topic"); } @Test(timeout = 5000) public void test_remove_all_qos0() throws ExecutionException, InterruptedException { clientQueuePersistence.removeAllQos0Messages("client", false).get(); verify(localPersistence).removeAllQos0Messages(eq("client"), eq(false), anyInt()); } @Test(timeout = 5000) public void test_batched_add_no_new_message() throws ExecutionException, InterruptedException { when(localPersistence.size(eq("client"), anyBoolean(), anyInt())).thenReturn(1); final ImmutableList<PUBLISH> publishes = ImmutableList.of( createPublish(1, QoS.AT_LEAST_ONCE, "topic1"), createPublish(2, QoS.AT_LEAST_ONCE, "topic2")); clientQueuePersistence.add("client", false, publishes, false, 1000L).get(); verify(localPersistence).add( eq("client"), eq(false), eq(publishes), eq(1000L), eq(QueuedMessagesStrategy.DISCARD), anyBoolean(), anyInt()); verify(clientSessionLocalPersistence, never()).getSession( "client"); // Get session because new publishes are available verify(messageDroppedService, never()).queueFull("client", "topic", 1); } @Test(timeout = 5000) public void test_batched_add_new_message() throws ExecutionException, InterruptedException { when(localPersistence.size(eq("client"), anyBoolean(), anyInt())).thenReturn(0); final ImmutableList<PUBLISH> publishes = ImmutableList.of( createPublish(1, QoS.AT_LEAST_ONCE, "topic1"), createPublish(2, QoS.AT_LEAST_ONCE, "topic2")); clientQueuePersistence.add("client", false, publishes, false, 1000L).get(); verify(localPersistence).add( eq("client"), eq(false), eq(publishes), eq(1000L), eq(QueuedMessagesStrategy.DISCARD), anyBoolean(), anyInt()); verify(clientSessionLocalPersistence).getSession("client"); // Get session because new publishes are available verify(messageDroppedService, never()).queueFull("client", "topic", 1); } private PUBLISH createPublish(final int packetId, final QoS qos, final String topic) { return new PUBLISHFactory.Mqtt5Builder().withPacketIdentifier(packetId) .withQoS(qos) .withOnwardQos(qos) .withPublishId(1L) .withPayload("message".getBytes()) .withTopic(topic) .withHivemqId("hivemqId") .withPersistence(payloadPersistence) .build(); } }
5,017
543
<reponame>CoenRijsdijk/Bytecoder /* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.beans; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * An annotation used to specify some property-related information for the * automatically generated {@link BeanInfo} classes. This annotation is not used * if the annotated class has a corresponding user-defined {@code BeanInfo} * class, which does not imply the automatic analysis. If both the read and the * write methods of the property are annotated, then the read method annotation * will have more priority and replace the write method annotation. * * @author <NAME> * @see BeanInfo#getPropertyDescriptors * @since 9 */ @Documented @Target({METHOD}) @Retention(RUNTIME) public @interface BeanProperty { /** * The value that indicates whether the annotated property can be * a {@link PropertyDescriptor#isBound bound} property or not. * This value applies only to the beans that have the * {@link PropertyChangeListener propertyChange} event set. * * @return {@code true} if the annotated property can be a bound property; * {@code false} otherwise. */ boolean bound() default true; /** * The value that indicates whether the annotated property is * an {@link PropertyDescriptor#isExpert expert} property or not. * * @return {@code true} if the annotated property is an expert property; * {@code false} otherwise. */ boolean expert() default false; /** * The value that indicates whether the annotated property is * a {@link PropertyDescriptor#isHidden hidden} property or not. * * @return {@code true} if the annotated property is a hidden property; * {@code false} otherwise. */ boolean hidden() default false; /** * The value that indicates whether the annotated property is * a {@link PropertyDescriptor#isPreferred preferred} property or not. * * @return {@code true} if the annotated property is a preferred property; * {@code false} otherwise. */ boolean preferred() default false; /** * The value that indicates whether the annotated property is * a required property or not. * * @return {@code true} if the annotated property is a required property; * {@code false} otherwise. */ boolean required() default false; /** * The value that indicates whether the corresponding component * is repainted after the annotated property got changed or not. * * @return {@code true} if the corresponding component is repainted; * {@code false} otherwise. */ boolean visualUpdate() default false; /** * The {@link PropertyDescriptor#getShortDescription short description} * for the {@link BeanInfo#getPropertyDescriptors descriptor} * of the annotated property. * * @return the property description, * or an empty string if the description is not set. */ String description() default ""; /** * The array of names for the public static fields * that contains the valid values of the annotated property. * These names are used to generate the {@code enumerationValues} * {@link java.beans.BeanDescriptor#getValue feature attribute} * that must contain the following items per each property value: * a displayable name for the property value, the actual property value, * and a Java code piece used for the code generator. * * @return the names of the valid values of the annotated property, * or an empty array if the names are not provided. */ String[] enumerationValues() default {}; }
1,558
1,484
<gh_stars>1000+ import copy import datetime from anchore_engine.db import ImagePackageVulnerability from anchore_engine.subsys import logger def test_cmp(): c1 = ImagePackageVulnerability() c1.pkg_name = "testpkg1" c1.pkg_version = "1.0" c1.pkg_arch = "x86" c1.pkg_type = "rpm" c1.pkg_image_id = "image123" c1.pkg_user_id = "0" c1.vulnerability_namespace_name = "centos:6" c1.vulnerability_id = "CVE-2016-123" c1.created_at = datetime.datetime.utcnow() c2 = copy.deepcopy(c1) assert c1 == c2 c3 = copy.deepcopy(c1) assert c1 == c3 c4 = copy.deepcopy(c1) assert c1 == c4 c3.pkg_version = "1.1" c4.pkg_user_id = "1" assert c1 == c2 assert c1 != c4 assert c1 != c3 assert list({c1, c2, c3}) == list({c1, c3}) logger.info("Set: {}".format({c1, c2, c3}))
400
831
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.editors.strings; import com.android.tools.idea.actions.BrowserHelpAction; import com.android.tools.idea.editors.strings.table.FrozenColumnTableEvent; import com.android.tools.idea.editors.strings.table.FrozenColumnTableListener; import com.android.tools.idea.editors.strings.table.StringResourceTable; import com.android.tools.idea.editors.strings.table.StringResourceTableModel; import com.android.tools.idea.rendering.Locale; import com.google.common.annotations.VisibleForTesting; import com.intellij.icons.AllIcons; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.components.JBLoadingPanel; import com.intellij.uiDesigner.core.GridConstraints; import java.awt.BorderLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.text.JTextComponent; import org.jetbrains.android.facet.AndroidFacet; import org.jetbrains.annotations.NotNull; public final class StringResourceViewPanel implements Disposable { private final AndroidFacet myFacet; private final JBLoadingPanel myLoadingPanel; private JPanel myContainer; private JPanel myToolbarPanel; private StringResourceTable myTable; private JTextComponent myKeyTextField; @VisibleForTesting TextFieldWithBrowseButton myDefaultValueTextField; private TextFieldWithBrowseButton myTranslationTextField; private RemoveKeysAction myRemoveKeysAction; private AddLocaleAction myAddLocaleAction; private GoToDeclarationAction myGoToAction; private DeleteStringAction myDeleteAction; StringResourceViewPanel(AndroidFacet facet, Disposable parentDisposable) { myFacet = facet; Disposer.register(parentDisposable, this); myToolbarPanel.add(createToolbar().getComponent()); GridConstraints constraints = new GridConstraints(); constraints.setFill(GridConstraints.FILL_BOTH); constraints.setRow(1); myContainer.add(myTable.getScrollPane(), constraints); myLoadingPanel = new JBLoadingPanel(new BorderLayout(), this, 200); myLoadingPanel.setLoadingText("Loading string resource data"); myLoadingPanel.setName("translationsEditor"); myLoadingPanel.add(myContainer); myLoadingPanel.startLoading(); if (!ApplicationManager.getApplication().isUnitTestMode()) { new ResourceLoadingTask(this).queue(); } } @Override public void dispose() { } public void removeSelectedKeys() { myRemoveKeysAction.perform(); } private void createUIComponents() { createTable(); createTablePopupMenu(); myKeyTextField = new TranslationsEditorTextField(myTable, StringResourceTableModel.KEY_COLUMN); createDefaultValueTextField(); createTranslationTextField(); } private void createTable() { myRemoveKeysAction = new RemoveKeysAction(this); myDeleteAction = new DeleteStringAction(this); myGoToAction = new GoToDeclarationAction(this); myTable = new StringResourceTable(); myTable.putInActionMap("delete", myDeleteAction); myTable.addFrozenColumnTableListener(new CellSelectionListener()); myTable.addFrozenColumnTableListener(new RemoveLocaleMouseListener(this)); } private void createTablePopupMenu() { JPopupMenu menu = new JPopupMenu(); JMenuItem goTo = menu.add(myGoToAction); JMenuItem delete = menu.add(myDeleteAction); myTable.addFrozenColumnTableListener(new FrozenColumnTableListener() { @Override public void cellPopupTriggered(@NotNull FrozenColumnTableEvent event) { myGoToAction.update(goTo, event); myDeleteAction.update(delete, event); if (goTo.isVisible() || delete.isVisible()) { Point point = event.getPoint(); menu.show(event.getSubcomponent(), point.x, point.y); } } }); } private void createDefaultValueTextField() { JTextField textField = new TranslationsEditorTextField(myTable, StringResourceTableModel.DEFAULT_VALUE_COLUMN); new TranslationsEditorPasteAction().registerCustomShortcutSet(textField, this); myDefaultValueTextField = new TextFieldWithBrowseButton(textField, new ShowMultilineActionListener(), this); myDefaultValueTextField.setButtonIcon(AllIcons.Actions.ShowViewer); } private void createTranslationTextField() { JTextField textField = new TranslationsEditorTextField(myTable, myTable::getSelectedModelColumnIndex); new TranslationsEditorPasteAction().registerCustomShortcutSet(textField, this); myTranslationTextField = new TextFieldWithBrowseButton(textField, new ShowMultilineActionListener(), this); myTranslationTextField.setButtonIcon(AllIcons.Actions.ShowViewer); } void reloadData() { myLoadingPanel.setLoadingText("Updating string resource data"); myLoadingPanel.startLoading(); if (!ApplicationManager.getApplication().isUnitTestMode()) { new ResourceLoadingTask(this).queue(); } } private ActionToolbar createToolbar() { myAddLocaleAction = new AddLocaleAction(this); DefaultActionGroup group = new DefaultActionGroup(); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("TranslationsEditorToolbar", group, true); JComponent toolbarComponent = toolbar.getComponent(); toolbarComponent.setName("toolbar"); group.add(new AddKeyAction(this)); group.add(myRemoveKeysAction); group.add(myAddLocaleAction); group.add(new FilterKeysAction(myTable)); group.add(new FilterLocalesAction(myTable)); group.add(new ReloadStringResourcesAction(this)); group.add(new BrowserHelpAction("Translations editor", "https://developer.android.com/r/studio-ui/translations-editor.html")); return toolbar; } @NotNull AndroidFacet getFacet() { return myFacet; } @NotNull JBLoadingPanel getLoadingPanel() { return myLoadingPanel; } @NotNull public StringResourceTable getTable() { return myTable; } @NotNull JComponent getPreferredFocusedComponent() { return myTable.getScrollableTable(); } @VisibleForTesting @NotNull AddLocaleAction getAddLocaleAction() { return myAddLocaleAction; } private final class CellSelectionListener implements FrozenColumnTableListener { @Override public void selectedCellChanged() { if (myTable.getSelectedColumnCount() != 1 || myTable.getSelectedRowCount() != 1) { setTextAndEditable(myKeyTextField, "", false); setTextAndEditable(myDefaultValueTextField.getTextField(), "", false); setTextAndEditable(myTranslationTextField.getTextField(), "", false); myDefaultValueTextField.getButton().setEnabled(false); myTranslationTextField.getButton().setEnabled(false); return; } myKeyTextField.setEnabled(true); myDefaultValueTextField.setEnabled(true); myTranslationTextField.setEnabled(true); StringResourceTableModel model = myTable.getModel(); int row = myTable.getSelectedModelRowIndex(); int column = myTable.getSelectedModelColumnIndex(); Object locale = model.getLocale(column); // TODO: Keys are not editable; we want them to be refactor operations setTextAndEditable(myKeyTextField, model.getKey(row).getName(), false); String defaultValue = (String)model.getValueAt(row, StringResourceTableModel.DEFAULT_VALUE_COLUMN); boolean defaultValueEditable = isValueEditableInline(defaultValue); // don't allow editing multiline chars in a text field setTextAndEditable(myDefaultValueTextField.getTextField(), defaultValue, defaultValueEditable); myDefaultValueTextField.getButton().setEnabled(true); boolean translationEditable = false; String translation = ""; if (locale != null) { translation = (String)model.getValueAt(row, column); translationEditable = isValueEditableInline(translation); // don't allow editing multiline chars in a text field } setTextAndEditable(myTranslationTextField.getTextField(), translation, translationEditable); myTranslationTextField.getButton().setEnabled(locale != null); } } /** * Check if the provided value can be edited inline or has to be edited using the multiline text field. * * <p>A Value can be edited inline if it contains no "\n" character. * * @param value The value to check * @return true is the value can be edited inline, false if it has to be edited with the multiline text field */ private static boolean isValueEditableInline(@NotNull String value) { return !StringUtil.containsChar(value, '\n'); } private static void setTextAndEditable(@NotNull JTextComponent component, @NotNull String text, boolean editable) { component.setText(text); component.setCaretPosition(0); component.setEditable(editable); // If a text component is not editable when it gains focus and becomes editable while still focused, // the caret does not appear, so we need to set the caret visibility manually component.getCaret().setVisible(editable && component.hasFocus()); component.setFont(StringResourceEditor.getFont(component.getFont())); } private class ShowMultilineActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (myTable.getSelectedRowCount() != 1 || myTable.getSelectedColumnCount() != 1) { return; } int row = myTable.getSelectedModelRowIndex(); int column = myTable.getSelectedModelColumnIndex(); StringResourceTableModel model = myTable.getModel(); String value = (String)model.getValueAt(row, StringResourceTableModel.DEFAULT_VALUE_COLUMN); Locale locale = model.getLocale(column); String translation = locale == null ? null : (String)model.getValueAt(row, column); MultilineStringEditorDialog d = new MultilineStringEditorDialog(myFacet, model.getKey(row).getName(), value, locale, translation); if (d.showAndGet()) { if (!StringUtil.equals(value, d.getDefaultValue())) { model.setValueAt(d.getDefaultValue(), row, StringResourceTableModel.DEFAULT_VALUE_COLUMN); setTextAndEditable(myDefaultValueTextField.getTextField(), d.getDefaultValue(), isValueEditableInline(d.getDefaultValue())); } if (locale != null && !StringUtil.equals(translation, d.getTranslation())) { model.setValueAt(d.getTranslation(), row, column); setTextAndEditable(myTranslationTextField.getTextField(), d.getTranslation(), isValueEditableInline(d.getTranslation())); } } } } }
3,772
629
#!/usr/bin/env python import getopt import os import pysvg.parser import shutil from subprocess import Popen, PIPE import sys from subprocess import call # Converts the svglibrary assets to png. # This script depends on the rsvg-convert to perform the conversion. def main(argv): rsvgConvert = "/usr/bin/rsvg-convert" localRsvgConvert = "/usr/local/bin/rsvg-convert" imConvert = "/usr/bin/convert" localImConvert = "/usr/local/bin/convert" svgDirectory = '' pngDirectory = '' if not os.path.isfile(rsvgConvert): if os.path.isfile(localRsvgConvert): rsvgConvert = localRsvgConvert else: print 'You must install librsvg2-bin to build' sys.exit(1) if not os.path.isfile(imConvert): if os.path.isfile(localImConvert): imConvert = localImConvert else: print 'You must install ImageMagick to build' sys.exit(1) try: opts, args = getopt.getopt(argv,"hi:o:",["input=","output="]) except getopt.GetoptError: print 'convert-svg-to-png.py -i <svgDirectory> -o <pngDirectory>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'convert-svg-to-png.py -i <svgDirectory> -o <pngDirectory>' sys.exit() elif opt in ("-i", "--input"): svgDirectory = arg.lstrip() elif opt in ("-o", "--output"): pngDirectory = arg.lstrip() print 'Input svg directory is ' + svgDirectory print 'Output png directory is ' + pngDirectory MAX_WIDTH = 180 MAX_HEIGHT = 140 nullout = open(os.devnull,'wb') count = 0 for i in os.listdir(svgDirectory): tokens = i.split(".") fname = tokens[0] pngname = fname + ".png" inputFile = svgDirectory + "/" + i outputFile = pngDirectory + "/" + pngname # Handle large PNGs and other files if tokens[-1] == "png": # Downscale with ImageMagick call([imConvert, inputFile, "-resize", '%ix%i' % (MAX_WIDTH, MAX_HEIGHT), outputFile]) continue elif tokens[-1] != "svg": # Don't do any processing continue # Handle SVGs # hide stdout because pysvg.parser.parse spits out spurious warnings temp = sys.stdout sys.stdout = nullout svg = pysvg.parser.parse(svgDirectory + i) sys.stdout = temp svgHeight = float(svg.get_height()[:-2]) svgWidth = float(svg.get_width()[:-2]) ratio = svgWidth / svgHeight heightBoundByWidth = MAX_WIDTH / ratio if heightBoundByWidth > MAX_HEIGHT: call([rsvgConvert, "-h", str(MAX_HEIGHT), inputFile, "-o", outputFile]) else: call([rsvgConvert, "-w", str(MAX_WIDTH), inputFile, "-o", outputFile]) count = count + 1 nullout.close() print 'Converted {0} svgs to png'.format(count) if __name__ == "__main__": main(sys.argv[1:])
1,426
713
package org.infinispan.util.function; import java.io.Serializable; import java.util.function.DoubleFunction; /** * This is a functional interface that is the same as a {@link DoubleFunction} except that it must also be * {@link java.io.Serializable} * * @author wburns * @since 9.0 */ public interface SerializableDoubleFunction<R> extends Serializable, DoubleFunction<R> { }
113
957
<filename>Dev/Cpp/EffekseerRendererVulkan/EffekseerRenderer/ShaderHeader/sprite_lit_vs.h<gh_stars>100-1000 // 7.13.3381 #pragma once const uint32_t sprite_lit_vs[] = { 0x07230203,0x00010000,0x00080007,0x000000b9,0x00000000,0x00020011,0x00000001,0x0006000b, 0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001, 0x0012000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000007f,0x00000083,0x00000086, 0x00000089,0x0000008d,0x00000090,0x000000a1,0x000000a5,0x000000a9,0x000000ad,0x000000b0, 0x000000b3,0x000000b6,0x00030003,0x00000002,0x000001a4,0x00040005,0x00000004,0x6e69616d, 0x00000000,0x00050005,0x0000000a,0x495f5356,0x7475706e,0x00000000,0x00040006,0x0000000a, 0x00000000,0x00736f50,0x00050006,0x0000000a,0x00000001,0x6f6c6f43,0x00000072,0x00050006, 0x0000000a,0x00000002,0x6d726f4e,0x00006c61,0x00050006,0x0000000a,0x00000003,0x676e6154, 0x00746e65,0x00040006,0x0000000a,0x00000004,0x00315655,0x00040006,0x0000000a,0x00000005, 0x00325655,0x00050005,0x0000000c,0x4f5f5356,0x75707475,0x00000074,0x00050006,0x0000000c, 0x00000000,0x56736f50,0x00000053,0x00050006,0x0000000c,0x00000001,0x6f6c6f43,0x00000072, 0x00040006,0x0000000c,0x00000002,0x00005655,0x00050006,0x0000000c,0x00000003,0x6c726f57, 0x00004e64,0x00050006,0x0000000c,0x00000004,0x6c726f57,0x00004264,0x00050006,0x0000000c, 0x00000005,0x6c726f57,0x00005464,0x00050006,0x0000000c,0x00000006,0x50736f50,0x00000000, 0x000e0005,0x0000000f,0x69616d5f,0x7473286e,0x74637572,0x5f53562d,0x75706e49,0x66762d74, 0x66762d33,0x66762d34,0x66762d34,0x66762d34,0x66762d32,0x003b3132,0x00040005,0x0000000e, 0x75706e49,0x00000074,0x00040005,0x00000012,0x7074754f,0x00007475,0x00050005,0x00000019, 0x6c726f77,0x726f4e64,0x006c616d,0x00060005,0x00000028,0x6c726f77,0x6e615464,0x746e6567, 0x00000000,0x00060005,0x00000033,0x6c726f77,0x6e694264,0x616d726f,0x0000006c,0x00050005, 0x0000003d,0x6c726f77,0x736f5064,0x00000000,0x00070005,0x0000004e,0x435f5356,0x74736e6f, 0x42746e61,0x65666675,0x00000072,0x00050006,0x0000004e,0x00000000,0x6d61436d,0x00617265, 0x00060006,0x0000004e,0x00000001,0x6d61436d,0x50617265,0x006a6f72,0x00060006,0x0000004e, 0x00000002,0x4956556d,0x7265766e,0x00646573,0x00080006,0x0000004e,0x00000003,0x696c666d, 0x6f6f6270,0x7261506b,0x74656d61,0x00007265,0x00030005,0x00000050,0x0033375f,0x00030005, 0x0000005b,0x00317675,0x00040005,0x0000007d,0x75706e49,0x00000074,0x00050005,0x0000007f, 0x75706e49,0x6f505f74,0x00000073,0x00050005,0x00000083,0x75706e49,0x6f435f74,0x00726f6c, 0x00060005,0x00000086,0x75706e49,0x6f4e5f74,0x6c616d72,0x00000000,0x00060005,0x00000089, 0x75706e49,0x61545f74,0x6e65676e,0x00000074,0x00050005,0x0000008d,0x75706e49,0x56555f74, 0x00000031,0x00050005,0x00000090,0x75706e49,0x56555f74,0x00000032,0x00050005,0x00000093, 0x74616c66,0x546e6574,0x00706d65,0x00040005,0x00000094,0x61726170,0x0000006d,0x00050005, 0x00000097,0x736f705f,0x6f697469,0x0000006e,0x00060005,0x0000009f,0x505f6c67,0x65567265, 0x78657472,0x00000000,0x00060006,0x0000009f,0x00000000,0x505f6c67,0x7469736f,0x006e6f69, 0x00070006,0x0000009f,0x00000001,0x505f6c67,0x746e696f,0x657a6953,0x00000000,0x00070006, 0x0000009f,0x00000002,0x435f6c67,0x4470696c,0x61747369,0x0065636e,0x00030005,0x000000a1, 0x00000000,0x00080005,0x000000a5,0x746e655f,0x6f507972,0x4f746e69,0x75707475,0x6f435f74, 0x00726f6c,0x00080005,0x000000a9,0x746e655f,0x6f507972,0x4f746e69,0x75707475,0x56555f74, 0x00000000,0x00090005,0x000000ad,0x746e655f,0x6f507972,0x4f746e69,0x75707475,0x6f575f74, 0x4e646c72,0x00000000,0x00090005,0x000000b0,0x746e655f,0x6f507972,0x4f746e69,0x75707475, 0x6f575f74,0x42646c72,0x00000000,0x00090005,0x000000b3,0x746e655f,0x6f507972,0x4f746e69, 0x75707475,0x6f575f74,0x54646c72,0x00000000,0x00080005,0x000000b6,0x746e655f,0x6f507972, 0x4f746e69,0x75707475,0x6f505f74,0x00005073,0x00040048,0x0000004e,0x00000000,0x00000004, 0x00050048,0x0000004e,0x00000000,0x00000023,0x00000000,0x00050048,0x0000004e,0x00000000, 0x00000007,0x00000010,0x00040048,0x0000004e,0x00000001,0x00000004,0x00050048,0x0000004e, 0x00000001,0x00000023,0x00000040,0x00050048,0x0000004e,0x00000001,0x00000007,0x00000010, 0x00050048,0x0000004e,0x00000002,0x00000023,0x00000080,0x00050048,0x0000004e,0x00000003, 0x00000023,0x00000090,0x00030047,0x0000004e,0x00000002,0x00040047,0x00000050,0x00000022, 0x00000000,0x00040047,0x00000050,0x00000021,0x00000000,0x00040047,0x0000007f,0x0000001e, 0x00000000,0x00040047,0x00000083,0x0000001e,0x00000001,0x00040047,0x00000086,0x0000001e, 0x00000002,0x00040047,0x00000089,0x0000001e,0x00000003,0x00040047,0x0000008d,0x0000001e, 0x00000004,0x00040047,0x00000090,0x0000001e,0x00000005,0x00050048,0x0000009f,0x00000000, 0x0000000b,0x00000000,0x00050048,0x0000009f,0x00000001,0x0000000b,0x00000001,0x00050048, 0x0000009f,0x00000002,0x0000000b,0x00000003,0x00030047,0x0000009f,0x00000002,0x00030047, 0x000000a5,0x00000010,0x00040047,0x000000a5,0x0000001e,0x00000000,0x00030047,0x000000a9, 0x00000010,0x00040047,0x000000a9,0x0000001e,0x00000001,0x00040047,0x000000ad,0x0000001e, 0x00000002,0x00040047,0x000000b0,0x0000001e,0x00000003,0x00040047,0x000000b3,0x0000001e, 0x00000004,0x00040047,0x000000b6,0x0000001e,0x00000005,0x00020013,0x00000002,0x00030021, 0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006, 0x00000003,0x00040017,0x00000008,0x00000006,0x00000004,0x00040017,0x00000009,0x00000006, 0x00000002,0x0008001e,0x0000000a,0x00000007,0x00000008,0x00000008,0x00000008,0x00000009, 0x00000009,0x00040020,0x0000000b,0x00000007,0x0000000a,0x0009001e,0x0000000c,0x00000008, 0x00000008,0x00000009,0x00000007,0x00000007,0x00000007,0x00000008,0x00040021,0x0000000d, 0x0000000c,0x0000000b,0x00040020,0x00000011,0x00000007,0x0000000c,0x0004002b,0x00000006, 0x00000013,0x00000000,0x0007002c,0x00000008,0x00000014,0x00000013,0x00000013,0x00000013, 0x00000013,0x0005002c,0x00000009,0x00000015,0x00000013,0x00000013,0x0006002c,0x00000007, 0x00000016,0x00000013,0x00000013,0x00000013,0x000a002c,0x0000000c,0x00000017,0x00000014, 0x00000014,0x00000015,0x00000016,0x00000016,0x00000016,0x00000014,0x00040020,0x00000018, 0x00000007,0x00000008,0x00040015,0x0000001a,0x00000020,0x00000001,0x0004002b,0x0000001a, 0x0000001b,0x00000002,0x0004002b,0x00000006,0x0000001f,0x3f000000,0x0006002c,0x00000007, 0x00000020,0x0000001f,0x0000001f,0x0000001f,0x0004002b,0x00000006,0x00000022,0x40000000, 0x0004002b,0x0000001a,0x00000029,0x00000003,0x0004002b,0x0000001a,0x0000003e,0x00000000, 0x00040015,0x0000003f,0x00000020,0x00000000,0x0004002b,0x0000003f,0x00000040,0x00000000, 0x00040020,0x00000041,0x00000007,0x00000006,0x0004002b,0x0000003f,0x00000044,0x00000001, 0x0004002b,0x0000003f,0x00000047,0x00000002,0x0004002b,0x00000006,0x0000004a,0x3f800000, 0x00040018,0x0000004d,0x00000008,0x00000004,0x0006001e,0x0000004e,0x0000004d,0x0000004d, 0x00000008,0x00000008,0x00040020,0x0000004f,0x00000002,0x0000004e,0x0004003b,0x0000004f, 0x00000050,0x00000002,0x0004002b,0x0000001a,0x00000051,0x00000001,0x00040020,0x00000052, 0x00000002,0x0000004d,0x00040020,0x0000005a,0x00000007,0x00000009,0x0004002b,0x0000001a, 0x0000005c,0x00000004,0x00040020,0x0000005f,0x00000002,0x00000006,0x00040020,0x0000006d, 0x00000007,0x00000007,0x0004002b,0x0000001a,0x00000072,0x00000005,0x0004002b,0x0000001a, 0x00000076,0x00000006,0x00040020,0x0000007e,0x00000001,0x00000007,0x0004003b,0x0000007e, 0x0000007f,0x00000001,0x00040020,0x00000082,0x00000001,0x00000008,0x0004003b,0x00000082, 0x00000083,0x00000001,0x0004003b,0x00000082,0x00000086,0x00000001,0x0004003b,0x00000082, 0x00000089,0x00000001,0x00040020,0x0000008c,0x00000001,0x00000009,0x0004003b,0x0000008c, 0x0000008d,0x00000001,0x0004003b,0x0000008c,0x00000090,0x00000001,0x0004001c,0x0000009e, 0x00000006,0x00000044,0x0005001e,0x0000009f,0x00000008,0x00000006,0x0000009e,0x00040020, 0x000000a0,0x00000003,0x0000009f,0x0004003b,0x000000a0,0x000000a1,0x00000003,0x00040020, 0x000000a3,0x00000003,0x00000008,0x0004003b,0x000000a3,0x000000a5,0x00000003,0x00040020, 0x000000a8,0x00000003,0x00000009,0x0004003b,0x000000a8,0x000000a9,0x00000003,0x00040020, 0x000000ac,0x00000003,0x00000007,0x0004003b,0x000000ac,0x000000ad,0x00000003,0x0004003b, 0x000000ac,0x000000b0,0x00000003,0x0004003b,0x000000ac,0x000000b3,0x00000003,0x0004003b, 0x000000a3,0x000000b6,0x00000003,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003, 0x000200f8,0x00000005,0x0004003b,0x0000000b,0x0000007d,0x00000007,0x0004003b,0x00000011, 0x00000093,0x00000007,0x0004003b,0x0000000b,0x00000094,0x00000007,0x0004003b,0x00000018, 0x00000097,0x00000007,0x0004003d,0x00000007,0x00000080,0x0000007f,0x00050041,0x0000006d, 0x00000081,0x0000007d,0x0000003e,0x0003003e,0x00000081,0x00000080,0x0004003d,0x00000008, 0x00000084,0x00000083,0x00050041,0x00000018,0x00000085,0x0000007d,0x00000051,0x0003003e, 0x00000085,0x00000084,0x0004003d,0x00000008,0x00000087,0x00000086,0x00050041,0x00000018, 0x00000088,0x0000007d,0x0000001b,0x0003003e,0x00000088,0x00000087,0x0004003d,0x00000008, 0x0000008a,0x00000089,0x00050041,0x00000018,0x0000008b,0x0000007d,0x00000029,0x0003003e, 0x0000008b,0x0000008a,0x0004003d,0x00000009,0x0000008e,0x0000008d,0x00050041,0x0000005a, 0x0000008f,0x0000007d,0x0000005c,0x0003003e,0x0000008f,0x0000008e,0x0004003d,0x00000009, 0x00000091,0x00000090,0x00050041,0x0000005a,0x00000092,0x0000007d,0x00000072,0x0003003e, 0x00000092,0x00000091,0x0004003d,0x0000000a,0x00000095,0x0000007d,0x0003003e,0x00000094, 0x00000095,0x00050039,0x0000000c,0x00000096,0x0000000f,0x00000094,0x0003003e,0x00000093, 0x00000096,0x00050041,0x00000018,0x00000098,0x00000093,0x0000003e,0x0004003d,0x00000008, 0x00000099,0x00000098,0x0003003e,0x00000097,0x00000099,0x00050041,0x00000041,0x0000009a, 0x00000097,0x00000044,0x0004003d,0x00000006,0x0000009b,0x0000009a,0x0004007f,0x00000006, 0x0000009c,0x0000009b,0x00050041,0x00000041,0x0000009d,0x00000097,0x00000044,0x0003003e, 0x0000009d,0x0000009c,0x0004003d,0x00000008,0x000000a2,0x00000097,0x00050041,0x000000a3, 0x000000a4,0x000000a1,0x0000003e,0x0003003e,0x000000a4,0x000000a2,0x00050041,0x00000018, 0x000000a6,0x00000093,0x00000051,0x0004003d,0x00000008,0x000000a7,0x000000a6,0x0003003e, 0x000000a5,0x000000a7,0x00050041,0x0000005a,0x000000aa,0x00000093,0x0000001b,0x0004003d, 0x00000009,0x000000ab,0x000000aa,0x0003003e,0x000000a9,0x000000ab,0x00050041,0x0000006d, 0x000000ae,0x00000093,0x00000029,0x0004003d,0x00000007,0x000000af,0x000000ae,0x0003003e, 0x000000ad,0x000000af,0x00050041,0x0000006d,0x000000b1,0x00000093,0x0000005c,0x0004003d, 0x00000007,0x000000b2,0x000000b1,0x0003003e,0x000000b0,0x000000b2,0x00050041,0x0000006d, 0x000000b4,0x00000093,0x00000072,0x0004003d,0x00000007,0x000000b5,0x000000b4,0x0003003e, 0x000000b3,0x000000b5,0x00050041,0x00000018,0x000000b7,0x00000093,0x00000076,0x0004003d, 0x00000008,0x000000b8,0x000000b7,0x0003003e,0x000000b6,0x000000b8,0x000100fd,0x00010038, 0x00050036,0x0000000c,0x0000000f,0x00000000,0x0000000d,0x00030037,0x0000000b,0x0000000e, 0x000200f8,0x00000010,0x0004003b,0x00000011,0x00000012,0x00000007,0x0004003b,0x00000018, 0x00000019,0x00000007,0x0004003b,0x00000018,0x00000028,0x00000007,0x0004003b,0x00000018, 0x00000033,0x00000007,0x0004003b,0x00000018,0x0000003d,0x00000007,0x0004003b,0x0000005a, 0x0000005b,0x00000007,0x0003003e,0x00000012,0x00000017,0x00050041,0x00000018,0x0000001c, 0x0000000e,0x0000001b,0x0004003d,0x00000008,0x0000001d,0x0000001c,0x0008004f,0x00000007, 0x0000001e,0x0000001d,0x0000001d,0x00000000,0x00000001,0x00000002,0x00050083,0x00000007, 0x00000021,0x0000001e,0x00000020,0x0005008e,0x00000007,0x00000023,0x00000021,0x00000022, 0x00050051,0x00000006,0x00000024,0x00000023,0x00000000,0x00050051,0x00000006,0x00000025, 0x00000023,0x00000001,0x00050051,0x00000006,0x00000026,0x00000023,0x00000002,0x00070050, 0x00000008,0x00000027,0x00000024,0x00000025,0x00000026,0x00000013,0x0003003e,0x00000019, 0x00000027,0x00050041,0x00000018,0x0000002a,0x0000000e,0x00000029,0x0004003d,0x00000008, 0x0000002b,0x0000002a,0x0008004f,0x00000007,0x0000002c,0x0000002b,0x0000002b,0x00000000, 0x00000001,0x00000002,0x00050083,0x00000007,0x0000002d,0x0000002c,0x00000020,0x0005008e, 0x00000007,0x0000002e,0x0000002d,0x00000022,0x00050051,0x00000006,0x0000002f,0x0000002e, 0x00000000,0x00050051,0x00000006,0x00000030,0x0000002e,0x00000001,0x00050051,0x00000006, 0x00000031,0x0000002e,0x00000002,0x00070050,0x00000008,0x00000032,0x0000002f,0x00000030, 0x00000031,0x00000013,0x0003003e,0x00000028,0x00000032,0x0004003d,0x00000008,0x00000034, 0x00000019,0x0008004f,0x00000007,0x00000035,0x00000034,0x00000034,0x00000000,0x00000001, 0x00000002,0x0004003d,0x00000008,0x00000036,0x00000028,0x0008004f,0x00000007,0x00000037, 0x00000036,0x00000036,0x00000000,0x00000001,0x00000002,0x0007000c,0x00000007,0x00000038, 0x00000001,0x00000044,0x00000035,0x00000037,0x00050051,0x00000006,0x00000039,0x00000038, 0x00000000,0x00050051,0x00000006,0x0000003a,0x00000038,0x00000001,0x00050051,0x00000006, 0x0000003b,0x00000038,0x00000002,0x00070050,0x00000008,0x0000003c,0x00000039,0x0000003a, 0x0000003b,0x00000013,0x0003003e,0x00000033,0x0000003c,0x00060041,0x00000041,0x00000042, 0x0000000e,0x0000003e,0x00000040,0x0004003d,0x00000006,0x00000043,0x00000042,0x00060041, 0x00000041,0x00000045,0x0000000e,0x0000003e,0x00000044,0x0004003d,0x00000006,0x00000046, 0x00000045,0x00060041,0x00000041,0x00000048,0x0000000e,0x0000003e,0x00000047,0x0004003d, 0x00000006,0x00000049,0x00000048,0x00070050,0x00000008,0x0000004b,0x00000043,0x00000046, 0x00000049,0x0000004a,0x0003003e,0x0000003d,0x0000004b,0x0004003d,0x00000008,0x0000004c, 0x0000003d,0x00050041,0x00000052,0x00000053,0x00000050,0x00000051,0x0004003d,0x0000004d, 0x00000054,0x00000053,0x00050090,0x00000008,0x00000055,0x0000004c,0x00000054,0x00050041, 0x00000018,0x00000056,0x00000012,0x0000003e,0x0003003e,0x00000056,0x00000055,0x00050041, 0x00000018,0x00000057,0x0000000e,0x00000051,0x0004003d,0x00000008,0x00000058,0x00000057, 0x00050041,0x00000018,0x00000059,0x00000012,0x00000051,0x0003003e,0x00000059,0x00000058, 0x00050041,0x0000005a,0x0000005d,0x0000000e,0x0000005c,0x0004003d,0x00000009,0x0000005e, 0x0000005d,0x0003003e,0x0000005b,0x0000005e,0x00060041,0x0000005f,0x00000060,0x00000050, 0x0000001b,0x00000040,0x0004003d,0x00000006,0x00000061,0x00000060,0x00060041,0x0000005f, 0x00000062,0x00000050,0x0000001b,0x00000044,0x0004003d,0x00000006,0x00000063,0x00000062, 0x00050041,0x00000041,0x00000064,0x0000005b,0x00000044,0x0004003d,0x00000006,0x00000065, 0x00000064,0x00050085,0x00000006,0x00000066,0x00000063,0x00000065,0x00050081,0x00000006, 0x00000067,0x00000061,0x00000066,0x00050041,0x00000041,0x00000068,0x0000005b,0x00000044, 0x0003003e,0x00000068,0x00000067,0x0004003d,0x00000009,0x00000069,0x0000005b,0x00050041, 0x0000005a,0x0000006a,0x00000012,0x0000001b,0x0003003e,0x0000006a,0x00000069,0x0004003d, 0x00000008,0x0000006b,0x00000019,0x0008004f,0x00000007,0x0000006c,0x0000006b,0x0000006b, 0x00000000,0x00000001,0x00000002,0x00050041,0x0000006d,0x0000006e,0x00000012,0x00000029, 0x0003003e,0x0000006e,0x0000006c,0x0004003d,0x00000008,0x0000006f,0x00000033,0x0008004f, 0x00000007,0x00000070,0x0000006f,0x0000006f,0x00000000,0x00000001,0x00000002,0x00050041, 0x0000006d,0x00000071,0x00000012,0x0000005c,0x0003003e,0x00000071,0x00000070,0x0004003d, 0x00000008,0x00000073,0x00000028,0x0008004f,0x00000007,0x00000074,0x00000073,0x00000073, 0x00000000,0x00000001,0x00000002,0x00050041,0x0000006d,0x00000075,0x00000012,0x00000072, 0x0003003e,0x00000075,0x00000074,0x00050041,0x00000018,0x00000077,0x00000012,0x0000003e, 0x0004003d,0x00000008,0x00000078,0x00000077,0x00050041,0x00000018,0x00000079,0x00000012, 0x00000076,0x0003003e,0x00000079,0x00000078,0x0004003d,0x0000000c,0x0000007a,0x00000012, 0x000200fe,0x0000007a,0x00010038 };
8,384
575
import torch.nn as nn import transformers import config class NLUModel(nn.Module): def __init__(self,num_entity, num_intent, num_scenario): super(NLUModel,self).__init__() self.num_entity = num_entity self.num_intent = num_intent self.num_scenario = num_scenario self.bert = transformers.BertModel.from_pretrained( config.BASE_MODEL ) self.drop_1 = nn.Dropout(0.3) self.drop_2 = nn.Dropout(0.3) self.drop_3 = nn.Dropout(0.3) self.out_entity = nn.Linear(768,self.num_entity) self.out_intent = nn.Linear(768,self.num_intent) self.out_scenario = nn.Linear(768,self.num_scenario) def forward(self, ids,mask,token_type_ids): out = self.bert(input_ids=ids, attention_mask=mask, token_type_ids=token_type_ids ) hs, cls_hs = out['last_hidden_state'], out['pooler_output'] entity_hs = self.drop_1(hs) intent_hs = self.drop_2(cls_hs) scenario_hs = self.drop_3(cls_hs) entity_hs = self.out_entity(entity_hs) intent_hs = self.out_intent(intent_hs) scenario_hs = self.out_scenario(scenario_hs) return entity_hs,intent_hs,scenario_hs
679
1,253
<gh_stars>1000+ """ What is Anagram? An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Method #Bit Manipulation: If we start at a value of 0 and XOR all the characters of both strings, we should return an end value of 0 if they are anagrams because there would be an even occurrence of all characters in the anagram. Done forget to defend the code by validating inputs. Time Complexity: O(n) Space Complexity: O(1) """ str1 = input(); #abcd str2 = input(); #dabc def isAnagram(srt1,str2): if len(str1)!=len(str2): return False else: value=0 for i in range(len(str1)): value^=ord(str1[i])^ord(str2[i]) #ord() return Ascii value of character like 'a'->97,'A'->65 etc. if value==0: return True else: return False result=isAnagram(str1,str2) print(result)
368
14,668
<reponame>zealoussnow/chromium // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/scheduler/internal/impression_types.h" namespace notifications { Impression::Impression() = default; Impression::Impression(SchedulerClientType type, const std::string& guid, const base::Time& create_time) : create_time(create_time), guid(guid), type(type) {} Impression::Impression(const Impression& other) = default; Impression::~Impression() = default; bool Impression::operator==(const Impression& other) const { return create_time == other.create_time && feedback == other.feedback && impression == other.impression && integrated == other.integrated && guid == other.guid && type == other.type && impression_mapping == other.impression_mapping && custom_data == other.custom_data && ignore_timeout_duration == other.ignore_timeout_duration; } SuppressionInfo::SuppressionInfo(const base::Time& last_trigger, const base::TimeDelta& duration) : last_trigger_time(last_trigger), duration(duration), recover_goal(1) {} SuppressionInfo::SuppressionInfo(const SuppressionInfo& other) = default; bool SuppressionInfo::operator==(const SuppressionInfo& other) const { return last_trigger_time == other.last_trigger_time && duration == other.duration && recover_goal == other.recover_goal; } base::Time SuppressionInfo::ReleaseTime() const { return last_trigger_time + duration; } ClientState::ClientState() : type(SchedulerClientType::kUnknown), current_max_daily_show(0), negative_events_count(0) {} ClientState::ClientState(const ClientState& other) = default; ClientState::~ClientState() = default; bool ClientState::operator==(const ClientState& other) const { if (impressions.size() != other.impressions.size()) return false; for (size_t i = 0; i < impressions.size(); ++i) { if (!(impressions[i] == other.impressions[i])) return false; } return type == other.type && current_max_daily_show == other.current_max_daily_show && suppression_info == other.suppression_info && negative_events_count == other.negative_events_count && last_negative_event_ts == other.last_negative_event_ts && last_shown_ts == other.last_shown_ts; } } // namespace notifications
890
1,068
<reponame>kriegfrj/assertj-android package org.assertj.android.api.view; import android.support.annotation.IntDef; import android.view.View; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.SOURCE; @IntDef({ View.LAYOUT_DIRECTION_RTL, View.LAYOUT_DIRECTION_LTR, View.LAYOUT_DIRECTION_INHERIT, View.LAYOUT_DIRECTION_LOCALE }) @Retention(SOURCE) public @interface ViewLayoutDirection { }
172
9,225
<filename>src/_pytest/__init__.py<gh_stars>1000+ __all__ = ["__version__", "version_tuple"] try: from ._version import version as __version__, version_tuple except ImportError: # pragma: no cover # broken installation, we don't even try # unknown only works because we do poor mans version compare __version__ = "unknown" version_tuple = (0, 0, "unknown") # type:ignore[assignment]
136
6,278
<gh_stars>1000+ import unittest from tests.recipes.recipe_lib_test import BaseTestForMakeRecipe class TestLibx264Recipe(BaseTestForMakeRecipe, unittest.TestCase): """ An unittest for recipe :mod:`~pythonforandroid.recipes.libx264` """ recipe_name = "libx264" sh_command_calls = ["./configure"]
120
1,439
/******************************************************************************* * Copyright 2018 <NAME> http://galenframework.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.galenframework.rainbow4j.filters; import com.galenframework.rainbow4j.ImageHandler; import java.awt.*; import java.nio.ByteBuffer; public class QuantinizeFilter implements ImageFilter { private int colorsAmount; public QuantinizeFilter(int colorsAmount) { this.colorsAmount = colorsAmount; } public int getColorsAmount() { return colorsAmount; } public void setColorsAmount(int colorsAmount) { this.colorsAmount = colorsAmount; } @Override public void apply(ByteBuffer bytes, int width, int height, Rectangle area) { if (colorsAmount > 255) { colorsAmount = 255; } else if (colorsAmount < 2) { colorsAmount = 2; } int d = 256 / colorsAmount; for (int y = area.y; y < area.y + area.height; y++) { for (int x = area.x; x < area.x + area.width; x++) { int k = y * width * ImageHandler.BLOCK_SIZE + x * ImageHandler.BLOCK_SIZE; double red = (bytes.get(k) & 0xff) / d; double green = (bytes.get(k + 1) & 0xff) / d; double blue = (bytes.get(k + 2) & 0xff) / d; bytes.put(k, (byte) (Math.ceil(red) * d)); bytes.put(k + 1, (byte) (Math.ceil(green) * d)); bytes.put(k + 2, (byte) (Math.ceil(blue) * d)); } } } }
828
2,113
<reponame>vbillet/Torque3D //----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "core/util/zip/zipArchive.h" #include "core/stream/stream.h" #include "core/stream/fileStream.h" #include "core/filterStream.h" #include "core/util/zip/zipCryptStream.h" #include "core/crc.h" //#include "core/resManager.h" #include "console/console.h" #include "core/util/zip/compressor.h" #include "core/util/zip/zipTempStream.h" #include "core/util/zip/zipStatFilter.h" #ifdef TORQUE_ZIP_AES #include "core/zipAESCryptStream.h" #include "core/zip/crypto/aes.h" #endif #include "core/util/safeDelete.h" #include "app/version.h" namespace Zip { //----------------------------------------------------------------------------- // Constructor/Destructor //----------------------------------------------------------------------------- ZipArchive::ZipArchive() : mStream(NULL), mDiskStream(NULL), mMode(Read), mRoot(NULL), mFilename(NULL) { } ZipArchive::~ZipArchive() { closeArchive(); } //----------------------------------------------------------------------------- // Protected Methods //----------------------------------------------------------------------------- bool ZipArchive::readCentralDirectory() { mEntries.clear(); SAFE_DELETE(mRoot); mRoot = new ZipEntry; mRoot->mName = ""; mRoot->mIsDirectory = true; mRoot->mCD.setFilename(""); if(! mEOCD.findInStream(mStream)) return false; if(! mEOCD.read(mStream)) return false; if(mEOCD.mDiskNum != mEOCD.mStartCDDiskNum || mEOCD.mNumEntriesInThisCD != mEOCD.mTotalEntriesInCD) { if(isVerbose()) Con::errorf("ZipArchive::readCentralDirectory - %s: Zips that span multiple disks are not supported.", mFilename ? mFilename : "<no filename>"); return false; } if(! mStream->setPosition(mEOCD.mCDOffset)) return false; for(S32 i = 0;i < mEOCD.mNumEntriesInThisCD;++i) { ZipEntry *ze = new ZipEntry; if(! ze->mCD.read(mStream)) { delete ze; if(isVerbose()) Con::errorf("ZipArchive::readCentralDirectory - %s: Error reading central directory.", mFilename ? mFilename : "<no filename>"); return false; } insertEntry(ze); } return true; } void ZipArchive::dumpCentralDirectory(ZipEntry* entry, String* indent) { // if entry is null, use root if (entry == NULL) entry = mRoot; if (!entry) return; String emptyIndent; if (indent == NULL) indent = &emptyIndent; Con::printf("%s%s%s", indent->c_str(), entry->mIsDirectory ? "/" : "", entry->mName.c_str()); for (Map<String,ZipEntry*>::Iterator iter = entry->mChildren.begin(); iter != entry->mChildren.end(); ++iter) { String newIdent = *indent + " "; dumpCentralDirectory((*iter).value, &(newIdent)); } } //----------------------------------------------------------------------------- void ZipArchive::insertEntry(ZipEntry *ze) { char path[1024]; dStrncpy(path, ze->mCD.mFilename.c_str(), sizeof(path)); path[sizeof(path) - 1] = 0; for(S32 i = 0;i < dStrlen(path);++i) { if(path[i] == '\\') path[i] = '/'; } ZipEntry *root = mRoot; char *ptr = path, *slash = NULL; do { slash = dStrchr(ptr, '/'); if(slash) { // Add the directory *slash = 0; // try to get root, create if not found ZipEntry *newEntry = NULL; if (!root->mChildren.tryGetValue(ptr, newEntry)) { newEntry = new ZipEntry; newEntry->mParent = root; newEntry->mName = String(ptr); newEntry->mIsDirectory = true; newEntry->mCD.setFilename(path); root->mChildren[ptr] = newEntry; } root = newEntry; *slash = '/'; ptr = slash + 1; } else { // Add the file. if(*ptr) { ze->mIsDirectory = false; ze->mName = ptr; ze->mParent = root; root->mChildren[ptr] = ze; mEntries.push_back(ze); } else { // [tom, 2/6/2007] If ptr is empty, this was a directory entry. Since // we created a new entry for it above, we need to delete the old // pointer otherwise it will leak as it won't have got inserted. delete ze; } } } while(slash); } void ZipArchive::removeEntry(ZipEntry *ze) { if(ze == mRoot) { // [tom, 2/1/2007] We don't want to remove the root as it should always // be removed through closeArchive() AssertFatal(0, "ZipArchive::removeEntry - Attempting to remove the root"); return; } // Can't iterate the hash table, so we can't do this safely AssertFatal(!ze->mIsDirectory, "ZipArchive::removeEntry - Cannot remove a directory"); // See if we have a temporary file for this entry Vector<ZipTempStream *>::iterator i; for(i = mTempFiles.begin();i != mTempFiles.end();++i) { if((*i)->getCentralDir() == &ze->mCD) { SAFE_DELETE(*i); mTempFiles.erase(i); break; } } // Remove from the tree Vector<ZipEntry *>::iterator j; for(j = mEntries.begin();j != mEntries.end();++j) { if(*j == ze) { mEntries.erase(j); break; } } // [tom, 2/2/2007] This must be last, as ze is no longer valid once it's // removed from the parent. ZipEntry *z = ze->mParent->mChildren[ze->mName]; ze->mParent->mChildren.erase(ze->mName); delete z; } //----------------------------------------------------------------------------- CentralDir *ZipArchive::findFileInfo(const char *filename) { ZipEntry *ze = findZipEntry(filename); return ze ? &ze->mCD : NULL; } ZipArchive::ZipEntry *ZipArchive::findZipEntry(const char *filename) { char path[1024]; dStrncpy(path, filename, sizeof(path)); path[sizeof(path) - 1] = 0; for(S32 i = 0;i < dStrlen(path);++i) { if(path[i] == '\\') path[i] = '/'; } ZipEntry *root = mRoot; char *ptr = path, *slash = NULL; do { slash = dStrchr(ptr, '/'); if(slash) { // Find the directory *slash = 0; // check child dict for new root ZipEntry *newRoot = NULL; if (!root->mChildren.tryGetValue(ptr, newRoot)) return NULL; root = newRoot; ptr = slash + 1; } else { // Find the file ZipEntry* entry = NULL; if (root->mChildren.tryGetValue(ptr, entry)) return entry; } } while(slash); return NULL; } //----------------------------------------------------------------------------- Stream *ZipArchive::createNewFile(const char *filename, Compressor *method) { ZipEntry *ze = new ZipEntry; ze->mIsDirectory = false; ze->mCD.setFilename(filename); insertEntry(ze); ZipTempStream *stream = new ZipTempStream(&ze->mCD); if(stream->open()) { Stream *retStream = method->createWriteStream(&ze->mCD, stream); if(retStream == NULL) { delete stream; return NULL; } ZipStatFilter *filter = new ZipStatFilter(&ze->mCD); if(! filter->attachStream(retStream)) { delete filter; delete retStream; delete stream; return NULL; } ze->mCD.mCompressMethod = method->getMethod(); ze->mCD.mInternalFlags |= CDFileOpen; return filter; } return NULL; } void ZipArchive::updateFile(ZipTempStream *stream) { CentralDir *cd = stream->getCentralDir(); // [tom, 1/23/2007] Uncompressed size and CRC32 are updated by ZipStatFilter cd->mCompressedSize = stream->getStreamSize(); cd->mInternalFlags |= CDFileDirty; cd->mInternalFlags &= ~CDFileOpen; // Upper byte should be zero, lower is version as major * 10 + minor cd->mVersionMadeBy = (getVersionNumber() / 100) & 0xff; cd->mExtractVer = 20; U32 dosTime = currentTimeToDOSTime(); cd->mModTime = dosTime & 0x0000ffff; cd->mModDate = (dosTime & 0xffff0000) >> 16; mTempFiles.push_back(stream); } //----------------------------------------------------------------------------- U32 ZipArchive::localTimeToDOSTime(const Torque::Time::DateTime &dt) { // DOS time format // http://msdn.microsoft.com/en-us/library/ms724274(VS.85).aspx return TimeToDOSTime(Torque::Time(dt)); } U32 ZipArchive::TimeToDOSTime(const Torque::Time& t) { S32 year,month,day,hour,minute,second,microsecond; t.get(&year, &month, &day, &hour, &minute, &second, &microsecond); if(year > 1980) // De Do Do Do, De Da Da Da year -= 1980; return (((day) + (32 * (month)) + (512 * year)) << 16) | ((second/2) + (32* minute) + (2048 * (U32)hour)); } Torque::Time ZipArchive::DOSTimeToTime(U16 time, U16 date) { Torque::Time::DateTime dt; dt.microsecond = 0; dt.hour = (time & 0xF800) >> 11; dt.minute = (time & 0x07E0) >> 5; dt.second = (time & 0x001F)*2; dt.year = ((date & 0xFE00) >> 9) + 1980; dt.month = (date & 0x01E0) >> 5; dt.day = (date & 0x001F); return Torque::Time(dt); } Torque::Time ZipArchive::DOSTimeToTime(U32 dosTime) { U16 time = dosTime & 0x0000ffff; U16 date = (dosTime & 0xffff0000) >> 16; return ZipArchive::DOSTimeToTime(time, date); } U32 ZipArchive::currentTimeToDOSTime() { Torque::Time::DateTime dt; Torque::Time::getCurrentDateTime(dt); return localTimeToDOSTime(dt); } //----------------------------------------------------------------------------- // [tom, 1/24/2007] The general idea here is we want to create a new file, // copy any data from the old zip file and add the new stuff. Once the new // zip is created, delete the old one and rename the new one. bool ZipArchive::rebuildZip() { String newZipName; FileStream tempFile; Stream *zipFile = mStream; // FIXME [tom, 1/24/2007] Temporary for expediting testing if(mFilename == NULL) return false; if(mMode == ReadWrite) { newZipName = String(mFilename) + ".new"; if(! tempFile.open(newZipName, mMode == Write ? Torque::FS::File::Write : Torque::FS::File::ReadWrite)) return false; zipFile = &tempFile; } // Copy any unmodified files for(S32 i = 0;i < mEntries.size();++i) { ZipEntry *entry = mEntries[i]; // Directories are internal only for lookup purposes if(entry->mIsDirectory || (entry->mCD.mInternalFlags & (CDFileDirty | CDFileDeleted))) continue; copyFileToNewZip(&entry->mCD, zipFile); } // Copy any dirty files for(S32 i = 0;i < mTempFiles.size();++i) { ZipTempStream *zts = mTempFiles[i]; writeDirtyFileToNewZip(zts, zipFile); zts->close(); delete zts; mTempFiles[i] = NULL; } mTempFiles.clear(); // Write central directory mEOCD.mCDOffset = zipFile->getPosition(); mEOCD.mNumEntriesInThisCD = 0; for(S32 i = 0;i < mEntries.size();++i) { ZipEntry *entry = mEntries[i]; // [tom, 1/24/2007] Directories are internal only for lookup purposes if(entry->mIsDirectory || (entry->mCD.mInternalFlags & CDFileDeleted) != 0) continue; ++mEOCD.mNumEntriesInThisCD; if(! entry->mCD.write(zipFile)) break; } mEOCD.mCDSize = zipFile->getPosition() - mEOCD.mCDOffset; mEOCD.mTotalEntriesInCD = mEOCD.mNumEntriesInThisCD; mEOCD.mDiskNum = 0; mEOCD.mStartCDDiskNum = 0; mEOCD.write(zipFile); if(mMode == ReadWrite) { // Close file, replace old zip with it tempFile.close(); // [tom, 2/1/2007] The disk stream must be closed else we can't rename // the file. Since rebuildZip() is only called from closeArchive() this // should be safe. if(mDiskStream) { mDiskStream->close(); delete mDiskStream; mDiskStream = NULL; } String oldRename; oldRename = String(mFilename) + ".old"; if(! Torque::FS::Rename(mFilename, oldRename)) return false; if(! Torque::FS::Rename(newZipName, mFilename)) return false; Torque::FS::Remove(oldRename); } return true; } bool ZipArchive::writeDirtyFileToNewZip(ZipTempStream *fileStream, Stream *zipStream) { CentralDir *cdir = fileStream->getCentralDir(); FileHeader fh(*cdir); fh.setFilename(cdir->mFilename); cdir->mLocalHeadOffset = zipStream->getPosition(); // Write header and file if(! fh.write(zipStream)) return false; if(! fileStream->rewind()) return false; return zipStream->copyFrom(fileStream); } bool ZipArchive::copyFileToNewZip(CentralDir *cdir, Stream *newZipStream) { // [tom, 1/24/2007] Using the stored compressor allows us to copy the raw // data regardless of compression method without having to re-compress it. Compressor *comp = Compressor::findCompressor(Stored); if(comp == NULL) return false; if(! mStream->setPosition(cdir->mLocalHeadOffset)) return false; // Copy file header // FIXME [tom, 1/24/2007] This will currently not copy the extra fields FileHeader fh; if(! fh.read(mStream)) return false; cdir->mLocalHeadOffset = newZipStream->getPosition(); if(! fh.write(newZipStream)) return false; // Copy file data Stream *readS = comp->createReadStream(cdir, mStream); if(readS == NULL) return false; bool ret = newZipStream->copyFrom(readS); // [tom, 1/24/2007] closeFile() just frees the relevant filters and // thus it is safe to call from here. closeFile(readS); return ret; } //----------------------------------------------------------------------------- // Public Methods //----------------------------------------------------------------------------- void ZipArchive::setFilename(const char *filename) { SAFE_FREE(mFilename); if(filename) mFilename = dStrdup(filename); } //----------------------------------------------------------------------------- bool ZipArchive::openArchive(const char *filename, AccessMode mode /* = Read */) { if(mode != Read && mode != Write && mode != ReadWrite) return false; closeArchive(); mDiskStream = new FileStream; if(mDiskStream->open(filename, (Torque::FS::File::AccessMode)mode)) { setFilename(filename); if(openArchive(mDiskStream, mode)) return true; } // Cleanup just in case openArchive() failed closeArchive(); return false; } bool ZipArchive::openArchive(Stream *stream, AccessMode mode /* = Read */) { if(mode != Read && mode != Write && mode != ReadWrite) return false; mStream = stream; mMode = mode; if(mode == Read || mode == ReadWrite) { bool ret = readCentralDirectory(); if(mode == Read) return ret; return true; } else { mEntries.clear(); SAFE_DELETE(mRoot); mRoot = new ZipEntry; mRoot->mName = ""; mRoot->mIsDirectory = true; mRoot->mCD.setFilename(""); } return true; } void ZipArchive::closeArchive() { if(mMode == Write || mMode == ReadWrite) rebuildZip(); // Free any remaining temporary files for(S32 i = 0;i < mTempFiles.size();++i) { SAFE_DELETE(mTempFiles[i]); } mTempFiles.clear(); // Close the zip file stream and clean up if(mDiskStream) { mDiskStream->close(); delete mDiskStream; mDiskStream = NULL; } mStream = NULL; SAFE_FREE(mFilename); SAFE_DELETE(mRoot); mEntries.clear(); } //----------------------------------------------------------------------------- Stream * ZipArchive::openFile(const char *filename, AccessMode mode /* = Read */) { ZipEntry* ze = findZipEntry(filename); return openFile(filename, ze, mode); } Stream * ZipArchive::openFile(const char *filename, ZipEntry* ze, AccessMode mode /* = Read */) { if(mode == Read) { if(ze == NULL) return NULL; return openFileForRead(&ze->mCD); } if(mode == Write) { if(ze) { if(ze->mCD.mInternalFlags & CDFileOpen) { if(isVerbose()) Con::errorf("ZipArchive::openFile - File %s is already open", filename); return NULL; } // Remove the old entry so we can create a new one removeEntry(ze); ze = NULL; } return createNewFile(filename, Compressor::findCompressor(Deflated)); } if(isVerbose()) Con::errorf("ZipArchive::openFile - Files within zips can only be opened as read or write, but not both at the same time."); return NULL; } void ZipArchive::closeFile(Stream *stream) { FilterStream *currentStream, *nextStream; nextStream = dynamic_cast<FilterStream*>(stream); while (nextStream) { currentStream = nextStream; stream = currentStream->getStream(); currentStream->detachStream(); nextStream = dynamic_cast<FilterStream*>(stream); delete currentStream; } ZipTempStream *tempStream = dynamic_cast<ZipTempStream *>(stream); if(tempStream && (tempStream->getCentralDir()->mInternalFlags & CDFileOpen)) { // [tom, 1/23/2007] This is a temporary file we are writing to // so we need to update the relevant information in the header. updateFile(tempStream); } } //----------------------------------------------------------------------------- Stream *ZipArchive::openFileForRead(const CentralDir *fileCD) { if(mMode != Read && mMode != ReadWrite) return NULL; if((fileCD->mInternalFlags & (CDFileDeleted | CDFileOpen)) != 0) return NULL; Stream *stream = mStream; if(fileCD->mInternalFlags & CDFileDirty) { // File is dirty, we need to read from the temporary file for(S32 i = 0;i < mTempFiles.size();++i) { if(mTempFiles[i]->getCentralDir() == fileCD) { // Found the temporary file if(! mTempFiles[i]->rewind()) { if(isVerbose()) Con::errorf("ZipArchive::openFile - %s: %s is dirty, but could not rewind temporary file?", mFilename ? mFilename : "<no filename>", fileCD->mFilename.c_str()); return NULL; } stream = mTempFiles[i]; break; } } if(stream == mStream) { if(isVerbose()) Con::errorf("ZipArchive::openFile - %s: %s is dirty, but no temporary file found?", mFilename ? mFilename : "<no filename>", fileCD->mFilename.c_str()); return NULL; } } else { // Read from the zip file directly if(! mStream->setPosition(fileCD->mLocalHeadOffset)) { if(isVerbose()) Con::errorf("ZipArchive::openFile - %s: Could not locate local header for file %s", mFilename ? mFilename : "<no filename>", fileCD->mFilename.c_str()); return NULL; } FileHeader fh; if(! fh.read(mStream)) { if(isVerbose()) Con::errorf("ZipArchive::openFile - %s: Could not read local header for file %s", mFilename ? mFilename : "<no filename>", fileCD->mFilename.c_str()); return NULL; } } Stream *attachTo = stream; U16 compMethod = fileCD->mCompressMethod; if(fileCD->mFlags & Encrypted) { if(fileCD->mCompressMethod == AESEncrypted) { // [tom, 1/19/2007] Whilst AES support does exist, I'm not including it in TGB // to avoid having to deal with crypto export legal issues. Con::errorf("ZipArchive::openFile - %s: File %s is AES encrypted, but AES is not supported in this version.", mFilename ? mFilename : "<no filename>", fileCD->mFilename.c_str()); } else { ZipCryptRStream *cryptStream = new ZipCryptRStream; cryptStream->setPassword(<PASSWORD>); cryptStream->setFileEndPos(stream->getPosition() + fileCD->mCompressedSize); if(! cryptStream->attachStream(stream)) { delete cryptStream; return NULL; } attachTo = cryptStream; } } Compressor *comp = Compressor::findCompressor(compMethod); if(comp == NULL) { if(isVerbose()) Con::errorf("ZipArchive::openFile - %s: Unsupported compression method (%d) for file %s", mFilename ? mFilename : "<no filename>", fileCD->mCompressMethod, fileCD->mFilename.c_str()); return NULL; } return comp->createReadStream(fileCD, attachTo); } //----------------------------------------------------------------------------- bool ZipArchive::addFile(const char *filename, const char *pathInZip, bool replace /* = true */) { FileStream f; if (!f.open(filename, Torque::FS::File::Read)) return false; const CentralDir *cd = findFileInfo(pathInZip); if(! replace && cd && (cd->mInternalFlags & CDFileDeleted) == 0) return false; Stream *dest = openFile(pathInZip, Write); if(dest == NULL) { f.close(); return false; } bool ret = dest->copyFrom(&f); closeFile(dest); f.close(); return ret; } bool ZipArchive::extractFile(const char *pathInZip, const char *filename, bool *crcFail /* = NULL */) { if(crcFail) *crcFail = false; const CentralDir *realCD = findFileInfo(pathInZip); if(realCD == NULL) return false; FileStream dest; if(! dest.open(filename, Torque::FS::File::Write)) return false; Stream *source = openFile(pathInZip, Read); if(source == NULL) { dest.close(); return false; } // [tom, 2/7/2007] CRC checking the lazy man's way // ZipStatFilter only fails if it doesn't have a central directory, so this is safe CentralDir fakeCD; ZipStatFilter zsf(&fakeCD); zsf.attachStream(source); bool ret = dest.copyFrom(&zsf); zsf.detachStream(); if(ret && fakeCD.mCRC32 != realCD->mCRC32) { if(crcFail) *crcFail = true; if(isVerbose()) Con::errorf("ZipArchive::extractFile - CRC failure extracting file %s", pathInZip); ret = false; } closeFile(source); dest.close(); return ret; } bool ZipArchive::deleteFile(const char *filename) { if(mMode != Write && mMode != ReadWrite) return false; CentralDir *cd = findFileInfo(filename); if(cd == NULL) return false; cd->mInternalFlags |= CDFileDeleted; // CodeReview [tom, 2/9/2007] If this is a file we have a temporary file for, // we should probably delete it here rather then waiting til the archive is closed. return true; } //----------------------------------------------------------------------------- bool ZipArchive::isVerbose() { return Con::getBoolVariable("$pref::Zip::Verbose"); } void ZipArchive::setVerbose(bool verbose) { Con::setBoolVariable("$pref::Zip::Verbose", verbose); } } // end namespace Zip
9,544
3,428
{"id":"00044","group":"easy-ham-2","checksum":{"type":"MD5","value":"1ed173a136e8d0494533ebbf203d8722"},"text":"From <EMAIL> Tue Aug 6 11:07:14 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: yyyy<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 5C16344110\n\tfor <jm@localhost>; Tue, 6 Aug 2002 06:02:30 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 06 Aug 2002 11:02:30 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [194.125.145.45]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g72L4Jv12075 for\n <<EMAIL>>; Fri, 2 Aug 2002 22:04:19 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id WAA29176; Fri, 2 Aug 2002 22:02:22 +0100\nReceived: from ie.suberic.net (owsla.ie.suberic.net [6192.168.127.123]) by\n lugh.tuatha.org (8.9.3/8.9.3) with ESMTP id WAA29144 for <<EMAIL>>;\n Fri, 2 Aug 2002 22:02:15 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host owsla.ie.suberic.net\n [192.168.127.12] claimed to be ie.suberic.net\nReceived: from owsla.ie.suberic.net (owsla [127.0.0.1]) by ie.suberic.net\n (8.11.6/8.11.6) with ESMTP id g72L2FY27688 for <<EMAIL>>;\n Fri, 2 Aug 2002 22:02:15 +0100\nDate: Fri, 2 Aug 2002 22:02:13 +0100\nTo: ilug social <<EMAIL>>\nMessage-Id: <<EMAIL>>\nReferences: <OF<EMAIL>DA.23B0755F-<EMAIL>.<EMAIL>>\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Disposition: inline\nUser-Agent: Mutt/1.2.5.1i\nIn-Reply-To: <<EMAIL>>;\n from <EMAIL> on Fri, Aug 02, 2002 at 12:23:04PM +0100\nX-Operating-System: Linux 2.4.18-5 i686\nX-GPG-Fingerprint: 9C1D 16F4 11F1 6BD2 933C 048D ACC7 9840 89D0 7646\nFrom: <NAME> <<EMAIL>>\nMail-Followup-To: <EMAIL>+dated+1<EMAIL>754135.<EMAIL>,\n\[email protected]\nX-Delivery-Agent: TMDA/0.57\nSubject: [ILUG-Social] Re: [ILUG] Dermot Beirne/Dublin/IE/Exel is out of the office.\nSender: [email protected]\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group social events <social.linux.ie>\nX-Beenthere: [email protected]\n\nOn Fri, Aug 02, 2002 at 12:23:04PM +0100, <NAME> wrote:\n> I will be out of the office starting 02/08/2002 and will not return until\n> 06/08/2002.\n...\n> The information in this email is confidential and may be legally\n[7+ line sig deleted]\n\nan automated message to ilug. one of those goofy confidentiality\nsignatures. more then four lines in a sig.\n\nis this a record?\n\nkevin\n\n-- <EMAIL> that a believer is happier than a skeptic is no more to\nfork()'ed on 37058400 the point than the fact that a drunken man is happier\nmeatspace place: home than a sober one. the happiness of credulity is a\nhttp://ie.suberic.net/~kevin cheap & dangerous quality -- g.b. shaw\n\n-- \nIrish Linux Users' Group Social Events: <EMAIL>\nhttp://www.linux.ie/mailman/listinfo/social for (un)subscription information.\nList maintainer: <EMAIL>\n\n\n"}
1,300
375
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft and ilovepose # Licensed under the MIT License. # Written by <NAME> (<EMAIL>) # Written by <NAME> & <NAME> # ------------------------------------------------------------------------------ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import time from collections import namedtuple from pathlib import Path import torch import torch.optim as optim import torch.nn as nn def create_logger(cfg, cfg_name, phase='train'): root_output_dir = Path(cfg.OUTPUT_DIR) # set up logger if not root_output_dir.exists(): print('=> creating {}'.format(root_output_dir)) root_output_dir.mkdir() dataset = cfg.DATASET.DATASET + '_' + cfg.DATASET.HYBRID_JOINTS_TYPE \ if cfg.DATASET.HYBRID_JOINTS_TYPE else cfg.DATASET.DATASET dataset = dataset.replace(':', '_') model = cfg.MODEL.NAME cfg_name = os.path.basename(cfg_name).split('.')[0] time_str = time.strftime('%Y-%m-%d-%H-%M') cfg_name = cfg_name + '_' + time_str final_output_dir = root_output_dir / dataset / model / cfg_name print('=> creating {}'.format(final_output_dir)) final_output_dir.mkdir(parents=True, exist_ok=True) log_file = 'running.log' running_log_file = final_output_dir / log_file head = '%(asctime)-15s %(message)s' logging.basicConfig(filename=str(running_log_file), format=head) logger = logging.getLogger() logger.setLevel(logging.INFO) console = logging.StreamHandler() logging.getLogger('').addHandler(console) tensorboard_log_dir = final_output_dir / 'tensorboard_log' print('=> creating {}'.format(tensorboard_log_dir)) tensorboard_log_dir.mkdir(parents=True, exist_ok=True) return logger, str(final_output_dir), str(tensorboard_log_dir) def get_optimizer(cfg, model): optimizer = None if cfg.TRAIN.OPTIMIZER == 'sgd': optimizer = optim.SGD( model.parameters(), lr=cfg.TRAIN.LR, momentum=cfg.TRAIN.MOMENTUM, weight_decay=cfg.TRAIN.WD, nesterov=cfg.TRAIN.NESTEROV ) elif cfg.TRAIN.OPTIMIZER == 'adam': optimizer = optim.Adam( model.parameters(), lr=cfg.TRAIN.LR ) return optimizer def save_checkpoint(states, is_best, output_dir, filename='checkpoint.pth'): torch.save(states, os.path.join(output_dir, filename)) if is_best and 'state_dict' in states: torch.save(states['best_state_dict'], os.path.join(output_dir, 'model_best.pth')) def get_model_summary(model, *input_tensors, item_length=26, verbose=False): """ :param model: :param input_tensors: :param item_length: :return: """ summary = [] ModuleDetails = namedtuple( "Layer", ["name", "input_size", "output_size", "num_parameters", "multiply_adds"]) hooks = [] layer_instances = {} def add_hooks(module): def hook(module, input, output): class_name = str(module.__class__.__name__) instance_index = 1 if class_name not in layer_instances: layer_instances[class_name] = instance_index else: instance_index = layer_instances[class_name] + 1 layer_instances[class_name] = instance_index layer_name = class_name + "_" + str(instance_index) params = 0 if class_name.find("Conv") != -1 or class_name.find("BatchNorm") != -1 or \ class_name.find("Linear") != -1: for param_ in module.parameters(): params += param_.view(-1).size(0) flops = "Not Available" if class_name.find("Conv") != -1 and hasattr(module, "weight"): flops = ( torch.prod( torch.LongTensor(list(module.weight.data.size()))) * torch.prod( torch.LongTensor(list(output.size())[2:]))).item() elif isinstance(module, nn.Linear): flops = (torch.prod(torch.LongTensor(list(output.size()))) \ * input[0].size(1)).item() if isinstance(input[0], list): input = input[0] if isinstance(output, list): output = output[0] summary.append( ModuleDetails( name=layer_name, input_size=list(input[0].size()), output_size=list(output.size()), num_parameters=params, multiply_adds=flops) ) if not isinstance(module, nn.ModuleList) \ and not isinstance(module, nn.Sequential) \ and module != model: hooks.append(module.register_forward_hook(hook)) model.eval() model.apply(add_hooks) space_len = item_length model(*input_tensors) for hook in hooks: hook.remove() details = '' if verbose: details = "Model Summary" + \ os.linesep + \ "Name{}Input Size{}Output Size{}Parameters{}Multiply Adds (Flops){}".format( ' ' * (space_len - len("Name")), ' ' * (space_len - len("Input Size")), ' ' * (space_len - len("Output Size")), ' ' * (space_len - len("Parameters")), ' ' * (space_len - len("Multiply Adds (Flops)"))) \ + os.linesep + '-' * space_len * 5 + os.linesep params_sum = 0 flops_sum = 0 for layer in summary: params_sum += layer.num_parameters if layer.multiply_adds != "Not Available": flops_sum += layer.multiply_adds if verbose: details += "{}{}{}{}{}{}{}{}{}{}".format( layer.name, ' ' * (space_len - len(layer.name)), layer.input_size, ' ' * (space_len - len(str(layer.input_size))), layer.output_size, ' ' * (space_len - len(str(layer.output_size))), layer.num_parameters, ' ' * (space_len - len(str(layer.num_parameters))), layer.multiply_adds, ' ' * (space_len - len(str(layer.multiply_adds)))) \ + os.linesep + '-' * space_len * 5 + os.linesep details += os.linesep \ + "Total Parameters: {:,}".format(params_sum) \ + os.linesep + '-' * space_len * 5 + os.linesep details += "Total Multiply Adds (For Convolution and Linear Layers only): {:,} GFLOPs".format(flops_sum/(1024**3)) \ + os.linesep + '-' * space_len * 5 + os.linesep details += "Number of Layers" + os.linesep for layer in layer_instances: details += "{} : {} layers ".format(layer, layer_instances[layer]) return details def load_checkpoint(checkpoint, model, optimizer=None, model_info=None, strict=True, filter_keys='not_filter'): """ https://github.com/peterliht/knowledge-distillation-pytorch/blob/master/utils.py#L141 Loads model parameters (state_dict) from file_path. If optimizer is provided, loads state_dict of optimizer assuming it is present in checkpoint. NOTE: load_checkpoint including three types (1) nn.module: torch.nn.Module.state_dict() (2) dataparallel: torch.nn.DataParallel.state_dict(), including 'module.' you need to remove 'module.' key (3) checkpoint: see save_checkpoint function in the same file like following example in train.py line 228 save_checkpoint states={}, including contents { 'epoch': epoch + 1, 'model': get_model_name(config), 'best_epoch': best_epoch + 1, 'state_dict': model.module.state_dict(), 'perf': perf_indicator, 'best_perf':best_perf, 'optimizer': optimizer.state_dict() } Args: checkpoint: (string) filename which needs to be loaded model: (torch.nn.Module) model for which the parameters are loaded optimizer: (torch.optim) optional: resume optimizer from checkpoint """ if not os.path.exists(checkpoint): raise("File doesn't exist {}".format(checkpoint)) if torch.cuda.is_available(): checkpoint = torch.load(checkpoint) else: # this helps avoid errors when loading single-GPU-trained weights onto CPU-model checkpoint = torch.load(checkpoint, map_location=lambda storage, loc: storage) if len(checkpoint) < 10 and 'state_dict' in checkpoint: checkpoint = checkpoint['state_dict'] if optimizer and 'optimizer' in checkpoint: optimizer.load_state_dict(checkpoint['optimizer']) if type(checkpoint).__name__ == 'OrderedDict' or type(checkpoint).__name__ == 'dict': # the data parallel layer will add 'module' before each layer name # load parallel model from checkpoint.pth.tar # remove score keys and remove module state_dict = {} for k, v in checkpoint.items(): if filter_keys not in k: state_dict[str.replace(k, 'module.', '')] = v # state_dict = {str.replace(k, 'module.', ''): v for k, v in checkpoint.items()} model.load_state_dict(state_dict,strict=strict) print("=> loading {} model state_dict end! ".format(model_info)) return checkpoint def save_yaml_file(cfg_name, cfg, final_output_dir): """ :param cfg_name: config name :param cfg: config data :param final_output_dir: save file path name :return: """ cfg_name = os.path.basename(cfg_name).split('.')[0] yaml_out_file = os.path.join(final_output_dir, cfg_name+'.yaml') print('=> creating {}'.format(yaml_out_file)) with open(yaml_out_file, 'w') as outfile: outfile.write(cfg.dump())
4,759
849
<filename>Sources/MultiProgressView.h<gh_stars>100-1000 // // MultiProgressView.h // MultiProgressView // // Created by <NAME> on 3/26/19. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for MultiProgressView. FOUNDATION_EXPORT double MultiProgressViewVersionNumber; //! Project version string for MultiProgressView. FOUNDATION_EXPORT const unsigned char MultiProgressViewVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <MultiProgressView/PublicHeader.h>
168
392
<gh_stars>100-1000 package com.baseflow.geolocator.location; import java.util.Map; public class AndroidIconResource { private final String name; private final String defType; public static AndroidIconResource parseArguments(Map<String, Object> arguments) { if (arguments == null) { return null; } final String name = (String) arguments.get("name"); final String defType = (String) arguments.get("defType"); return new AndroidIconResource( name, defType); } private AndroidIconResource(String name, String defType) { this.name = name; this.defType = defType; } public String getName() { return name; } public String getDefType() { return defType; } }
329
366
<reponame>AStarySky/manim_sandbox # from @鹤翔万里 # manim教程第四期 - SVG、图片与文字 from manimlib.imports import * from manim_sandbox.utils.imports import * from manim_projects.tony_useful.imports import * class CodeLine(Text): CONFIG = { 't2c': { 'RIGHT': ORANGE, 'LEFT': ORANGE, 'DOWN': ORANGE, 'UP': ORANGE, 'IN': ORANGE, 'OUT': ORANGE, 'ORIGIN': ORANGE, 'DL': ORANGE, 'DR': ORANGE, 'UL': ORANGE, 'UR': ORANGE, 'manim': GOLD, 'constants.py': GOLD, '#': GOLD, '_C': BLUE, 'BLUE_C': BLUE, 'BLUE': BLUE, 'GREEN': GREEN, 'YELLOW': YELLOW, 'RED': RED, 'np': BLACK, 'array': BLUE_D, 'ndarray': BLUE, 'move_to': BLUE_D, 'shift': BLUE_D, 'arrange': BLUE_D, 'VGroup': BLUE_D, 'VMobject': BLUE_D, 'ImageMobject': BLUE_D, 'TextMobject': BLUE_D, 'TexMobject': BLUE_D, 'Mobject': BLUE_D, 'list': BLUE_D, 'append': BLUE_D, 'remove': BLUE_D, 'next_to': BLUE_D, 'to_corner': BLUE_D, 'to_edge': BLUE_D, 'GREY_BROWN': GREY_BROWN, 'align_to': BLUE_D, 'scale': BLUE_D, 'rotate': BLUE_D, 'flip': BLUE_D, 'add': BLUE_D, 'add_to_back': BLUE_D, 'vector': ORANGE, 'play': BLUE_D, 'set_width': BLUE_D, 'set_stroke': BLUE_D, 'aligned_edge': RED, 'center': RED, 'radius': RED, ">>>": RED, 'coor_mask': RED, 'point_or_mobject': RED, 'python': GOLD, '0': average_color(BLUE, PINK), '1': average_color(BLUE, PINK), '2': average_color(BLUE, PINK), '3': average_color(BLUE, PINK), '4': average_color(BLUE, PINK), '5': average_color(BLUE, PINK), '6': average_color(BLUE, PINK), '7': average_color(BLUE, PINK), '8': average_color(BLUE, PINK), '9': average_color(BLUE, PINK), 'True': average_color(BLUE, PINK), '2D': RED_B, '3D': RED_B, 'self': PINK, 'mob': RED_D, 'style': PURPLE, 'stroke': BLUE_D, 'fill': BLUE_D, 'background_stroke': BLUE_D, 'opacity': BLUE_D, 'set_color': BLUE_D, 'set_fill': BLUE_D, 'set_background_stroke': BLUE_D, "SVG": GREEN, "图片": GREEN, "assets": PINK, "assets/": PINK, "raster_images": PINK, "raster_images/": PINK, "svg_images": PINK, "svg_images/": PINK, "sounds": PINK, "sounds/": PINK, "manim.py": GOLD, "manimlib": GOLD, "~": "#EBEBEB", 'ImageMobject': BLUE_D, "SVGMobject": BLUE_D, "stroke_width": ORANGE, "color": ORANGE, "background_stroke_color": ORANGE, "coin.svg": GOLD_D, "up.png": GOLD_D, "height": ORANGE, "invert": ORANGE, "Uncreate": BLUE_D, "Write": BLUE_D, "Transform": BLUE_D, "FadeOut": BLUE_D, "img": RED_D, "square": RED_D, "LaTeX": GOLD, "xelatex": GOLD, "Text": BLUE_D, "Text ": GOLD_D, "\\": PURPLE, "ab": GOLD_D, "cde": GOLD_D, "text2": DARK_GRAY, "text3": DARK_GRAY, "text4": DARK_GRAY, "妈咪叔": BLUE_D, "www.latexlive.com": PURPLE, "debugTeX": BLUE_D, "\\\\sum^n_{i=1}i^3=?": GOLD_D, "$": GOLD_D, "\\\\text{": GOLD_D, "bcd": GOLD_D, "a bbcde\\n\\tfghi": GOLD_D, "\\n": PURPLE, "\\t": PURPLE, "t2c": ORANGE, "font": ORANGE, "Consolas": GOLD_D, }, 'font': 'Consolas', 'size': 0.72, 'color': DARK_GRAY, 'plot_depth': 2, } def __init__(self, text, **kwargs): Text.__init__(self, text, **kwargs) class CodeLines(VGroup): def __init__(self, *text, **kwargs): VGroup.__init__(self) for each in text: self.add(CodeLine(each, **kwargs)) self.arrange(DOWN, aligned_edge=LEFT) class SVGCode(CodeLine): CONFIG = { "t2c": { "x": BLUE_D, "y": BLUE_D, "cx": BLUE_D, "cy": BLUE_D, "r": BLUE_D, "rx": BLUE_D, "ry": BLUE_D, "points": BLUE_D, "d": BLUE_D, "width": BLUE_D, "height": BLUE_D, '"': GOLD_D, "xml": RED_D, "svg": RED_D, "path": RED_D, "rect": RED_D, "polygon": RED_D, "polyline": RED_D, "circle": RED_D, "ellipse": RED_D, "text": RED_D, "image": RED_D, }, "size": 0.6 } class LaTeXCode(CodeLine): CONFIG = { "t2c": { "preview": ORANGE, "standalone": BLUE_D, "usepackage": RED_D, "begin": GREEN_D, "end": GREEN_D, "document": ORANGE, "align*": ORANGE, "~": "#EBEBEB", "documentclass": RED_D, "\\": DARK_GRAY, }, "size": 0.6 } class CodeBackground(BackgroundRectangle): CONFIG = { "fill_color": "#EBEBEB", "fill_opacity": 1, "stroke_width": 1, "stroke_opacity": 1, "stroke_color": DARK_GRAY, "buff": 0.5 } class Scene_(Scene): CONFIG = { "camera_config": { "background_color": WHITE, "use_plot_depth": True, } } def setup(self): self.caps_cnt = 1 def next_caps(self): self.play(Transform(self.caps[0], self.caps[self.caps_cnt])) self.wait() self.caps_cnt += 1 # def tear_down(self): # self.play(FadeOut(Group(*self.mobjects))) class OpeningScene(Scene_): def construct(self): t2c = { "manim": average_color(PINK, RED), "SVG": BLUE, "图片": average_color(BLUE, GREEN), "文字": GREEN, } text_color = DARK_GRAY font = "庞门正道标题体" text_1 = Text("大家好!", font=font, color=text_color, size=2, t2c=t2c).to_edge(UP * 2, buff=1) text_2 = Text("欢迎来到manim视频教程", font=font, color=text_color, size=2, t2c=t2c).to_edge(UP * 3.2, buff=1) text_3 = Text("这一期我们将学习manim中", font=font, color=text_color, size=2, t2c=t2c).to_edge(UP * 1.8, buff=1) text_4 = Text("SVG、图片和文字的用法", font=font, color=text_color, size=2, t2c=t2c).to_edge(UP * 3., buff=1) text_34, text_12 = VGroup(text_3, text_4), VGroup(text_1, text_2) methods = [ ["SVGMobject", "ImageMobject"], ["TextMobject", "TexMobject", "Text"], ["LaTeX, ", "cairo"] ] m_group_1 = VGroup(*[Text(tex + ', ', size=0.9, font='Consolas', stroke_width=2, color=BLUE_D) for tex in methods[0]]).arrange(RIGHT) m_group_2 = VGroup(*[Text(tex + ', ', size=0.9, font='Consolas', stroke_width=2, color=BLUE_D) for tex in methods[1]]).arrange(RIGHT) m_group_3 = VGroup(*[Text(tex, size=0.9, font='Consolas', stroke_width=2, color=BLUE_D) for tex in methods[2]]).arrange(RIGHT) m_group = VGroup(m_group_1, m_group_2, m_group_3).arrange(DOWN, aligned_edge=LEFT, buff=0.42) methodes_group = VGroup(*m_group_1, *m_group_2, *m_group_3).next_to(text_34, DOWN, buff=0.7) # self.add(picture) self.wait(0.5) self.play(Write(text_1)) self.wait(0.5) self.play(WriteRandom(text_2), run_time=1.5) self.wait(1.8) self.play(ReplacementTransform(text_12, text_34), run_time=1.2) self.wait(1.2) self.play(FadeInRandom(methodes_group), run_time=2.4) self.wait(2.6) self.play(FadeOutRandom(methodes_group), FadeOutRandom(text_3), FadeOutRandom(text_4), run_time=1.8) self.wait(1) class AssetsDir(Scene_): def start(self): t2c = { "manim": GOLD, "SVG": BLUE, "图片": average_color(BLUE, GREEN), "文字": GREEN, } title = VGroup( Text("Chapter Ⅰ.", font="Monaco for Powerline", color=BLUE_D, size=1, t2c=t2c), Text("素材文件夹", font="思源黑体 CN Bold", color=DARK_GRAY, size=1, t2c=t2c), ).arrange(RIGHT, buff=0.5, aligned_edge=DOWN) self.wait() self.play(DrawBorderThenFill(title)) self.wait(2) self.play(FadeOutAndShiftDown(title)) def construct(self): self.start() captions = [ "在manim中使用外部图片或SVG文件时,可以直接使用绝对路径定位文件", "也可以放在与manim.py、manimlib同级的文件夹内,使用相对路径", "但更推荐的方法是放在素材目录(assets/)中", "assets/目录并不自带,所以要自己在manim.py的同级目录中创建文件夹", "assets/文件夹下还要创建三个子文件夹,分别是", "raster_images/、svg_images/、sounds/(一般不用)", "把需要使用的图片素材放到assets/raster_images/中", "需要使用的SVG素材放到assets/svg_images/中", "这样之后,仅仅使用文件名(后缀名可省略)manim就可以自动定位到对应文件", ] self.caps = VGroup( *[ CodeLine(cap, font='Source Han Sans CN Bold', size=0.64).to_edge(DOWN * 1.2) for cap in captions ] ) self.wait() self.play(Write(self.caps[0])) absdir = VGroup( CodeLine("\"D:\\\\...\\\\manim\\\\picture.png\"", size=0.8).set_color(DARK_GRAY), CodeLine("\"/home/.../manim/picture.png\"", size=0.8).set_color(DARK_GRAY) ).arrange(DOWN, aligned_edge=LEFT).to_edge(UP) for each in absdir: each[1:-1].set_color(GOLD_D) self.wait() self.play(Write(absdir)) self.wait(2) self.next_caps() tree = CodeLines( "manim", "├── manim.py", "├── manimlib", "│ └── ... ", "├── picture.png", "└── svg_file.png", ).arrange(DOWN, aligned_edge=LEFT, buff=0).shift(UP*0.7) tree[0].next_to(tree[1].get_left(), UP, buff=0.35) self.play(Write(tree[0])) self.play(FadeInFromDown(tree[1:])) self.wait(3) self.next_caps() self.wait(3) self.next_caps() self.play(tree.shift, LEFT*3) tree2 = CodeLines( "manim", "├── manim.py", "├── manimlib", "│ └── ... ", "└── assets", "~ ├── raster_images", "~ │ └── picture.png", "~ ├── svg_images", "~ │ └── svg_file.svg", "~ └── sounds" ).arrange(DOWN, aligned_edge=LEFT, buff=0).shift(RIGHT*3) tree2[0].next_to(tree2[1].get_left(), UP, buff=0.35) tree2[5:].shift(DOWN*0.1) self.wait() self.play(TransformFromCopy(tree, tree2[:5])) self.wait(2) self.next_caps() self.wait(2) self.next_caps() self.play( FadeInFromDown( VGroup(tree2[5], tree2[6][4], tree2[7], tree2[8][4], tree2[9]) ) ) self.wait(2) self.next_caps() self.play(Write(tree2[6][8:])) self.wait(2) self.next_caps() self.play(Write(tree2[8][8:])) self.wait(2) self.next_caps() self.wait(4) class UseSVG(Scene_): def start(self): t2c = { "manim": GOLD, "SVG": BLUE, "图片": average_color(BLUE, GREEN), "文字": GREEN, } title = VGroup( Text("Chapter ⅠI.", font="Monaco for Powerline", color=BLUE_D, size=1, t2c=t2c), Text("manim中插入SVG", font="思源黑体 CN Bold", color=DARK_GRAY, size=1, t2c=t2c), ).arrange(RIGHT, buff=0.5, aligned_edge=DOWN) self.wait() self.play(DrawBorderThenFill(title)) self.wait(2) self.play(FadeOutAndShiftDown(title)) def construct(self): self.start() captions = [ "manim中插入SVG图片直接使用SVGMobject即可", "传入的唯一参数为一个字符串,指向SVG文件(具体写法见上一部分)", "关键字参数有stroke_width(路径粗细)等和VMobject共有的属性", "由于SVGMobject是VMobject的子类,所以可以使用所有动画效果", "另外,SVGMobject能够处理的和显示有关的SVG元素只有如下几个:", "path, rect, circle, ellipse, polygon, polyline", "而其余的元素(例如image和text)都会省略,所以制作SVG时需要注意", ] self.caps = VGroup( *[ CodeLine(cap, font='Source Han Sans CN Bold', size=0.64).to_edge(DOWN * 1.2) for cap in captions ] ) codes = VGroup( CodeLine(">>> mob = SVGMobject(", size=0.8), CodeLine('~~~~~~~~"coin.svg",', size=0.8), CodeLine("~~~~~~~~color=BLUE,", size=0.8), VGroup( CodeLine("~~~~~~~~stroke_width=", size=0.8), DecimalNumberText(0) ).arrange(RIGHT), CodeLine("~~~~)", size=0.8), CodeLine(">>> self.play(Uncreate(mob))", size=0.8), VGroup(*[ CodeLine("~", size=0.8) for _ in range(4) ]).arrange(DOWN) ).arrange(DOWN, aligned_edge=LEFT).to_edge(RIGHT, buff=0.8) codebg = CodeBackground(codes) mob = SVGMobject("coin.svg", color=BLUE, stroke_width=0) mob.scale(1.5).shift(LEFT*3.5) self.wait() self.play(Write(self.caps[0])) self.wait() self.play(FadeInFromDown(codebg)) self.play(Write(VGroup(codes[0], codes[4]))) self.wait(2) self.next_caps() self.play(Write(codes[1])) self.wait(3) self.next_caps() self.play(Write(VGroup(codes[2], codes[3]))) self.play(FadeIn(mob)) self.wait() sw = ValueTracker(0) codes[3][1].add_updater(lambda m: m.set_value(sw.get_value())) mob.add_updater(lambda m: m.set_stroke(width=sw.get_value())) self.play(sw.increment_value, 10, run_time=3, rate_func=linear) self.play(sw.increment_value, -5, run_time=1.5, rate_func=linear) codes[3][1].clear_updaters() mob.clear_updaters() self.wait(3) self.next_caps() self.play(Write(codes[5])) self.wait() self.play(Uncreate(mob)) self.wait(2) self.play(FadeOut(codes)) self.next_caps() svg = VGroup( SVGCode("<?xml ...>\n..."), SVGCode("<svg ...>"), SVGCode('<path d="........." ... />'), SVGCode('<rect width="..." height="..." x="..." y="..." ... />'), SVGCode('<circle cx="..." cy="..." r="..." ... />'), SVGCode('<ellipse cx="..." cy="..." rx="..." ry="..." ... />'), SVGCode('<polygon points="... ..." ... />'), SVGCode('<polyline points="... ..." ... />'), SVGCode('<image ... />'), SVGCode('<text x="..." y="..." ... > ... </text>'), SVGCode('</svg>') ).arrange(DOWN, aligned_edge=LEFT).shift(UP*0.4) svgbg = CodeBackground(svg) check = VGroup( TexMobject("\\checkmark", color=GREEN, background_stroke_color=GREEN).scale(0.7).next_to(svg[2], LEFT, buff=0.1), TexMobject("\\checkmark", color=GREEN, background_stroke_color=GREEN).scale(0.7).next_to(svg[3], LEFT, buff=0.1), TexMobject("\\checkmark", color=GREEN, background_stroke_color=GREEN).scale(0.7).next_to(svg[4], LEFT, buff=0.1), TexMobject("\\checkmark", color=GREEN, background_stroke_color=GREEN).scale(0.7).next_to(svg[5], LEFT, buff=0.1), TexMobject("\\checkmark", color=GREEN, background_stroke_color=GREEN).scale(0.7).next_to(svg[6], LEFT, buff=0.1), TexMobject("\\checkmark", color=GREEN, background_stroke_color=GREEN).scale(0.7).next_to(svg[7], LEFT, buff=0.1), TexMobject("\\times", color=RED, background_stroke_color=RED, background_stroke_width=2.5).scale(0.7).next_to(svg[8], LEFT, buff=0.15), TexMobject("\\times", color=RED, background_stroke_color=RED, background_stroke_width=2.5).scale(0.7).next_to(svg[9], LEFT, buff=0.15) ) self.play(ReplacementTransform(codebg, svgbg)) self.play(FadeIn(svg)) self.wait() self.next_caps() for each in check[:-2]: self.play(Write(each)) self.wait(2) self.next_caps() for each in check[-2:]: self.play(Write(each)) self.wait(3) class UseImage(Scene_): def start(self): t2c = { "manim": GOLD, "SVG": BLUE, "图片": average_color(BLUE, GREEN), "文字": GREEN, } title = VGroup( Text("Chapter ⅠII.", font="Monaco for Powerline", color=BLUE_D, size=1, t2c=t2c), Text("manim中插入图片", font="思源黑体 CN Bold", color=DARK_GRAY, size=1, t2c=t2c), ).arrange(RIGHT, buff=0.5, aligned_edge=DOWN) self.wait() self.play(DrawBorderThenFill(title)) self.wait(2) self.play(FadeOutAndShiftDown(title)) def construct(self): self.start() captions = [ "在manim中插入图片,需要使用ImageMobject", "与SVGMobject类似,传入一个参数表示图片文件名(jpg,png,gif均可)", "height表示插入图片的高度(默认为2),invert表示是否反色(默认False)", "ImageMobject不是VMobject的子类,所以有很多动画无法使用", ] self.caps = VGroup( *[ CodeLine(cap, font='Source Han Sans CN Bold', size=0.64).to_edge(DOWN * 1.2) for cap in captions ] ) self.wait() self.play(Write(self.caps[0])) self.wait() codes = CodeLines( '>>> img = ImageMobject(', '~~~~~~~~"up.png",', '~~~~~~~~height=3,', '~~~~~~~~invert=True', '~~~~)', '>>> self.play(Uncreate(img))', '>>> self.play(Transform(img, square))', '>>> self.play(FadeOut(img))', '~', ).to_edge(RIGHT, buff=0.7) codebg = CodeBackground(codes) img = ImageMobject("Tony.png", height=2).shift(LEFT*4) img2 = ImageMobject("Tony.png", height=3, invert=True).shift(LEFT*4) self.play(FadeInFromDown(codebg)) self.play(Write(VGroup(codes[0], codes[4]))) self.wait(2) self.next_caps() self.play(Write(codes[1])) self.play(FadeIn(img)) self.wait(3) self.next_caps() self.play(Write(codes[2])) self.wait() self.play(img.scale, 1.5) self.wait(2) self.play(Write(codes[3])) self.wait() self.play(Transform(img, img2)) self.wait(3) self.next_caps() self.play(Write(codes[5])) self.wait() self.play(Write(Cross(codes[5][4:], plot_depth=10))) self.wait(2) self.play(Write(codes[6])) self.wait() self.play(Write(Cross(codes[6][4:], plot_depth=10))) self.wait(2) self.play(Write(codes[7])) self.wait() self.play(FadeOut(img)) self.wait(3) class UseTextMobject(Scene_): def start(self): t2c = { "manim": GOLD, "SVG": BLUE, "图片": average_color(BLUE, GREEN), "文字": GREEN, } title = VGroup( Text("Chapter IV.", font="Monaco for Powerline", color=BLUE_D, size=1, t2c=t2c), Text("manim中使用文字", font="思源黑体 CN Bold", color=DARK_GRAY, size=1, t2c=t2c), ).arrange(RIGHT, buff=0.5, aligned_edge=DOWN) self.wait() self.play(DrawBorderThenFill(title)) self.wait(2) self.play(FadeOutAndShiftDown(title)) def construct(self): self.start() captions = [ "在manim中使用文字,可以使用TextMobject(利用LaTeX编译转换出SVG)", "传入一个字符串,来表示显示的文字(会套入模板中使用xelatex编译)", "其他属性和VMobject的均相同,也可以使用所有动画效果", "注意:其中需要使用LaTeX命令的\\都需要替换为\\\\转义,或在字符串前加'r'", "一个TextMobject中也可以传入多个字符串,会单独编译,连在一起显示", "一个TextMobject包含一个或多个子物体,指向传入的每个字符串", "而下一级的子物体,就是这个字符串里的每条路径了(一般是字符)", "所以可以通过两级下标来访问到每个字符" ] self.caps = VGroup( *[ CodeLine(cap, font='Source Han Sans CN Bold', size=0.64).to_edge(DOWN * 1.2) for cap in captions ] ) self.caps[3][-2].set_color(BLUE_D) codes = VGroup( CodeLine(">>> text = TextMobject(", size=0.68), VGroup( CodeLine('~~~~~~~~"Text ', size=0.68), Text("文字", color=GOLD_D, size=0.6, font="思源黑体 CN Regular"), CodeLine('",', size=0.68), ).arrange(RIGHT, buff=0.05, aligned_edge=UP), CodeLine("~~~~~~~~color=BLUE,", size=0.68), CodeLine("~~~~~~~~background_stroke_color=RED", size=0.68), CodeLine("~~~~)", size=0.68), CodeLine(">>> self.play(Uncreate(text))", size=0.68), CodeLine(">>> text2 = TextMobject(", size=0.68), VGroup( CodeLine('~~~~~~~~"\\\\LaTeX\\\\\\\\', size=0.68), Text("换行", color=GOLD_D, size=0.6, font="思源黑体 CN Regular"), CodeLine('")', size=0.68), ).arrange(RIGHT, buff=0.05, aligned_edge=UP), CodeLine(">>> text3 = TextMobject(", size=0.68), CodeLine('~~~~~~~~r"\\LaTeX")', size=0.68), CodeLine(">>> text4 = TextMobject(", size=0.68), CodeLine('~~~~~~~~"ab", "cde")', size=0.68) ).arrange(DOWN, aligned_edge=LEFT, buff=0.15).to_edge(RIGHT, buff=0.8).shift(UP*0.2) codes[9][8].set_color(BLUE_D) codebg = CodeBackground(codes, buff=0.38) text = TextMobject("Text文字", color=BLACK).scale(1.5).shift(LEFT*3.5) text2 = TextMobject("\\LaTeX\\\\换行", color=BLACK).scale(1.5) text3 = TextMobject("\\LaTeX", color=BLACK).scale(1.5) text4 = TextMobject("ab", "cde", color=BLACK).scale(1.5) VGroup(text2, text3, text4).arrange(DOWN, buff=0.4).move_to(LEFT*3.5) self.wait() self.play(Write(self.caps[0])) self.play(FadeInFromDown(codebg)) self.wait() self.play(Write(VGroup(codes[0], codes[4]))) self.wait(2) self.next_caps() self.play(Write(codes[1])) self.wait() self.play(Write(text)) self.wait(3) self.next_caps() self.play(Write(codes[2])) self.wait() self.play(text.set_color, BLUE) self.wait(2) self.play(Write(codes[3])) self.wait() self.play(text.set_background_stroke, {"color": RED}) self.wait(2) self.play(Write(codes[5])) self.wait() self.play(Uncreate(text)) self.wait(3) self.next_caps() self.play(Write(VGroup(codes[6], codes[7]))) self.wait() self.play(Write(text2)) self.wait(2) self.play(Write(VGroup(codes[8], codes[9]))) self.wait() self.play(Write(text3)) self.wait(3) self.next_caps() self.play(Write(VGroup(codes[10], codes[11]))) self.wait() self.play(Write(text4)) self.wait(4.5) self.next_caps() self.play(FadeOut(codes), FadeOut(codebg), FadeOut(text2), FadeOut(text3), FadeOut(text4)) title = CodeLine('text = TextMobject("ab", "cde")', size=1).to_edge(UP) level1 = VGroup( CodeLine('text:', size=0.7), TextMobject("ab", "cde", color=BLACK), ).arrange(RIGHT).next_to(title, DOWN, buff=0.8) level2 = VGroup( VGroup( CodeLine('text[0]:', size=0.7), level1[1][0].copy() ).arrange(RIGHT), VGroup( CodeLine('text[1]:', size=0.7), level1[1][1].copy() ).arrange(RIGHT) ).arrange(RIGHT, buff=2).next_to(level1, DOWN, buff=0.9) level3 = VGroup( VGroup( level2[0][1][0].copy(), CodeLine('text[0][0]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[0][1][1].copy(), CodeLine('text[0][1]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[1][1][0].copy(), CodeLine('text[1][0]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[1][1][1].copy(), CodeLine('text[1][1]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[1][1][2].copy(), CodeLine('text[1][2]', size=0.6), ).arrange(DOWN, buff=0.5), ).arrange(RIGHT, buff=0.8, aligned_edge=DOWN).next_to(level2, DOWN, buff=0.9) level1bg = CodeBackground(level1, buff=0.15).round_corners(0.2) level2bg = VGroup() for each in level2: level2bg.add(CodeBackground(each, buff=0.15).round_corners(0.2)) level3bg = VGroup() base = CodeBackground(level3[1][0], buff=0.2).round_corners(0.2) for each in level3: level3bg.add(base.copy().move_to(each[0], coor_mask=np.array([1, 0, 1]))) lines12 = VGroup( Line(level1bg.get_bottom(), level2bg[0].get_top(), color=DARK_GRAY, stroke_width=3), Line(level1bg.get_bottom(), level2bg[1].get_top(), color=DARK_GRAY, stroke_width=3), ) lines23 = VGroup( Line(level2bg[0].get_bottom(), level3bg[0].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[0].get_bottom(), level3bg[1].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[1].get_bottom(), level3bg[2].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[1].get_bottom(), level3bg[3].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[1].get_bottom(), level3bg[4].get_top(), color=DARK_GRAY, stroke_width=3), ) self.play(Write(title)) self.wait() self.play(FadeInFromDown(level1bg)) self.play(Write(level1)) self.wait(3) self.play( *[Write(line) for line in lines12], FadeInFrom(level2bg, UP) ) self.wait(2.5) self.play( Write(level2[0][0]), Write(level2[1][0]), ) self.play( TransformFromCopy(level1[1][0], level2[0][1]), TransformFromCopy(level1[1][1], level2[1][1]), run_time=2 ) self.wait(3) self.next_caps() self.play( *[Write(line) for line in lines23], FadeInFrom(level3bg, UP) ) self.wait(2.5) self.play( TransformFromCopy(level2[0][1][0], level3[0][0]), TransformFromCopy(level2[0][1][1], level3[1][0]), TransformFromCopy(level2[1][1][0], level3[2][0]), TransformFromCopy(level2[1][1][1], level3[3][0]), TransformFromCopy(level2[1][1][2], level3[4][0]), run_time=2.5 ) self.wait(3) self.next_caps() self.play( AnimationGroup( *[FadeInFromDown(level3[i][1], lag_ratio=0.05) for i in range(5)], lag_ratio=0.4 ) ) self.wait(7) class UseTexMobject(Scene_): def construct(self): captions = [ "书写公式常使用TexMobject,即LaTeX的align*环境", "使用LaTeX的数学公式语法编写公式,结构也和TextMobject类似", "而TextMobject和TexMobject的区别在于:", "TextMobject直接将内容写在LaTeX的document中\n" " 而TexMobject使用了LaTeX的align*公式环境", "所以对于文字和公式,上面这两种写法是等价的", "关于LaTeX公式的预览和教程,可以尝试妈咪叔维护的www.latexlive.com", "可以对实时预览公式,并且含有一些基础的公式教程" ] self.caps = VGroup( *[ CodeLine(cap, font='Source Han Sans CN Bold', size=0.64).to_edge(DOWN * 1.2) for cap in captions ] ) codes = VGroup( CodeLine(">>> tex = TexMobject("), CodeLine(r'~~~~~~~~"\\sum^n_{i=1}i^3=?"'), CodeLine("~~~~).scale(2)"), CodeLine(">>> debugTeX(self, tex[0])"), CodeLine("~~~~#↑自定义的显示子物体下标的函数", font="思源黑体 CN Regular", size=0.6), CodeLine("~~~~# 在manim_sandbox中有定义", font="思源黑体 CN Regular", size=0.6), CodeLine("~"), CodeLine("~"), CodeLine("~"), ).arrange(DOWN, aligned_edge=LEFT).to_edge(RIGHT, buff=0.7) tex = TexMobject("\\sum^n_{i=1}i^3=?", color=BLACK).scale(2).shift(LEFT*3.5) codes[4][4:].set_color(GREEN) codes[5][4:].set_color(GREEN) codebg = CodeBackground(codes) self.wait() self.play(Write(self.caps[0])) self.wait() self.play(FadeInFromDown(codebg)) self.play(Write(VGroup(codes[0], codes[2][:5]))) self.wait(3) self.next_caps() self.play(Write(codes[1])) self.play(Write(codes[2][5:])) self.wait() self.play(Write(tex)) self.wait(3) self.play(Write(codes[3])) self.play(Write(VGroup(codes[4], codes[5]))) self.wait() index = VGroup() for i, j in enumerate(tex[0]): index.add(Text(str(i), font="Consolas", size=0.8, color=RED).move_to(j)) self.play(FadeInFromLarge(index[-1]), run_time=0.5) self.wait(5) self.next_caps() self.play(FadeOut(VGroup(codes, codebg, tex, index))) self.wait() self.next_caps() text_temp = VGroup( LaTeXCode("\\documentclass[preview]{standalone}"), LaTeXCode("~"), LaTeXCode("\\usepackage{...}"), LaTeXCode("..."), LaTeXCode("\\usepackage{...}"), LaTeXCode("~"), LaTeXCode("\\begin{document}"), LaTeXCode("~"), LaTeXCode("~"), LaTeXCode("TextMobject"), LaTeXCode("~"), LaTeXCode("~"), LaTeXCode("\\end{document}"), ).arrange(DOWN, aligned_edge=LEFT, buff=0.15) tex_temp = VGroup( LaTeXCode("\\documentclass[preview]{standalone}"), LaTeXCode("~"), LaTeXCode("\\usepackage{...}"), LaTeXCode("..."), LaTeXCode("\\usepackage{...}"), LaTeXCode("~"), LaTeXCode("\\begin{document}"), LaTeXCode("~"), LaTeXCode("\\begin{align*}"), LaTeXCode("TexMobject"), LaTeXCode("\\end{align*}"), LaTeXCode("~"), LaTeXCode("\\end{document}"), ).arrange(DOWN, aligned_edge=LEFT, buff=0.15) VGroup(text_temp, tex_temp).arrange(RIGHT, aligned_edge=UP, buff=1.5).shift(UP*0.3) texbg = CodeBackground(tex_temp) textbg = texbg.copy().move_to(text_temp, coor_mask=np.array([1, 0, 1])) # self.add(textbg, text_temp, texbg, tex_temp) self.play(FadeInFromDown(textbg)) self.play(Write(VGroup(text_temp[:7], text_temp[-1]))) self.wait(2) self.play(Write(text_temp[9])) self.wait(3) self.play(FadeInFrom(texbg, LEFT)) self.play( TransformFromCopy(text_temp[:7], tex_temp[:7]), TransformFromCopy(text_temp[-1], tex_temp[-1]), run_time=2 ) self.wait() self.play(Write(VGroup(tex_temp[8], tex_temp[10]))) self.wait(2) self.play(Write(tex_temp[9])) self.wait(5) equal = VGroup( VGroup( CodeLine('TextMobject("', size=0.68), Text("文字", color=GOLD_D, size=0.6, font="思源黑体 CN Regular"), CodeLine('$', size=0.68), Text("公式", color=GOLD_D, size=0.6, font="思源黑体 CN Regular"), CodeLine('$")', size=0.68) ).arrange(RIGHT, aligned_edge=UP, buff=0.05), TexMobject("\\Longleftrightarrow", color=ORANGE, background_stroke_color=ORANGE).scale(0.7), VGroup( CodeLine('TexMobject("\\\\text{', size=0.68), Text("文字", color=GOLD_D, size=0.6, font="思源黑体 CN Regular"), CodeLine('}', size=0.68, color=GOLD_D), Text("公式", color=GOLD_D, size=0.6, font="思源黑体 CN Regular"), CodeLine('")', size=0.68) ).arrange(RIGHT, aligned_edge=UP, buff=0.05), ).arrange(RIGHT, buff=0.3) self.play(FadeOut(VGroup(texbg, textbg, tex_temp, text_temp))) self.wait() self.play(Write(equal)) self.next_caps() self.wait(4) img = ImageMobject("latexlive.png", height=8) rects = VGroup(*[Rectangle() for x in range(2)]) rects.set_stroke(width=0) rects.set_fill(GREY, 0.5) rects.set_height(2.2, stretch=True) rects.set_width(7.4, stretch=True) rects[0].move_to(DOWN*0.1) rects[1].set_height(1.5, stretch=True) rects[1].set_width(3, stretch=True) rects[1].move_to(DOWN*2.75) inv_rects = VGroup() for rect in rects: fsr = FullScreenFadeRectangle() fsr.append_points(rect.points[::-1]) inv_rects.add(fsr) inv_rects.set_fill(BLACK, 0.7) url = TextMobject("www.latexlive.com", color=BLUE, plot_depth=10).scale(1.5).to_corner(UL) self.play(FadeOut(equal)) self.next_caps() self.play(FadeIn(img), FadeIn(url)) self.wait(2) self.next_caps() self.wait() self.play(FadeOut(self.caps[0])) self.play(VFadeIn(inv_rects[0])) self.wait(2) self.play(Transform(inv_rects[0], inv_rects[1])) self.wait(2) self.play(VFadeOut(inv_rects[0])) self.wait(3) img2 = ImageMobject("latexhelp.png", height=8) url2 = TextMobject("www.latexlive.com/help", color=BLUE, plot_depth=10).scale(1.5).to_corner(UL) self.play( Transform(img, img2), Transform(url, url2) ) self.wait(3) class UseText(Scene_): def construct(self): captions = [ "如果只使用文字,或者想自定义字体的话,可以使用Text(需要最新版manim)", "只能传入一个字符串,支持\\t\\n等,还要传入想要使用的字体名称", "还可以传入一个t2c字典来实现自动上色", "Text类是SVGMobject的子类,所以有其全部属性,和动画效果", "一个Text的子物体就是他的每个字符,空格\\n也包括在内,\\t算为4空格", "有关Text的更多用法,可以查看这个官方中文文档" ] self.caps = VGroup( *[ CodeLine(cap, font='Source Han Sans CN Bold', size=0.64).to_edge(DOWN * 1.2) for cap in captions ] ) codes = CodeLines( ">>> text = Text(", '~~~~~~~~"a bbcde\\n\\tfghi",', '~~~~~~~~color=BLACK,', '~~~~~~~~font="Consolas",', '~~~~~~~~t2c={"bcd": BLUE},', '~~~~).scale(2)', '>>> self.play(Write(text))', '>>> debugTeX(self, text)', ).to_edge(RIGHT, buff=1) codebg = CodeBackground(codes) text = Text("a bbcde\n\tfghi", color=BLACK, font="Consolas").scale(2).shift(LEFT*3.5) self.wait() self.play(Write(self.caps[0])) self.wait() self.play(FadeInFromDown(codebg)) self.play(Write(VGroup(codes[0], codes[5][:5]))) self.wait(2) self.next_caps() self.play(Write(VGroup(codes[1:3], codes[5][5:]))) self.wait() self.play(Write(codes[3])) self.wait() self.play(Write(text)) self.wait(3) self.next_caps() self.play(Write(codes[4])) self.wait() self.play(text[3:6].set_color, BLUE) self.wait(3) self.next_caps() self.play(Write(codes[6])) self.wait() self.play(Write(text)) self.wait(3) self.next_caps() comment = Text("注:目前版本非显示字符在前一个显示字符的位置上,可能后续会改变", font="思源黑体 CN Bold", \ size=0.6, t2c={"目前版本": RED}, color=DARK_GRAY).to_edge(UP) self.add(comment) self.play(Write(codes[7])) self.wait() index = VGroup() for i, j in enumerate(text): index.add(Text(str(i), font="Consolas", size=0.8, color=RED).move_to(j)) self.play(FadeInFromLarge(index[-1]), run_time=0.5) self.wait(5) img = ImageMobject("TextDoc.png", height=8) url = Text("github.com/manim-kindergarten/manim_sandbox/wiki/text_mobject-文字对象", \ color=BLUE_D, background_stroke_width=1, font="思源宋体 CN", size=0.6).shift(UP*2.5) self.next_caps() bg = BackgroundRectangle(self.caps[0], color=WHITE, fill_opacity=0.9, plot_depth=1.5, buff=0.05) self.play(FadeOut(VGroup(index, text, codes, codebg)), FadeIn(img), FadeIn(bg)) self.play(Write(url)) self.wait(7) class DownProgressBar(Scene_): def construct(self): methods_dict = { '素材文件夹': '0022', 'SVGMobject': '0123', 'ImageMobject': '0230', 'TextMobject': '0330', 'TexMobject': '0525', 'Text': '0703', ' ': '0815' } total_time = '0828' func_time = lambda t: int(t[0:2]) * 60 + int(t[2:]) func_loc = lambda t: func_time(t)/func_time(total_time) * FRAME_WIDTH * RIGHT + FRAME_WIDTH * LEFT / 2 p_list = [FRAME_WIDTH * LEFT / 2] for v in methods_dict.values(): p_list.append(func_loc(v)) p_list.append(func_loc(total_time)) colors = color_gradient([BLUE, PINK, RED, ORANGE, GREEN], len(methods_dict)+1) lines = VGroup(*[Line(p_list[i], p_list[i+1]-0.02*RIGHT, color=colors[i], stroke_width=20) for i in range(len(methods_dict)+1)]) lines.to_edge(DOWN * 0.22, buff=1) texts = VGroup(*[Text(t, color=WHITE, font='思源黑体 CN Bold', size=0.28) for t in methods_dict.keys()], plot_depth=1) text = Text('空降', color=WHITE, font='庞门正道标题体', size=0.44).to_edge(DOWN * 0.132, buff=1).to_edge(LEFT, buff=0.4) text[1].shift(RIGHT*0.03) text[0].shift(LEFT*0.01) for i in range(len(methods_dict)): texts[i].move_to(lines[i+1]) self.add(lines, texts, text) class VideoCover(Scene): def construct(self): background = Polygon( LEFT_SIDE * 2 + BOTTOM, BOTTOM, LEFT_SIDE / 2 + TOP, LEFT_SIDE * 2 + TOP, fill_opacity=0.7, fill_color=BLACK, stroke_width=0 ).shift(RIGHT) text = VGroup( Text("manim教程", font="庞门正道标题体", color=BLUE, size=2).scale(0.9), Text("第四讲", font="庞门正道标题体", color=BLUE, size=2).scale(1.1), Text("SVG、图片与文字", font="庞门正道标题体", color=ORANGE, size=2).scale(1.5) ).arrange(DOWN, aligned_edge=LEFT, buff=0.4) text[2].shift(DOWN*0.4) text.center().to_edge(LEFT, buff=0.8).shift(UP*0.5) text2 = VGroup( Text("manim教程", font="庞门正道标题体", color=BLUE, size=2).scale(0.9).set_stroke(width=12, opacity=0.4), Text("第四讲", font="庞门正道标题体", color=BLUE, size=2).scale(1.1).set_stroke(width=12, opacity=0.4), Text("SVG、图片与文字", font="庞门正道标题体", color=ORANGE, size=2).scale(1.5).set_stroke(width=13, opacity=0.4) ).arrange(DOWN, aligned_edge=LEFT, buff=0.4) text2[2].shift(DOWN*0.4) text2.center().to_edge(LEFT, buff=0.8).shift(UP*0.5) self.add(background, text2, text) class PreView(Scene_): def construct(self): title = VGroup( Text("SVG?", font="思源黑体 CN Heavy", color=BLUE, size=2.7), Text("图片?", font="思源黑体 CN Heavy", color=average_color(BLUE, GREEN), size=2.7), Text("文字?", font="思源黑体 CN Heavy", color=GREEN, size=2.7), ).arrange(RIGHT, buff=0.7).to_edge(UP) content = VGroup( CodeLine("SVGMobject()", size=2), CodeLine("ImageMobject()", size=2), CodeLine("TextMobject()", size=2), CodeLine("TexMobject()", size=2), CodeLine("Text()", size=2), ).arrange(DOWN, aligned_edge=LEFT).next_to(title, DOWN) self.add(title) self.wait() self.play(TransformFromCopy(title[0], content[0])) self.play(TransformFromCopy(title[1], content[1])) self.play(TransformFromCopy(title[2], content[2:])) self.wait(2) self.clear() title = CodeLine('text = TextMobject("ab", "cde")', size=1).to_edge(UP) level1 = VGroup( CodeLine('text:', size=0.7), TextMobject("ab", "cde", color=BLACK), ).arrange(RIGHT).next_to(title, DOWN, buff=1.5) level2 = VGroup( VGroup( CodeLine('text[0]:', size=0.7), level1[1][0].copy() ).arrange(RIGHT), VGroup( CodeLine('text[1]:', size=0.7), level1[1][1].copy() ).arrange(RIGHT) ).arrange(RIGHT, buff=2).next_to(level1, DOWN, buff=0.9) level3 = VGroup( VGroup( level2[0][1][0].copy(), CodeLine('text[0][0]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[0][1][1].copy(), CodeLine('text[0][1]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[1][1][0].copy(), CodeLine('text[1][0]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[1][1][1].copy(), CodeLine('text[1][1]', size=0.6), ).arrange(DOWN, buff=0.5), VGroup( level2[1][1][2].copy(), CodeLine('text[1][2]', size=0.6), ).arrange(DOWN, buff=0.5), ).arrange(RIGHT, buff=0.8, aligned_edge=DOWN).next_to(level2, DOWN, buff=0.9) level1bg = CodeBackground(level1, buff=0.15).round_corners(0.2) level2bg = VGroup() for each in level2: level2bg.add(CodeBackground(each, buff=0.15).round_corners(0.2)) level3bg = VGroup() base = CodeBackground(level3[1][0], buff=0.2).round_corners(0.2) for each in level3: level3bg.add(base.copy().move_to(each[0], coor_mask=np.array([1, 0, 1]))) lines12 = VGroup( Line(level1bg.get_bottom(), level2bg[0].get_top(), color=DARK_GRAY, stroke_width=3), Line(level1bg.get_bottom(), level2bg[1].get_top(), color=DARK_GRAY, stroke_width=3), ) lines23 = VGroup( Line(level2bg[0].get_bottom(), level3bg[0].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[0].get_bottom(), level3bg[1].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[1].get_bottom(), level3bg[2].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[1].get_bottom(), level3bg[3].get_top(), color=DARK_GRAY, stroke_width=3), Line(level2bg[1].get_bottom(), level3bg[4].get_top(), color=DARK_GRAY, stroke_width=3), ) self.add(title) self.play(FadeInFromDown(level1bg)) self.play(Write(level1)) self.play( *[Write(line) for line in lines12], FadeInFrom(level2bg, UP) ) self.play( Write(level2[0][0]), Write(level2[1][0]), ) self.play( TransformFromCopy(level1[1][0], level2[0][1]), TransformFromCopy(level1[1][1], level2[1][1]), run_time=1 ) self.play( *[Write(line) for line in lines23], FadeInFrom(level3bg, UP) ) self.play( TransformFromCopy(level2[0][1][0], level3[0][0]), TransformFromCopy(level2[0][1][1], level3[1][0]), TransformFromCopy(level2[1][1][0], level3[2][0]), TransformFromCopy(level2[1][1][1], level3[3][0]), TransformFromCopy(level2[1][1][2], level3[4][0]), run_time=1 ) self.play( AnimationGroup( *[FadeInFromDown(level3[i][1], lag_ratio=0.02) for i in range(5)], lag_ratio=0.2 ) ) self.wait(2)
26,776
435
{ "copyright_text": "Standard YouTube License", "description": "This talk discusses ongoing work to build streaming data processing systems for Python with Dask, a Pythonic library for parallel computing. This talk will discuss streaming primitives, dataframes, and integration with the Jupyter notebook and use example from financial time series and cyber-security.", "duration": 2351, "language": "eng", "recorded": "2017-11-27", "related_urls": [ { "label": "schedule", "url": "https://pydata.org/nyc2017/schedule/" }, { "label": "slides", "url": "https://matthewrocklin.com/slides/pydata-nyc-2017.html" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/yI_yZoUaz60/maxresdefault.jpg", "title": "Streaming Processing with Dask", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=yI_yZoUaz60" } ] }
361
5,169
<filename>Specs/e/6/9/SYRFTime/0.0.7/SYRFTime.podspec.json<gh_stars>1000+ { "name": "SYRFTime", "version": "0.0.7", "summary": "SYRFTime library for synchronized time.", "description": "SYRFTime library for synchronized time.\nThe library utilizes NTP servers for time precision.", "homepage": "https://github.com/sailing-yacht-research-foundation/client-sdk-ios-swift", "license": { "type": "MIT", "file": "FILE_LICENSE" }, "authors": { "Scopic Software": "<EMAIL>" }, "platforms": { "ios": "13.0" }, "swift_versions": "5.0", "source": { "git": "https://github.com/sailing-yacht-research-foundation/client-sdk-ios-swift.git", "tag": "0.0.7" }, "source_files": [ "SYRFTime", "SYRFTime/SYRFTime/**/*.{swift}" ], "exclude_files": "SYRFTime/Exclude", "dependencies": { "Kronos": [ "~> 4.2.1" ] }, "swift_version": "5.0" }
394
1,615
<reponame>mmdongxin/MLN /* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE 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. */ #ifndef UnitBezier_h #define UnitBezier_h #include "Defines.h" #include <math.h> ANIMATOR_NAMESPACE_BEGIN struct UnitBezier { UnitBezier(double p1x, double p1y, double p2x, double p2y) { // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1). cx = 3.0 * p1x; bx = 3.0 * (p2x - p1x) - cx; ax = 1.0 - cx -bx; cy = 3.0 * p1y; by = 3.0 * (p2y - p1y) - cy; ay = 1.0 - cy - by; } double sampleCurveX(double t) { // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule. return ((ax * t + bx) * t + cx) * t; } double sampleCurveY(double t) { return ((ay * t + by) * t + cy) * t; } double sampleCurveDerivativeX(double t) { return (3.0 * ax * t + 2.0 * bx) * t + cx; } // Given an x value, find a parametric value it came from. double solveCurveX(double x, double epsilon) { double t0; double t1; double t2; double x2; double d2; int i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; if (fabs (x2) < epsilon) return t2; d2 = sampleCurveDerivativeX(t2); if (fabs(d2) < 1e-6) break; t2 = t2 - x2 / d2; } // Fall back to the bisection method for reliability. t0 = 0.0; t1 = 1.0; t2 = x; if (t2 < t0) return t0; if (t2 > t1) return t1; while (t0 < t1) { x2 = sampleCurveX(t2); if (fabs(x2 - x) < epsilon) return t2; if (x > x2) t0 = t2; else t1 = t2; t2 = (t1 - t0) * .5 + t0; } // Failure. return t2; } double solve(double x, double epsilon) { return sampleCurveY(solveCurveX(x, epsilon)); } private: double ax; double bx; double cx; double ay; double by; double cy; }; ANIMATOR_NAMESPACE_END #endif
1,580
2,151
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content; import android.net.Uri; import android.util.Xml; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import java.util.Stack; /** * Inserts default data from InputStream, should be in XML format. * If the provider syncs data to the server, the imported data will be synced to the server. * <p>Samples:</p> * <br/> * Insert one row: * <pre> * &lt;row uri="content://contacts/people"> * &lt;Col column = "name" value = "<NAME> "/> * &lt;Col column = "addr" value = "Tx"/> * &lt;/row></pre> * <br/> * Delete, it must be in order of uri, select, and arg: * <pre> * &lt;del uri="content://contacts/people" select="name=? and addr=?" * arg1 = "<NAME>" arg2 ="Tx"/></pre> * <br/> * Use first row's uri to insert into another table, * content://contacts/people/1/phones: * <pre> * &lt;row uri="content://contacts/people"> * &lt;col column = "name" value = "<NAME>"/> * &lt;col column = "addr" value = "Tx"/> * &lt;row postfix="phones"> * &lt;col column="number" value="512-514-6535"/> * &lt;/row> * &lt;row postfix="phones"> * &lt;col column="cell" value="512-514-6535"/> * &lt;/row> * &lt;/row></pre> * <br/> * Insert multiple rows in to same table and same attributes: * <pre> * &lt;row uri="content://contacts/people" > * &lt;row> * &lt;col column= "name" value = "<NAME>"/> * &lt;col column= "addr" value = "Tx"/> * &lt;/row> * &lt;row> * &lt;/row> * &lt;/row></pre> * * @hide */ public class DefaultDataHandler implements ContentInsertHandler { private final static String ROW = "row"; private final static String COL = "col"; private final static String URI_STR = "uri"; private final static String POSTFIX = "postfix"; private final static String DEL = "del"; private final static String SELECT = "select"; private final static String ARG = "arg"; private Stack<Uri> mUris = new Stack<Uri>(); private ContentValues mValues; private ContentResolver mContentResolver; public void insert(ContentResolver contentResolver, InputStream in) throws IOException, SAXException { mContentResolver = contentResolver; Xml.parse(in, Xml.Encoding.UTF_8, this); } public void insert(ContentResolver contentResolver, String in) throws SAXException { mContentResolver = contentResolver; Xml.parse(in, this); } private void parseRow(Attributes atts) throws SAXException { String uriStr = atts.getValue(URI_STR); Uri uri; if (uriStr != null) { // case 1 uri = Uri.parse(uriStr); if (uri == null) { throw new SAXException("attribute " + atts.getValue(URI_STR) + " parsing failure"); } } else if (mUris.size() > 0){ // case 2 String postfix = atts.getValue(POSTFIX); if (postfix != null) { uri = Uri.withAppendedPath(mUris.lastElement(), postfix); } else { uri = mUris.lastElement(); } } else { throw new SAXException("attribute parsing failure"); } mUris.push(uri); } private Uri insertRow() { Uri u = mContentResolver.insert(mUris.lastElement(), mValues); mValues = null; return u; } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (ROW.equals(localName)) { if (mValues != null) { // case 2, <Col> before <Row> insert last uri if (mUris.empty()) { throw new SAXException("uri is empty"); } Uri nextUri = insertRow(); if (nextUri == null) { throw new SAXException("insert to uri " + mUris.lastElement().toString() + " failure"); } else { // make sure the stack lastElement save uri for more than one row mUris.pop(); mUris.push(nextUri); parseRow(atts); } } else { int attrLen = atts.getLength(); if (attrLen == 0) { // case 3, share same uri as last level mUris.push(mUris.lastElement()); } else { parseRow(atts); } } } else if (COL.equals(localName)) { int attrLen = atts.getLength(); if (attrLen != 2) { throw new SAXException("illegal attributes number " + attrLen); } String key = atts.getValue(0); String value = atts.getValue(1); if (key != null && key.length() > 0 && value != null && value.length() > 0) { if (mValues == null) { mValues = new ContentValues(); } mValues.put(key, value); } else { throw new SAXException("illegal attributes value"); } } else if (DEL.equals(localName)){ Uri u = Uri.parse(atts.getValue(URI_STR)); if (u == null) { throw new SAXException("attribute " + atts.getValue(URI_STR) + " parsing failure"); } int attrLen = atts.getLength() - 2; if (attrLen > 0) { String[] selectionArgs = new String[attrLen]; for (int i = 0; i < attrLen; i++) { selectionArgs[i] = atts.getValue(i+2); } mContentResolver.delete(u, atts.getValue(1), selectionArgs); } else if (attrLen == 0){ mContentResolver.delete(u, atts.getValue(1), null); } else { mContentResolver.delete(u, null, null); } } else { throw new SAXException("unknown element: " + localName); } } public void endElement(String uri, String localName, String name) throws SAXException { if (ROW.equals(localName)) { if (mUris.empty()) { throw new SAXException("uri mismatch"); } if (mValues != null) { insertRow(); } mUris.pop(); } } public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub } public void endDocument() throws SAXException { // TODO Auto-generated method stub } public void endPrefixMapping(String prefix) throws SAXException { // TODO Auto-generated method stub } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub } public void processingInstruction(String target, String data) throws SAXException { // TODO Auto-generated method stub } public void setDocumentLocator(Locator locator) { // TODO Auto-generated method stub } public void skippedEntity(String name) throws SAXException { // TODO Auto-generated method stub } public void startDocument() throws SAXException { // TODO Auto-generated method stub } public void startPrefixMapping(String prefix, String uri) throws SAXException { // TODO Auto-generated method stub } }
3,884
1,444
package mage.cards.r; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.common.combat.CanAttackAsThoughItDidntHaveDefenderSourceEffect; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.keyword.DefenderAbility; import mage.abilities.keyword.TrampleAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import java.util.UUID; /** * @author TheElk801 */ public final class RovingKeep extends CardImpl { public RovingKeep(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.ARTIFACT, CardType.CREATURE}, "{7}"); this.subtype.add(SubType.WALL); this.power = new MageInt(5); this.toughness = new MageInt(7); // Defender this.addAbility(DefenderAbility.getInstance()); // {7}: Roving Keep gets +2/+0 and gains trample until end of turn. It can attack this turn as though it didn't have defender. Ability ability = new SimpleActivatedAbility( new BoostSourceEffect(2, 0, Duration.EndOfTurn) .setText("{this} gets +2/+0"), new GenericManaCost(7) ); ability.addEffect(new GainAbilitySourceEffect( TrampleAbility.getInstance(), Duration.EndOfTurn ).setText("and gains trample until end of turn")); ability.addEffect(new CanAttackAsThoughItDidntHaveDefenderSourceEffect(Duration.EndOfTurn) .setText("It can attack this turn as though it didn't have defender")); this.addAbility(ability); } private RovingKeep(final RovingKeep card) { super(card); } @Override public RovingKeep copy() { return new RovingKeep(this); } } // sexy hexy is back, baby!
755
4,537
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "master/detector/standalone.hpp" #include <set> #include <mesos/master/detector.hpp> #include <process/defer.hpp> #include <process/dispatch.hpp> #include <process/future.hpp> #include <process/id.hpp> #include <process/process.hpp> #include "common/protobuf_utils.hpp" using namespace process; using std::set; namespace mesos { namespace master { namespace detector { class StandaloneMasterDetectorProcess : public Process<StandaloneMasterDetectorProcess> { public: StandaloneMasterDetectorProcess() : ProcessBase(ID::generate("standalone-master-detector")) {} explicit StandaloneMasterDetectorProcess(const MasterInfo& _leader) : ProcessBase(ID::generate("standalone-master-detector")), leader(_leader) {} ~StandaloneMasterDetectorProcess() override { discardPromises(&promises); } void appoint(const Option<MasterInfo>& leader_) { leader = leader_; setPromises(&promises, leader); } Future<Option<MasterInfo>> detect( const Option<MasterInfo>& previous = None()) { if (leader != previous) { return leader; } Promise<Option<MasterInfo>>* promise = new Promise<Option<MasterInfo>>(); promise->future() .onDiscard(defer(self(), &Self::discard, promise->future())); promises.insert(promise); return promise->future(); } private: void discard(const Future<Option<MasterInfo>>& future) { // Discard the promise holding this future. discardPromises(&promises, future); } Option<MasterInfo> leader; // The appointed master. set<Promise<Option<MasterInfo>>*> promises; }; StandaloneMasterDetector::StandaloneMasterDetector() { process = new StandaloneMasterDetectorProcess(); spawn(process); } StandaloneMasterDetector::StandaloneMasterDetector(const MasterInfo& leader) { process = new StandaloneMasterDetectorProcess(leader); spawn(process); } StandaloneMasterDetector::StandaloneMasterDetector(const UPID& leader) { process = new StandaloneMasterDetectorProcess( mesos::internal::protobuf::createMasterInfo(leader)); spawn(process); } StandaloneMasterDetector::~StandaloneMasterDetector() { terminate(process); process::wait(process); delete process; } void StandaloneMasterDetector::appoint(const Option<MasterInfo>& leader) { dispatch(process, &StandaloneMasterDetectorProcess::appoint, leader); } void StandaloneMasterDetector::appoint(const UPID& leader) { dispatch(process, &StandaloneMasterDetectorProcess::appoint, mesos::internal::protobuf::createMasterInfo(leader)); } Future<Option<MasterInfo>> StandaloneMasterDetector::detect( const Option<MasterInfo>& previous) { return dispatch(process, &StandaloneMasterDetectorProcess::detect, previous); } } // namespace detector { } // namespace master { } // namespace mesos {
1,123
21,684
<reponame>zadcha/rethinkdb // Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef _WIN32 #include <sys/wait.h> #include <sys/time.h> #include <sys/socket.h> #else // _WIN32 #include <atomic> #endif // _WIN32 #include <sys/types.h> #include <signal.h> #include <unistd.h> #include "arch/process.hpp" #include "extproc/extproc_job.hpp" #include "extproc/extproc_spawner.hpp" #include "extproc/extproc_worker.hpp" #include "arch/fd_send_recv.hpp" #include "utils.hpp" extproc_spawner_t *extproc_spawner_t::instance = nullptr; // This is the class that runs in the external process, doing all the work class worker_run_t { public: worker_run_t(fd_t _socket, process_id_t _spawner_pid) : socket(_socket), socket_stream(socket.get(), make_scoped<blocking_fd_watcher_t>()) { #ifdef _WIN32 // TODO WINDOWS: make sure the worker process gets killed #else guarantee(spawner_pid == INVALID_PROCESS_ID); spawner_pid = _spawner_pid; // Set ourselves to get interrupted when our parent dies struct sigaction sa = make_sa_handler(0, check_ppid_for_death); const int sigaction_res = sigaction(SIGALRM, &sa, nullptr); guarantee_err(sigaction_res == 0, "worker: could not set action for ALRM signal"); struct itimerval timerval; timerval.it_interval.tv_sec = 0; timerval.it_interval.tv_usec = 500 * THOUSAND; timerval.it_value = timerval.it_interval; struct itimerval old_timerval; const int itimer_res = setitimer(ITIMER_REAL, &timerval, &old_timerval); guarantee_err(itimer_res == 0, "worker: setitimer failed"); guarantee(old_timerval.it_value.tv_sec == 0 && old_timerval.it_value.tv_usec == 0, "worker: setitimer saw that we already had an itimer!"); // Send our pid over to the main process (because it didn't fork us directly) write_message_t wm; serialize<cluster_version_t::LATEST_OVERALL>(&wm, getpid()); int res = send_write_message(&socket_stream, &wm); guarantee(res == 0); #endif // _WIN32 } ~worker_run_t() { #ifndef _WIN32 guarantee(spawner_pid != INVALID_PROCESS_ID); spawner_pid = INVALID_PROCESS_ID; #endif } // Returning from this indicates an error, orderly shutdown will exit() manually void main_loop() { // Receive and run a function from the main process until one returns false bool (*fn) (read_stream_t *, write_stream_t *); while (true) { int64_t read_size = sizeof(fn); const int64_t read_res = force_read(&socket_stream, &fn, read_size); if (read_res != read_size) { break; } if (!fn(&socket_stream, &socket_stream)) { break; } // Trade magic numbers with the parent uint64_t magic_from_parent; { archive_result_t res = deserialize<cluster_version_t::LATEST_OVERALL>(&socket_stream, &magic_from_parent); if (res != archive_result_t::SUCCESS || magic_from_parent != extproc_worker_t::parent_to_worker_magic) { break; } } write_message_t wm; serialize<cluster_version_t::LATEST_OVERALL>( &wm, extproc_worker_t::worker_to_parent_magic); int res = send_write_message(&socket_stream, &wm); if (res != 0) { break; } } } private: #ifndef _WIN32 static pid_t spawner_pid; static void check_ppid_for_death(int) { pid_t ppid = getppid(); if (spawner_pid != -1 && spawner_pid != ppid) { ::_exit(EXIT_FAILURE); } } #endif // _WIN32 scoped_fd_t socket; socket_stream_t socket_stream; }; #ifndef _WIN32 pid_t worker_run_t::spawner_pid = -1; #endif #ifndef _WIN32 class spawner_run_t { public: explicit spawner_run_t(fd_t _socket) : socket(_socket) { // We set our PGID to our own PID (rather than inheriting our parent's PGID) // so that a signal (eg. SIGINT) sent to the parent's PGID (by eg. hitting // Ctrl-C at a terminal) will not propagate to us or our children. // // This is desirable because the RethinkDB engine deliberately crashes with // an error message if the spawner or a worker process dies; but a // command-line SIGINT should trigger a clean shutdown, not a crash. const int setpgid_res = setpgid(0, 0); guarantee_err(setpgid_res == 0, "spawner could not set PGID"); // We ignore SIGCHLD so that we don't accumulate zombie children. { // NB. According to `man 2 sigaction` on linux, POSIX.1-2001 says that // this will prevent zombies, but may not be "fully portable". struct sigaction sa = make_sa_handler(0, SIG_IGN); const int res = sigaction(SIGCHLD, &sa, nullptr); guarantee_err(res == 0, "spawner: Could not ignore SIGCHLD"); } } void main_loop() { process_id_t spawner_pid = current_process(); while(true) { fd_t worker_socket; fd_recv_result_t recv_res = recv_fds(socket.get(), 1, &worker_socket); if (recv_res != FD_RECV_OK) { break; } pid_t res = ::fork(); if (res == 0) { // Worker process here socket.reset(); // Don't need the spawner's pipe worker_run_t worker_runner(worker_socket, spawner_pid); worker_runner.main_loop(); ::_exit(EXIT_FAILURE); } guarantee_err(res != -1, "could not fork worker process"); scoped_fd_t closer(worker_socket); } } private: scoped_fd_t socket; }; #endif extproc_spawner_t::extproc_spawner_t() { // TODO: guarantee we aren't in a thread pool guarantee(instance == nullptr); instance = this; #ifdef _WIN32 // TODO WINDOWS: ensure the workers die if the parent process does, // perhaps using CreateJobObject and JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE #else spawner_pid = INVALID_PROCESS_ID; fork_spawner(); #endif } extproc_spawner_t::~extproc_spawner_t() { // TODO: guarantee we aren't in a thread pool guarantee(instance == this); instance = nullptr; #ifdef _WIN32 // TODO WINDOWS: cleanup worker processes #else // This should trigger the spawner to exit spawner_socket.reset(); // Wait on the spawner's return value to clean up the process int status; int res = waitpid(spawner_pid, &status, 0); guarantee_err(res == spawner_pid, "failed to wait for extproc spawner process to exit"); #endif } extproc_spawner_t *extproc_spawner_t::get_instance() { return instance; } #ifndef _WIN32 void extproc_spawner_t::fork_spawner() { guarantee(spawner_socket.get() == INVALID_FD); fd_t fds[2]; int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds); guarantee_err(res == 0, "could not create socket pair for spawner process"); res = ::fork(); if (res == 0) { // This is the spawner process, just instantiate ourselves and handle requests do { res = ::close(fds[0]); } while (res == 0 && get_errno() == EINTR); spawner_run_t spawner(fds[1]); spawner.main_loop(); ::_exit(EXIT_SUCCESS); } spawner_pid = res; guarantee_err(spawner_pid != -1, "could not fork spawner process"); scoped_fd_t closer(fds[1]); spawner_socket.reset(fds[0]); } #endif // Spawns a new worker process and returns the fd of the socket used to communicate with it scoped_fd_t extproc_spawner_t::spawn(process_id_t *pid_out) { #ifdef _WIN32 static std::atomic<uint64_t> unique = 0; char rethinkdb_path[MAX_PATH]; DWORD res = GetModuleFileName(NULL, rethinkdb_path, sizeof(rethinkdb_path)); guarantee_winerr(res != 0 && res != sizeof(rethinkdb_path), "GetModuleFileName failed"); scoped_fd_t fd; std::string pipe_path = strprintf("\\\\.\\pipe\\rethinkdb-worker-%d-%d", GetCurrentProcessId(), ++unique); fd.reset(CreateNamedPipe(pipe_path.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 2048, 2048, 0, nullptr)); guarantee_winerr(fd.get() != INVALID_FD, "CreateNamedPipe failed"); std::string command_line = strprintf("RethinkDB " SUBCOMMAND_START_WORKER " %s", pipe_path.c_str()); std::vector<char> mutable_command_line(command_line.begin(), command_line.end()); mutable_command_line.push_back('\0'); STARTUPINFO startup_info; memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(startup_info); PROCESS_INFORMATION process_info; BOOL res2 = CreateProcess(rethinkdb_path, &mutable_command_line[0], nullptr, nullptr, false, NORMAL_PRIORITY_CLASS, nullptr, nullptr, &startup_info, &process_info); guarantee_winerr(res2, "CreateProcess failed"); // TODO WINDOWS: add new process to job group *pid_out = process_id_t(GetProcessId(process_info.hProcess)); CloseHandle(process_info.hThread); return fd; #else // _WIN32 guarantee(spawner_socket.get() != INVALID_FD); fd_t fds[2]; int res = socketpair(AF_UNIX, SOCK_STREAM, 0, fds); guarantee_err(res == 0, "could not create socket pair for worker process"); scoped_fd_t fd0(fds[0]); scoped_fd_t fd1(fds[1]); res = send_fds(spawner_socket.get(), 1, &fds[1]); if (res != 0) { throw extproc_worker_exc_t("could not send file descriptor to worker process"); } socket_stream_t stream_out(fds[0]); // Get the pid of the new worker process archive_result_t archive_res; archive_res = deserialize<cluster_version_t::LATEST_OVERALL>(&stream_out, pid_out); if (archive_res != archive_result_t::SUCCESS || *pid_out == INVALID_PROCESS_ID) { throw extproc_worker_exc_t("malformed response from fresh worker process"); } return fd0; #endif // _WIN32 } #ifdef _WIN32 bool extproc_maybe_run_worker(int argc, char **argv) { if (argc != 3 || strcmp(argv[1], SUBCOMMAND_START_WORKER)) { return false; } // Don't handle signals like ^C in the extproc worker process SetConsoleCtrlHandler(nullptr, true); fd_t fd = CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); guarantee_winerr(fd != INVALID_FD, "opening '%s'", argv[2]); worker_run_t worker(fd, INVALID_PROCESS_ID); worker.main_loop(); ::_exit(EXIT_SUCCESS); return true; } #endif // _WIN32
5,419
3,655
from http.server import BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write('hello:RANDOMNESS_PLACEHOLDER'.encode()) return
124
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _CNTWALL_HXX #define _CNTWALL_HXX #include "svl/svldllapi.h" #ifndef SHL_HXX #include <tools/shl.hxx> #endif #include <tools/rtti.hxx> #include <tools/color.hxx> #include <svl/poolitem.hxx> class SvStream; class SVL_DLLPUBLIC CntWallpaperItem : public SfxPoolItem { private: UniString _aURL; Color _nColor; sal_uInt16 _nStyle; public: TYPEINFO(); CntWallpaperItem( sal_uInt16 nWhich ); CntWallpaperItem( sal_uInt16 nWhich, SvStream& rStream, sal_uInt16 nVersion ); CntWallpaperItem( const CntWallpaperItem& rCpy ); ~CntWallpaperItem(); virtual sal_uInt16 GetVersion(sal_uInt16) const; virtual int operator==( const SfxPoolItem& ) const; virtual SfxPoolItem* Create( SvStream&, sal_uInt16 nItemVersion ) const; virtual SvStream& Store( SvStream&, sal_uInt16 nItemVersion ) const; virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const; virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const; virtual sal_Bool PutValue ( const com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ); void SetBitmapURL( const UniString& rURL ) { _aURL = rURL; } void SetColor( Color nColor ) { _nColor = nColor; } void SetStyle( sal_uInt16 nStyle ) { _nStyle = nStyle; } const UniString& GetBitmapURL() const { return _aURL; } Color GetColor() const { return _nColor; } sal_uInt16 GetStyle() const { return _nStyle; } }; //////////////////////////////////////////////////////////////////////////////// #endif // _CNTWALL_HXX
901
764
<reponame>641589523/token-profile<gh_stars>100-1000 {"symbol": "XBL","address": "0x49AeC0752E68D0282Db544C677f6BA407BA17ED7","overview":{"en": ""},"email": "<EMAIL>","website": "https://billionairetoken.com/","state": "NORMAL","links": {"blog": "","twitter": "https://twitter.com/BillionaireTkn","telegram": "","github": "https://github.com/billionairetoken/TokenCore"}}
136
764
{"symbol": "RUT","address": "0xf050E54d2b50c055C9919a4B856A195221D3DB71","overview":{"en": "Fee-less decentralized application platform."},"email": "<EMAIL>","website": "https://rutile.io/","state": "NORMAL","links": {"blog": "","twitter": "","telegram": "https://t.me/joinchat/LW4kzhaNZ3ZrK0gDOjqnzg","github": "https://github.com/Rutile-io"}}
139
1,091
// // RMTableViewController.h // HeapInspectorExample // // Created by <NAME> on 01.09.14. // Copyright (c) 2014 tapwork. All rights reserved. // #import <UIKit/UIKit.h> #import "HINSPTableViewCell.h" @interface HINSPTableViewController : UITableViewController @property (nonatomic, strong) NSArray *dataSource; @property (nonatomic, readonly) NSArray *dataSourceUnfiltered; @property (nonatomic, strong) id inspectingObject; - (instancetype)initWithObject:(id)object; - (instancetype)initWithPointerString:(NSString *)pointer; - (instancetype)initWithDataSource:(NSArray *)dataSource; - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar; - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar; - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar; - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText; @end
292
825
#pragma once #pragma once #include "HexControl.h" class MemoryBuffer : public IBufferManager { public: MemoryBuffer(uint32_t initialSize = 0); MemoryBuffer(const uint8_t* data, uint32_t size); void Init(const uint8_t* data, uint32_t size); // Inherited via IBufferManager uint32_t GetData(int64_t offset, uint8_t* buffer, uint32_t count) override; bool Insert(int64_t offset, const uint8_t* data, uint32_t count) override; bool Delete(int64_t offset, size_t count) override; bool SetData(int64_t offset, const uint8_t* data, uint32_t count) override; int64_t GetSize() const override; uint8_t* GetRawData(int64_t offset) override; bool IsReadOnly() const override; bool Increase(uint32_t size) override; private: std::vector<uint8_t> _buffer; };
276
401
<filename>liteflow-core/src/main/java/com/yomahub/liteflow/exception/ExecutableItemNotFoundException.java /** * <p>Title: liteflow</p> * <p>Description: 轻量级的组件式流程框架</p> * @author Bryan.Zhang * @email <EMAIL> * @Date 2020/4/1 */ package com.yomahub.liteflow.exception; public class ExecutableItemNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; /** 异常信息 */ private String message; public ExecutableItemNotFoundException() { } public ExecutableItemNotFoundException(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
259
423
<gh_stars>100-1000 import json, csv sites = {} sites = [] with open("sites.csv", "r") as csvfile: filereader = csv.DictReader(csvfile) for row in filereader: try: sites.append([row['domain'], float(row['lat']), float(row['lng'])]) except ValueError: # for sites that dont have location pass with open("sites-geocoded.json", "w") as jsonfile: json.dump(sites, jsonfile, indent=4)
182
1,426
<reponame>ovidiuiuonas/robospice package com.octo.android.robospice.request.listener; /** * Listens to a SpiceRequest that may be pending, or not. It will be notified of * request's result if such a request is pending, otherwise it will notified * that such a request is not currently pending. */ public interface PendingRequestListener<RESULT> extends RequestListener<RESULT> { void onRequestNotFound(); }
119
2,494
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef gc_Rooting_h #define gc_Rooting_h #include "js/RootingAPI.h" class JSAtom; class JSLinearString; namespace js { class PropertyName; class ScriptSourceObject; class Shape; namespace types { struct TypeObject; } // These are internal counterparts to the public types such as HandleObject. typedef JS::Handle<Shape*> HandleShape; typedef JS::Handle<types::TypeObject*> HandleTypeObject; typedef JS::Handle<JSAtom*> HandleAtom; typedef JS::Handle<JSLinearString*> HandleLinearString; typedef JS::Handle<PropertyName*> HandlePropertyName; typedef JS::Handle<ScriptSourceObject*> HandleScriptSource; typedef JS::MutableHandle<Shape*> MutableHandleShape; typedef JS::MutableHandle<JSAtom*> MutableHandleAtom; typedef JS::Rooted<Shape*> RootedShape; typedef JS::Rooted<types::TypeObject*> RootedTypeObject; typedef JS::Rooted<JSAtom*> RootedAtom; typedef JS::Rooted<JSLinearString*> RootedLinearString; typedef JS::Rooted<PropertyName*> RootedPropertyName; typedef JS::Rooted<ScriptSourceObject*> RootedScriptSource; } /* namespace js */ #endif /* gc_Rooting_h */
563
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/local_search_service/test_utils.h" #include <cmath> #include <map> #include <string> #include <utility> #include <vector> namespace chromeos { namespace local_search_service { namespace { // (content-id, content). using ContentWithId = std::pair<std::string, std::string>; // (content-id, content, weight). using WeightedContentWithId = std::tuple<std::string, std::string, float>; } // namespace std::vector<Data> CreateTestData( const std::map<std::string, std::vector<ContentWithId>>& input) { std::vector<Data> output; for (const auto& item : input) { Data data; data.id = item.first; // Hardcode to "en" because it's unclear what config locale will be when // running a test. // TODO(jiameng): allow locale to be passed in if there's a need to use // non-en data in tests. data.locale = "en"; std::vector<Content>& contents = data.contents; for (const auto& content_with_id : item.second) { const Content content(content_with_id.first, base::UTF8ToUTF16(content_with_id.second)); contents.push_back(content); } output.push_back(data); } return output; } std::vector<Data> CreateTestData( const std::map<std::string, std::vector<std::tuple<std::string, std::string, float>>>& input) { std::vector<Data> output; for (const auto& item : input) { Data data; data.id = item.first; // Hardcode to "en" because it's unclear what config locale will be when // running a test. // TODO(jiameng): allow locale to be passed in if there's a need to use // non-en data in tests. data.locale = "en"; std::vector<Content>& contents = data.contents; for (const auto& weighted_content_with_id : item.second) { const Content content( std::get<0>(weighted_content_with_id), base::UTF8ToUTF16(std::get<1>(weighted_content_with_id)), std::get<2>(weighted_content_with_id)); contents.push_back(content); } output.push_back(data); } return output; } void CheckResult(const Result& result, const std::string& expected_id, float expected_score, size_t expected_number_positions) { EXPECT_EQ(result.id, expected_id); EXPECT_NEAR(result.score, expected_score, 0.001); EXPECT_EQ(result.positions.size(), expected_number_positions); } float TfIdfScore(size_t num_docs, size_t num_docs_with_term, float weighted_num_term_occurrence_in_doc, size_t doc_length) { const float idf = 1.0 + log((1.0 + num_docs) / (1.0 + num_docs_with_term)); const float tf = weighted_num_term_occurrence_in_doc / doc_length; return tf * idf; } } // namespace local_search_service } // namespace chromeos
1,189
1,062
<gh_stars>1000+ // // Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class NSMutableArray, NSMutableIndexSet, NSPredicate; @protocol ManagedListSortInfo; @interface ManagedList : NSObject { NSMutableArray *_orderedObjects; // 8 = 0x8 NSMutableIndexSet *_unfilteredIndexes; // 16 = 0x10 id _comparator; // 24 = 0x18 NSPredicate *_filterPredicate; // 32 = 0x20 id <ManagedListSortInfo> _sortInfo; // 40 = 0x28 } @property(retain, nonatomic) id <ManagedListSortInfo> sortInfo; // @synthesize sortInfo=_sortInfo; @property(retain, nonatomic) NSPredicate *filterPredicate; // @synthesize filterPredicate=_filterPredicate; @property(copy, nonatomic) id comparator; // @synthesize comparator=_comparator; // - (void).cxx_destruct; // IMP=0x00000001001d5bb7 - (unsigned long long)_removeObjectIfPresent:(id)arg1 fromArray:(id)arg2 inSortedRange:(struct _NSRange)arg3 usingComparator:(id)arg4 didRemove:(char *)arg5; // IMP=0x00000001001d5a61 - (unsigned long long)_insertObjectIfAbsent:(id)arg1 intoArray:(id)arg2 inSortedRange:(struct _NSRange)arg3 usingComparator:(id)arg4 didInsert:(char *)arg5; // IMP=0x00000001001d5955 - (unsigned long long)_removeObject:(id)arg1 inSortedRange:(struct _NSRange)arg2 didRemove:(char *)arg3; // IMP=0x00000001001d587f - (id)mutableCopyOfOrderedObjects; // IMP=0x00000001001d5773 - (id)copyOfOrderedObjects; // IMP=0x00000001001d574d - (unsigned long long)indexOfOrderedObject:(id)arg1; // IMP=0x00000001001d566f - (void)enumerateOrderedObjectsUsingBlock:(id)arg1; // IMP=0x00000001001d551f @property(readonly, nonatomic) unsigned long long orderedObjectsCount; - (unsigned long long)_unadjustedIndexForAdjustedIndex:(unsigned long long)arg1; // IMP=0x00000001001d53f5 - (id)orderedObjectsAtIndexes:(id)arg1; // IMP=0x00000001001d52de - (void)setOrderedObject:(id)arg1 atIndex:(unsigned long long)arg2; // IMP=0x00000001001d5279 - (id)orderedObjectAtIndex:(unsigned long long)arg1; // IMP=0x00000001001d5247 - (unsigned long long)removeObject:(id)arg1; // IMP=0x00000001001d5165 - (id)removeObjects:(id)arg1; // IMP=0x00000001001d4f06 - (unsigned long long)mergeObject:(id)arg1; // IMP=0x00000001001d4d74 - (id)mergeObjects:(id)arg1; // IMP=0x00000001001d488a - (void)applyFilterReturningAddedIndexes:(id *)arg1 removedIndexes:(id *)arg2; // IMP=0x00000001001d4655 - (void)invert; // IMP=0x00000001001d451e - (void)resort; // IMP=0x00000001001d4381 - (id)init; // IMP=0x00000001001d42f4 @end
995
371
<reponame>pambros/StereoKit #include "model.h" #include "../libraries/array.h" #include "../sk_math.h" #define MICRO_PLY_IMPL #include "../libraries/micro_ply.h" #include <stdio.h> namespace sk { /////////////////////////////////////////// bool modelfmt_ply(model_t model, const char *filename, void *file_data, size_t file_length, shader_t shader) { material_t material = shader == nullptr ? material_find(default_id_material) : material_create(shader); bool result = true; char id[512]; snprintf(id, sizeof(id), "%s/mesh", filename); mesh_t mesh = mesh_find(id); if (mesh) { model_add_subset(model, mesh, material, matrix_identity); } else { // Parse the data using ply_read ply_file_t file; if (!ply_read(file_data, file_length, &file)) return false; vert_t *verts = nullptr; vind_t *inds = nullptr; int32_t vert_count = 0; int32_t ind_count = 0; // Describe the way the contents of the PLY file map to our own vertex // format. If the property can't be found in the file, the default value // will be assigned. float fzero = 0; uint8_t white = 255; ply_map_t map_verts[] = { { PLY_PROP_POSITION_X, ply_prop_decimal, sizeof(float), 0, &fzero }, { PLY_PROP_POSITION_Y, ply_prop_decimal, sizeof(float), 4, &fzero }, { PLY_PROP_POSITION_Z, ply_prop_decimal, sizeof(float), 8, &fzero }, { PLY_PROP_NORMAL_X, ply_prop_decimal, sizeof(float), 12, &fzero }, { PLY_PROP_NORMAL_Y, ply_prop_decimal, sizeof(float), 16, &fzero }, { PLY_PROP_NORMAL_Z, ply_prop_decimal, sizeof(float), 20, &fzero }, { PLY_PROP_TEXCOORD_X, ply_prop_decimal, sizeof(float), 24, &fzero }, { PLY_PROP_TEXCOORD_Y, ply_prop_decimal, sizeof(float), 28, &fzero }, { PLY_PROP_COLOR_R, ply_prop_uint, sizeof(uint8_t), 32, &white }, { PLY_PROP_COLOR_G, ply_prop_uint, sizeof(uint8_t), 33, &white }, { PLY_PROP_COLOR_B, ply_prop_uint, sizeof(uint8_t), 34, &white }, { PLY_PROP_COLOR_A, ply_prop_uint, sizeof(uint8_t), 35, &white }, }; ply_convert(&file, PLY_ELEMENT_VERTICES, map_verts, sizeof(map_verts)/sizeof(map_verts[0]), sizeof(vert_t), (void**)&verts, &vert_count); // Properties defined as lists in the PLY format will get triangulated // during conversion, so you don't need to worry about quads or n-gons in // the geometry. uint32_t izero = 0; ply_map_t map_inds[] = { { PLY_PROP_INDICES, ply_prop_uint, sizeof(uint32_t), 0, &izero } }; ply_convert(&file, PLY_ELEMENT_FACES, map_inds, sizeof(map_inds)/sizeof(map_inds[0]), sizeof(uint32_t), (void**)&inds, &ind_count); // You gotta free the memory manually! ply_free(&file); // Make a mesh out of it all mesh = mesh_create(); mesh_set_id (mesh, id); mesh_set_verts(mesh, verts, vert_count); mesh_set_inds (mesh, inds, ind_count); model_add_subset(model, mesh, material, matrix_identity); free(verts); free(inds); } mesh_release (mesh); material_release(material); return result; } }
1,283
764
<reponame>641589523/token-profile { "symbol": "PAYC", "address": "0xab3eF3eCB6cFaFEbdb11ed919151503dE17A5831", "overview":{ "en": "PAYC is committed to creating a variety of open tools for blockchain payment scenarios, providing them to merchants and enterprises, and ultimately creating an open ecosystem based on blockchain finance.", "zh": "PAYC致力于打造各种应用于区块链支付场景的开放工具,提供给商家和企业,最终打造基于区块链金融的开放生态系统。" }, "email": "<EMAIL>", "website": "https://www.payc.cc", "whitepaper": "https://www.payc.cc/PAYCEN.pdf", "state": "NORMAL", "published_on": "2020-08-26", "links": { "telegram": "https://t.me/paycgroup", "twitter": "https://twitter.com/paymentchain" } }
407
1,615
import sys sys.path.append('..') from helpers import render_frames from graphs.FLIPPass import FLIPPass as g from falcor import * m.addGraph(g) # default render_frames(m, 'default') # useMagma for useMagma in [False, True]: g.updatePass('FLIP', {'useMagma': useMagma}) render_frames(m, 'useMagma.' + str(useMagma)) # isHDR for isHDR in [False, True]: g.updatePass('FLIP', {'isHDR': isHDR}) render_frames(m, 'isHDR.' + str(isHDR)) # toneMapper for toneMapper in [FLIPToneMapperType.ACES, FLIPToneMapperType.Hable, FLIPToneMapperType.Reinhard]: g.updatePass('FLIP', {'isHDR': True, 'toneMapper': toneMapper}) render_frames(m, 'toneMapper.' + str(toneMapper)) exit()
285
3,428
{"id":"01146","group":"easy-ham-1","checksum":{"type":"MD5","value":"fe05a7a131928bf0997793278e203448"},"text":"From <EMAIL> Wed Oct 2 11:43:17 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 11B4A16F03\n\tfor <jm@localhost>; Wed, 2 Oct 2002 11:43:17 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Wed, 02 Oct 2002 11:43:17 +0100 (IST)\nReceived: from listman.spamassassin.taint.org (listman.spamassassin.taint.org [66.187.233.211]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g924NTK25461 for\n <<EMAIL>>; Wed, 2 Oct 2002 05:23:30 +0100\nReceived: from listman.spamassassin.taint.org (localhost.localdomain [127.0.0.1]) by\n listman.redhat.com (Postfix) with ESMTP id 82B7F3EA36; Wed, 2 Oct 2002\n 00:24:04 -0400 (EDT)\nDelivered-To: <EMAIL>int.<EMAIL>\nReceived: from int-mx1.corp.spamassassin.taint.org (int-mx1.corp.spamassassin.taint.org\n [172.16.52.254]) by listman.redhat.com (Postfix) with ESMTP id 0BC7440AD2\n for <<EMAIL>>; Wed, 2 Oct 2002 00:21:29 -0400\n (EDT)\nReceived: (from mail@localhost) by int-mx1.corp.spamassassin.taint.org (8.11.6/8.11.6)\n id g924LSG11235 for <EMAIL>; Wed, 2 Oct 2002\n 00:21:28 -0400\nReceived: from mx1.spamassassin.taint.org (mx1.spamassassin.taint.org [172.16.48.31]) by\n int-mx1.corp.redhat.com (8.11.6/8.11.6) with SMTP id g924LSf11231 for\n <<EMAIL>>; Wed, 2 Oct 2002 00:21:28 -0400\nReceived: from dimebox.bmc.com (adsl-66-140-152-233.dsl.hstntx.swbell.net\n [66.140.152.233]) by mx1.redhat.com (8.11.6/8.11.6) with SMTP id\n g9242fi19217 for <<EMAIL>>; Wed, 2 Oct 2002 00:02:41 -0400\nReceived: by dimebox.bmc.com (Postfix, from userid 1205) id 3F74337EA9;\n Tue, 1 Oct 2002 23:21:27 -0500 (CDT)\nReceived: from dimebox.bmc.com (localhost [127.0.0.1]) by dimebox.bmc.com\n (Postfix) with ESMTP id 0A11D37EA6 for <<EMAIL>>;\n Tue, 1 Oct 2002 23:21:27 -0500 (CDT)\nX-Mailer: exmh version 2.5 07/13/2001 cvs 10/01/2002 with nmh-1.0.4\nTo: <EMAIL>int.org\nSubject: Unseen window versus Sequences Window\nMIME-Version: 1.0\nFrom: <NAME> <<EMAIL>>\nX-Image-Url: http://www.geocities.com/hal_devore_ii/haleye48.gif\nContent-Type: text/plain; charset=us-ascii\nMessage-Id: <<EMAIL>>\nX-Loop: ex<EMAIL>int.org\nSender: exmh-workers-admin<EMAIL>int.org\nErrors-To: <EMAIL>\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.1\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <https://listman.spamassassin.taint.org/mailman/listinfo/exmh-workers>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Discussion list for EXMH developers <exmh-workers.spamassassin.taint.org>\nList-Unsubscribe: <https://listman.spamassassin.taint.org/mailman/listinfo/exmh-workers>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <https://listman.spamassassin.taint.org/mailman/private/exmh-workers/>\nDate: Tue, 01 Oct 2002 23:21:21 -0500\n\n\nI apologize for not catching up to the current code in so long.\n\nNow that I have I'm trying to resolve \"breakage\" and differences.\n\nThe unseen window seems to have been replaced with the sequences \nwindow. While I appreciate the flexibility of the sequences \nwindow, the unseen window filled an important-to-me need: It \nwas tiny and could be set to show on all desktops of a virtual \nwindow manager without taking a lot of space. Since my normal \nmode of operation involves two copies of exmh displaying on a \n1024x768 vnc session, screen space is at a premium.\n\nAs things stand now, I have a sequences window that shows a lot\nmore information than I need to have handy and takes up a lot \nmore room than I can \"spare\".\n\nI can see that I could like the new sequences window a lot for \ncertain operations. But I'd like a nice uncluttered, tiny \nwindow that _only_ shows me info on my unread mail.\n\nOne possibility that occurs to me would be a button or mouse\nclick that \"shrinks\" the Sequences window to show only the\nsequences in the \"always show\" list. And of course a way to \nexpand it back.\n\n--Hal\n\n\n\n\n_______________________________________________\nExmh-workers mailing list\n<EMAIL>\nhttps://listman.redhat.com/mailman/listinfo/exmh-workers\n\n\n"}
1,773
482
<gh_stars>100-1000 package io.cattle.platform.resource.pool; import io.cattle.platform.util.type.Named; public interface PooledResource extends Named { }
51
997
<reponame>mkannwischer/PQClean #include "vec128.h" vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_set1_16b(uint16_t a) { return _mm_set1_epi16(a); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_setzero(void) { return _mm_setzero_si128(); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_and(vec128 a, vec128 b) { return _mm_and_si128(a, b); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_xor(vec128 a, vec128 b) { return _mm_xor_si128(a, b); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_or(vec128 a, vec128 b) { return _mm_or_si128(a, b); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_sll_2x(vec128 a, int s) { return _mm_slli_epi64(a, s); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_srl_2x(vec128 a, int s) { return _mm_srli_epi64(a, s); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_set2x(uint64_t a0, uint64_t a1) { return _mm_set_epi64x(a1, a0); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_unpack_low(vec128 a, vec128 b) { return _mm_unpacklo_epi64(a, b); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_unpack_high(vec128 a, vec128 b) { return _mm_unpackhi_epi64(a, b); } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_setbits(uint64_t a) { return _mm_set1_epi64x(-a); } void PQCLEAN_MCELIECE460896F_AVX_vec128_copy(vec128 *dest, const vec128 *src) { int i; for (i = 0; i < GFBITS; i++) { dest[i] = src[i]; } } void PQCLEAN_MCELIECE460896F_AVX_vec128_add(vec128 *c, const vec128 *a, const vec128 *b) { int i; for (i = 0; i < GFBITS; i++) { c[i] = PQCLEAN_MCELIECE460896F_AVX_vec128_xor(a[i], b[i]); } } vec128 PQCLEAN_MCELIECE460896F_AVX_vec128_or_reduce(const vec128 *a) { int i; vec128 ret; ret = a[0]; for (i = 1; i < GFBITS; i++) { ret = PQCLEAN_MCELIECE460896F_AVX_vec128_or(ret, a[i]); } return ret; } /* bitsliced field multiplications */ void PQCLEAN_MCELIECE460896F_AVX_vec128_mul(vec128 *h, vec128 *f, const vec128 *g) { PQCLEAN_MCELIECE460896F_AVX_vec128_mul_asm(h, f, g, 16); }
1,077
1,253
//Finding power of x to the n, where n can be a positive or negative integer. //As we already we know that negative exponent is equal to 1 by power(x,n) //And this is a iterative approach //Problem link: https://leetcode.com/problems/powx-n/ /********************************** * Dry Run of Program: * power(2.0,10)=(2*2)^5 = 4^5 =1024 * 4^5 = 4*4^4 = 1024 * 4^4 = (4*4)^2 = 16^2 = 256 * 16^2 = (16*16) = 256^1 =256 * 256^1 = 256*256^0 = 256 ***********************************/ #include<bits/stdc++.h> using namespace std; double power(double x,int n){ double ans=1.0; int nn=n; if(nn<0){ //Checking for negative integer nn=-1*nn; } while(nn){ if(nn%2 == 1){ ans=x*ans; nn=nn-1; } else{ x=x*x; nn=nn/2; } } if(n<0){ ans=(double)(1.0)/(double)(ans); } return ans; } int main(){ double x; cin>>x; int n;cin>>n; cout<<power(x,n)<<endl; return 0; }
488
1,199
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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. r"""Metrics for TOP and MTOP parses.""" from language.casper.utils import top_utils def _safe_divide(x, y): return x / y if y != 0 else 0.0 def top_metrics(targets, predictions): """Returns eval metrics for TOP and MTOP datasets.""" num_correct = 0 num_total = 0 num_invalid = 0 num_intent_correct = 0 num_frame_correct = 0 for target, predicted in zip(targets, predictions): if target == predicted: num_correct += 1 num_total += 1 target_lf = top_utils.deserialize_top(target) predicted_lf = top_utils.deserialize_top(predicted) assert target_lf is not None if not predicted_lf: num_invalid += 1 continue target_frame = top_utils.get_frame_top(target_lf) predicted_frame = top_utils.get_frame_top(predicted_lf) target_intent = target_frame.split("-")[0] predicted_intent = predicted_frame.split("-")[0] num_intent_correct += int(predicted_intent == target_intent) num_frame_correct += int(predicted_frame == target_frame) return dict( num_total=num_total, full_accuracy=_safe_divide(num_correct, num_total), intent_accuracy=_safe_divide(num_intent_correct, num_total), intent_arg_accuracy=_safe_divide(num_frame_correct, num_total), invalid_predictions=_safe_divide(num_invalid, num_total))
658
746
<reponame>Keendata/impala // 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. #pragma once #include <memory> #include <vector> #include "common/status.h" #include "gen-cpp/Types_types.h" #include "gen-cpp/admission_control_service.pb.h" #include "gen-cpp/common.pb.h" #include "scheduling/admission-controller.h" namespace impala { // Base class used to abstract out the logic for submitting queries to an admission // controller running locally or to one running remotely. class AdmissionControlClient { public: static const std::string QUERY_EVENT_SUBMIT_FOR_ADMISSION; static const std::string QUERY_EVENT_QUEUED; static const std::string QUERY_EVENT_COMPLETED_ADMISSION; // Creates a new AdmissionControlClient and returns it in 'client'. static void Create( const TQueryCtx& query_ctx, std::unique_ptr<AdmissionControlClient>* client); virtual ~AdmissionControlClient() {} // Called to schedule and admit the query. Blocks until an admission decision is made. virtual Status SubmitForAdmission(const AdmissionController::AdmissionRequest& request, RuntimeProfile::EventSequence* query_events, std::unique_ptr<QuerySchedulePB>* schedule_result) = 0; // Called when the query has completed to release all of its resources. virtual void ReleaseQuery(int64_t peak_mem_consumption) = 0; // Called with a list of backends the query has completed on, to release the resources // for the query on those backends. virtual void ReleaseQueryBackends(const std::vector<NetworkAddressPB>& host_addr) = 0; // Called to cancel admission for the query. virtual void CancelAdmission() = 0; }; } // namespace impala
670
1,337
<filename>modules/web-widgets/src/com/haulmont/cuba/web/widgets/client/addons/aceeditor/SetDiff.java /* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.haulmont.cuba.web.widgets.client.addons.aceeditor; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceAnnotation.MarkerAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.AceAnnotation.RowAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDiff.TransportSetDiffForMarkerAnnotations; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDiff.TransportSetDiffForRowAnnotations; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDoc.TransportMarkerAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDoc.TransportRowAnnotation; import com.haulmont.cuba.web.widgets.client.addons.aceeditor.TransportDoc.TransportableAs; public class SetDiff<V extends TransportableAs<T>,T> { private final Set<V> added; private final Set<V> removed; public SetDiff(Set<V> added, Set<V> removed) { this.added = added; this.removed = removed; } public SetDiff() { added = Collections.emptySet(); removed = Collections.emptySet(); } public static class Differ<V extends TransportableAs<T>,T> { public SetDiff<V,T> diff(Set<V> s1, Set<V> s2) { Set<V> removed = new HashSet<V>(s1); removed.removeAll(s2); Set<V> added = new HashSet<V>(s2); added.removeAll(s1); return new SetDiff<V,T>(added, removed); } // public SetDiff<V,T> fromTransport(TransportSetDiff<T> tsd) { // Set<V> added = new HashSet<V>(); // for (T t : tsd.added) { // added.add(t.fromTransport()); // } // Set<V> removed = new HashSet<V>(); // for (T t : tsd.removed) { // removed.add(t.fromTransport()); // } // return new SetDiff<V,T>(added, removed); // } } // XXX Unnecessary copy-pasting public static SetDiff<RowAnnotation,TransportRowAnnotation> fromTransport(TransportSetDiffForRowAnnotations tsd) { Set<RowAnnotation> added = new HashSet<RowAnnotation>(); for (TransportRowAnnotation t : tsd.added) { added.add(t.fromTransport()); } Set<RowAnnotation> removed = new HashSet<RowAnnotation>(); for (TransportRowAnnotation t : tsd.removed) { removed.add(t.fromTransport()); } return new SetDiff<RowAnnotation,TransportRowAnnotation>(added, removed); } // XXX Unnecessary copy-pasting public static SetDiff<MarkerAnnotation,TransportMarkerAnnotation> fromTransport(TransportSetDiffForMarkerAnnotations tsd) { Set<MarkerAnnotation> added = new HashSet<MarkerAnnotation>(); for (TransportMarkerAnnotation t : tsd.added) { added.add(t.fromTransport()); } Set<MarkerAnnotation> removed = new HashSet<MarkerAnnotation>(); for (TransportMarkerAnnotation t : tsd.removed) { removed.add(t.fromTransport()); } return new SetDiff<MarkerAnnotation,TransportMarkerAnnotation>(added, removed); } public Set<V> applyTo(Set<V> s1) { Set<V> s2 = new HashSet<V>(s1); s2.removeAll(removed); s2.addAll(added); return s2; } // public TransportSetDiff<T> asTransport() { // HashSet<T> ta = new HashSet<T>(); // for (V v : added) { // ta.add(v.asTransport()); // } // HashSet<T> tr = new HashSet<T>(); // for (V v : removed) { // tr.add(v.asTransport()); // } // return new TransportSetDiff<T>(ta, tr); // } // XXX Unnecessary copy-pasting public TransportSetDiffForRowAnnotations asTransportRowAnnotations() { HashSet<TransportRowAnnotation> ta = new HashSet<TransportRowAnnotation>(); for (V v : added) { ta.add((TransportRowAnnotation) v.asTransport()); } HashSet<TransportRowAnnotation> tr = new HashSet<TransportRowAnnotation>(); for (V v : removed) { tr.add((TransportRowAnnotation) v.asTransport()); } return new TransportSetDiffForRowAnnotations(ta, tr); } // XXX Unnecessary copy-pasting public TransportSetDiffForMarkerAnnotations asTransportMarkerAnnotations() { HashSet<TransportMarkerAnnotation> ta = new HashSet<TransportMarkerAnnotation>(); for (V v : added) { ta.add((TransportMarkerAnnotation) v.asTransport()); } HashSet<TransportMarkerAnnotation> tr = new HashSet<TransportMarkerAnnotation>(); for (V v : removed) { tr.add((TransportMarkerAnnotation) v.asTransport()); } return new TransportSetDiffForMarkerAnnotations(ta, tr); } @Override public String toString() { return "added: " + added + ", removed: " + removed; } }
1,856
743
<reponame>althink/hermes package pl.allegro.tech.hermes.consumers.consumer.oauth.client; public class OAuthTokenRequestException extends RuntimeException { public OAuthTokenRequestException(String message, Throwable cause) { super(message, cause); } public OAuthTokenRequestException(String message) { super(message); } }
119
1,858
<reponame>aarogyaswamy/100daysofpython import uplink from requests import Response class FormatError(Exception): pass @uplink.response_handler def raise_for_status(response: Response): response.raise_for_status() return response @uplink.response_handler def response_to_data(response: Response): try: return response.json() except Exception as x: raise FormatError("Invalid format, could not parse JSON. Error: {}, status={}, text={}".format( x, response.status_code, response.text )) from x
197
1,391
<reponame>BezMan/CompieTest<gh_stars>1000+ /* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.android.example.devsummit.archdemo.model; import com.android.example.devsummit.archdemo.App; import com.android.example.devsummit.archdemo.vo.FeedItem; import com.android.example.devsummit.archdemo.vo.Post; import com.android.example.devsummit.archdemo.vo.User; import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; public class FeedModel extends BaseModel { private static final String PREF_NAME = "feed_pref"; private static final String KEY_LAST_FEED_TIMESTAMP = "timestamp"; private static final String KEY_LOCAL_POST_ID = "local_post_id"; private SharedPreferences mPrefs; @Inject UserModel mUserModel; @Inject PostModel mPostModel; @Inject Context mAppContext; public FeedModel(App app, SQLiteDatabase database) { super(app, database); app.getAppComponent().inject(this); } public void saveFeedTimestamp(long timestamp, @Nullable Long userId) { getPref().edit().putLong(createUserTimestampKey(userId), timestamp).commit(); } public List<FeedItem> loadFeed(long since, @Nullable Long userId) { final List<Post> posts; if (userId == null) { posts = mComponent.postModel().loadPostsSince(since); } else { posts = mComponent.postModel().loadPostsOfUser(userId, since); } List<Long> userIds = new ArrayList<>(); for (Post post : posts) { userIds.add(post.getUserId()); } Map<Long, User> users = mComponent.userModel().loadUsersAsMap(userIds); List<FeedItem> result = new ArrayList<>(); for (Post post : posts) { User user = users.get(post.getUserId()); if (user != null) { result.add(new FeedItem(post, user)); } } return result; } public long getLatestTimestamp(@Nullable Long userId) { return getPref().getLong(createUserTimestampKey(userId), 0); } public synchronized long generateIdForNewLocalPost() { long id = getPref().getLong(KEY_LOCAL_POST_ID, Long.MIN_VALUE); getPref().edit().putLong(KEY_LOCAL_POST_ID, id + 1).commit(); return id; } private SharedPreferences getPref() { if (mPrefs == null) { mPrefs = mAppContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); } return mPrefs; } private static String createUserTimestampKey(@Nullable Long userId) { if (userId == null) { return KEY_LAST_FEED_TIMESTAMP; } return KEY_LAST_FEED_TIMESTAMP + "_" + userId; } public void clear() { getPref().edit().clear().commit(); } }
1,372
2,406
<reponame>monroid/openvino // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <ngraph/function.hpp> #include <ngraph/opsets/opset5.hpp> #include <cpp/ie_cnn_network.h> TEST(SmartReshapeTests, SS_Squeeze) { std::shared_ptr<ngraph::Function> f(nullptr); { auto input = std::make_shared<ngraph::opset5::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3}); auto ss = std::make_shared<ngraph::opset5::StridedSlice>( input, ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {1, 1}), std::vector<int64_t>{1, 1}, std::vector<int64_t>{1, 1}); auto squeeze = std::make_shared<ngraph::opset5::Squeeze>(ss, ngraph::opset5::Constant::create(ngraph::element::i64, {1}, {0})); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{squeeze}, ngraph::ParameterVector{input}); } InferenceEngine::CNNNetwork network(f); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({1, 3})); ASSERT_NO_THROW(network.setBatchSize(2)); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({2, 3})); } TEST(SmartReshapeTests, SS_Squeeze_mask_use_negative) { std::shared_ptr<ngraph::Function> f(nullptr); { auto input = std::make_shared<ngraph::opset5::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3}); auto ss = std::make_shared<ngraph::opset5::StridedSlice>( input, ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {1, 1}), std::vector<int64_t>{1, 1}, std::vector<int64_t>{1, 1}, std::vector<int64_t>{0, 1}); auto squeeze = std::make_shared<ngraph::opset5::Squeeze>(ss, ngraph::opset5::Constant::create(ngraph::element::i64, {1}, {0})); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{squeeze}, ngraph::ParameterVector{input}); } InferenceEngine::CNNNetwork network(f); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({1, 3})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({1, 3})); ASSERT_ANY_THROW(network.setBatchSize(2)); } TEST(SmartReshapeTests, SS_Squeeze_negative_stride_negative) { std::shared_ptr<ngraph::Function> f(nullptr); { auto input = std::make_shared<ngraph::opset5::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3}); auto ss = std::make_shared<ngraph::opset5::StridedSlice>( input, ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {-1, -1}), std::vector<int64_t>{1, 1}, std::vector<int64_t>{1, 1}); auto squeeze = std::make_shared<ngraph::opset5::Squeeze>(ss, ngraph::opset5::Constant::create(ngraph::element::i64, {1}, {0})); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{squeeze}, ngraph::ParameterVector{input}); } InferenceEngine::CNNNetwork network(f); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({1, 3})); ASSERT_ANY_THROW(network.setBatchSize(2)); } TEST(SmartReshapeTests, SS_SharedSqueezes) { std::shared_ptr<ngraph::Function> f(nullptr); { auto input = std::make_shared<ngraph::opset5::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3}); auto ss = std::make_shared<ngraph::opset5::StridedSlice>( input, ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {2}, {1, 1}), std::vector<int64_t>{1, 1}, std::vector<int64_t>{1, 1}); auto squeeze_1 = std::make_shared<ngraph::opset5::Squeeze>(ss, ngraph::opset5::Constant::create(ngraph::element::i64, {1}, {0})); auto squeeze_2 = std::make_shared<ngraph::opset5::Squeeze>(ss, ngraph::opset5::Constant::create(ngraph::element::i64, {1}, {0})); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{squeeze_1, squeeze_2}, ngraph::ParameterVector{input}); } InferenceEngine::CNNNetwork network(f); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({1, 3})); ASSERT_NO_THROW(network.setBatchSize(2)); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({2, 3})); } TEST(SmartReshapeTests, SS_SqueezeNegativeAxes) { std::shared_ptr<ngraph::Function> f(nullptr); { auto input = std::make_shared<ngraph::opset5::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 1, 8, 1, 2}); auto ss = std::make_shared<ngraph::opset5::StridedSlice>( input, ngraph::opset5::Constant::create(ngraph::element::i64, {6}, {0, 0, 0, 0, 0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {6}, {0, 0, 0, 0, 0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {6}, {1, 1, 1, 1, 1, 1}), std::vector<int64_t>{1, 1, 1, 1, 1, 1}, std::vector<int64_t>{1, 1, 1, 1, 1, 1}); auto squeeze = std::make_shared<ngraph::opset5::Squeeze>(ss, ngraph::opset5::Constant::create(ngraph::element::i64, {3}, {-2, 0, -4})); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{squeeze}, ngraph::ParameterVector{input}); } InferenceEngine::CNNNetwork network(f); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3, 8, 2})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({1, 3, 1, 8, 1, 2})); ASSERT_NO_THROW(network.setBatchSize(2)); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3, 8, 2})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({2, 3, 1, 8, 1, 2})); } TEST(SmartReshapeTests, Squeeze_SSNegativeAxes) { std::shared_ptr<ngraph::Function> f(nullptr); { auto input = std::make_shared<ngraph::opset5::Parameter>(ngraph::element::f32, ngraph::Shape{1, 3, 1, 8, 1, 2}); auto squeeze = std::make_shared<ngraph::opset5::Squeeze>(input, ngraph::opset5::Constant::create(ngraph::element::i64, {3}, {-2, 0, -4})); auto ss = std::make_shared<ngraph::opset5::StridedSlice>( squeeze, ngraph::opset5::Constant::create(ngraph::element::i64, {3}, {0, 0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {3}, {0, 0, 0}), ngraph::opset5::Constant::create(ngraph::element::i64, {3}, {1, 1, 1}), std::vector<int64_t>{1, 1, 1}, std::vector<int64_t>{1, 1, 1}); f = std::make_shared<ngraph::Function>(ngraph::NodeVector{ss}, ngraph::ParameterVector{input}); } InferenceEngine::CNNNetwork network(f); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3, 8, 2})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({1, 3, 1, 8, 1, 2})); ASSERT_NO_THROW(network.setBatchSize(2)); ASSERT_TRUE(network.getFunction()->get_results()[0]->get_output_partial_shape(0).compatible({3, 8, 2})) << network.getFunction()->get_results()[0]->get_output_partial_shape(0); ASSERT_TRUE(network.getFunction()->get_parameters()[0]->get_partial_shape().compatible({2, 3, 1, 8, 1, 2})); }
4,201
488
<filename>Sources/ParallaxView tvOS.h<gh_stars>100-1000 // // ParallaxView tvOS.h // ParallaxView tvOS // // Created by <NAME> on 06/05/16. // // #import <UIKit/UIKit.h> //! Project version number for ParallaxView. FOUNDATION_EXPORT double ParallaxViewVersionNumber; //! Project version string for ParallaxView. FOUNDATION_EXPORT const unsigned char ParallaxViewVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <ParallaxView_tvOS/PublicHeader.h>
174
1,056
<reponame>arusinha/incubator-netbeans /* * 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.openide.filesystems; import java.util.EventListener; /** Listener for changes in <code>FileObject</code>s. Can be attached to any <code>FileObject</code>. * <P> * When attached to a file it listens for file changes (due to saving from inside NetBeans) and * for deletes and renames. * <P> * When attached to a folder it listens for all actions taken on this folder. * These include any modifications of data files or folders, * and creation of new data files or folders. * * @see FileObject#addFileChangeListener * * @author <NAME>, <NAME> */ public interface FileChangeListener extends EventListener { /** Fired when a new folder is created. This action can only be * listened to in folders containing the created folder up to the root of * filesystem. * * @param fe the event describing context where action has taken place */ public abstract void fileFolderCreated(FileEvent fe); /** Fired when a new file is created. This action can only be * listened in folders containing the created file up to the root of * filesystem. * * @param fe the event describing context where action has taken place */ public abstract void fileDataCreated(FileEvent fe); /** Fired when a file is changed. * @param fe the event describing context where action has taken place */ public abstract void fileChanged(FileEvent fe); /** Fired when a file is deleted. * @param fe the event describing context where action has taken place */ public abstract void fileDeleted(FileEvent fe); /** Fired when a file is renamed. * @param fe the event describing context where action has taken place * and the original name and extension. */ public abstract void fileRenamed(FileRenameEvent fe); /** Fired when a file attribute is changed. * @param fe the event describing context where action has taken place, * the name of attribute and the old and new values. */ public abstract void fileAttributeChanged(FileAttributeEvent fe); }
809
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.java.metrics.hints; import com.sun.source.tree.AssertTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.TreePath; import org.netbeans.api.java.source.support.ErrorAwareTreePathScanner; import java.util.Collection; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import org.netbeans.spi.editor.hints.ErrorDescription; import org.netbeans.spi.java.hints.BooleanOption; import org.netbeans.spi.java.hints.ErrorDescriptionFactory; import org.netbeans.spi.java.hints.Hint; import org.netbeans.spi.java.hints.HintContext; import org.netbeans.spi.java.hints.IntegerOption; import org.netbeans.spi.java.hints.TriggerPattern; import org.netbeans.spi.java.hints.TriggerPatterns; import org.netbeans.spi.java.hints.TriggerTreeKind; import org.netbeans.spi.java.hints.UseOptions; import org.openide.util.NbBundle; import static org.netbeans.modules.java.metrics.hints.Bundle.*; /** * Inspections based on metrics computed for individual methods. * * @author sdedic */ @NbBundle.Messages({ "# {0} - method name", "# {1} - cyclomatic complexity of the method", "TEXT_MethodTooComplex=The method ''{0}'' is too complex; cyclomatic complexity: {1}", "# {0} - method name", "# {1} - maximum depth of statements in method", "TEXT_MethodTooDeepNesting=Method ''{0}'' contains too deep statement structure: {1}", "# {0} - method name", "# {1} - number of lines in method", "TEXT_MethodTooLongLines=Method ''{0}'' is too long: {1} lines", "# {0} - method name", "# {1} - number of lines in method", "TEXT_MethodTooLongStatements=Method ''{0}'' is too long: {1} statements", "# {0} - method name", "# {1} - number of exceptions declared by the method", "TEXT_MethodTooManyExceptions=Method ''{0}'' declares too many exceptions: {1}", "# {0} - method name", "# {1} - number of parameters declared by the method", "TEXT_MethodTooManyParameters=Method ''{0}'' takes too many parameters: {1}", "# {0} - method name", "# {1} - number of return points", "TEXT_MethodMultipleReturns=Method ''{0}'' has multiple return points: {1}", "# {0} - method name", "# {1} - number of negations", "TEXT_MethodMultipleNegations=Method ''{0}'' contains too many negations: {1}", "# {0} - method name", "# {1} - number of loops", "TEXT_MethodMultipleLoops=Method ''{0}'' contains {1} loops", "# {0} - method name", "# {1} - number of dependencies", "TEXT_MethodTooCoupled=Method ''{0}'' is too coupled. References {1} types", "# {0} - cyclomatic complexity of the method", "TEXT_ConstructorTooComplex=Constructor is too complex; cyclomatic complexity: {0}", "# {0} - maximum depth of statements in method", "TEXT_ConstructorTooDeepNesting=Constructor contains too deep statement structure: {0}", "# {0} - number of lines in method", "TEXT_ConstructorTooLongLines=Constructor is too long: {0} lines", "# {0} - number of lines in method", "TEXT_ConstructorTooLongStatements=Constructor is too long: {0} statements", "# {0} - number of exceptions declared by the method", "TEXT_ConstructorTooManyExceptions=Constructor declares too many exceptions: {0}", "# {0} - number of parameters declared by the method", "TEXT_ConstructorTooManyParameters=Constructor takes too many parameters: {0}", "# {0} - number of return points", "TEXT_ConstructorMultipleReturns=Constructor has multiple return points: {0}", "# {0} - number of negations", "TEXT_ConstructorMultipleNegations=Constructor contains too many negations: {0}", "# {0} - number of loops", "TEXT_ConstructorMultipleLoops=Constructor contains {0} loops", "# {0 - number of dependencies", "TEXT_ConstructorTooCoupled=Constructor is too coupled. References {0} types" }) public class MethodMetrics { static final int DEFAULT_COMPLEXITY_LIMIT = 10; static final int DEFAULT_NESTING_LIMIT = 6; static final int DEFAULT_LINES_LIMIT = 60; static final int DEFAULT_EXCEPTIONS_LIMIT = 3; static final int DEFAULT_STATEMENTS_LIMIT = 30; static final int DEFAULT_METHOD_PARAMETERS_LIMIT = 8; static final int DEFAULT_CTOR_PARAMETERS_LIMIT = 12; static final boolean DEFAULT_IGNORE_RETURN_GUARDS = true; static final boolean DEFAULT_IGNORE_EQUALS = true; static final int DEFAULT_RETURN_LIMIT = 2; static final int DEFAULT_NEGATIONS_LIMIT = 3; static final boolean DEFAULT_NEGATIONS_IGNORE_ASSERT = true; static final boolean DEFAULT_NEGATIONS_IGNORE_EQUALS = true; static final boolean DEFAULT_COUPLING_IGNORE_JAVA = true; static final int DEFAULT_LOOPS_LIMIT = 3; static final int DEFAULT_COUPLING_LIMIT = 15; @IntegerOption( displayName = "#OPTNAME_MethodComplexityLimit", tooltip = "#OPTDESC_MethodComplexityLimit", maxValue = 1000, step = 1, defaultValue = DEFAULT_COMPLEXITY_LIMIT ) public static final String OPTION_COMPLEXITY_TRESHOLD = "metrics.method.complexity.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodDepthLimit", tooltip = "#OPTDESC_MethodDepthLimit", maxValue = 100, step = 1, defaultValue = DEFAULT_NESTING_LIMIT ) public static final String OPTION_NESTING_LIMIT = "metrics.method.depth.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodLinesLimit", tooltip = "#OPTDESC_MethodLinesLimit", maxValue = 60, step = 50, defaultValue = DEFAULT_LINES_LIMIT ) public static final String OPTION_LINES_LIMIT = "metrics.method.lines.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodStatementsLimit", tooltip = "#OPTDESC_MethodStatementsLimit", maxValue = 30, step = 5, defaultValue = DEFAULT_LINES_LIMIT ) public static final String OPTION_STATEMENTS_LIMIT = "metrics.method.statements.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodExceptionsLimit", tooltip = "#OPTDESC_MethodExceptionsLimit", maxValue = 50, minValue = 1, step = 1, defaultValue = DEFAULT_EXCEPTIONS_LIMIT ) public static final String OPTION_EXCEPTIONS_LIMIT = "metrics.method.exceptions.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodParametersLimit", tooltip = "#OPTDESC_MethodParametersLimit", maxValue = 100, minValue = 2, step = 1, defaultValue = DEFAULT_METHOD_PARAMETERS_LIMIT ) public static final String OPTION_METHOD_PARAMETERS_LIMIT = "metrics.method.parameters.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_CtorParametersLimit", tooltip = "#OPTDESC_CtorParametersLimit", maxValue = 100, minValue = 2, step = 1, defaultValue = DEFAULT_CTOR_PARAMETERS_LIMIT ) public static final String OPTION_CTOR_PARAMETERS_LIMIT = "metrics.constructor.parameters.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodReturnLimit", tooltip = "#OPTDESC_MethodReturnLimit", maxValue = 100, minValue = 1, step = 1, defaultValue = DEFAULT_RETURN_LIMIT ) public static final String OPTION_RETURN_LIMIT = "metrics.method.return.limit"; // NOI18N @BooleanOption( displayName = "#OPTNAME_MethodIgnoreReturnGuards", tooltip = "#OPTDESC_MethodIgnoreReturnGuards", defaultValue = DEFAULT_IGNORE_RETURN_GUARDS ) public static final String OPTION_RETURN_IGNORE_GUARDS = "metrics.method.returns.ignoreguards"; // NOI18N @BooleanOption( displayName = "#OPTNAME_MethodIgnoreReturnEquals", tooltip = "#OPTDESC_MethodIgnoreReturnEquals", defaultValue = DEFAULT_IGNORE_EQUALS ) public static final String OPTION_RETURN_IGNORE_EQUALS = "metrics.method.returns.ignoreequals"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodNegationsLimit", tooltip = "#OPTDESC_MethodNegationsLimit", maxValue = 100, step = 1, defaultValue = DEFAULT_NEGATIONS_LIMIT ) public static final String OPTION_NEGATIONS_LIMIT = "metrics.method.negations.limit"; // NOI18N @BooleanOption( displayName = "#OPTNAME_MethodNegationsIgnoreEquals", tooltip = "#OPTDESC_MethodNegationsIgnoreEquals", defaultValue = DEFAULT_NEGATIONS_IGNORE_EQUALS ) public static final String OPTION_NEGATIONS_IGNORE_EQUALS = "metrics.method.negations.ignoreequals"; // NOI18N @BooleanOption( displayName = "#OPTNAME_MethodNegationsIgnoreAsserts", tooltip = "#OPTDESC_MethodNegationsIgnoreAsserts", defaultValue = DEFAULT_NEGATIONS_IGNORE_ASSERT ) public static final String OPTION_NEGATIONS_IGNORE_ASSERT = "metrics.method.negations.ignoreassert"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodLoopsLimit", tooltip = "#OPTDESC_MethodLoopsLimit", maxValue = 100, step = 1, defaultValue = DEFAULT_LOOPS_LIMIT ) public static final String OPTION_LOOPS_LIMIT = "metrics.method.loops.limit"; // NOI18N @IntegerOption( displayName = "#OPTNAME_MethodCouplingLimit", tooltip = "#OPTDESC_MethodCouplingLimit", maxValue = 1000, step = 1, defaultValue = DEFAULT_COUPLING_LIMIT ) public static final String OPTION_COUPLING_LIMIT = "metrics.method.coupling.limit"; // NOI18N @BooleanOption( displayName = "#OPTNAME_MethodCouplingIgnoreJava", tooltip = "#OPTDESC_MethodCouplingIgnoreJava", defaultValue = DEFAULT_COUPLING_IGNORE_JAVA ) public static final String OPTION_COUPLING_IGNORE_JAVA = "metrics.method.coupling.nojava"; // NOI18N public static final String OPTION_COUPLING_IGNORE_LIBS = "metrics.method.coupling.nolibraries"; // NOI18N private static boolean methodOrConstructor(HintContext ctx) { Element el = ctx.getInfo().getTrees().getElement(ctx.getPath()); return el.getKind() == ElementKind.CONSTRUCTOR; } @Hint(category = "metrics", displayName = "#DN_MethodTooComplex", description = "#DESC_MethodTooComplex", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @TriggerTreeKind(Tree.Kind.METHOD) @UseOptions(value = { OPTION_COMPLEXITY_TRESHOLD }) public static ErrorDescription methodTooComplex(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; CyclomaticComplexityVisitor v = new CyclomaticComplexityVisitor(); v.scan(ctx.getPath(), v); int complexity = v.getComplexity(); int treshold = ctx.getPreferences().getInt(OPTION_COMPLEXITY_TRESHOLD, DEFAULT_COMPLEXITY_LIMIT); if (complexity <= treshold) { return null; } return ErrorDescriptionFactory.forName(ctx, t, methodOrConstructor(ctx) ? TEXT_ConstructorTooComplex(complexity) : TEXT_MethodTooComplex(method.getName().toString(), complexity) ); } @Hint( category = "metrics", displayName = "#DN_MethodTooDeepNesting", description = "#DESC_MethodTooDeepNesting", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @TriggerTreeKind(Tree.Kind.METHOD) @UseOptions(value = { OPTION_NESTING_LIMIT }) public static ErrorDescription tooDeepNesting(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; DepthVisitor v = new DepthVisitor(); v.scan(ctx.getPath(), null); int depth = v.getDepth(); int treshold = ctx.getPreferences().getInt(OPTION_NESTING_LIMIT, DEFAULT_NESTING_LIMIT); if (depth <= treshold) { return null; } return ErrorDescriptionFactory.forName(ctx, t, methodOrConstructor(ctx) ? TEXT_ConstructorTooDeepNesting(depth) : TEXT_MethodTooDeepNesting(method.getName().toString(), depth) ); } @Hint( category = "metrics", displayName = "#DN_MethodTooLong", description = "#DESC_MethodTooLong", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @TriggerTreeKind(Tree.Kind.METHOD) @UseOptions({ OPTION_LINES_LIMIT, OPTION_STATEMENTS_LIMIT }) public static ErrorDescription tooLong(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; NCLOCVisitor v = new NCLOCVisitor(ctx.getInfo().getSnapshot().getText(), ctx.getInfo().getTrees().getSourcePositions()); v.scan(ctx.getPath(), null); int count = v.getLineCount(); int treshold = ctx.getPreferences().getInt(OPTION_LINES_LIMIT, DEFAULT_LINES_LIMIT); if (count > treshold) { return ErrorDescriptionFactory.forName(ctx, t, methodOrConstructor(ctx) ? TEXT_ConstructorTooLongLines(count) : TEXT_MethodTooLongLines(method.getName().toString(), count) ); } count = v.getStatementCount(); treshold = ctx.getPreferences().getInt(OPTION_STATEMENTS_LIMIT, DEFAULT_STATEMENTS_LIMIT); if (count > treshold) { return ErrorDescriptionFactory.forName(ctx, t, methodOrConstructor(ctx) ? TEXT_ConstructorTooLongStatements(count) : TEXT_MethodTooLongStatements(method.getName().toString(), count) ); } else { return null; } } @Hint( category = "metrics", displayName = "#DN_MethodTooManyExceptions", description = "#DESC_MethodTooManyExceptions", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @UseOptions(value = { OPTION_EXCEPTIONS_LIMIT }) @TriggerPatterns({ @TriggerPattern("$modifiers$ <$typeParams$> $returnType $name($args$) throws $thrown1, $thrown2$ { $body$; }"), @TriggerPattern("$modifiers$ <$typeParams$> $name($args$) throws $thrown1, $thrown2$ { $body$; }"), }) public static ErrorDescription tooManyExceptions(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; Collection<? extends TreePath> exc2 = ctx.getMultiVariables().get("$thrown2$"); // NOI18N int limit = ctx.getPreferences().getInt(OPTION_EXCEPTIONS_LIMIT, DEFAULT_EXCEPTIONS_LIMIT); int count = exc2 == null ? 1 :exc2.size() + 1; if (count <= limit) { return null; } Element el = ctx.getInfo().getTrees().getElement(ctx.getPath()); return ErrorDescriptionFactory.forName(ctx, t, methodOrConstructor(ctx) ? TEXT_ConstructorTooManyExceptions(count) : TEXT_MethodTooManyExceptions(method.getName().toString(), count) ); } @Hint( category = "metrics", displayName = "#DN_MethodTooManyParameters", description = "#DESC_MethodTooManyParameters", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @UseOptions(value = { OPTION_METHOD_PARAMETERS_LIMIT }) @TriggerPattern("$modifiers$ <$typeParams$> $returnType $name($args1, $arg2, $args$) throws $whatever$ { $body$; }") public static ErrorDescription tooManyParameters(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; Collection<? extends TreePath> args = ctx.getMultiVariables().get("$args$"); // NOI18N int limit = ctx.getPreferences().getInt(OPTION_METHOD_PARAMETERS_LIMIT, DEFAULT_METHOD_PARAMETERS_LIMIT); int count = args.size() + 2; if (count <= limit) { return null; } return ErrorDescriptionFactory.forName(ctx, t, methodOrConstructor(ctx) ? TEXT_ConstructorTooManyParameters(count) : TEXT_MethodTooManyParameters(method.getName().toString(), count) ); } @Hint( category = "metrics", displayName = "#DN_CtorTooManyParameters", description = "#DESC_CtorTooManyParameters", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @UseOptions(value = { OPTION_METHOD_PARAMETERS_LIMIT }) @TriggerPattern("$modifiers$ <$typeParams$> $name($args1, $arg2, $args$) throws $whatever$ { $body$; }") public static ErrorDescription tooManyParametersCtor(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; Collection<? extends TreePath> args = ctx.getMultiVariables().get("$args$"); // NOI18N int limit = ctx.getPreferences().getInt(OPTION_METHOD_PARAMETERS_LIMIT, DEFAULT_METHOD_PARAMETERS_LIMIT); int count = args.size() + 2; if (count <= limit) { return null; } return ErrorDescriptionFactory.forName(ctx, t, TEXT_MethodTooManyParameters(method.getName().toString(), count) ); } @Hint( category = "metrics", displayName = "#DN_MethodMultipleReturns", description = "#DESC_MethodMultipleReturns", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @UseOptions({ OPTION_RETURN_LIMIT, OPTION_RETURN_IGNORE_EQUALS, OPTION_RETURN_IGNORE_GUARDS }) @TriggerTreeKind(Tree.Kind.METHOD) public static ErrorDescription multipleReturnPoints(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; boolean ignoreEquals = ctx.getPreferences().getBoolean(OPTION_RETURN_IGNORE_EQUALS, DEFAULT_IGNORE_EQUALS); if (ignoreEquals && method.getName().contentEquals("equals")) { // NOI18N return null; } ReturnCountVisitor v = new ReturnCountVisitor( ctx.getPreferences().getBoolean(OPTION_RETURN_IGNORE_GUARDS, DEFAULT_IGNORE_RETURN_GUARDS) ); v.scan(ctx.getPath(), null); int count = v.getReturnCount(); int limit = ctx.getPreferences().getInt(OPTION_RETURN_LIMIT, DEFAULT_RETURN_LIMIT); if (count > limit) { return ErrorDescriptionFactory.forName(ctx, t, TEXT_MethodMultipleReturns(method.getName().toString(), count) ); } else { return null; } } /** * The visitor will ignore returns, which are the *sole* statement in a if-branch. * Such branches are considered to be guards, which abort further processing. */ private static class ReturnCountVisitor extends ErrorAwareTreePathScanner { /** * Suppressed in local classes */ private boolean suppress; private int returnCount; /** * If true, ignores guard returns */ private final boolean ignoreGuards; public ReturnCountVisitor(boolean ignoreGuards) { this.ignoreGuards = ignoreGuards; } public int getReturnCount() { return returnCount; } @Override public Object visitClass(ClassTree node, Object p) { boolean s = this.suppress; this.suppress = true; Object o = super.visitClass(node, p); this.suppress = s; return o; } @Override public Object visitReturn(ReturnTree node, Object p) { TreePath path = getCurrentPath(); TreePath parentPath = path.getParentPath(); if (suppress) { return super.visitReturn(node, p); } if (ignoreGuards && parentPath != null) { Tree parentTree = parentPath.getLeaf(); TreePath branchPath = path; while (parentTree.getKind() == Tree.Kind.BLOCK) { branchPath = parentPath; parentPath = parentPath.getParentPath(); parentTree = parentPath.getLeaf(); } if (parentTree.getKind() == Tree.Kind.IF) { IfTree ifTree = (IfTree)parentTree; StatementTree trueTree = ifTree.getThenStatement() == branchPath.getLeaf() ? ifTree.getThenStatement() : ifTree.getElseStatement(); if (trueTree == node) { return super.visitReturn(node, p); } if (trueTree.getKind() == Tree.Kind.BLOCK) { BlockTree bt = (BlockTree)trueTree; if (bt.getStatements().size() == 1) { return super.visitReturn(node, p); } } } } returnCount++; return super.visitReturn(node, p); } } @Hint( category = "metrics", displayName = "#DN_MethodMultipleNegations", description = "#DESC_MethodMultipleNegations", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @TriggerTreeKind(Tree.Kind.METHOD) @UseOptions(value = { OPTION_NEGATIONS_IGNORE_ASSERT, OPTION_NEGATIONS_IGNORE_EQUALS, OPTION_NEGATIONS_LIMIT }) public static ErrorDescription multipleNegations(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; boolean ignoreEquals = ctx.getPreferences().getBoolean(OPTION_NEGATIONS_IGNORE_EQUALS, DEFAULT_IGNORE_EQUALS); if (ignoreEquals && method.getName().contentEquals("equals")) { // NOI18N return null; } boolean ignoreAsserts = ctx.getPreferences().getBoolean(OPTION_NEGATIONS_IGNORE_ASSERT, DEFAULT_NEGATIONS_IGNORE_ASSERT); NegationsVisitor v = new NegationsVisitor(ignoreAsserts); v.scan(ctx.getPath(), null); int limit = ctx.getPreferences().getInt(OPTION_NEGATIONS_LIMIT, DEFAULT_NEGATIONS_LIMIT); int count = v.getNegationsCount(); if (count > limit) { return ErrorDescriptionFactory.forName(ctx, t, TEXT_MethodMultipleNegations(method.getName().toString(), count) ); } else { return null; } } /** * Counts number of 'negations' in a Tree. A negation is either unary ! or binary != inequality * operator. */ private static class NegationsVisitor extends ErrorAwareTreePathScanner { private int negationsCount; private final boolean ignoreAsserts; public NegationsVisitor(boolean ignoreAsserts) { this.ignoreAsserts = ignoreAsserts; } public int getNegationsCount() { return negationsCount; } @Override public Object visitUnary(UnaryTree node, Object p) { if (node.getKind() == Tree.Kind.LOGICAL_COMPLEMENT) { negationsCount++; } return super.visitUnary(node, p); } @Override public Object visitBinary(BinaryTree node, Object p) { if (node.getKind() == Tree.Kind.NOT_EQUAL_TO) { negationsCount++; } return super.visitBinary(node, p); } @Override public Object visitAssert(AssertTree node, Object p) { int saveCount = negationsCount; Object o = super.visitAssert(node, p); if (ignoreAsserts) { this.negationsCount = saveCount; } return o; } } /** * Utility scanner class, which counts all kinds of loops in the scanned subtree */ private static class LoopFinder extends ErrorAwareTreePathScanner { private int loopCount; public int getLoopCount() { return loopCount; } @Override public Object visitClass(ClassTree node, Object p) { int save = loopCount; Object o = super.visitClass(node, p); this.loopCount = save; return o; } @Override public Object visitDoWhileLoop(DoWhileLoopTree node, Object p) { loopCount++; return super.visitDoWhileLoop(node, p); } @Override public Object visitWhileLoop(WhileLoopTree node, Object p) { loopCount++; return super.visitWhileLoop(node, p); } @Override public Object visitForLoop(ForLoopTree node, Object p) { loopCount++; return super.visitForLoop(node, p); } @Override public Object visitEnhancedForLoop(EnhancedForLoopTree node, Object p) { loopCount++; return super.visitEnhancedForLoop(node, p); } } @Hint( category = "metrics", displayName = "#DN_MethodMultipleLoops", description = "#DESC_MethodMultipleLoops", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @TriggerTreeKind(Tree.Kind.METHOD) @UseOptions({ OPTION_LOOPS_LIMIT }) public static ErrorDescription multipleLoops(HintContext ctx) { Tree t = ctx.getPath().getLeaf(); MethodTree method = (MethodTree)t; LoopFinder v = new LoopFinder(); v.scan(ctx.getPath(), null); int count = v.getLoopCount(); int limit = ctx.getPreferences().getInt(OPTION_LOOPS_LIMIT, DEFAULT_LOOPS_LIMIT); if (count > limit) { return ErrorDescriptionFactory.forName(ctx, t, TEXT_MethodMultipleLoops(method.getName().toString(), count) ); } else { return null; } } @Hint( category = "metrics", displayName = "#DN_MethodCoupled", description = "#DESC_MethodCoupled", options = { Hint.Options.QUERY, Hint.Options.HEAVY }, enabled = false ) @TriggerTreeKind(Tree.Kind.METHOD) @UseOptions({ OPTION_COUPLING_LIMIT, OPTION_COUPLING_IGNORE_JAVA }) public static ErrorDescription tooManyDependencies(HintContext ctx) { MethodTree m = (MethodTree)ctx.getPath().getLeaf(); boolean ignoreJava = ctx.getPreferences().getBoolean(OPTION_COUPLING_IGNORE_JAVA, DEFAULT_COUPLING_IGNORE_JAVA); TypeElement outermost = ctx.getInfo().getElementUtilities().outermostTypeElement(ctx.getInfo().getTrees().getElement(ctx.getPath())); DependencyCollector col = new DependencyCollector(ctx.getInfo()); col.setIgnoreJavaLibraries(ignoreJava); col.setOutermostClass(outermost); /* left for the case that superclass references should be excluded optionally ExecutableElement el = (ExecutableElement)ctx.getInfo().getTrees().getElement(ctx.getPath()); Element parent = el.getEnclosingElement(); while (parent != null && (parent.getKind() == ElementKind.INTERFACE || parent.getKind() == ElementKind.CLASS || parent.getKind() == ElementKind.ENUM)) { Element p = parent; while (true) { TypeElement tel = (TypeElement)p; col.addIgnoredQName(tel.getQualifiedName()); TypeMirror tm = tel.getSuperclass(); if (tm.getKind() == TypeKind.DECLARED) { p = ctx.getInfo().getTypes().asElement(tm); } else { break; } } parent = parent.getEnclosingElement(); }*/ col.scan(ctx.getPath(), null); int deps = col.getSeenQNames().size(); int limit = ctx.getPreferences().getInt(OPTION_COUPLING_LIMIT, DEFAULT_COUPLING_LIMIT); if (deps > limit) { return ErrorDescriptionFactory.forName(ctx, m, TEXT_MethodTooCoupled(m.getName().toString(), deps)); } else { return null; } } }
12,951
392
<reponame>rcpacheco/ojAlgo<gh_stars>100-1000 /* * Copyright 1997-2021 Optimatika * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.ojalgo.netio; import java.util.List; import org.ojalgo.array.operation.COPY; public class Message { private static String EMPTY = ""; public static String toString(final List<Message> aCollection) { final StringBuilder retVal = new StringBuilder(); if (aCollection.size() >= 1) { retVal.append(aCollection.get(0)); for (int i = 1; i < aCollection.size(); i++) { retVal.append(ASCII.LF); retVal.append(aCollection.get(i)); } } return retVal.toString(); } private final String[] myCommand; public Message(final String aCommand) { super(); myCommand = new String[] { aCommand }; } public Message(final String aCommand, final String anArgument) { super(); myCommand = new String[] { aCommand, anArgument }; } public Message(final String aCommand, final String anArgument, final String aParameter) { super(); myCommand = new String[] { aCommand, anArgument, aParameter }; } public Message(final String[] aCommand) { super(); myCommand = COPY.copyOf(aCommand); } @SuppressWarnings("unused") private Message() { this(EMPTY); } public String getArgument() { final StringBuilder retVal = new StringBuilder(); if (myCommand.length >= 2) { retVal.append(myCommand[1]); for (int i = 2; i < myCommand.length; i++) { retVal.append(ASCII.SP); retVal.append(myCommand[i]); } } return retVal.toString(); } public String getCommand() { return myCommand[0]; } @Override public String toString() { final StringBuilder retVal = new StringBuilder(); retVal.append(myCommand[0]); for (int i = 1; i < myCommand.length; i++) { retVal.append(ASCII.SP); retVal.append(myCommand[i]); } retVal.append(ASCII.SEMICOLON); return retVal.toString(); } }
1,231
5,823
<reponame>onix39/engine // Copyright 2013 The Flutter 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 LIB_TONIC_TYPED_DATA_TYPED_LIST_H_ #define LIB_TONIC_TYPED_DATA_TYPED_LIST_H_ #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/converter/dart_converter.h" namespace tonic { // A simple wrapper around Dart TypedData objects. It uses // Dart_TypedDataAcquireData to obtain a raw pointer to the data, which is // released when this object is destroyed. // // This is designed to be used with DartConverter only. template <Dart_TypedData_Type kTypeName, typename ElemType> class TypedList { public: explicit TypedList(Dart_Handle list); TypedList(TypedList<kTypeName, ElemType>&& other); TypedList(); ~TypedList(); ElemType& at(intptr_t i) { TONIC_CHECK(0 <= i); TONIC_CHECK(i < num_elements_); return data_[i]; } const ElemType& at(intptr_t i) const { TONIC_CHECK(0 <= i); TONIC_CHECK(i < num_elements_); return data_[i]; } ElemType& operator[](intptr_t i) { return at(i); } const ElemType& operator[](intptr_t i) const { return at(i); } const ElemType* data() const { return data_; } intptr_t num_elements() const { return num_elements_; } Dart_Handle dart_handle() const { return dart_handle_; } void Release(); private: ElemType* data_; intptr_t num_elements_; Dart_Handle dart_handle_; }; template <Dart_TypedData_Type kTypeName, typename ElemType> struct DartConverter<TypedList<kTypeName, ElemType>> { static void SetReturnValue(Dart_NativeArguments args, TypedList<kTypeName, ElemType> val); static TypedList<kTypeName, ElemType> FromArguments(Dart_NativeArguments args, int index, Dart_Handle& exception); static Dart_Handle ToDart(const ElemType* buffer, unsigned int length); }; #define TONIC_TYPED_DATA_FOREACH(F) \ F(Int8, int8_t) \ F(Uint8, uint8_t) \ F(Int16, int16_t) \ F(Uint16, uint16_t) \ F(Int32, int32_t) \ F(Uint32, uint32_t) \ F(Int64, int64_t) \ F(Uint64, uint64_t) \ F(Float32, float) \ F(Float64, double) #define TONIC_TYPED_DATA_DECLARE(name, type) \ using name##List = TypedList<Dart_TypedData_k##name, type>; \ extern template class TypedList<Dart_TypedData_k##name, type>; \ extern template struct DartConverter<name##List>; TONIC_TYPED_DATA_FOREACH(TONIC_TYPED_DATA_DECLARE) #undef TONIC_TYPED_DATA_DECLARE } // namespace tonic #endif // LIB_TONIC_TYPED_DATA_TYPED_LIST_H_
1,298
584
<gh_stars>100-1000 """Constants for the resoulution manager.""" from enum import Enum from pathlib import Path from ..const import SUPERVISOR_DATA FILE_CONFIG_RESOLUTION = Path(SUPERVISOR_DATA, "resolution.json") SCHEDULED_HEALTHCHECK = 3600 MINIMUM_FREE_SPACE_THRESHOLD = 1 MINIMUM_FULL_BACKUPS = 2 class ContextType(str, Enum): """Place where somethings was happening.""" ADDON = "addon" CORE = "core" OS = "os" PLUGIN = "plugin" SUPERVISOR = "supervisor" STORE = "store" SYSTEM = "system" class UnsupportedReason(str, Enum): """Reasons for unsupported status.""" APPARMOR = "apparmor" CONTENT_TRUST = "content_trust" DBUS = "dbus" DOCKER_CONFIGURATION = "docker_configuration" DOCKER_VERSION = "docker_version" JOB_CONDITIONS = "job_conditions" LXC = "lxc" NETWORK_MANAGER = "network_manager" OS = "os" OS_AGENT = "os_agent" PRIVILEGED = "privileged" SOFTWARE = "software" SOURCE_MODS = "source_mods" SYSTEMD = "systemd" class UnhealthyReason(str, Enum): """Reasons for unsupported status.""" DOCKER = "docker" SUPERVISOR = "supervisor" SETUP = "setup" PRIVILEGED = "privileged" UNTRUSTED = "untrusted" class IssueType(str, Enum): """Issue type.""" FREE_SPACE = "free_space" DOCKER_RATELIMIT = "docker_ratelimit" CORRUPT_DOCKER = "corrupt_docker" CORRUPT_REPOSITORY = "corrupt_repository" SECURITY = "security" MISSING_IMAGE = "missing_image" UPDATE_FAILED = "update_failed" UPDATE_ROLLBACK = "update_rollback" FATAL_ERROR = "fatal_error" DNS_LOOP = "dns_loop" PWNED = "pwned" TRUST = "trust" class SuggestionType(str, Enum): """Sugestion type.""" CLEAR_FULL_BACKUP = "clear_full_backup" CREATE_FULL_BACKUP = "create_full_backup" EXECUTE_UPDATE = "execute_update" EXECUTE_REPAIR = "execute_repair" EXECUTE_RESET = "execute_reset" EXECUTE_RELOAD = "execute_reload" EXECUTE_REMOVE = "execute_remove" EXECUTE_STOP = "execute_stop" REGISTRY_LOGIN = "registry_login"
892
634
<filename>modules/desktop-awt/desktop-ui-impl/src/main/java/consulo/ui/desktop/internal/image/DesktopIconLibraryManagerImpl.java /* * Copyright 2013-2020 consulo.io * * 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 consulo.ui.desktop.internal.image; import consulo.ui.image.Image; import consulo.ui.impl.image.BaseIconLibraryManager; import consulo.ui.impl.image.BaseIconLibraryImpl; import javax.annotation.Nonnull; /** * @author VISTALL * @since 2020-09-26 */ public class DesktopIconLibraryManagerImpl extends BaseIconLibraryManager { public static final DesktopIconLibraryManagerImpl ourInstance = new DesktopIconLibraryManagerImpl(); @Nonnull @Override protected BaseIconLibraryImpl createLibrary(@Nonnull String id) { return new DesktopIconLibrary(id, this); } @Nonnull @Override public Image forceChangeLibrary(@Nonnull String libraryId, @Nonnull Image image) { if(image instanceof DesktopImage) { return ((DesktopImage<?>)image).copyWithTargetIconLibrary(libraryId, it -> forceChangeLibrary(libraryId, image)); } return image; } }
456
4,879
<filename>iphone/Maps/Core/Location/MWMLocationPredictor.h #import "MWMMyPositionMode.h" #include "platform/location.hpp" using TPredictionBlock = void (^)(CLLocation *); @interface MWMLocationPredictor : NSObject - (instancetype)initWithOnPredictionBlock:(TPredictionBlock)onPredictBlock; - (void)reset:(CLLocation *)info; - (void)setMyPositionMode:(MWMMyPositionMode)mode; @end
136
788
package org.apache.usergrid.persistence.collection.serialization.impl; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.UUID; import org.apache.usergrid.persistence.collection.MvccLogEntry; import org.apache.usergrid.persistence.collection.serialization.MvccLogEntrySerializationStrategy; import org.apache.usergrid.persistence.core.scope.ApplicationScope; import org.apache.usergrid.persistence.model.entity.Id; import com.google.common.base.Preconditions; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; /** * Iterator that will iterate all versions of the entity from max to min */ public class LogEntryIterator implements Iterator<MvccLogEntry> { private final MvccLogEntrySerializationStrategy logEntrySerializationStrategy; private final ApplicationScope scope; private final Id entityId; private final int pageSize; private Iterator<MvccLogEntry> elementItr; private UUID nextStart; private UUID startVersion; /** * @param logEntrySerializationStrategy The serialization strategy to get the log entries * @param scope The scope of the entity * @param entityId The id of the entity * @param pageSize The fetch size to get when querying the serialization strategy */ public LogEntryIterator( final MvccLogEntrySerializationStrategy logEntrySerializationStrategy, final ApplicationScope scope, final Id entityId, final UUID startVersion, final int pageSize ) { Preconditions.checkArgument( pageSize > 0, "pageSize must be > 0" ); this.logEntrySerializationStrategy = logEntrySerializationStrategy; this.scope = scope; this.entityId = entityId; this.pageSize = pageSize; this.startVersion = startVersion; } @Override public boolean hasNext() { if ( elementItr == null || !elementItr.hasNext() && nextStart != null ) { try { advance(); } catch ( ConnectionException e ) { throw new RuntimeException( "Unable to query cassandra", e ); } } return elementItr.hasNext(); } @Override public MvccLogEntry next() { if ( !hasNext() ) { throw new NoSuchElementException( "No more elements exist" ); } return elementItr.next(); } @Override public void remove() { throw new UnsupportedOperationException( "Remove is unsupported" ); } /** * Advance our iterator */ public void advance() throws ConnectionException { final int requestedSize; UUID start; if ( nextStart != null ) { requestedSize = pageSize + 1; start = nextStart; } else { requestedSize = pageSize; start = startVersion; } //loop through even entry that's < this one and remove it List<MvccLogEntry> results = logEntrySerializationStrategy.load( scope, entityId, start, requestedSize ); //we always remove the first version if it's equal since it's returned if ( nextStart != null && results.size() > 0 && results.get( 0 ).getVersion().equals( nextStart ) ) { results.remove( 0 ); } //we have results, set our next start. If we miss our start version (due to deletion) and we request a +1, we want to ensure we set our next, hence the >= if ( results.size() >= pageSize ) { nextStart = results.get( results.size() - 1 ).getVersion(); } //nothing left to do else { nextStart = null; } elementItr = results.iterator(); } }
1,440
2,142
package com.liaoinstan.springview.duheader; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; /** * 仿"毒"App 下拉动画的自定义view,通过不同的拉动系数设置其绘制效果 * {@link #setProgress(float)} 参数范围 0 - 100 * 当参数为0时,显示完整的'毒'字,为100时笔画完全散落,可以超出100 */ public class DuView extends View { private static final float widthDu = 124; private Paint paint = new Paint(); private List<Line> lines = new ArrayList<>(); public DuView(Context context) { this(context, null); } public DuView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public DuView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); } private void init() { paint.setStrokeWidth(3); paint.setAntiAlias(true); //一横 lines.add(new Line(20, 24, 61, 24, 4.5f, 1.7f, 57f)); lines.add(new Line(61, 24, 101, 24, 4.3f, 1, 53.5f)); //二横 lines.add(new Line(20, 38, 61, 38, 4.2f, 1.9f, 49f)); lines.add(new Line(61, 38, 102, 38, 4, 1.5f, 45.5f)); //竖 lines.add(new Line(61, 20, 61, 53, 3.7f, 1.7f, 42f)); //母:一横 lines.add(new Line(19, 52, 61, 52, 3.5f, 1.7f, 38.5f)); lines.add(new Line(61, 52, 104, 52, 3.3f, 1.7f, 35f)); //母:左竖 lines.add(new Line(20, 51, 20, 88, 3.1f, 2, 31.5f)); //母:右竖 lines.add(new Line(103, 51, 103, 88, 3, 2, 28f)); //母:二横 lines.add(new Line(16, 69, 62, 69, 3, 2, 24.5f)); lines.add(new Line(62, 69, 107, 69, 3, 2, 21f)); //母:三横 lines.add(new Line(19, 87, 62, 87, 3, 2, 17.5f)); lines.add(new Line(62, 87, 104, 87, 3, 3, 14f)); //母:中竖 lines.add(new Line(65, 52, 60, 69, 3, 2, 10.5f)); lines.add(new Line(65, 69, 60, 87, 3, 2.5f, 7f)); //勾 lines.add(new Line(102, 87, 97, 102, 3, 3, 3.5f)); lines.add(new Line(52, 102, 98, 102, 3, 3.5f, 0)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int mWidth = (int) widthDu + getPaddingLeft() + getPaddingRight(); int mHeight = (int) widthDu + getPaddingTop() + getPaddingBottom(); if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT && getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) { setMeasuredDimension(mWidth, mHeight); } else if (getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) { setMeasuredDimension(mWidth, heightSize); } else if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) { setMeasuredDimension(widthSize, mHeight); } for (Line line : lines) { line.setOffsetX(getMeasuredWidth() / 2 - widthDu / 2); line.setOffsetY(getMeasuredHeight() / 2 - widthDu / 2); } } /** * 0-100,可以超出 */ public void setProgress(float progress) { for (Line line : lines) { line.setProgress(progress); } postInvalidate(); } //################################## //######### 动画 ########### //################################## int value; Runnable runnable = new Runnable() { @Override public void run() { value++; if (value >= lines.size() + 3) { value = 0; } for (Line line : lines) { line.heightLight = false; } if (value - 1 >= 0 && value - 1 < lines.size()) { lines.get(value - 1).heightLight = true; } if (value - 2 >= 0 && value - 2 < lines.size()) { lines.get(value - 2).heightLight = true; } if (value - 3 >= 0 && value - 3 < lines.size()) { lines.get(value - 3).heightLight = true; } postInvalidate(); postDelayed(runnable, 70); } }; public void startAnim() { post(runnable); } public void stopAnim() { removeCallbacks(runnable); } public void resetAnim() { removeCallbacks(runnable); value = 0; for (Line line : lines) { line.heightLight = false; } postInvalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (Line line : lines) { line.drawLine(canvas); } } private class Line { float x1, y1, x2, y2; float offsetX, offsetY; float degree; float translateX; float zoom = 1; float zoomSize = 1; float degK; float transK; float delay; static final float WIDTH = 3; boolean heightLight; Line(float x1, float y1, float x2, float y2) { this(x1, y1, x2, y2, 0, 0, 0); } Line(float x1, float y1, float x2, float y2, float degK, float transK, float delay) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.degK = degK; this.transK = transK; this.delay = delay; } void setOffsetX(float offsetX) { this.offsetX = offsetX; } void setOffsetY(float offsetY) { this.offsetY = offsetY; } void setProgress(float progress) { float dProgress = progress - delay > 0 ? progress - delay : 0; degree = dProgress * degK; translateX = dProgress * transK; zoom = 1 - dProgress / 100; zoomSize = 1 - dProgress / (100 - delay); } float[] center() { float cx = (getX1() + getX2()) / 2; float cy = (getY1() + getY2()) / 2; return new float[]{cx, cy}; } Line rotate(float degree) { float[] center = center(); float cx = center[0]; float cy = center[1]; float dx = getX2() - cx; float dy = getY2() - cy; float k = (float) Math.toRadians((double) degree); float dtx = (float) (Math.cos(k) * dx + Math.sin(k) * dy); float dty = (float) (Math.cos(k) * dy - Math.sin(k) * dx); float x1 = cx + dtx; float y1 = cy + dty; float x2 = 2 * cx - x1; float y2 = 2 * cy - y1; return new Line(x1, y1, x2, y2); } Line zoom(float zoom) { float[] center = center(); float cx = center[0]; float cy = center[1]; float x1 = (1 - zoom) * cx + zoom * getX1(); float y1 = (1 - zoom) * cy + zoom * getY1(); float x2 = 2 * cx - x1; float y2 = 2 * cy - y1; return new Line(x1, y1, x2, y2); } Line translateX(float tansX) { return new Line(getX1() + tansX, getY1(), getX2() + tansX, getY2()); } void drawLine(Canvas canvas) { Line drawLine = this.rotate(degree).translateX(translateX).zoom(zoom); if (zoomSize == 0) { paint.setAlpha(0); paint.setStrokeWidth(0.01f); } else { paint.setAlpha(1); paint.setStrokeWidth(WIDTH * zoomSize); } paint.setColor(Color.parseColor(heightLight ? "#aa000000" : "#55000000")); canvas.drawLine(drawLine.getX1(), drawLine.getY1(), drawLine.getX2(), drawLine.getY2(), paint); } //get & set float getX1() { return x1 + offsetX; } float getY1() { return y1 + offsetY; } float getX2() { return x2 + offsetX; } float getY2() { return y2 + offsetY; } } }
4,423
9,701
import abc import logging import re from typing import Text, List, Dict, Any, Optional from rasa.engine.graph import ExecutionContext, GraphComponent from rasa.engine.storage.resource import Resource from rasa.engine.storage.storage import ModelStorage from rasa.shared.nlu.training_data.training_data import TrainingData from rasa.shared.nlu.training_data.message import Message from rasa.nlu.constants import TOKENS_NAMES, MESSAGE_ATTRIBUTES from rasa.shared.nlu.constants import ( INTENT, INTENT_RESPONSE_KEY, RESPONSE_IDENTIFIER_DELIMITER, ACTION_NAME, ) import rasa.shared.utils.io logger = logging.getLogger(__name__) class Token: """Used by `Tokenizers` which split a single message into multiple `Token`s.""" def __init__( self, text: Text, start: int, end: Optional[int] = None, data: Optional[Dict[Text, Any]] = None, lemma: Optional[Text] = None, ) -> None: """Create a `Token`. Args: text: The token text. start: The start index of the token within the entire message. end: The end index of the token within the entire message. data: Additional token data. lemma: An optional lemmatized version of the token text. """ self.text = text self.start = start self.end = end if end else start + len(text) self.data = data if data else {} self.lemma = lemma or text def set(self, prop: Text, info: Any) -> None: """Set property value.""" self.data[prop] = info def get(self, prop: Text, default: Optional[Any] = None) -> Any: """Returns token value.""" return self.data.get(prop, default) def __eq__(self, other: Any) -> bool: if not isinstance(other, Token): return NotImplemented return (self.start, self.end, self.text, self.lemma) == ( other.start, other.end, other.text, other.lemma, ) def __lt__(self, other: Any) -> bool: if not isinstance(other, Token): return NotImplemented return (self.start, self.end, self.text, self.lemma) < ( other.start, other.end, other.text, other.lemma, ) def __repr__(self) -> Text: return f"<Token object value='{self.text}' start={self.start} end={self.end} \ at {hex(id(self))}>" def fingerprint(self) -> Text: """Returns a stable hash for this Token.""" return rasa.shared.utils.io.deep_container_fingerprint( [self.text, self.start, self.end, self.lemma, self.data] ) class Tokenizer(GraphComponent, abc.ABC): """Base class for tokenizers.""" def __init__(self, config: Dict[Text, Any]) -> None: """Construct a new tokenizer.""" self._config = config # flag to check whether to split intents self.intent_tokenization_flag = config["intent_tokenization_flag"] # split symbol for intents self.intent_split_symbol = config["intent_split_symbol"] # token pattern to further split tokens token_pattern = config.get("token_pattern") self.token_pattern_regex = None if token_pattern: self.token_pattern_regex = re.compile(token_pattern) @classmethod def create( cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, ) -> GraphComponent: """Creates a new component (see parent class for full docstring).""" return cls(config) @abc.abstractmethod def tokenize(self, message: Message, attribute: Text) -> List[Token]: """Tokenizes the text of the provided attribute of the incoming message.""" ... def process_training_data(self, training_data: TrainingData) -> TrainingData: """Tokenize all training data.""" for example in training_data.training_examples: for attribute in MESSAGE_ATTRIBUTES: if ( example.get(attribute) is not None and not example.get(attribute) == "" ): if attribute in [INTENT, ACTION_NAME, INTENT_RESPONSE_KEY]: tokens = self._split_name(example, attribute) else: tokens = self.tokenize(example, attribute) example.set(TOKENS_NAMES[attribute], tokens) return training_data def process(self, messages: List[Message]) -> List[Message]: """Tokenize the incoming messages.""" for message in messages: for attribute in MESSAGE_ATTRIBUTES: if isinstance(message.get(attribute), str): if attribute in [ INTENT, ACTION_NAME, RESPONSE_IDENTIFIER_DELIMITER, ]: tokens = self._split_name(message, attribute) else: tokens = self.tokenize(message, attribute) message.set(TOKENS_NAMES[attribute], tokens) return messages def _tokenize_on_split_symbol(self, text: Text) -> List[Text]: words = ( text.split(self.intent_split_symbol) if self.intent_tokenization_flag else [text] ) return words def _split_name(self, message: Message, attribute: Text = INTENT) -> List[Token]: text = message.get(attribute) # for INTENT_RESPONSE_KEY attribute, # first split by RESPONSE_IDENTIFIER_DELIMITER if attribute == INTENT_RESPONSE_KEY: intent, response_key = text.split(RESPONSE_IDENTIFIER_DELIMITER) words = self._tokenize_on_split_symbol( intent ) + self._tokenize_on_split_symbol(response_key) else: words = self._tokenize_on_split_symbol(text) return self._convert_words_to_tokens(words, text) def _apply_token_pattern(self, tokens: List[Token]) -> List[Token]: """Apply the token pattern to the given tokens. Args: tokens: list of tokens to split Returns: List of tokens. """ if not self.token_pattern_regex: return tokens final_tokens = [] for token in tokens: new_tokens = self.token_pattern_regex.findall(token.text) new_tokens = [t for t in new_tokens if t] if not new_tokens: final_tokens.append(token) running_offset = 0 for new_token in new_tokens: word_offset = token.text.index(new_token, running_offset) word_len = len(new_token) running_offset = word_offset + word_len final_tokens.append( Token( new_token, token.start + word_offset, data=token.data, lemma=token.lemma, ) ) return final_tokens @staticmethod def _convert_words_to_tokens(words: List[Text], text: Text) -> List[Token]: running_offset = 0 tokens = [] for word in words: word_offset = text.index(word, running_offset) word_len = len(word) running_offset = word_offset + word_len tokens.append(Token(word, word_offset)) return tokens
3,572
4,526
<reponame>EricWang1hitsz/osrm-backend<filename>include/guidance/turn_discovery.hpp<gh_stars>1000+ #ifndef OSRM_GUIDANCE_TURN_DISCOVERY_HPP_ #define OSRM_GUIDANCE_TURN_DISCOVERY_HPP_ #include "extractor/node_restriction_map.hpp" #include "guidance/intersection.hpp" #include "guidance/turn_lane_data.hpp" #include "util/typedefs.hpp" #include <unordered_set> namespace osrm { namespace util { struct Coordinate; } namespace extractor { class CompressedEdgeContainer; } namespace guidance { namespace lanes { // OSRM processes edges by looking at a via_edge, coming into an intersection. For turn lanes, we // might require to actually look back a turn. We do so in the hope that the turn lanes match up at // the previous intersection for all incoming lanes. bool findPreviousIntersection( const NodeID node, const EdgeID via_edge, const Intersection &intersection, const util::NodeBasedDynamicGraph &node_based_graph, // query edge data const extractor::EdgeBasedNodeDataContainer &node_data_container, const std::vector<util::Coordinate> &node_coordinates, const extractor::CompressedEdgeContainer &compressed_geometries, const extractor::RestrictionMap &node_restriction_map, const std::unordered_set<NodeID> &barrier_nodes, const extractor::TurnLanesIndexedArray &turn_lanes_data, // output parameters, will be in an arbitrary state on failure NodeID &result_node, EdgeID &result_via_edge, extractor::intersection::IntersectionView &result_intersection); } // namespace lanes } // namespace guidance } // namespace osrm #endif /*OSRM_GUIDANCE_TURN_DISCOVERY_HPP_*/
553
691
/*============================================================================= Copyright (c) 2011-2019 <NAME> https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_MEMORY_GET_POINTER_HPP #define SPROUT_MEMORY_GET_POINTER_HPP #include <memory> #include <sprout/config.hpp> namespace sprout { // // get_pointer // template<typename T> inline SPROUT_CONSTEXPR T* get_pointer(T* p) SPROUT_NOEXCEPT { return p; } #if !defined(SPROUT_NO_AUTO_PTR) template<typename T> inline SPROUT_NON_CONSTEXPR T* get_pointer(std::auto_ptr<T> const& p) SPROUT_NOEXCEPT { return p.get(); } #endif #if !defined(SPROUT_NO_CXX11_SMART_PTR) template<typename T> inline SPROUT_NON_CONSTEXPR T* get_pointer(std::unique_ptr<T> const& p) SPROUT_NOEXCEPT { return p.get(); } template<typename T> inline SPROUT_NON_CONSTEXPR T* get_pointer(std::shared_ptr<T> const& p) SPROUT_NOEXCEPT { return p.get(); } #endif } // namespace sprout #endif // #ifndef SPROUT_MEMORY_GET_POINTER_HPP
521
1,403
/* * CsCommandQueue.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by <NAME>) * See "LICENSE.txt" for license information. */ #include "CsCommandQueue.h" namespace SharpLLGL { CommandQueue::CommandQueue(LLGL::CommandQueue* native) : native_ { native } { } LLGL::CommandQueue* CommandQueue::Native::get() { return native_; } /* ----- Command Buffers ----- */ void CommandQueue::Submit(CommandBuffer^ commandBuffer) { native_->Submit(*commandBuffer->Native::get()); } /* ----- Fences ----- */ void CommandQueue::Submit(Fence^ fence) { native_->Submit(*fence->Native::get()); } bool CommandQueue::WaitFence(Fence^ fence, UInt64 timeout) { return native_->WaitFence(*fence->Native::get(), static_cast<std::uint64_t>(timeout)); } void CommandQueue::WaitIdle() { native_->WaitIdle(); } } // /namespace SharpLLGL // ================================================================================
313
1,185
<filename>src/main/java/com/github/lianjiatech/retrofit/spring/boot/core/AutoConfiguredRetrofitScannerRegistrar.java package com.github.lianjiatech.retrofit.spring.boot.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.AnnotationMetadata; import java.util.List; /** * This will just scan the same base package as Spring Boot does. If you want more power, you can explicitly use * {@link com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitScan} but this will get typed mappers working correctly, out-of-the-box, * similar to using Spring Data JPA repositories. * * @author 陈添明 */ public class AutoConfiguredRetrofitScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware { private static final Logger logger = LoggerFactory.getLogger(AutoConfiguredRetrofitScannerRegistrar.class); private BeanFactory beanFactory; private ResourceLoader resourceLoader; private ClassLoader classLoader; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (!AutoConfigurationPackages.has(this.beanFactory)) { logger.debug("Could not determine auto-configuration package, automatic retrofit scanning disabled."); return; } logger.debug("Searching for retrofits annotated with @RetrofitClient"); List<String> packages = AutoConfigurationPackages.get(this.beanFactory); if (logger.isDebugEnabled()) { packages.forEach(pkg -> logger.debug("Using auto-configuration base package '{}'", pkg)); } // Scan the @RetrofitClient annotated interface under the specified path and register it to the BeanDefinitionRegistry ClassPathRetrofitClientScanner scanner = new ClassPathRetrofitClientScanner(registry, classLoader); if (resourceLoader != null) { scanner.setResourceLoader(resourceLoader); } String[] packageArr = packages.toArray(new String[0]); scanner.registerFilters(); // Scan and register to BeanDefinition scanner.doScan(packageArr); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } }
1,028
348
{"nom":"<NAME>","circ":"2ème circonscription","dpt":"Orne","inscrits":65,"abs":31,"votants":34,"blancs":2,"nuls":0,"exp":32,"res":[{"nuance":"REM","nom":"<NAME>","voix":16},{"nuance":"LR","nom":"<NAME>","voix":16}]}
88