max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
32,544
<reponame>DBatOWL/tutorials package com.baeldung.spring.data.reactive.redis.model; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; @Data @ToString @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode public class Employee implements Serializable { private static final long serialVersionUID = 1603714798906422731L; private String id; private String name; private String department; }
180
1,204
<gh_stars>1000+ /* * Copyright 2015 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.impl.bag.sorted.mutable; import java.util.Comparator; import java.util.concurrent.ExecutorService; import com.gs.collections.api.LazyIterable; import com.gs.collections.api.annotation.Beta; import com.gs.collections.api.bag.sorted.ImmutableSortedBag; import com.gs.collections.api.bag.sorted.MutableSortedBag; import com.gs.collections.api.bag.sorted.ParallelSortedBag; import com.gs.collections.api.block.function.Function; import com.gs.collections.api.block.function.Function2; import com.gs.collections.api.block.function.primitive.BooleanFunction; import com.gs.collections.api.block.function.primitive.ByteFunction; import com.gs.collections.api.block.function.primitive.CharFunction; import com.gs.collections.api.block.function.primitive.DoubleFunction; import com.gs.collections.api.block.function.primitive.FloatFunction; import com.gs.collections.api.block.function.primitive.IntFunction; import com.gs.collections.api.block.function.primitive.LongFunction; import com.gs.collections.api.block.function.primitive.ShortFunction; import com.gs.collections.api.block.predicate.Predicate; import com.gs.collections.api.block.predicate.Predicate2; import com.gs.collections.api.block.procedure.Procedure; import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure; import com.gs.collections.api.list.MutableList; import com.gs.collections.api.list.primitive.MutableBooleanList; import com.gs.collections.api.list.primitive.MutableByteList; import com.gs.collections.api.list.primitive.MutableCharList; import com.gs.collections.api.list.primitive.MutableDoubleList; import com.gs.collections.api.list.primitive.MutableFloatList; import com.gs.collections.api.list.primitive.MutableIntList; import com.gs.collections.api.list.primitive.MutableLongList; import com.gs.collections.api.list.primitive.MutableShortList; import com.gs.collections.api.map.sorted.MutableSortedMap; import com.gs.collections.api.partition.bag.sorted.PartitionMutableSortedBag; import com.gs.collections.api.tuple.Pair; import com.gs.collections.impl.bag.mutable.AbstractMutableBagIterable; import com.gs.collections.impl.factory.SortedBags; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.list.mutable.primitive.BooleanArrayList; import com.gs.collections.impl.list.mutable.primitive.ByteArrayList; import com.gs.collections.impl.list.mutable.primitive.CharArrayList; import com.gs.collections.impl.list.mutable.primitive.DoubleArrayList; import com.gs.collections.impl.list.mutable.primitive.FloatArrayList; import com.gs.collections.impl.list.mutable.primitive.IntArrayList; import com.gs.collections.impl.list.mutable.primitive.LongArrayList; import com.gs.collections.impl.list.mutable.primitive.ShortArrayList; import com.gs.collections.impl.map.sorted.mutable.TreeSortedMap; import com.gs.collections.impl.partition.bag.sorted.PartitionTreeBag; import com.gs.collections.impl.utility.internal.IterableIterate; public abstract class AbstractMutableSortedBag<T> extends AbstractMutableBagIterable<T> implements MutableSortedBag<T> { @SuppressWarnings("AbstractMethodOverridesAbstractMethod") public abstract MutableSortedBag<T> clone(); public ImmutableSortedBag<T> toImmutable() { return SortedBags.immutable.ofSortedBag(this); } public UnmodifiableSortedBag<T> asUnmodifiable() { return UnmodifiableSortedBag.of(this); } public MutableSortedBag<T> asSynchronized() { return SynchronizedSortedBag.of(this); } public MutableSortedBag<T> tap(Procedure<? super T> procedure) { this.forEach(procedure); return this; } public MutableSortedMap<T, Integer> toMapOfItemToCount() { final MutableSortedMap<T, Integer> map = TreeSortedMap.newMap(this.comparator()); this.forEachWithOccurrences(new ObjectIntProcedure<T>() { public void value(T item, int count) { map.put(item, count); } }); return map; } public <S> MutableSortedBag<S> selectInstancesOf(final Class<S> clazz) { Comparator<? super S> comparator = (Comparator<? super S>) this.comparator(); final MutableSortedBag<S> result = TreeBag.newBag(comparator); this.forEachWithOccurrences(new ObjectIntProcedure<T>() { public void value(T each, int occurrences) { if (clazz.isInstance(each)) { result.addOccurrences(clazz.cast(each), occurrences); } } }); return result; } public MutableSortedBag<T> takeWhile(Predicate<? super T> predicate) { MutableSortedBag<T> result = TreeBag.newBag(this.comparator()); return IterableIterate.takeWhile(this, predicate, result); } public MutableSortedBag<T> dropWhile(Predicate<? super T> predicate) { MutableSortedBag<T> result = TreeBag.newBag(this.comparator()); return IterableIterate.dropWhile(this, predicate, result); } public MutableSortedBag<T> select(Predicate<? super T> predicate) { return this.select(predicate, TreeBag.newBag(this.comparator())); } public <P> MutableSortedBag<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.selectWith(predicate, parameter, TreeBag.newBag(this.comparator())); } public MutableSortedBag<T> reject(Predicate<? super T> predicate) { return this.reject(predicate, TreeBag.newBag(this.comparator())); } public <P> MutableSortedBag<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter) { return this.rejectWith(predicate, parameter, TreeBag.newBag(this.comparator())); } public PartitionMutableSortedBag<T> partition(final Predicate<? super T> predicate) { final PartitionMutableSortedBag<T> result = new PartitionTreeBag<T>(this.comparator()); this.forEachWithOccurrences(new ObjectIntProcedure<T>() { public void value(T each, int index) { MutableSortedBag<T> bucket = predicate.accept(each) ? result.getSelected() : result.getRejected(); bucket.addOccurrences(each, index); } }); return result; } public <P> PartitionMutableSortedBag<T> partitionWith(final Predicate2<? super T, ? super P> predicate, final P parameter) { final PartitionMutableSortedBag<T> result = new PartitionTreeBag<T>(this.comparator()); this.forEachWithOccurrences(new ObjectIntProcedure<T>() { public void value(T each, int index) { MutableSortedBag<T> bucket = predicate.accept(each, parameter) ? result.getSelected() : result.getRejected(); bucket.addOccurrences(each, index); } }); return result; } public PartitionMutableSortedBag<T> partitionWhile(Predicate<? super T> predicate) { PartitionTreeBag<T> result = new PartitionTreeBag<T>(this.comparator()); return IterableIterate.partitionWhile(this, predicate, result); } public <V> MutableList<V> collect(Function<? super T, ? extends V> function) { return this.collect(function, FastList.<V>newList(this.size())); } public <P, V> MutableList<V> collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter) { return this.collectWith(function, parameter, FastList.<V>newList()); } public <V> MutableList<V> collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function) { return this.collectIf(predicate, function, FastList.<V>newList()); } public <V> MutableList<V> flatCollect(Function<? super T, ? extends Iterable<V>> function) { return this.flatCollect(function, FastList.<V>newList()); } public MutableBooleanList collectBoolean(BooleanFunction<? super T> booleanFunction) { return this.collectBoolean(booleanFunction, new BooleanArrayList()); } public MutableByteList collectByte(ByteFunction<? super T> byteFunction) { return this.collectByte(byteFunction, new ByteArrayList()); } public MutableCharList collectChar(CharFunction<? super T> charFunction) { return this.collectChar(charFunction, new CharArrayList()); } public MutableDoubleList collectDouble(DoubleFunction<? super T> doubleFunction) { return this.collectDouble(doubleFunction, new DoubleArrayList()); } public MutableFloatList collectFloat(FloatFunction<? super T> floatFunction) { return this.collectFloat(floatFunction, new FloatArrayList()); } public MutableIntList collectInt(IntFunction<? super T> intFunction) { return this.collectInt(intFunction, new IntArrayList()); } public MutableLongList collectLong(LongFunction<? super T> longFunction) { return this.collectLong(longFunction, new LongArrayList()); } public MutableShortList collectShort(ShortFunction<? super T> shortFunction) { return this.collectShort(shortFunction, new ShortArrayList()); } public <S> MutableList<Pair<T, S>> zip(Iterable<S> that) { return this.zip(that, FastList.<Pair<T, S>>newList()); } public MutableSortedBag<T> toReversed() { throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".toReversed() not implemented yet"); } public void reverseForEach(Procedure<? super T> procedure) { throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".reverseForEach() not implemented yet"); } public LazyIterable<T> asReversed() { throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".asReversed() not implemented yet"); } public int detectLastIndex(Predicate<? super T> predicate) { throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".detectLastIndex() not implemented yet"); } @Beta public ParallelSortedBag<T> asParallel(ExecutorService executorService, int batchSize) { if (executorService == null) { throw new NullPointerException(); } if (batchSize < 1) { throw new IllegalArgumentException(); } throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".asParallel() not implemented yet"); } }
4,589
1,767
<reponame>aNNiMON/Lightweight-Stream-API package com.annimon.stream.streamtests; import com.annimon.stream.Functions; import com.annimon.stream.Stream; import com.annimon.stream.function.Predicate; import com.annimon.stream.function.UnaryOperator; import com.annimon.stream.test.hamcrest.StreamMatcher; import java.util.Iterator; import java.util.NoSuchElementException; import org.junit.Test; import org.junit.function.ThrowingRunnable; import static com.annimon.stream.test.hamcrest.StreamMatcher.assertElements; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; public final class TakeWhileTest { @Test public void testTakeWhile() { Stream.of(2, 4, 6, 7, 8, 10, 11) .takeWhile(Functions.remainder(2)) .custom(assertElements(contains( 2, 4, 6 ))); } @Test public void testTakeWhileNonFirstMatch() { Stream.of(2, 4, 6, 7, 8, 10, 11) .takeWhile(Functions.remainder(3)) .custom(StreamMatcher.<Integer>assertIsEmpty()); } @Test public void testTakeWhileAllMatch() { Stream.of(2, 4, 6, 7, 8, 10, 11) .takeWhile(Functions.remainder(1)) .custom(assertElements(contains( 2, 4, 6, 7, 8, 10, 11 ))); } @Test public void testTakeWhileIterator() { Iterator<? extends Integer> it = Stream.of(2, 4, 5, 6) .takeWhile(Functions.remainder(2)) .iterator(); assertThat(it.next(), is(2)); assertThat(it.next(), is(4)); assertThat(it.hasNext(), is(false)); assertThat(it.hasNext(), is(false)); } @Test public void testTakeWhileIterator2() { Iterator<? extends Integer> it = Stream.of(1) .takeWhile(Functions.remainder(2)) .iterator(); assertThat(it.hasNext(), is(false)); assertThat(it.hasNext(), is(false)); } @Test public void testTakeWhileIterator3() { final Iterator<? extends Integer> it = Stream.of(2) .takeWhile(Functions.remainder(2)) .iterator(); assertThat(it.hasNext(), is(true)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.hasNext(), is(false)); assertThrows(NoSuchElementException.class, new ThrowingRunnable() { @Override public void run() throws Throwable { it.next(); } }); } @Test public void testTakeWhileAndMapIssue193() { boolean match = Stream.of(42, 44, 46, null, 48) .takeWhile(new Predicate<Integer>() { @Override public boolean test(Integer value) { return value != null; } }) .map(new UnaryOperator<Integer>() { @Override public Integer apply(Integer integer) { return integer + 2; } }) .anyMatch(Functions.remainder(10)); assertFalse(match); } }
1,651
1,327
/******************************************************************************* * Copyright 2020-2021 Arm Ltd. and 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. *******************************************************************************/ #ifndef CPU_AARCH64_ACL_CONVOLUTION_UTILS_HPP #define CPU_AARCH64_ACL_CONVOLUTION_UTILS_HPP #include "cpu/cpu_convolution_pd.hpp" #include "cpu/aarch64/acl_utils.hpp" namespace dnnl { namespace impl { namespace cpu { namespace aarch64 { template <typename NEConv> struct acl_obj_t { NEConv conv; arm_compute::NEArithmeticAddition add; arm_compute::NEActivationLayer act; arm_compute::Tensor src_tensor; arm_compute::Tensor wei_tensor; arm_compute::Tensor bia_tensor; arm_compute::Tensor dst_tensor; arm_compute::Tensor dst_acc_tensor; }; struct acl_conv_conf_t { bool with_bias; bool is_int8; bool sum_with_eltwise; bool fast_math; arm_compute::TensorInfo src_info; arm_compute::TensorInfo wei_info; arm_compute::TensorInfo bia_info; arm_compute::TensorInfo dst_info; arm_compute::PadStrideInfo padstride_info; arm_compute::Size2D dilation_info; arm_compute::WeightsInfo weights_info; arm_compute::ActivationLayerInfo act_info; }; namespace acl_convolution_utils { status_t init_conf_gemm(acl_conv_conf_t &acp, memory_desc_t &src_md, memory_desc_t &weights_md, memory_desc_t &dst_md, memory_desc_t &bias_md, const convolution_desc_t &cd, const primitive_attr_t &attr); status_t init_conf_indirect_gemm(acl_conv_conf_t &acp, memory_desc_t &src_md, memory_desc_t &weights_md, memory_desc_t &dst_md, memory_desc_t &bias_md, const convolution_desc_t &cd, const primitive_attr_t &attr); status_t init_conf_wino(acl_conv_conf_t &acp, memory_desc_t &src_md, memory_desc_t &weights_md, memory_desc_t &dst_md, memory_desc_t &bias_md, const convolution_desc_t &cd, const primitive_attr_t &attr); } // namespace acl_convolution_utils template <typename conv_obj_t, typename conv_pd_t, typename src_data_t, typename wei_data_t = src_data_t, typename dst_data_t = src_data_t, typename bia_data_t = src_data_t> status_t execute_forward_conv_acl( const exec_ctx_t &ctx, conv_obj_t &acl_conv_obj, const conv_pd_t *pd) { bool with_bias = pd->acp_.with_bias; bool sum_with_eltwise = pd->acp_.sum_with_eltwise; auto src_base = CTX_IN_MEM(const src_data_t *, DNNL_ARG_SRC); auto wei_base = CTX_IN_MEM(const wei_data_t *, DNNL_ARG_WEIGHTS); auto dst_base = CTX_OUT_MEM(dst_data_t *, DNNL_ARG_DST); // import_memory() and free() methods do not allocate/free any additional // memory, only acquire/release pointers. acl_conv_obj.src_tensor.allocator()->import_memory( const_cast<src_data_t *>(src_base)); acl_conv_obj.wei_tensor.allocator()->import_memory( const_cast<wei_data_t *>(wei_base)); acl_conv_obj.dst_tensor.allocator()->import_memory(dst_base); if (with_bias) { auto bia_base = CTX_IN_MEM(const bia_data_t *, DNNL_ARG_BIAS); acl_conv_obj.bia_tensor.allocator()->import_memory( const_cast<bia_data_t *>(bia_base)); } acl_conv_obj.conv.run(); if (sum_with_eltwise) { acl_conv_obj.add.run(); acl_conv_obj.act.run(); } acl_conv_obj.src_tensor.allocator()->free(); acl_conv_obj.wei_tensor.allocator()->free(); acl_conv_obj.dst_tensor.allocator()->free(); if (with_bias) { acl_conv_obj.bia_tensor.allocator()->free(); } return status::success; } } // namespace aarch64 } // namespace cpu } // namespace impl } // namespace dnnl #endif // CPU_AARCH64_ACL_CONVOLUTION_UTILS_HPP
1,762
5,450
<reponame>infosia/VRM.h { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "glTFid.schema.json", "title": "glTF Id", "type": "integer", "minimum": 0 }
92
679
<filename>main/filter/source/xsltfilter/uof2merge.cxx /************************************************************** * * 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. * **************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove //This file is about the conversion of the UOF v2.0 and ODF document format #include "precompiled_filter.hxx" #include "uof2merge.hxx" #include <cppuhelper/implbase1.hxx> #include <rtl/ustrbuf.hxx> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp> #include <com/sun/star/io/XInputStream.hpp> #include <com/sun/star/io/XOutputStream.hpp> #include <com/sun/star/xml/sax/XParser.hpp> #include <com/sun/star/io/XActiveDataSource.hpp> #include <com/sun/star/xml/sax/InputSource.hpp> #include <com/sun/star/xml/sax/XAttributeList.hpp> #include "XMLBase64Codec.hxx" namespace XSLT{ const ::rtl::OUString UOF2ROOTELEM = ::rtl::OUString::createFromAscii("uof:UOF_0000"); const ::rtl::OUString UOF2OBJDATAXML = ::rtl::OUString::createFromAscii("objectdata.xml"); const ::rtl::OUString UOF2DATADIR = ::rtl::OUString::createFromAscii("data"); /************************************************************************/ /* class UOF2AttributeList */ /************************************************************************/ class UOF2AttributeList : public ::cppu::WeakImplHelper1< ::com::sun::star::xml::sax::XAttributeList > { public: struct UOF2Attribute { ::rtl::OUString m_sName; ::rtl::OUString m_sValue; ::rtl::OUString m_sType; UOF2Attribute( const ::rtl::OUString& rName, const ::rtl::OUString& rValue, const ::rtl::OUString& rType) : m_sName(rName) , m_sValue(rValue) , m_sType(rType) { } }; explicit UOF2AttributeList(); virtual ~UOF2AttributeList(); void addAttribute( const UOF2Attribute& rAttribute ); virtual sal_Int16 SAL_CALL getLength() throw ( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 i) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 i) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getTypeByName( const ::rtl::OUString& rName ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 i ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getValueByName( const ::rtl::OUString& rName ) throw ( ::com::sun::star::uno::RuntimeException ); private: ::std::vector< UOF2Attribute > m_aAttributes; }; UOF2AttributeList::UOF2AttributeList() { } UOF2AttributeList::~UOF2AttributeList() { } void UOF2AttributeList::addAttribute( const UOF2Attribute& rAttribute ) { if(rAttribute.m_sName.getLength() && rAttribute.m_sValue.getLength()) m_aAttributes.push_back(rAttribute); } sal_Int16 SAL_CALL UOF2AttributeList::getLength() throw ( ::com::sun::star::uno::RuntimeException ) { return static_cast< sal_Int16 >(m_aAttributes.size()); } ::rtl::OUString SAL_CALL UOF2AttributeList::getNameByIndex( sal_Int16 i ) throw ( ::com::sun::star::uno::RuntimeException ) { return m_aAttributes[i].m_sName; } ::rtl::OUString SAL_CALL UOF2AttributeList::getTypeByIndex( sal_Int16 i ) throw ( ::com::sun::star::uno::RuntimeException ) { return m_aAttributes[i].m_sType; } ::rtl::OUString SAL_CALL UOF2AttributeList::getTypeByName( const ::rtl::OUString& rName ) throw ( ::com::sun::star::uno::RuntimeException ) { ::std::vector< UOF2AttributeList::UOF2Attribute >::const_iterator aIter = m_aAttributes.begin(); ::std::vector< UOF2AttributeList::UOF2Attribute >::const_iterator aEnd = m_aAttributes.end(); while(aIter != aEnd) { if((*aIter).m_sName.equals(rName)) return (*aIter).m_sType; ++aIter; } return ::rtl::OUString(); } ::rtl::OUString SAL_CALL UOF2AttributeList::getValueByIndex( sal_Int16 i ) throw ( ::com::sun::star::uno::RuntimeException ) { return m_aAttributes[i].m_sValue; } ::rtl::OUString SAL_CALL UOF2AttributeList::getValueByName( const ::rtl::OUString& rName ) throw ( ::com::sun::star::uno::RuntimeException ) { ::std::vector< UOF2AttributeList::UOF2Attribute >::const_iterator aIter = m_aAttributes.begin(); ::std::vector< UOF2AttributeList::UOF2Attribute >::const_iterator aEnd = m_aAttributes.end(); while(aIter != aEnd) { if((*aIter).m_sName.equals(rName)) return (*aIter).m_sValue; ++aIter; } return ::rtl::OUString(); } /************************************************************************/ /* class UOF2FlatDocMergeHandler */ /************************************************************************/ class UOF2FlatDocMergeHandler : public ::cppu::WeakImplHelper1< ::com::sun::star::xml::sax::XDocumentHandler > { public: explicit UOF2FlatDocMergeHandler(UOF2Merge& rUOF2Merge); virtual ~UOF2FlatDocMergeHandler(); virtual void SAL_CALL startDocument() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endDocument() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL startElement( const ::rtl::OUString& rElemName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& rAttribs ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endElement( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL characters( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& rWhiteSpaces ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL processingInstruction( const ::rtl::OUString& rTarget, const ::rtl::OUString& rData ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& xLocator ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); protected: UOF2Merge& getUOF2Merge(){ return m_rUOF2Merge; } private: UOF2Merge& m_rUOF2Merge; sal_Int32 m_nLevel; private: UOF2FlatDocMergeHandler(const UOF2FlatDocMergeHandler& rDocHdl); UOF2FlatDocMergeHandler& operator=(const UOF2FlatDocMergeHandler& rDocHdl); }; UOF2FlatDocMergeHandler::UOF2FlatDocMergeHandler( UOF2Merge& rUOF2Merge ) : m_rUOF2Merge(rUOF2Merge) , m_nLevel(0) { } UOF2FlatDocMergeHandler::~UOF2FlatDocMergeHandler() { } void SAL_CALL UOF2FlatDocMergeHandler::startDocument() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL UOF2FlatDocMergeHandler::endDocument() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL UOF2FlatDocMergeHandler::startElement( const ::rtl::OUString& rElemName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& rAttribs ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { ++m_nLevel; if( m_nLevel == 1) { UOF2AttributeList *pUOF2AttrList = new UOF2AttributeList; sal_Int16 nLen = rAttribs->getLength(); if(nLen > 0) { for( sal_Int16 i = 0; i < nLen; ++i) { bool bIsExistNMS = false; if((rAttribs->getNameByIndex(i).indexOf( ::rtl::OUString::createFromAscii("xmlns:"))) == 0) { bIsExistNMS = m_rUOF2Merge.isInsertedNamespace(rAttribs->getNameByIndex(i)); if(!bIsExistNMS) m_rUOF2Merge.addNamespace(rAttribs->getNameByIndex(i), rAttribs->getValueByIndex(i)); } if(!bIsExistNMS) { pUOF2AttrList->addAttribute( UOF2AttributeList::UOF2Attribute( rAttribs->getNameByIndex(i), rAttribs->getValueByIndex(i), rAttribs->getTypeByIndex(i)) ); } } } ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > xAttrList(pUOF2AttrList); m_rUOF2Merge.getSaxWriter()->startElement(rElemName, xAttrList); } else m_rUOF2Merge.getSaxWriter()->startElement(rElemName, rAttribs); } void SAL_CALL UOF2FlatDocMergeHandler::endElement( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { --m_nLevel; m_rUOF2Merge.getSaxWriter()->endElement(rElemName); } void SAL_CALL UOF2FlatDocMergeHandler::characters( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { m_rUOF2Merge.getSaxWriter()->characters(rElemName); } void SAL_CALL UOF2FlatDocMergeHandler::ignorableWhitespace( const ::rtl::OUString& /*rWhiteSpaces*/ ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL UOF2FlatDocMergeHandler::processingInstruction( const ::rtl::OUString& /*rTarget*/, const ::rtl::OUString&/* rData */) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { } void SAL_CALL UOF2FlatDocMergeHandler::setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& /*xLocator*/ ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { } /************************************************************************/ /* class UOF2UOFXMLDocMergeHandler */ /************************************************************************/ class UOF2UOFXMLDocMergeHandler : public UOF2FlatDocMergeHandler { public: explicit UOF2UOFXMLDocMergeHandler( UOF2Merge& rUOF2Merge); virtual ~UOF2UOFXMLDocMergeHandler(); virtual void SAL_CALL endElement( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); }; UOF2UOFXMLDocMergeHandler::UOF2UOFXMLDocMergeHandler( UOF2Merge& rUOF2Merge ) : UOF2FlatDocMergeHandler(rUOF2Merge) { } UOF2UOFXMLDocMergeHandler::~UOF2UOFXMLDocMergeHandler() { } void SAL_CALL UOF2UOFXMLDocMergeHandler::endElement( const ::rtl::OUString& /*rElemName*/ ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { } /************************************************************************/ /* class UOF2ObjdataXMLDocMergeHandler */ /************************************************************************/ class UOF2ObjdataXMLDocMergeHandler : public UOF2FlatDocMergeHandler { public: UOF2ObjdataXMLDocMergeHandler( UOF2Merge& rMerge ); virtual ~UOF2ObjdataXMLDocMergeHandler(); virtual void SAL_CALL startElement( const ::rtl::OUString& rElemName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& rAttribs ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endElement( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL characters( const ::rtl::OUString& rChars ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); private: static const ::rtl::OUString OBJPATH; static const ::rtl::OUString OBJDATA; bool m_bIsObjPathElem; }; const ::rtl::OUString UOF2ObjdataXMLDocMergeHandler::OBJPATH( ::rtl::OStringToOUString( ::rtl::OString("对象:路径_D703"), RTL_TEXTENCODING_UTF8 ) ); const ::rtl::OUString UOF2ObjdataXMLDocMergeHandler::OBJDATA( ::rtl::OStringToOUString( ::rtl::OString("对象:数据_D702"), RTL_TEXTENCODING_UTF8 ) ); UOF2ObjdataXMLDocMergeHandler::UOF2ObjdataXMLDocMergeHandler( UOF2Merge& rMerge ) : UOF2FlatDocMergeHandler(rMerge) , m_bIsObjPathElem(false) { } UOF2ObjdataXMLDocMergeHandler::~UOF2ObjdataXMLDocMergeHandler() { } void SAL_CALL UOF2ObjdataXMLDocMergeHandler::startElement( const ::rtl::OUString& rElemName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& rAttribs ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { if(rElemName.equals(OBJPATH)) { m_bIsObjPathElem = true; UOF2FlatDocMergeHandler::startElement(OBJDATA, rAttribs); } else { UOF2FlatDocMergeHandler::startElement(rElemName, rAttribs); m_bIsObjPathElem = false; } } void SAL_CALL UOF2ObjdataXMLDocMergeHandler::endElement( const ::rtl::OUString& rElemName ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { if(m_bIsObjPathElem) UOF2FlatDocMergeHandler::endElement(OBJDATA); else UOF2FlatDocMergeHandler::endElement(rElemName); m_bIsObjPathElem = false; } void SAL_CALL UOF2ObjdataXMLDocMergeHandler::characters( const ::rtl::OUString& rChars ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ) { if(m_bIsObjPathElem) { ::rtl::OUStringBuffer sBuffer; bool bHasBase64 = getUOF2Merge().getBase64Codec(sBuffer, rChars); if(bHasBase64) UOF2FlatDocMergeHandler::characters(sBuffer.makeStringAndClear()); } else UOF2FlatDocMergeHandler::characters(rChars); } /************************************************************************/ /* class UOF2Merge */ /************************************************************************/ UOF2Merge::UOF2Merge( UOF2Storage& rStorage, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rxFactory ) : m_rUOF2Storage(rStorage) , m_xServiceFactory(rxFactory) { OSL_ENSURE(rxFactory.is(), "UOF2Merge::UOF2Merge need XMultiServiceFactory"); OSL_ENSURE(rStorage.isValidUOF2Doc(), "UOF2Merge::UOF2Merge - You must import valid UOF2 document"); init(); } UOF2Merge::~UOF2Merge() { } void UOF2Merge::init() { try { m_xPipeInStream.set(m_xServiceFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.io.Pipe") ), ::com::sun::star::uno::UNO_QUERY); m_xPipeOutStream.set(m_xPipeInStream, ::com::sun::star::uno::UNO_QUERY); m_xSaxParser.set(m_xServiceFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.xml.sax.Parser") ), ::com::sun::star::uno::UNO_QUERY); m_xExtDocHdl.set(m_xServiceFactory->createInstance( ::rtl::OUString::createFromAscii("com.sun.star.xml.sax.Writer") ), ::com::sun::star::uno::UNO_QUERY); ::com::sun::star::uno::Reference< ::com::sun::star::io::XActiveDataSource > xmlSource( m_xExtDocHdl, ::com::sun::star::uno::UNO_QUERY); xmlSource->setOutputStream(m_xPipeOutStream); } catch( ::com::sun::star::uno::Exception& exc) { OSL_ENSURE(0, ::rtl::OUStringToOString(exc.Message, RTL_TEXTENCODING_ASCII_US).getStr()); } } bool UOF2Merge::merge() { bool bRet = true; ::std::vector< ::rtl::OUString > aElemNames; StorageRef storageRef = m_rUOF2Storage.getMainStorageRef(); storageRef->getElementNames(aElemNames); m_xExtDocHdl->startDocument(); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xUOFXMLInputStream = storageRef->openInputStream(UOFELEMNAME); startUOFRootXML(xUOFXMLInputStream); ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > xUOF2SubXMLDocHdl( new UOF2FlatDocMergeHandler(*this) ); ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > xObjdataXMLDocHdl; ::std::vector< ::rtl::OUString >::const_iterator aIter = aElemNames.begin(); ::std::vector< ::rtl::OUString >::const_iterator aEndIt = aElemNames.end(); while(aIter != aEndIt) { m_xSaxParser->setDocumentHandler(xUOF2SubXMLDocHdl); if((*aIter) != UOFELEMNAME) { ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xInputStream = storageRef->openInputStream(*aIter); if(xInputStream.is()) { if((*aIter) == UOF2OBJDATAXML) { xObjdataXMLDocHdl.set( new UOF2ObjdataXMLDocMergeHandler(*this) ); m_xSaxParser->setDocumentHandler(xObjdataXMLDocHdl); } ::com::sun::star::xml::sax::InputSource inputSource; inputSource.sSystemId = *aIter; inputSource.aInputStream = xInputStream; m_xSaxParser->parseStream(inputSource); } else { StorageRef subStorage = storageRef->openSubStorage(*aIter, false); if(subStorage.get()) { if((*aIter) != UOF2DATADIR) { ::std::vector< ::rtl::OUString > aSubElemNames; subStorage->getElementNames(aSubElemNames); if(!aSubElemNames.empty()) { ::std::vector< ::rtl::OUString >::const_iterator aSubIter = aSubElemNames.begin(); ::std::vector< ::rtl::OUString >::const_iterator aSubEnd = aSubElemNames.end(); while(aSubIter != aSubEnd) { ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xSubInputStream = subStorage->openInputStream(*aSubIter); if(xSubInputStream.is()) { ::com::sun::star::xml::sax::InputSource inputSource; inputSource.sSystemId = *aSubIter; inputSource.aInputStream = xSubInputStream; m_xSaxParser->parseStream(inputSource); } ++aSubIter; } } } } } } ++aIter; } endUOFRootXML(); m_xExtDocHdl->endDocument(); return bRet; } ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > UOF2Merge::getMergedInStream() const { return m_xPipeInStream; } ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XExtendedDocumentHandler > UOF2Merge::getSaxWriter() { return m_xExtDocHdl; } void UOF2Merge::startUOFRootXML( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xUOFXMLInStream ) { ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > xUOFXMLDocHdl(new UOF2UOFXMLDocMergeHandler(*this)); m_xSaxParser->setDocumentHandler(xUOFXMLDocHdl); ::com::sun::star::xml::sax::InputSource inputSource; inputSource.sSystemId = UOFELEMNAME; inputSource.aInputStream = xUOFXMLInStream; m_xSaxParser->parseStream(inputSource); } void UOF2Merge::endUOFRootXML() { m_xExtDocHdl->endElement( ::rtl::OUString::createFromAscii("uof:UOF_0000") ); } void UOF2Merge::addNamespace( const ::rtl::OUString& rName, const ::rtl::OUString& rURL ) { if(rName.getLength()> 0 && rURL.getLength() > 0) { m_aNamespaceMap.insert( ::std::map< ::rtl::OUString, ::rtl::OUString >::value_type( rName, rURL )); } } bool UOF2Merge::isInsertedNamespace( const ::rtl::OUString& rName ) const { bool bRet = false; typedef ::std::map< ::rtl::OUString, ::rtl::OUString >::const_iterator NMSIter; NMSIter aFoundIter = m_aNamespaceMap.find( rName ); if(aFoundIter != m_aNamespaceMap.end()) bRet = true; return bRet; } bool UOF2Merge::getBase64Codec( ::rtl::OUStringBuffer& rBuffer, const ::rtl::OUString& rObjPath ) { bool bRet = false; if(rObjPath.getLength()) { ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xInputStream = m_rUOF2Storage.getMainStorageRef()->openInputStream(rObjPath); if(xInputStream.is()) { sal_Int32 nMax = 512; ::com::sun::star::uno::Sequence< sal_Int8 > aOutSeq; sal_Int32 nRead = 0; while(true) { ::com::sun::star::uno::Sequence< sal_Int8 > aInSeq; nRead = xInputStream->readBytes(aInSeq, nMax); if(nRead) { sal_Int32 nLen = aInSeq.getLength(); if(nLen) { sal_Int32 nOrigLen = aOutSeq.getLength(); aOutSeq.realloc(nOrigLen + nLen); sal_Int8 * pArray = aOutSeq.getArray() + nOrigLen; for(sal_Int32 i = 0; i < nLen; ++i) { *pArray++ = aInSeq[i]; } } } else break; } if(aOutSeq.getLength() > 0) { XMLBase64Codec::encodeBase64(rBuffer, aOutSeq); bRet = true; } } } return bRet; } }
8,388
387
""" ################################################################################################## # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : spatial_temporal_east_det.py # Abstract : YORO detection model # Current Version: 1.0.0 # Date : 2021-05-25 #################################################################################################### """ from mmdet.models.builder import DETECTORS from mmdet.models import builder from davarocr.davar_det.models.detectors.seg_based_det import SegBasedDet from davarocr.davar_common.core import build_postprocess @DETECTORS.register_module() class SpatialTempoEASTDet(SegBasedDet): """ YORO detection model use EAST as backbone """ def __init__(self, backbone, neck=None, mask_head=None, train_cfg=None, test_cfg=None, pretrained=None): """ Args: backbone(dict): network backbone (e.g. ResNet) neck(dict): network neck (e.g., EASTMerge) head(dict): head for loss calculation (e.g., EASTHead) train_cfg(dict): related parameters for training test_cfg(dict): related parameters for test pretrained(dict): pretrained model """ super().__init__(backbone=backbone, neck=neck, mask_head=mask_head, train_cfg=train_cfg, test_cfg=test_cfg, pretrained=pretrained) # Config set self.train_cfg = train_cfg self.test_cfg = test_cfg self.head_cfg = {'head_cfg': self.train_cfg} self.backbone = builder.build_backbone(backbone) if neck is not None: self.neck = builder.build_neck(neck) # You can set the train cfg to decide whether to fix backbone if self.train_cfg and self.train_cfg.get('fix_backbone', False): for param in self.parameters(): param.requires_grad = False mask_head = dict(mask_head, **self.head_cfg) self.mask_head = builder.build_head(mask_head) self.init_weights(pretrained=pretrained) if hasattr(self.test_cfg, 'postprocess'): self.post_processor = build_postprocess(self.test_cfg.postprocess) else: self.post_processor = None def forward_train(self, img, img_metas, gt_masks, **kwargs ): """Forward training process and loss computing Args: img (list[Tensor]): input images img_metas(dict) : image meta-info gt_masks(np.ndarray): ground-truth label for training Returns: dict: losses for training data """ losses = dict() # You can set the train cfg to decide whether to fix backbone if self.train_cfg and self.train_cfg.get('fix_backbone', False): self.backbone.eval() self.neck.eval() x = self.extract_feat(img) mask_pred = self.mask_head(x, img_metas) # Get ground-truth label mask_targets = self.mask_head.get_target(gt_masks) # Compute loss loss_mask = self.mask_head.loss(mask_pred, mask_targets) # Update loss losses.update(loss_mask) return losses def simple_test(self, img, img_meta, **kwargs): """Forward inference Args: img(Tensor): input image img_meta(dict): image meta-info Returns: dict: predicted results. e.g. {'bboxes': [{'points':[[x1, y1, ...., xn, yn],[]...]}, {},....],}. """ final_result = dict() x = self.extract_feat(img) # If the previous features exist, we only forward last frame, and save this frame's info if img_meta[-1]['pre_features'] is not None: final_result['pre_features'] = x final_result['img_metas'] = img_meta # Or we forward window size frames and only to save [1:] previous features for next forward else: final_result['pre_features'] = x[1:] final_result['img_metas'] = img_meta[1:] results = self.mask_head.simple_test(x, img_meta) if self.post_processor is not None: results = self.post_processor.post_processing(results, img_meta) final_result['bboxes'] = results return final_result def aug_test(self, img, img_meta): raise NotImplementedError
2,065
4,283
<reponame>software-is-art/hazelcast /* * Copyright 2021 Hazelcast Inc. * * Licensed under the Hazelcast Community License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://hazelcast.com/hazelcast-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast; import com.hazelcast.core.Hazelcast; import com.hazelcast.instance.HazelcastInstanceProxy; import com.hazelcast.internal.serialization.InternalSerializationService; import com.hazelcast.internal.serialization.impl.TestObject; import com.hazelcast.nio.serialization.Data; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; public final class TestSerialization { private TestSerialization() { } public static void main(String[] args) throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(42, "hello world"); TestObject testObject = new TestObject( true, (byte) 42, 'd', (short) 42, 42, 42, 4.2f, 4.2, "hello world", newArrayList("hello world"), newHashSet("hello world"), map ); HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) Hazelcast.newHazelcastInstance(); InternalSerializationService service = proxy.getSerializationService(); Data data = service.toData(testObject); byte[] serialized = data.toByteArray(); try (OutputStream out = new FileOutputStream("./testObject")) { out.write(serialized); } proxy.shutdown(); } }
700
1,590
<gh_stars>1000+ { "parameters": { "scanId": "latest", "workspaceId": "55555555-6666-7777-8888-999999999999", "api-version": "2020-07-01-preview", "resourceId": "subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/Rg/providers/Microsoft.HybridCompute/machines/MyMachine/sqlServers/server1/databases/master" }, "responses": { "200": { "body": { "id": "/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/Rg/providers/Microsoft.HybridCompute/machines/MyMachine/sqlServers/server1/databases/master/providers/Microsoft.Security/sqlVulnerabilityAssessments/default/scans/Scheduled-20200623", "name": "Scheduled-20200623", "type": "Microsoft.Security/sqlVulnerabilityAssessments/scans", "properties": { "triggerType": "Recurring", "state": "Failed", "server": "server1", "database": "master", "sqlVersion": "15.0.2000", "startTime": "2020-06-23T06:49:00.6455136+00:00", "endTime": "2020-06-23T06:49:00.7236217Z", "highSeverityFailedRulesCount": 3, "mediumSeverityFailedRulesCount": 2, "lowSeverityFailedRulesCount": 1, "totalPassedRulesCount": 20, "totalFailedRulesCount": 6, "totalRulesCount": 26, "isBaselineApplied": false } } } } }
642
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.tests.gui.framework.fixture; import com.android.tools.idea.tests.gui.framework.GuiTests; import com.android.tools.idea.tests.gui.framework.matcher.Matchers; import com.google.common.collect.ImmutableList; import com.intellij.openapi.actionSystem.ex.ComboBoxAction; import com.intellij.ui.components.JBList; import com.intellij.ui.popup.PopupFactoryImpl; import com.intellij.ui.popup.list.ListPopupModel; import org.fest.swing.core.GenericTypeMatcher; import org.fest.swing.core.Robot; import org.fest.swing.edt.GuiQuery; import org.fest.swing.edt.GuiTask; import org.fest.swing.fixture.JButtonFixture; import org.fest.swing.fixture.JListFixture; import org.fest.swing.timing.Wait; import org.jetbrains.annotations.NotNull; import java.util.List; import javax.swing.*; import java.awt.*; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.*; public class ComboBoxActionFixture { @NotNull private Robot myRobot; @NotNull private JButton myTarget; private static final Class<?> ourComboBoxButtonClass; static { Class<?> temp = null; try { temp = ComboBoxActionFixture.class.getClassLoader().loadClass(ComboBoxAction.class.getCanonicalName() + "$ComboBoxButton"); } catch (ClassNotFoundException e) { e.printStackTrace(); } ourComboBoxButtonClass = temp; } public static ComboBoxActionFixture findComboBox(@NotNull Robot robot, @NotNull Container root) { JButton comboBoxButton = robot.finder().find(root, new GenericTypeMatcher<JButton>(JButton.class) { @Override protected boolean isMatching(@NotNull JButton component) { return ourComboBoxButtonClass.isInstance(component); } }); return new ComboBoxActionFixture(robot, comboBoxButton); } public static ComboBoxActionFixture findComboBoxByTooltip(@NotNull Robot robot, @NotNull Container root, @NotNull final String tooltip) { JButton comboBoxButton = robot.finder().find(root, Matchers.byTooltip(JButton.class, tooltip)); return new ComboBoxActionFixture(robot, comboBoxButton); } public static ComboBoxActionFixture findComboBoxByClientPropertyAndText(@NotNull Robot robot, @NotNull Container root, @NotNull Object key, @NotNull Class<?> valueClass, @NotNull String text) { JButton comboBoxButton = robot.finder().find(root, Matchers.byClientProperty(JButton.class, key, valueClass).and(Matchers.byText(JButton.class, text))); return new ComboBoxActionFixture(robot, comboBoxButton); } public ComboBoxActionFixture(@NotNull Robot robot, @NotNull JButton target) { myRobot = robot; myTarget = target; } public void selectItem(@NotNull String itemName) { click(); selectItemByText(itemName); } public List<String> items() { click(); JBList list = getList(); final JListFixture listFixture = new JListFixture(myRobot, list); final ImmutableList<String> result = ImmutableList.copyOf(listFixture.contents()); click(); return result; } @NotNull public String getSelectedItemText() { return GuiQuery.getNonNull(myTarget::getText); } private void click() { final JButtonFixture comboBoxButtonFixture = new JButtonFixture(myRobot, myTarget); Wait.seconds(1).expecting("comboBoxButton to be enabled") .until(() -> GuiQuery.getNonNull(() -> comboBoxButtonFixture.target().isEnabled())); comboBoxButtonFixture.click(); } @NotNull private JBList getList() { return GuiTests.waitUntilShowingAndEnabled(myRobot, null, new GenericTypeMatcher<JBList>(JBList.class) { @Override protected boolean isMatching(@NotNull JBList list) { return list.getClass().getName().equals("com.intellij.ui.popup.list.ListPopupImpl$MyList"); } }); } private void selectItemByText(@NotNull final String text) { JList list = getList(); Wait.seconds(1).expecting("the list to be populated") .until(() -> { ListPopupModel popupModel = (ListPopupModel)list.getModel(); for (int i = 0; i < popupModel.getSize(); ++i) { PopupFactoryImpl.ActionItem actionItem = (PopupFactoryImpl.ActionItem)popupModel.get(i); if (text.equals(actionItem.getText())) { return true; } } return false; }); int appIndex = GuiQuery.getNonNull( () -> { ListPopupModel popupModel = (ListPopupModel)list.getModel(); for (int i = 0; i < popupModel.getSize(); ++i) { PopupFactoryImpl.ActionItem actionItem = (PopupFactoryImpl.ActionItem)popupModel.get(i); if (text.equals(actionItem.getText())) { return i; } } return -1; }); assertThat(appIndex).isAtLeast(0); GuiTask.execute(() -> list.setSelectedIndex(appIndex)); assertEquals(text, ((PopupFactoryImpl.ActionItem)list.getSelectedValue()).getText()); } }
2,263
515
<reponame>paulo-e/caelum-stella package br.com.caelum.stella.gateway.pagseguro; import java.math.BigDecimal; import br.com.caelum.stella.gateway.core.BigDecimalFormatter; /** * Representa um item do carrinho que deve ser enviado ao UOL. * @author <NAME> * */ public class PagSeguroItem { private String id; private String descricao; private int quantidade; private BigDecimal valor; private BigDecimal frete; private Double pesoGramas; private BigDecimal taxaExtra; /** * Uso controlado para montar a autorizacao. * @param id * @param descricao * @param quantidade * @param valor * @param frete * @param pesoGramas * @param taxaExtra */ PagSeguroItem(String id, String descricao, int quantidade, BigDecimal valor, BigDecimal frete,BigDecimal taxaExtra) { // TODO Auto-generated constructor stub this(id,descricao,quantidade,valor,frete,null,taxaExtra); } /** * Usado para itens que não precisam de frete * @param id * @param descricao * @param quantidade * @param valor */ public PagSeguroItem(String id, String descricao, int quantidade, BigDecimal valor) { this(id,descricao,quantidade,valor,BigDecimal.ZERO,0d); } /** * Usado para itens que precisam de frete. * @param id * @param descricao * @param quantidade * @param valor * @param frete * @param pesoGramas */ public PagSeguroItem(String id, String descricao, int quantidade, BigDecimal valor, BigDecimal frete, Double pesoGramas) { this(id,descricao,quantidade,valor,frete,pesoGramas,BigDecimal.ZERO); } /** * * @param id * @param descricao * @param quantidade * @param valor * @param frete * @param pesoGramas * @param taxaExtra */ private PagSeguroItem(String id, String descricao, int quantidade, BigDecimal valor, BigDecimal frete, Double pesoGramas,BigDecimal taxaExtra) { super(); this.id = id; this.descricao = descricao; this.quantidade = quantidade; this.valor = valor; this.frete = frete; this.pesoGramas = pesoGramas; this.taxaExtra = taxaExtra; } public String getId() { return id; } public String getDescricao() { return descricao; } public int getQuantidade() { return quantidade; } public BigDecimal getValor() { return valor; } public BigDecimal getFrete() { return frete; } public Double getPesoGramas() { return pesoGramas; } /** * * @return o valor em centavos. */ public String getValorFormatado(){ return new BigDecimalFormatter().bigDecimalToStringInCents(valor); } /** * * @return o frete em centavos */ public String getValorFreteFormatado(){ return new BigDecimalFormatter().bigDecimalToStringInCents(frete); } /** * * @return o peso sem casas decimais */ public String getPesoFormatado(){ return String.format("%.0f",pesoGramas); } /** * * @return taxa extra aplicada sobre o item. */ public BigDecimal getTaxaExtra() { if(taxaExtra==null){ taxaExtra = BigDecimal.ZERO; } return taxaExtra; } }
1,408
611
<reponame>theredled/idea-php-symfony2-plugin package fr.adrienbrault.idea.symfony2plugin.profiler.factory; import com.intellij.openapi.project.Project; import fr.adrienbrault.idea.symfony2plugin.Settings; import fr.adrienbrault.idea.symfony2plugin.profiler.HttpProfilerIndex; import fr.adrienbrault.idea.symfony2plugin.profiler.ProfilerIndexInterface; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author <NAME> <<EMAIL>> */ public class HttpProfilerFactory implements ProfilerFactoryInterface { @Nullable @Override public ProfilerIndexInterface createProfilerIndex(@NotNull Project project) { String profilerHttpUrl = Settings.getInstance(project).profilerHttpUrl; if(!profilerHttpUrl.startsWith("http")) { return null; } return new HttpProfilerIndex(project, StringUtils.stripEnd(profilerHttpUrl, "/")); } @Override public boolean accepts(@NotNull Project project) { return Settings.getInstance(project).profilerHttpEnabled; } }
400
456
<reponame>alexingcool/presto /* * 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.presto.testing; import com.facebook.presto.Session; import com.facebook.presto.spi.ConnectorPageSource; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.SqlDate; import com.facebook.presto.spi.type.SqlTime; import com.facebook.presto.spi.type.SqlTimeWithTimeZone; import com.facebook.presto.spi.type.SqlTimestamp; import com.facebook.presto.spi.type.SqlTimestampWithTimeZone; import com.facebook.presto.spi.type.Type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.joda.time.DateTimeZone; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class MaterializedResult implements Iterable<MaterializedRow> { public static final int DEFAULT_PRECISION = 5; private final List<MaterializedRow> rows; private final List<Type> types; private final Map<String, String> setSessionProperties; private final Set<String> resetSessionProperties; public MaterializedResult(List<MaterializedRow> rows, List<? extends Type> types) { this(rows, types, ImmutableMap.of(), ImmutableSet.of()); } public MaterializedResult(List<MaterializedRow> rows, List<? extends Type> types, Map<String, String> setSessionProperties, Set<String> resetSessionProperties) { this.rows = ImmutableList.copyOf(checkNotNull(rows, "rows is null")); this.types = ImmutableList.copyOf(checkNotNull(types, "types is null")); this.setSessionProperties = ImmutableMap.copyOf(checkNotNull(setSessionProperties, "setSessionProperties is null")); this.resetSessionProperties = ImmutableSet.copyOf(checkNotNull(resetSessionProperties, "resetSessionProperties is null")); } public int getRowCount() { return rows.size(); } @Override public Iterator<MaterializedRow> iterator() { return rows.iterator(); } public List<MaterializedRow> getMaterializedRows() { return rows; } public List<Type> getTypes() { return types; } public Map<String, String> getSetSessionProperties() { return setSessionProperties; } public Set<String> getResetSessionProperties() { return resetSessionProperties; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } MaterializedResult o = (MaterializedResult) obj; return Objects.equals(types, o.types) && Objects.equals(rows, o.rows) && Objects.equals(setSessionProperties, o.setSessionProperties) && Objects.equals(resetSessionProperties, o.resetSessionProperties); } @Override public int hashCode() { return Objects.hash(rows, types, setSessionProperties, resetSessionProperties); } @Override public String toString() { return toStringHelper(this) .add("rows", rows) .add("types", types) .add("setSessionProperties", setSessionProperties) .add("resetSessionProperties", resetSessionProperties) .toString(); } public MaterializedResult toJdbcTypes() { ImmutableList.Builder<MaterializedRow> jdbcRows = ImmutableList.builder(); for (MaterializedRow row : rows) { jdbcRows.add(convertToJdbcTypes(row)); } return new MaterializedResult(jdbcRows.build(), types, setSessionProperties, resetSessionProperties); } private static MaterializedRow convertToJdbcTypes(MaterializedRow prestoRow) { List<Object> jdbcValues = new ArrayList<>(); for (int field = 0; field < prestoRow.getFieldCount(); field++) { Object prestoValue = prestoRow.getField(field); Object jdbcValue; if (prestoValue instanceof SqlDate) { int days = ((SqlDate) prestoValue).getDays(); jdbcValue = new Date(TimeUnit.DAYS.toMillis(days)); } else if (prestoValue instanceof SqlTime) { jdbcValue = new Time(((SqlTime) prestoValue).getMillisUtc()); } else if (prestoValue instanceof SqlTimeWithTimeZone) { jdbcValue = new Time(((SqlTimeWithTimeZone) prestoValue).getMillisUtc()); } else if (prestoValue instanceof SqlTimestamp) { jdbcValue = new Timestamp(((SqlTimestamp) prestoValue).getMillisUtc()); } else if (prestoValue instanceof SqlTimestampWithTimeZone) { jdbcValue = new Timestamp(((SqlTimestampWithTimeZone) prestoValue).getMillisUtc()); } else { jdbcValue = prestoValue; } jdbcValues.add(jdbcValue); } return new MaterializedRow(prestoRow.getPrecision(), jdbcValues); } public MaterializedResult toTimeZone(DateTimeZone oldTimeZone, DateTimeZone newTimeZone) { ImmutableList.Builder<MaterializedRow> jdbcRows = ImmutableList.builder(); for (MaterializedRow row : rows) { jdbcRows.add(toTimeZone(row, oldTimeZone, newTimeZone)); } return new MaterializedResult(jdbcRows.build(), types); } private static MaterializedRow toTimeZone(MaterializedRow prestoRow, DateTimeZone oldTimeZone, DateTimeZone newTimeZone) { List<Object> values = new ArrayList<>(); for (int field = 0; field < prestoRow.getFieldCount(); field++) { Object value = prestoRow.getField(field); if (value instanceof Date) { long oldMillis = ((Date) value).getTime(); long newMillis = oldTimeZone.getMillisKeepLocal(newTimeZone, oldMillis); value = new Date(newMillis); } values.add(value); } return new MaterializedRow(prestoRow.getPrecision(), values); } public static MaterializedResult materializeSourceDataStream(Session session, ConnectorPageSource pageSource, List<Type> types) { return materializeSourceDataStream(session.toConnectorSession(), pageSource, types); } public static MaterializedResult materializeSourceDataStream(ConnectorSession session, ConnectorPageSource pageSource, List<Type> types) { MaterializedResult.Builder builder = resultBuilder(session, types); while (!pageSource.isFinished()) { Page outputPage = pageSource.getNextPage(); if (outputPage == null) { break; } builder.page(outputPage); } return builder.build(); } public static Builder resultBuilder(Session session, Type... types) { return resultBuilder(session.toConnectorSession(), types); } public static Builder resultBuilder(Session session, Iterable<? extends Type> types) { return resultBuilder(session.toConnectorSession(), types); } public static Builder resultBuilder(ConnectorSession session, Type... types) { return resultBuilder(session, ImmutableList.copyOf(types)); } public static Builder resultBuilder(ConnectorSession session, Iterable<? extends Type> types) { return new Builder(session, ImmutableList.copyOf(types)); } public static class Builder { private final ConnectorSession session; private final List<Type> types; private final ImmutableList.Builder<MaterializedRow> rows = ImmutableList.builder(); Builder(ConnectorSession session, List<Type> types) { this.session = session; this.types = ImmutableList.copyOf(types); } public Builder rows(List<MaterializedRow> rows) { this.rows.addAll(rows); return this; } public Builder row(Object... values) { rows.add(new MaterializedRow(DEFAULT_PRECISION, values)); return this; } public Builder rows(Object[][] rows) { for (Object[] row : rows) { row(row); } return this; } public Builder pages(Iterable<Page> pages) { for (Page page : pages) { this.page(page); } return this; } public Builder page(Page page) { checkNotNull(page, "page is null"); checkArgument(page.getChannelCount() == types.size(), "Expected a page with %s columns, but got %s columns", types.size(), page.getChannelCount()); for (int position = 0; position < page.getPositionCount(); position++) { List<Object> values = new ArrayList<>(page.getChannelCount()); for (int channel = 0; channel < page.getChannelCount(); channel++) { Type type = types.get(channel); Block block = page.getBlock(channel); values.add(type.getObjectValue(session, block, position)); } values = Collections.unmodifiableList(values); rows.add(new MaterializedRow(DEFAULT_PRECISION, values)); } return this; } public MaterializedResult build() { return new MaterializedResult(rows.build(), types); } } }
4,353
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Reliability { namespace FailoverManagerComponent { class ReplicaDownTask : public DynamicStateMachineTask { DENY_COPY(ReplicaDownTask); public: ReplicaDownTask( ReplicaDownOperationSPtr const& operation, FailoverManager & fm, FailoverUnitId const& failoverUnitId, ReplicaDescription && replicaDescription, Federation::NodeInstance const& from); void CheckFailoverUnit( LockedFailoverUnitPtr & lockedFailoverUnit, std::vector<StateMachineActionUPtr> & actions); private: // This implementation makes use of the current state machine // behavior that the dynamic action will always be there before // we execute its action, otherwise it is not safe. class ReplicaDownAction : public StateMachineAction { DENY_COPY(ReplicaDownAction); public: ReplicaDownAction(ReplicaDownTask & task_); int OnPerformAction(FailoverManager & fm); void WriteTo(Common::TextWriter & w, Common::FormatOptions const&) const; void WriteToEtw(uint16 contextSequenceId) const; private: ReplicaDownTask & task_; }; FailoverManager & fm_; ReplicaDownOperationSPtr operation_; FailoverUnitId failoverUnitId_; ReplicaDescription replicaDescription_; Federation::NodeInstance from_; }; } }
800
428
<gh_stars>100-1000 from pytest_factoryboy import register import pytest from rest_framework.test import APIClient from accounts.factories import AccountFactory from events.factories import CategoryFactory, EventFactory from comments.factories import CommentFactory register(AccountFactory, 'account') register(CategoryFactory, 'category') register(EventFactory, 'event') register(CommentFactory, 'comment') @pytest.fixture def authenticated_user(client, account): """Create an authenticated user for a test""" # user = G(User, email='<EMAIL>') account.email = '<EMAIL>' account.set_password('<PASSWORD>') account.save() client.login(email='<EMAIL>', password='<PASSWORD>') return account @pytest.fixture def authenticated(): client = APIClient() client.post('http://127.0.0.1:8000/auth/users/', data={"first_name": "iyanu", "last_name": "ajao", "email": "<EMAIL>", "password": "<PASSWORD>"}) response = client.post('http://127.0.0.1:8000/auth/token/login/', data={"password": "<PASSWORD>", "email": "<EMAIL>"}) auth_token = response.data['auth_token'] client.credentials(HTTP_AUTHORIZATION='Token ' + auth_token) return client
655
777
<gh_stars>100-1000 // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/power_button_controller.h" #include "ash/common/accelerators/accelerator_controller.h" #include "ash/common/ash_switches.h" #include "ash/common/session/session_state_delegate.h" #include "ash/common/system/chromeos/audio/tray_audio.h" #include "ash/common/system/tray/system_tray.h" #include "ash/common/wm/maximize_mode/maximize_mode_controller.h" #include "ash/common/wm_shell.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/shell.h" #include "ash/system/chromeos/power/tablet_power_button_controller.h" #include "ash/wm/lock_state_controller.h" #include "ash/wm/session_state_animator.h" #include "base/command_line.h" #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/display/types/display_snapshot.h" #include "ui/wm/core/compound_event_filter.h" namespace ash { PowerButtonController::PowerButtonController(LockStateController* controller) : power_button_down_(false), lock_button_down_(false), volume_down_pressed_(false), volume_percent_before_screenshot_(0), brightness_is_zero_(false), internal_display_off_and_external_display_on_(false), has_legacy_power_button_( base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAuraLegacyPowerButton)), lock_state_controller_(controller) { chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver( this); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshEnableTouchView) || base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kAshEnableTouchViewTesting)) { tablet_controller_.reset( new TabletPowerButtonController(lock_state_controller_)); } Shell::GetInstance()->display_configurator()->AddObserver(this); Shell::GetInstance()->PrependPreTargetHandler(this); } PowerButtonController::~PowerButtonController() { Shell::GetInstance()->RemovePreTargetHandler(this); Shell::GetInstance()->display_configurator()->RemoveObserver(this); tablet_controller_.reset(); chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver( this); } void PowerButtonController::OnScreenBrightnessChanged(double percent) { brightness_is_zero_ = percent <= 0.001; } void PowerButtonController::OnPowerButtonEvent( bool down, const base::TimeTicks& timestamp) { power_button_down_ = down; if (lock_state_controller_->ShutdownRequested()) return; bool should_take_screenshot = down && volume_down_pressed_ && WmShell::Get() ->maximize_mode_controller() ->IsMaximizeModeWindowManagerEnabled(); if (!has_legacy_power_button_ && !should_take_screenshot && tablet_controller_ && tablet_controller_->ShouldHandlePowerButtonEvents()) { tablet_controller_->OnPowerButtonEvent(down, timestamp); return; } // Avoid starting the lock/shutdown sequence if the power button is pressed // while the screen is off (http://crbug.com/128451), unless an external // display is still on (http://crosbug.com/p/24912). if (brightness_is_zero_ && !internal_display_off_and_external_display_on_) return; // Take screenshot on power button down plus volume down when in touch view. if (should_take_screenshot) { SystemTray* system_tray = Shell::GetInstance()->GetPrimarySystemTray(); if (system_tray && system_tray->GetTrayAudio()) system_tray->GetTrayAudio()->HideDetailedView(false); WmShell::Get()->accelerator_controller()->PerformActionIfEnabled( TAKE_SCREENSHOT); // Restore volume. chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get(); audio_handler->SetOutputVolumePercentWithoutNotifyingObservers( volume_percent_before_screenshot_, chromeos::CrasAudioHandler::VOLUME_CHANGE_MAXIMIZE_MODE_SCREENSHOT); return; } const SessionStateDelegate* session_state_delegate = WmShell::Get()->GetSessionStateDelegate(); if (has_legacy_power_button_) { // If power button releases won't get reported correctly because we're not // running on official hardware, just lock the screen or shut down // immediately. if (down) { if (session_state_delegate->CanLockScreen() && !session_state_delegate->IsUserSessionBlocked() && !lock_state_controller_->LockRequested()) { lock_state_controller_->StartLockAnimationAndLockImmediately(false); } else { lock_state_controller_->RequestShutdown(); } } } else { // !has_legacy_power_button_ if (down) { // If we already have a pending request to lock the screen, wait. if (lock_state_controller_->LockRequested()) return; if (session_state_delegate->CanLockScreen() && !session_state_delegate->IsUserSessionBlocked()) { lock_state_controller_->StartLockAnimation(true); } else { lock_state_controller_->StartShutdownAnimation(); } } else { // Button is up. if (lock_state_controller_->CanCancelLockAnimation()) lock_state_controller_->CancelLockAnimation(); else if (lock_state_controller_->CanCancelShutdownAnimation()) lock_state_controller_->CancelShutdownAnimation(); } } } void PowerButtonController::OnLockButtonEvent( bool down, const base::TimeTicks& timestamp) { lock_button_down_ = down; const SessionStateDelegate* session_state_delegate = WmShell::Get()->GetSessionStateDelegate(); if (!session_state_delegate->CanLockScreen() || session_state_delegate->IsScreenLocked() || lock_state_controller_->LockRequested() || lock_state_controller_->ShutdownRequested()) { return; } // Give the power button precedence over the lock button. if (power_button_down_) return; if (down) lock_state_controller_->StartLockAnimation(false); else lock_state_controller_->CancelLockAnimation(); } void PowerButtonController::OnKeyEvent(ui::KeyEvent* event) { if (event->key_code() == ui::VKEY_VOLUME_DOWN) { volume_down_pressed_ = event->type() == ui::ET_KEY_PRESSED; if (!event->is_repeat()) { chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get(); volume_percent_before_screenshot_ = audio_handler->GetOutputVolumePercent(); } } } void PowerButtonController::OnDisplayModeChanged( const display::DisplayConfigurator::DisplayStateList& display_states) { bool internal_display_off = false; bool external_display_on = false; for (const display::DisplaySnapshot* display : display_states) { if (display->type() == display::DISPLAY_CONNECTION_TYPE_INTERNAL) { if (!display->current_mode()) internal_display_off = true; } else if (display->current_mode()) { external_display_on = true; } } internal_display_off_and_external_display_on_ = internal_display_off && external_display_on; } void PowerButtonController::PowerButtonEventReceived( bool down, const base::TimeTicks& timestamp) { OnPowerButtonEvent(down, timestamp); } } // namespace ash
2,707
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_BUCKETS_BUCKET_HOST_H_ #define CONTENT_BROWSER_BUCKETS_BUCKET_HOST_H_ #include "base/memory/raw_ptr.h" #include "components/services/storage/public/cpp/buckets/bucket_info.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "third_party/blink/public/mojom/buckets/bucket_manager_host.mojom.h" #include "third_party/blink/public/mojom/quota/quota_types.mojom.h" namespace content { class BucketManagerHost; // Implements a Storage Bucket object in the browser process. // // BucketManagerHost owns all BucketHost instances for an origin. // A new instance is created for every request to open or create a // StorageBucket. Instances are destroyed when all corresponding mojo // connections are closed, or when BucketContext is destroyed. class BucketHost : public blink::mojom::BucketHost { public: BucketHost(BucketManagerHost* bucket_manager_host, const storage::BucketInfo& bucket_info, blink::mojom::BucketPoliciesPtr policies); ~BucketHost() override; BucketHost(const BucketHost&) = delete; BucketHost& operator=(const BucketHost&) = delete; // Create mojo data pipe and return remote to pass to the renderer // for the StorageBucket object. mojo::PendingRemote<blink::mojom::BucketHost> CreateStorageBucketBinding(); // blink::mojom::BucketHost void Persist(PersistCallback callback) override; void Persisted(PersistedCallback callback) override; void Estimate(EstimateCallback callback) override; void Durability(DurabilityCallback callback) override; void SetExpires(base::Time expires, SetExpiresCallback callback) override; void Expires(ExpiresCallback callback) override; private: void OnReceiverDisconnected(); // Raw pointer use is safe here because BucketManagerHost owns this // BucketHost. raw_ptr<BucketManagerHost> bucket_manager_host_; const storage::BucketInfo bucket_info_; // TODO(ayui): The authoritative source of bucket policies should be the // buckets database. blink::mojom::BucketPoliciesPtr policies_; mojo::ReceiverSet<blink::mojom::BucketHost> receivers_; }; } // namespace content #endif // CONTENT_BROWSER_BUCKETS_BUCKET_HOST_H_
772
3,269
// Time: O(nlogn) // Space: O(1) class Solution { public: int minimumEffort(vector<vector<int>>& tasks) { sort(begin(tasks), end(tasks), [](const auto& a, const auto& b) { return a[1] - a[0] < b[1] - b[0]; // sort by waste in asc }); int result = 0; // you can see proof here, https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/discuss/944633/Explanation-on-why-sort-by-difference for (const auto& task : tasks) { // we need to pick all the wastes, so greedily to pick the least waste first is always better result = max(result + task[0], task[1]); } return result; } }; // Time: O(nlogn) // Space: O(1) class Solution2 { public: int minimumEffort(vector<vector<int>>& tasks) { sort(begin(tasks), end(tasks), [](const auto& a, const auto& b) { return a[1] - a[0] > b[1] - b[0]; // sort by save in desc }); int result = 0, curr = 0; for (const auto& task : tasks) { // we need to pick all the saves, so greedily to pick the most save first is always better result += max(task[1] - curr, 0); curr = max(curr, task[1]) - task[0]; } return result; } };
608
1,402
<reponame>h-rover/gtsam<filename>gtsam/nonlinear/DoglegOptimizer.h /* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: <NAME>, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file DoglegOptimizer.h * @brief * @author <NAME> * @date Feb 26, 2012 */ #pragma once #include <gtsam/nonlinear/NonlinearOptimizer.h> namespace gtsam { class DoglegOptimizer; /** Parameters for Levenberg-Marquardt optimization. Note that this parameters * class inherits from NonlinearOptimizerParams, which specifies the parameters * common to all nonlinear optimization algorithms. This class also contains * all of those parameters. */ class GTSAM_EXPORT DoglegParams : public NonlinearOptimizerParams { public: /** See DoglegParams::dlVerbosity */ enum VerbosityDL { SILENT, VERBOSE }; double deltaInitial; ///< The initial trust region radius (default: 10.0) VerbosityDL verbosityDL; ///< The verbosity level for Dogleg (default: SILENT), see also NonlinearOptimizerParams::verbosity DoglegParams() : deltaInitial(1.0), verbosityDL(SILENT) {} ~DoglegParams() override {} void print(const std::string& str = "") const override { NonlinearOptimizerParams::print(str); std::cout << " deltaInitial: " << deltaInitial << "\n"; std::cout.flush(); } double getDeltaInitial() const { return deltaInitial; } std::string getVerbosityDL() const { return verbosityDLTranslator(verbosityDL); } void setDeltaInitial(double deltaInitial) { this->deltaInitial = deltaInitial; } void setVerbosityDL(const std::string& verbosityDL) { this->verbosityDL = verbosityDLTranslator(verbosityDL); } private: VerbosityDL verbosityDLTranslator(const std::string& verbosityDL) const; std::string verbosityDLTranslator(VerbosityDL verbosityDL) const; }; /** * This class performs Dogleg nonlinear optimization */ class GTSAM_EXPORT DoglegOptimizer : public NonlinearOptimizer { protected: DoglegParams params_; public: typedef boost::shared_ptr<DoglegOptimizer> shared_ptr; /// @name Standard interface /// @{ /** Standard constructor, requires a nonlinear factor graph, initial * variable assignments, and optimization parameters. For convenience this * version takes plain objects instead of shared pointers, but internally * copies the objects. * @param graph The nonlinear factor graph to optimize * @param initialValues The initial variable assignments * @param params The optimization parameters */ DoglegOptimizer(const NonlinearFactorGraph& graph, const Values& initialValues, const DoglegParams& params = DoglegParams()); /** Standard constructor, requires a nonlinear factor graph, initial * variable assignments, and optimization parameters. For convenience this * version takes plain objects instead of shared pointers, but internally * copies the objects. * @param graph The nonlinear factor graph to optimize * @param initialValues The initial variable assignments */ DoglegOptimizer(const NonlinearFactorGraph& graph, const Values& initialValues, const Ordering& ordering); /// @} /// @name Advanced interface /// @{ /** Virtual destructor */ ~DoglegOptimizer() override {} /** * Perform a single iteration, returning GaussianFactorGraph corresponding to * the linearized factor graph. */ GaussianFactorGraph::shared_ptr iterate() override; /** Read-only access the parameters */ const DoglegParams& params() const { return params_; } /** Access the current trust region radius delta */ double getDelta() const; /// @} protected: /** Access the parameters (base class version) */ const NonlinearOptimizerParams& _params() const override { return params_; } /** Internal function for computing a COLAMD ordering if no ordering is specified */ DoglegParams ensureHasOrdering(DoglegParams params, const NonlinearFactorGraph& graph) const; }; }
1,199
1,338
/* * Copyright 2005-2008, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT license. * * Author: * <NAME> <<EMAIL>> */ #ifndef OFFSCREEN_WINDOW_H #define OFFSCREEN_WINDOW_H #include "Window.h" #include <AutoDeleter.h> class BitmapHWInterface; class ServerBitmap; class OffscreenWindow : public Window { public: OffscreenWindow(ServerBitmap* bitmap, const char* name, ::ServerWindow* window); virtual ~OffscreenWindow(); virtual bool IsOffscreenWindow() const { return true; } private: ServerBitmap* fBitmap; ObjectDeleter<BitmapHWInterface> fHWInterface; }; #endif // OFFSCREEN_WINDOW_H
264
2,151
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CC_TREES_LATENCY_INFO_SWAP_PROMISE_H_ #define CC_TREES_LATENCY_INFO_SWAP_PROMISE_H_ #include <stdint.h> #include "base/compiler_specific.h" #include "cc/trees/swap_promise.h" #include "ui/latency/latency_info.h" namespace cc { class CC_EXPORT LatencyInfoSwapPromise : public SwapPromise { public: explicit LatencyInfoSwapPromise(const ui::LatencyInfo& latency_info); ~LatencyInfoSwapPromise() override; void DidActivate() override {} void WillSwap(viz::CompositorFrameMetadata* metadata, FrameTokenAllocator* frame_token_allocator) override; void DidSwap() override; DidNotSwapAction DidNotSwap(DidNotSwapReason reason) override; void OnCommit() override; int64_t TraceId() const override; private: ui::LatencyInfo latency_; }; } // namespace cc #endif // CC_TREES_LATENCY_INFO_SWAP_PROMISE_H_
374
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_DOWNLOAD_DOWNLOAD_MANAGER_CONSUMER_H_ #define IOS_CHROME_BROWSER_UI_DOWNLOAD_DOWNLOAD_MANAGER_CONSUMER_H_ #import <Foundation/Foundation.h> #import "ios/chrome/browser/ui/download/download_manager_state.h" // Consumer for the download manager mediator. @protocol DownloadManagerConsumer // Sets name of the file being downloaded. - (void)setFileName:(NSString*)fileName; // Sets the received size of the file being downloaded in bytes. - (void)setCountOfBytesReceived:(int64_t)value; // Sets the expected size of the file being downloaded in bytes. -1 if unknown. - (void)setCountOfBytesExpectedToReceive:(int64_t)value; // Sets the download progress. 1.0 if the download is complete. - (void)setProgress:(float)progress; // Sets the state of the download task. Default is // kDownloadManagerStateNotStarted. - (void)setState:(DownloadManagerState)state; // Sets visible state to Install Google Drive button. - (void)setInstallDriveButtonVisible:(BOOL)visible animated:(BOOL)animated; @end #endif // IOS_CHROME_BROWSER_UI_DOWNLOAD_DOWNLOAD_MANAGER_CONSUMER_H_
405
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.websvc.design.view.widget; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.geom.Area; import java.awt.geom.RoundRectangle2D; import org.netbeans.api.visual.border.BorderFactory; import org.netbeans.api.visual.layout.LayoutFactory; import org.netbeans.api.visual.model.ObjectScene; import org.netbeans.api.visual.model.ObjectState; import org.netbeans.api.visual.widget.Widget; import org.netbeans.api.visual.widget.SeparatorWidget; /** * @author <NAME> */ public abstract class AbstractTitledWidget extends Widget implements ExpandableWidget { public static final Color BORDER_COLOR = new Color(169, 197, 235); public static final Color TITLE_COLOR = new Color(184, 215, 255); public static final Color TITLE_COLOR_BRIGHT = new Color(241, 245, 252); public static final Color TITLE_COLOR_PARAMETER = new Color(235,255,255); public static final Color TITLE_COLOR_OUTPUT = new Color(240,240,240); public static final Color TITLE_COLOR_FAULT = new Color(245,227,225); public static final Color TITLE_COLOR_DESC = new Color(240,240,240); public static final Color BORDER_COLOR_BLACK = Color.BLACK; public static final int RADIUS = 12; private Color borderColor = BORDER_COLOR; private int radius = RADIUS; //private int hgap = RADIUS; private int cgap = RADIUS; private int depth = radius/3; private boolean expanded; private transient Widget headerWidget; private transient Widget seperatorWidget; private transient Widget contentWidget; private transient ExpanderWidget expander; /** * Creates a new instance of RoundedRectangleWidget * with default rounded radius and gap and no gradient color * @param scene scene this widget belongs to * @param radius of the rounded arc * @param color color of the border and gradient title */ public AbstractTitledWidget(ObjectScene scene, int radius, Color color) { this(scene,radius,radius,radius,color); } /** * Creates a new instance of RoundedRectangleWidget * with default rounded radius and gap and no gradient color * @param scene scene this widget belongs to * @param radius of the rounded arc * @param gap for header widget * @param gap for content widget * @param color color of the border and gradient title */ public AbstractTitledWidget(ObjectScene scene, int radius, int hgap, int cgap, Color color) { super(scene); this.radius = radius; this.borderColor = color; //this.hgap = hgap; this.cgap = cgap; depth = radius/3; setLayout(LayoutFactory.createVerticalFlowLayout(LayoutFactory.SerialAlignment.JUSTIFY, 0)); setBorder(new RoundedBorder3D(this,radius, depth, 0, 0, borderColor)); headerWidget = new Widget(getScene()); headerWidget.setBorder(BorderFactory.createEmptyBorder(hgap, hgap/2)); headerWidget.setLayout(LayoutFactory.createHorizontalFlowLayout(LayoutFactory.SerialAlignment.CENTER, hgap)); // headerWidget.setLayout(new BorderLayout(headerWidget)); addChild(headerWidget); seperatorWidget = new SeparatorWidget(getScene(),SeparatorWidget.Orientation.HORIZONTAL); seperatorWidget.setForeground(borderColor); if(isExpandable()) { contentWidget = createContentWidget(); expanded = ExpanderWidget.isExpanded(this, true); if(expanded) { expandWidget(); } else { collapseWidget(); } expander = new ExpanderWidget(getScene(), this, expanded); } getActions().addAction(scene.createSelectAction()); } protected Widget getContentWidget() { return contentWidget; } protected final Widget createContentWidget() { Widget widget = new Widget(getScene()); widget.setLayout(LayoutFactory.createVerticalFlowLayout( LayoutFactory.SerialAlignment.JUSTIFY, cgap)); widget.setBorder(BorderFactory.createEmptyBorder(cgap)); return widget; } protected final Widget createHeaderWidget() { Widget widget = new Widget(getScene()); widget.setLayout(LayoutFactory.createVerticalFlowLayout( LayoutFactory.SerialAlignment.JUSTIFY, radius)); return widget; } protected Widget getHeaderWidget() { return headerWidget; } protected ExpanderWidget getExpanderWidget() { return expander; } @org.netbeans.api.annotations.common.SuppressWarnings(" NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") protected final void paintWidget() { Rectangle bounds = getClientArea(); Graphics2D g = getGraphics(); Paint oldPaint = g.getPaint(); RoundRectangle2D rect = new RoundRectangle2D.Double(bounds.x + 0.75f, bounds.y+ 0.75f, bounds.width - 1.5f, bounds.height - 1.5f, radius, radius); if(isExpanded()) { int titleHeight = headerWidget.getBounds().height; Area titleArea = new Area(rect); titleArea.subtract(new Area(new Rectangle(bounds.x, bounds.y + titleHeight, bounds.width, bounds.height))); g.setPaint(getTitlePaint(titleArea.getBounds())); g.fill(titleArea); if(isOpaque()) { Area bodyArea = new Area(rect); bodyArea.subtract(titleArea); g.setPaint(getBackground()); g.fill(bodyArea); } } else { g.setPaint(getTitlePaint(bounds)); g.fill(rect); } g.setPaint(oldPaint); } protected Paint getTitlePaint(Rectangle bounds) { return new GradientPaint(bounds.x, bounds.y, TITLE_COLOR_BRIGHT, bounds.x, bounds.y + bounds.height, TITLE_COLOR); } protected void collapseWidget() { if(seperatorWidget.getParentWidget()!=null) { removeChild(seperatorWidget); } if(getContentWidget().getParentWidget()!=null) { removeChild(getContentWidget()); } } protected void expandWidget() { if(seperatorWidget.getParentWidget()==null) { addChild(seperatorWidget); } if(getContentWidget().getParentWidget()==null) { addChild(getContentWidget()); } } public Object hashKey() { return null; } public void setExpanded(boolean expanded) { if(!isExpandable()) return; if(this.expanded != expanded) { this.expanded = expanded; revalidate(true); if(expanded) { expandWidget(); } else { collapseWidget(); } getScene().validate(); expander.setSelected(expanded); } } public boolean isExpanded() { return expanded; } protected boolean isExpandable() { return true; } protected void notifyAdded() { super.notifyAdded(); final Object key = hashKey(); if(key!=null) { getObjectScene().addObject(key, this); } } protected void notifyRemoved() { super.notifyRemoved(); Object key = hashKey(); if(key!=null&&getObjectScene().isObject(key)) { getObjectScene().removeObject(key); } } protected void notifyStateChanged(ObjectState previousState, ObjectState state) { if (previousState.isSelected() != state.isSelected()) revalidate(true); } protected ObjectScene getObjectScene() { return (ObjectScene)super.getScene(); } }
3,470
419
<gh_stars>100-1000 /* Cock's Identity Based Encryption Encryption phase Generates a random AES session key, and uses it to encrypt a file. Outputs ciphertext <filename>.ipk The session key is ID_PKC encrypted, and written to <filename>.key Requires : big.cpp */ #include <iostream> #include <fstream> #include <cstring> #include "big.h" using namespace std; void strip(char *name) { /* strip off filename extension */ int i; for (i=0;name[i]!='\0';i++) { if (name[i]!='.') continue; name[i]='\0'; break; } } // Using SHA-1 as basic hash algorithm #define HASH_LEN 20 // // Public Hash Function // Big H(char *string,Big n) { // Hash a zero-terminated string to a number h < modulus n // Then increment this number until (h/n)=+1 Big h; char s[HASH_LEN]; int i,j; sha sh; shs_init(&sh); for (i=0;;i++) { if (string[i]==0) break; shs_process(&sh,string[i]); } shs_hash(&sh,s); h=1; j=0; i=1; forever { h*=256; if (j==HASH_LEN) {h+=i++; j=0;} else h+=s[j++]; if (h>=n) break; } while (jacobi(h,n)!=1) h+=1; h%=n; return h; } int main() { miracl *mip=mirsys(36,0); // thread-safe ready. ifstream common("common.ipk"); ifstream plaintext; ofstream key_file,ciphertext; char ifname[100],ofname[100],ch,iv[16],key[16]; Big t,s,n,x; Big tp[128],tm[128],wp[128],wm[128]; int i,j,bit; long seed; aes a; mip->IOBASE=16; common >> n; cout << "Enter 9 digit random number seed = "; cin >> seed; irand(seed); // // Generate random numbers (off-line) // and generate a random key // ch=0; for (i=0;i<128;i++) { tp[i]=rand(n); // random t bit=jacobi(tp[i],n); ch<<=1; if (bit==1) ch|=1; do { tm[i]=rand(n); // different t, same (t/n) } while (jacobi(tm[i],n)!=bit); if (i%8==7) { key[i/8]=ch; ch=0; } } multi_inverse(128,tp,n,wp); // generate 1/t multi_inverse(128,tm,n,wm); // ENCRYPT char id[1000]; cout << "Enter your correspondents email address (lower case)" << endl; cin.get(); cin.getline(id,1000); x=H(id,n); // figure out where input is coming from cout << "Text file to be encrypted = " ; cin >> ifname; /* set up input file */ strcpy(ofname,ifname); // // Now ID-PKC encrypt a random session key // strip(ofname); strcat(ofname,".key"); mip->IOBASE=16; key_file.open(ofname); for (i=0;i<128;i++) { // ID-PKC encrypt s=tp[i]+modmult(x,wp[i],n); if (s>=n) s-=n; key_file << s << endl; s=tm[i]-modmult(x,wm[i],n); if (s<0) s+=n; key_file << s << endl; } // // prepare to encrypt file with random session key // for (i=0;i<16;i++) iv[i]=i; // set CFB IV aes_init(&a,MR_CFB1,16,key,iv); /* set up input file */ strcpy(ofname,ifname); strip(ofname); strcat(ofname,".ipk"); plaintext.open(ifname,ios::in); if (!plaintext) { cout << "Unable to open file " << ifname << "\n"; return 0; } cout << "encrypting message\n"; ciphertext.open(ofname,ios::binary|ios::out); // now encrypt the plaintext file forever { // encrypt input .. plaintext.get(ch); if (plaintext.eof()) break; aes_encrypt(&a,&ch); ciphertext << ch; } aes_end(&a); return 0; }
1,804
1,109
<filename>modules/functional-test/src/main/java/com/intuit/wasabi/tests/service/PrioritiesTest.java /******************************************************************************* * Copyright 2016 Intuit * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.intuit.wasabi.tests.service; import com.intuit.wasabi.tests.library.TestBase; import com.intuit.wasabi.tests.library.util.Constants; import com.intuit.wasabi.tests.library.util.serialstrategies.DefaultNameExclusionStrategy; import com.intuit.wasabi.tests.model.Application; import com.intuit.wasabi.tests.model.Bucket; import com.intuit.wasabi.tests.model.Experiment; import com.intuit.wasabi.tests.model.factory.ApplicationFactory; import com.intuit.wasabi.tests.model.factory.BucketFactory; import com.intuit.wasabi.tests.model.factory.ExperimentFactory; import org.slf4j.Logger; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static com.intuit.wasabi.tests.library.util.ModelAssert.assertEqualModelItems; import static org.slf4j.LoggerFactory.getLogger; /** * Tests for experiment priorities in application. */ public class PrioritiesTest extends TestBase { private static final Logger LOGGER = getLogger(PrioritiesTest.class); private final Application priorityApp = ApplicationFactory.createApplication().setName(Constants.DEFAULT_PREFIX_APPLICATION + "PrioritiesTest"); private final Application newApp = ApplicationFactory.createApplication().setName(Constants.NEW_PREFIX_APPLICATION + "PrioritiesTest"); private Experiment experiment; private final List<Experiment> experiments = new ArrayList<>(Constants.EXP_SPAWN_COUNT); private List<Experiment> priorities; private final String[] labels = {"red", "blue"}; private final double[] allocations = {.50, .50}; private final boolean[] control = {false, false}; /** * Cleans up the app first. */ @Test(dependsOnGroups = {"ping"}) public void t_prepareApp() { List<Experiment> experiments = getApplicationExperiments(priorityApp); for (Experiment experiment : experiments) { deleteExperiment(experiment); } } /** * Tests priority handling. */ @Test(dependsOnMethods = {"t_prepareApp"}) public void t_createAndValidatePriorityList() { LOGGER.info("Creating %d experiments.", Constants.EXP_SPAWN_COUNT); for (int i = 0; i < Constants.EXP_SPAWN_COUNT; ++i) { experiment = ExperimentFactory.createExperiment().setApplication(priorityApp); experiments.add(experiment); Experiment created = postExperiment(experiment); experiment.update(created); toCleanUp.add(experiment); } LOGGER.info("Making the first experiment mutually exclusive with the others."); postExclusions(experiments.get(0), experiments.subList(1, experiments.size())); LOGGER.info("Setting priorities."); putApplicationPriorities(priorityApp, experiments); LOGGER.info("Retrieving priority list"); List<Experiment> priorities = getApplicationPriorities(priorityApp); LOGGER.info("Checking if the priorities match."); assertEqualModelItems(priorities, experiments, new DefaultNameExclusionStrategy("creationTime", "modificationTime", "ruleJson", "hypothesisIsCorrect", "results")); } /** * Tests that priority list will not accept invalid uuids. */ @Test(dependsOnMethods = {"t_createAndValidatePriorityList"}) public void t_testNewExperimentAddDeleteFlowOnPriorityList() { LOGGER.info("Adding a new experiment to the application."); Experiment nExperiment = ExperimentFactory.createExperiment().setApplication(priorityApp); Experiment created = postExperiment(nExperiment); final List<Experiment> newExpWithPriorityListExp = new ArrayList<>(experiments.size() + 1); newExpWithPriorityListExp.addAll(experiments); newExpWithPriorityListExp.add(created); LOGGER.info("Checking that the new experiment automatically gets added to the end of the priority list."); priorities = getApplicationPriorities(priorityApp); //Once the experiment is added, it automatically reflects at the end of the priority list of the application assertEqualModelItems(priorities, newExpWithPriorityListExp, new DefaultNameExclusionStrategy("creationTime", "modificationTime", "ruleJson", "hypothesisIsCorrect", "results")); LOGGER.info("Check if deleted experiments disappear from the priority list."); deleteExperiment(created); priorities = getApplicationPriorities(priorityApp); //Once the experiment is deleted, it stops reflecting in the priority list of the application assertEqualModelItems(priorities, experiments, new DefaultNameExclusionStrategy("creationTime", "modificationTime", "ruleJson", "hypothesisIsCorrect", "results")); } /** * Tests that priority list will not accept experiment of different applications. */ @Test(dependsOnMethods = {"t_createAndValidatePriorityList"}) public void t_testAddingExperimentOfDifferentAppToPriorityList() { LOGGER.info("Checking that priority list will not accept experiments from a different application"); Experiment experiment = ExperimentFactory.createExperiment().setApplication(newApp); Experiment expForDifferentAppCreated = postExperiment(experiment); experiment.update(expForDifferentAppCreated); toCleanUp.add(experiment); final List<Experiment> differentAppExpWithPriorityListExp = new ArrayList<>(experiments.size() + 1); differentAppExpWithPriorityListExp.addAll(experiments); differentAppExpWithPriorityListExp.add(expForDifferentAppCreated); LOGGER.info("Setting priorities."); putApplicationPriorities(priorityApp, differentAppExpWithPriorityListExp); LOGGER.info("Retrieving priority list"); priorities = getApplicationPriorities(priorityApp); //The priority list reflects only the same application experiments, not the new experiment of different application assertEqualModelItems(priorities, experiments, new DefaultNameExclusionStrategy("creationTime", "modificationTime", "ruleJson", "hypothesisIsCorrect", "results")); } /** * Tests that priority list will not accept experiments with invalid uuids. */ @Test(dependsOnMethods = {"t_createAndValidatePriorityList"}) public void t_testAddingInvalidUUIDExperimentToPriorityList() { LOGGER.info("Checking that priority list will not accept invalid uuids"); Experiment invalidUUIDExperiment = new Experiment(); invalidUUIDExperiment.id = "bbbac42e-50c5-4c9a-a398-8588bf6bbe33"; toCleanUp.add(invalidUUIDExperiment); final List<Experiment> invalidUUIDExpWithPriorityListExp = new ArrayList<>(experiments.size() + 1); invalidUUIDExpWithPriorityListExp.addAll(experiments); invalidUUIDExpWithPriorityListExp.add(invalidUUIDExperiment); LOGGER.info("Setting priorities."); putApplicationPriorities(priorityApp, invalidUUIDExpWithPriorityListExp); LOGGER.info("Retrieving priority list"); priorities = getApplicationPriorities(priorityApp); //The priority List reflects only the normal experiments, not the one with invalid uuid assertEqualModelItems(priorities, experiments, new DefaultNameExclusionStrategy("creationTime", "modificationTime", "ruleJson", "hypothesisIsCorrect", "results")); } /** * Tests that priority list will not accept experiments in TERMINATED or DELETED states. */ @Test(dependsOnMethods = {"t_createAndValidatePriorityList"}) public void t_testAddingTerminatedExperimentToPriorityList() { LOGGER.info("Checking that priority list will not accept experiments in TERMINATED or DELETED states"); experiment = ExperimentFactory.createExperiment().setApplication(priorityApp); Experiment experimentToBeTerminated = postExperiment(experiment); toCleanUp.add(experimentToBeTerminated); List<Bucket> buckets = BucketFactory.createCompleteBuckets(experimentToBeTerminated, allocations, labels, control); List<Bucket> resultBuckets = postBuckets(buckets); Assert.assertEquals(buckets, resultBuckets); experimentToBeTerminated.setState(Constants.EXPERIMENT_STATE_RUNNING); putExperiment(experimentToBeTerminated); Assert.assertEquals(experimentToBeTerminated.state, Constants.EXPERIMENT_STATE_RUNNING); experimentToBeTerminated.setState(Constants.EXPERIMENT_STATE_TERMINATED); putExperiment(experimentToBeTerminated); Assert.assertEquals(experimentToBeTerminated.state, Constants.EXPERIMENT_STATE_TERMINATED); final List<Experiment> terminatedExpWithPriorityListExp = new ArrayList<>(experiments.size() + 1); terminatedExpWithPriorityListExp.addAll(experiments); terminatedExpWithPriorityListExp.add(experimentToBeTerminated); LOGGER.info("Setting priorities."); putApplicationPriorities(priorityApp, terminatedExpWithPriorityListExp); LOGGER.info("Retrieving priority list"); priorities = getApplicationPriorities(priorityApp); //The priority List reflects only the normal experiments, not the terminated one assertEqualModelItems(priorities, experiments, new DefaultNameExclusionStrategy("creationTime", "modificationTime", "ruleJson", "hypothesisIsCorrect", "results")); } }
3,311
335
{ "word": "Refractometer", "definitions": [ "An instrument for measuring a refractive index." ], "parts-of-speech": "Noun" }
62
543
<reponame>fredells/riiablo package com.riiablo.widget; import com.badlogic.gdx.utils.Disposable; public class TextArea extends com.badlogic.gdx.scenes.scene2d.ui.TextArea implements Disposable { public TextArea(TextFieldStyle style) { this("", style); } public TextArea(String text, TextFieldStyle style) { super(text, style); } @Override public void dispose() { } public static class TextFieldStyle extends com.badlogic.gdx.scenes.scene2d.ui.TextArea.TextFieldStyle { public TextFieldStyle() { } } }
191
593
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2022 Ruhr University Bochum, Paderborn University, Hackmanit GmbH * * Licensed under Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0.txt */ package de.rub.nds.tlsattacker.core.protocol.serializer.extension; import de.rub.nds.tlsattacker.core.constants.ExtensionType; import de.rub.nds.tlsattacker.core.protocol.message.extension.SessionTicketTLSExtensionMessage; import de.rub.nds.tlsattacker.core.protocol.parser.extension.SessionTicketTLSExtensionParserTest; import java.util.Collection; import static org.junit.Assert.assertArrayEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class SessionTicketTLSExtensionSerializerTest { /** * Gets the test vectors of the SessionTicketTLSExtensionHandlerTest class. * * @return Collection of the parameters */ @Parameterized.Parameters public static Collection<Object[]> generateData() { return SessionTicketTLSExtensionParserTest.generateData(); } private final ExtensionType extensionType; private final int extensionLength; private final byte[] sessionTicket; private final byte[] expectedBytes; private SessionTicketTLSExtensionMessage message; /** * Constructor for parameterized setup. * * @param extensionType * @param extensionLength * @param sessionTicket * @param expectedBytes * @param startParsing */ public SessionTicketTLSExtensionSerializerTest(ExtensionType extensionType, int extensionLength, byte[] sessionTicket, byte[] expectedBytes, int startParsing) { this.extensionType = extensionType; this.extensionLength = extensionLength; this.sessionTicket = sessionTicket; this.expectedBytes = expectedBytes; } /** * Tests the serializeExtensionContent method of the SessionTicketTLSExtensionSerializer class */ @Test public void testSerializeExtensionContent() { message = new SessionTicketTLSExtensionMessage(); message.setExtensionType(extensionType.getValue()); message.setExtensionLength(extensionLength); message.getSessionTicket().setIdentity(sessionTicket); SessionTicketTLSExtensionSerializer serializer = new SessionTicketTLSExtensionSerializer(message); assertArrayEquals(expectedBytes, serializer.serialize()); } }
857
362
<reponame>hsiangawang/whois<gh_stars>100-1000 package net.ripe.db.whois.update.autokey.dao; import net.ripe.db.whois.update.domain.X509KeycertId; public interface X509Repository extends AutoKeyRepository<X509KeycertId> { }
88
478
<filename>paper-code/pytorch_src/logME.py import torch import numpy as np from numba import njit @njit def each_evidence(y_, f, fh, v, s, vh, N, D): """ compute the maximum evidence for each class """ alpha = 1.0 beta = 1.0 lam = alpha / beta tmp = (vh @ (f @ y_)) for _ in range(11): # should converge after at most 10 steps # typically converge after two or three steps gamma = (s / (s + lam)).sum() # A = v @ np.diag(alpha + beta * s) @ v.transpose() # no need to compute A # A_inv = v @ np.diag(1.0 / (alpha + beta * s)) @ v.transpose() # no need to compute A_inv m = v @ (tmp * beta / (alpha + beta * s)) alpha_de = (m * m).sum() alpha = gamma / alpha_de beta_de = ((y_ - fh @ m) ** 2).sum() beta = (N - gamma) / beta_de new_lam = alpha / beta if np.abs(new_lam - lam) / lam < 0.01: break lam = new_lam evidence = D / 2.0 * np.log(alpha) \ + N / 2.0 * np.log(beta) \ - 0.5 * np.sum(np.log(alpha + beta * s)) \ - beta / 2.0 * beta_de \ - alpha / 2.0 * alpha_de \ - N / 2.0 * np.log(2 * np.pi) return evidence / N # use pseudo data to compile the function # D = 20, N = 50 f_tmp = np.random.randn(20, 50).astype(np.float64) each_evidence(np.random.randint(0, 2, 50).astype(np.float64), f_tmp, f_tmp.transpose(), np.eye(20, dtype=np.float64), np.ones(20, dtype=np.float64), np.eye(20, dtype=np.float64), 50, 20) def LogME(f: torch.Tensor, y: torch.Tensor, regression=False): """ :param f: [N, F], feature matrix from pre-trained model :param y: target labels. For classification, y has shape [N] with element in [0, C_t). For regression, y has shape [N, C] with C regression-labels :param regression: whether regression :return: LogME score (how well f can fit y directly) """ f = f.detach().cpu().numpy().astype(np.float64) y = y.detach().cpu().numpy() if regression: y = y.astype(np.float64) fh = f f = f.transpose() D, N = f.shape v, s, vh = np.linalg.svd(f @ fh, full_matrices=True) evidences = [] if regression: K = y.shape[1] for i in range(K): y_ = y[:, i] evidence = each_evidence(y_, f, fh, v, s, vh, N, D) evidences.append(evidence) else: K = int(y.max() + 1) for i in range(K): y_ = (y == i).astype(np.float64) evidence = each_evidence(y_, f, fh, v, s, vh, N, D) evidences.append(evidence) return np.mean(evidences)
1,275
764
{ "symbol": "UINFO", "address": "0xfd7aa5e3005dabf3a30a8b5f22b46a0ae446ce80", "overview": { "en": "UINFO capitalization is a high-quality information platform, based on block chain technology achieving personal quality approval and pricing information and decentralized trading, apply its information function to save encrypted personal information to the local, UINFO does not save the information, make information owners take control of your own information and gain profit. UINFO is the ecological pass for users to enjoy services, which naturally anchors the value of personal information assets. With the gradual improvement of UINFO ecology, UINFO will have a great potential of appreciation.", "zh": "优信宝是一个优质信息资产化平台,基于区块链技术实现个人优质信息的确权,定价及去中心化交易,其信息保管箱功能将个人信息加密后保存到本地,优信宝并不获取保存这些信息,让信息所有权掌握自己的信息并从中获得收益.UINFO是优信宝生态中进行个人信息资产交易,用户享受服务的生态通证,天然锚定了个人信息资产价值,随着优信宝生态的逐步完善UINFO将具备非常大的升值潜力." }, "email": "<EMAIL>", "website": "http://www.uinfo.org/", "whitepaper": "http://www.uinfo.org/UINFO.pdf", "state": "NORMAL", "published_on": "2018-08-15", "initial_price": { "ETH": "0.00050582 ETH" }, "links": { "blog": "https://weibo.com/uinfo", "twitter": "https://twitter.com/UINFOGlobal", "telegram": "https://t.me/joinchat/Ho5Ho0pjDODCsE5IGDnfmg" } }
755
347
"""extended_groups Revision ID: <KEY> Revises: a90076b18837 Create Date: 2017-05-19 17:08:34.780367 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = 'a90076b18837' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('grouptypes', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('name', sa.String(length=100), nullable=False), sa.PrimaryKeyConstraint('id', name=op.f('pk_grouptypes')), sa.UniqueConstraint('name', name=op.f('uq_grouptypes_name')) ) op.create_table('grouptypes_grouptypes', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('grouptype_id', sa.BigInteger(), nullable=False), sa.Column('part_of_id', sa.BigInteger(), nullable=False), sa.ForeignKeyConstraint(['grouptype_id'], ['grouptypes.id'], name=op.f('fk_grouptypes_grouptypes_grouptype_id_grouptypes'), ondelete='CASCADE'), sa.ForeignKeyConstraint(['part_of_id'], ['grouptypes.id'], name=op.f('fk_grouptypes_grouptypes_part_of_id_grouptypes'), ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', name=op.f('pk_grouptypes_grouptypes')), sa.UniqueConstraint('grouptype_id', 'part_of_id', name=op.f('uq_grouptypes_grouptypes_grouptype_id')) ) op.create_index(op.f('ix_grouptypes_grouptypes_grouptype_id'), 'grouptypes_grouptypes', ['grouptype_id'], unique=False) op.create_index(op.f('ix_grouptypes_grouptypes_part_of_id'), 'grouptypes_grouptypes', ['part_of_id'], unique=False) op.create_table('groups_groups', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('group_id', sa.BigInteger(), nullable=False), sa.Column('part_of_id', sa.BigInteger(), nullable=False), sa.ForeignKeyConstraint(['group_id'], ['groups.id'], name=op.f('fk_groups_groups_group_id_groups'), ondelete='CASCADE'), sa.ForeignKeyConstraint(['part_of_id'], ['groups.id'], name=op.f('fk_groups_groups_part_of_id_groups'), ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', name=op.f('pk_groups_groups')), sa.UniqueConstraint('group_id', 'part_of_id', name=op.f('uq_groups_groups_group_id')) ) op.create_index(op.f('ix_groups_groups_group_id'), 'groups_groups', ['group_id'], unique=False) op.create_index(op.f('ix_groups_groups_part_of_id'), 'groups_groups', ['part_of_id'], unique=False) op.add_column('groups', sa.Column('grouptype_id', sa.BigInteger(), nullable=False)) op.create_index(op.f('ix_groups_grouptype_id'), 'groups', ['grouptype_id'], unique=False) op.create_foreign_key(op.f('fk_groups_grouptype_id_grouptypes'), 'groups', 'grouptypes', ['grouptype_id'], ['id'], ondelete='CASCADE') ### end Alembic commands ### op.execute(""" CREATE OR REPLACE FUNCTION check_grouptypes_grouptypes_cycle() RETURNS trigger AS $$ DECLARE cycles INTEGER; BEGIN LOCK TABLE grouptypes_grouptypes IN ACCESS EXCLUSIVE MODE; WITH RECURSIVE search_graph(part_of_id, group_id, id, depth, path, cycle) AS ( SELECT NEW.part_of_id, NEW.group_id, NEW.id, 1, ARRAY[NEW.id], false UNION ALL SELECT g.part_of_id, g.group_id, g.id, sg.depth + 1, path || g.id, g.id = ANY(path) FROM grouptypes_grouptypes g, search_graph sg WHERE g.part_of_id = sg.group_id AND NOT cycle ) SELECT INTO cycles COUNT(*) FROM search_graph WHERE cycle=true; RAISE NOTICE 'cycles: %', cycles; IF cycles > 0 THEN RAISE EXCEPTION 'cycle'; END IF; RETURN NEW; END $$ LANGUAGE plpgsql; CREATE TRIGGER check_grouptypes_grouptypes_cycle AFTER INSERT OR UPDATE ON grouptypes_grouptypes FOR EACH ROW EXECUTE PROCEDURE check_grouptypes_grouptypes_cycle(); """) op.execute(""" CREATE OR REPLACE FUNCTION check_groups_groups_cycle() RETURNS trigger AS $$ DECLARE cycles INTEGER; BEGIN LOCK TABLE groups_groups IN ACCESS EXCLUSIVE MODE; WITH RECURSIVE search_graph(part_of_id, group_id, id, depth, path, cycle) AS ( SELECT NEW.part_of_id, NEW.group_id, NEW.id, 1, ARRAY[NEW.id], false UNION ALL SELECT g.part_of_id, g.group_id, g.id, sg.depth + 1, path || g.id, g.id = ANY(path) FROM groups_groups g, search_graph sg WHERE g.part_of_id = sg.group_id AND NOT cycle ) SELECT INTO cycles COUNT(*) FROM search_graph WHERE cycle=true; RAISE NOTICE 'cycles: %', cycles; IF cycles > 0 THEN RAISE EXCEPTION 'cycle'; END IF; RETURN NEW; END $$ LANGUAGE plpgsql; CREATE TRIGGER check_groups_groups_cycle AFTER INSERT OR UPDATE ON groups_groups FOR EACH ROW EXECUTE PROCEDURE check_groups_groups_cycle(); """) def downgrade(): ### commands auto generated by Alembic - please adjust! ### raise NotImplementedError() ### end Alembic commands ###
2,275
5,937
<reponame>txlos/wpf // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //+--------------------------------------------------------------------------- // // // Description: // Declares CShapeClipperForFEB // #pragma once class CSnappingFrame; //+------------------------------------------------------------------------ // // Class: CShapeClipperForFEB // // Synopsis: // Helper for path rendering: class to execute clipping of arbitrary // shape with the shape contained in Finite Extent Brush (FEB). // Yet another role of this helper is to provide pixel snapping. // // Instance of CShapeClipperForFEB supposed to live in stack frame. // To do its job, it might create temporary objects. // Life time of temporary objects is controlled by constructor // and destructor. // // Usage pattern: // // 1. Create an instance: // CShapeClipperForFEB clipper(shape parameters) // // 2. Optionally, call clipper.ApplyGuidelines(); // Execute pixel snapping. See GuidelineCollection.h for more details. // // 3. Optionally, call clipper.ApplyBrush(). // Note it does not necessary mean that given shape will be changed. // // 4. Use clipper.Get*() functions to get results. // class CShapeClipperForFEB { public: // CShapeClipperForFEB(); no default constructor for this class // ~CShapeClipperForFEB(); no destructor required CShapeClipperForFEB( __in_ecount(1) const IShapeData *pShape, __in_ecount(1) const CRectF<CoordinateSpace::Shape> *prcGivenShapeBounds, __in_ecount_opt(1) const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> *pmatShapeToDevice ); HRESULT ApplyGuidelines( __in_ecount_opt(1) CSnappingFrame *pSnappingFrame, __inout_ecount(1) CShape *pScratchShape ); HRESULT ApplyBrush( __in_ecount_opt(1) const CMILBrush *pBrush, __in_ecount(1) const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &matWorldToDevice, __inout_ecount(1) CShape *pScratchShape ); bool ShapeHasBeenCorrected() const { return m_pFinalShape != m_pGivenShape; } HRESULT GetBoundsInDeviceSpace( __out_ecount(1) CRectF<CoordinateSpace::Device> *prcBoundsDeviceSpace ) const { HRESULT hr = S_OK; if (m_fGivenShapeBoundsEmpty) { prcBoundsDeviceSpace->SetEmpty(); } else { IFC(m_finalShapeBoundsDeviceSpace.GetCachedBounds(*prcBoundsDeviceSpace)); } Cleanup: RRETURN(hr); } const IShapeData* GetShape() const { return m_pFinalShape; } const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> * GetShapeToDeviceTransformOrNull() const { return m_pmatShapeToDevice; } const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> * GetShapeToDeviceTransform() const { return m_pmatShapeToDevice ? m_pmatShapeToDevice : m_pmatShapeToDevice->pIdentity(); } private: HRESULT DoApplyGuidelines( __in_ecount(1) CSnappingFrame *pSnappingFrame, __inout_ecount(1) CShape *pScratchShape ); private: const IShapeData *m_pGivenShape; bool m_fGivenShapeBoundsEmpty; const IShapeData* m_pFinalShape; CParallelogram m_finalShapeBoundsDeviceSpace; const CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> * m_pmatShapeToDevice; CMatrix<CoordinateSpace::Shape,CoordinateSpace::Device> m_matShapeToDevice; }; //+------------------------------------------------------------------------ // // Function: CShapeClipperForFEB::ApplyGuidelines // // Synopsis: // Execute pixel snapping: shift every point in the shape by // small offset (up to 1/2 of pixel), using given CSnappingFrame. // //------------------------------------------------------------------------- MIL_FORCEINLINE HRESULT CShapeClipperForFEB::ApplyGuidelines( __in_ecount_opt(1) CSnappingFrame *pSnappingFrame, __inout_ecount(1) CShape *pScratchShape ) { return pSnappingFrame && !pSnappingFrame->IsEmpty() ? DoApplyGuidelines(pSnappingFrame, pScratchShape) : S_OK; }
1,634
749
#!/usr/bin/env python3 import pkg_resources extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx_autodoc_typehints' ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'AnyIO' author = '<NAME>' copyright = '2018, ' + author v = pkg_resources.get_distribution('anyio').parsed_version version = v.base_version release = v.public language = None exclude_patterns = ['_build'] pygments_style = 'sphinx' autodoc_default_options = { 'members': True, 'show-inheritance': True } todo_include_todos = False html_theme = 'sphinx_rtd_theme' html_static_path = ['_static'] htmlhelp_basename = 'anyiodoc' intersphinx_mapping = {'python': ('https://docs.python.org/3/', None)}
300
5,169
{ "name": "RoomKit", "version": "0.1.3", "swift_version": "4.0", "summary": "RoomKit is a framework that allows for you to train and then use a model of bluetooth signals in the rooms of a space.", "description": "RoomKit is a framework that allows for you to train and then use a model of bluetooth signals in the rooms of a space. The framework will comunicate with the a server than handles all the machine learning and will use a bluetooth beacon library to get signal strengths.", "homepage": "https://github.com/dali-lab/RoomKit", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "johnlev": "<EMAIL>" }, "source": { "git": "https://github.com/dali-lab/RoomKit.git", "tag": "0.1.3" }, "platforms": { "ios": "8.0" }, "source_files": "RoomKit/Classes/**/*", "dependencies": { "SwiftyJSON": [ ] } }
316
460
/* * Copyright (C) 2009 Google 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WorkerThreadableLoader_h #define WorkerThreadableLoader_h #if ENABLE(WORKERS) #include "PlatformString.h" #include "ThreadableLoader.h" #include "ThreadableLoaderClient.h" #include "ThreadableLoaderClientWrapper.h" #include <wtf/PassOwnPtr.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/RefPtr.h> #include <wtf/Threading.h> namespace WebCore { class ResourceError; class ResourceRequest; class WorkerContext; class WorkerLoaderProxy; struct CrossThreadResourceResponseData; struct CrossThreadResourceRequestData; class WorkerThreadableLoader : public RefCounted<WorkerThreadableLoader>, public ThreadableLoader { public: static void loadResourceSynchronously(WorkerContext*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&); static PassRefPtr<WorkerThreadableLoader> create(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options) { return adoptRef(new WorkerThreadableLoader(workerContext, client, taskMode, request, options)); } ~WorkerThreadableLoader(); virtual void cancel(); bool done() const { return m_workerClientWrapper->done(); } using RefCounted<WorkerThreadableLoader>::ref; using RefCounted<WorkerThreadableLoader>::deref; protected: virtual void refThreadableLoader() { ref(); } virtual void derefThreadableLoader() { deref(); } private: // Creates a loader on the main thread and bridges communication between // the main thread and the worker context's thread where WorkerThreadableLoader runs. // // Regarding the bridge and lifetimes of items used in callbacks, there are a few cases: // // all cases. All tasks posted from the worker context's thread are ok because // the last task posted always is "mainThreadDestroy", so MainThreadBridge is // around for all tasks that use it on the main thread. // // case 1. worker.terminate is called. // In this case, no more tasks are posted from the worker object's thread to the worker // context's thread -- WorkerContextProxy implementation enforces this. // // case 2. xhr gets aborted and the worker context continues running. // The ThreadableLoaderClientWrapper has the underlying client cleared, so no more calls // go through it. All tasks posted from the worker object's thread to the worker context's // thread do "ThreadableLoaderClientWrapper::ref" (automatically inside of the cross thread copy // done in createCallbackTask), so the ThreadableLoaderClientWrapper instance is there until all // tasks are executed. class MainThreadBridge : public ThreadableLoaderClient { public: // All executed on the worker context's thread. MainThreadBridge(PassRefPtr<ThreadableLoaderClientWrapper>, WorkerLoaderProxy&, const String& taskMode, const ResourceRequest&, const ThreadableLoaderOptions&); void cancel(); void destroy(); private: // Executed on the worker context's thread. void clearClientWrapper(); // All executed on the main thread. static void mainThreadDestroy(ScriptExecutionContext*, MainThreadBridge*); ~MainThreadBridge(); static void mainThreadCreateLoader(ScriptExecutionContext*, MainThreadBridge*, PassOwnPtr<CrossThreadResourceRequestData>, ThreadableLoaderOptions); static void mainThreadCancel(ScriptExecutionContext*, MainThreadBridge*); virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent); virtual void didReceiveResponse(const ResourceResponse&); virtual void didReceiveData(const char*, int lengthReceived); virtual void didFinishLoading(unsigned long identifier); virtual void didFail(const ResourceError&); virtual void didFailRedirectCheck(); virtual void didReceiveAuthenticationCancellation(const ResourceResponse&); // Only to be used on the main thread. RefPtr<ThreadableLoader> m_mainThreadLoader; // ThreadableLoaderClientWrapper is to be used on the worker context thread. // The ref counting is done on either thread. RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper; // May be used on either thread. WorkerLoaderProxy& m_loaderProxy; // For use on the main thread. String m_taskMode; }; WorkerThreadableLoader(WorkerContext*, ThreadableLoaderClient*, const String& taskMode, const ResourceRequest&, const ThreadableLoaderOptions&); RefPtr<WorkerContext> m_workerContext; RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper; MainThreadBridge& m_bridge; }; } // namespace WebCore #endif // ENABLE(WORKERS) #endif // WorkerThreadableLoader_h
2,390
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.j2seplatform.platformdefinition; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.List; import java.util.ArrayList; import org.netbeans.api.java.platform.JavaPlatform; import org.netbeans.modules.java.platform.implspi.JavaPlatformProvider; /** * * @author tom */ public final class JavaPlatformProviderImpl implements JavaPlatformProvider { private PropertyChangeSupport support; private List<JavaPlatform> platforms; private JavaPlatform defaultPlatform; /** Creates a new instance of JavaPlatformProviderImpl */ public JavaPlatformProviderImpl() { this.support = new PropertyChangeSupport (this); this.platforms = new ArrayList<JavaPlatform>(); this.addPlatform (this.createDefaultPlatform()); } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { this.support.addPropertyChangeListener(listener); } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { this.support.removePropertyChangeListener (listener); } public void addPlatform (JavaPlatform platform) { this.platforms.add (platform); this.support.firePropertyChange(PROP_INSTALLED_PLATFORMS, null, null); } public void removePlatform (JavaPlatform platform) { this.platforms.remove(platform); this.support.firePropertyChange(PROP_INSTALLED_PLATFORMS, null, null); } @Override public JavaPlatform[] getInstalledPlatforms() { return this.platforms.toArray(new JavaPlatform[this.platforms.size()]); } @Override public JavaPlatform getDefaultPlatform() { return createDefaultPlatform (); } private synchronized JavaPlatform createDefaultPlatform () { if (this.defaultPlatform == null) { System.getProperties().put("jdk.home",System.getProperty("java.home")); //NOI18N this.defaultPlatform = DefaultPlatformImpl.create (null,null,null); } return defaultPlatform; } }
939
5,169
{ "name": "AgoraRtcEngine_iOS_temp", "version": "1.4.4.1", "summary": "Agora iOS Rtm SDK", "description": "iOS library for agora real-time message communication and broadcasting service.", "homepage": "https://www.agora.io/en/blog/download/", "license": { "type": "Copyright", "text": "Copyright 2019 agora.io. All rights reserved.\n" }, "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "http": "https://download.agora.io/rtmsdk/release/RTM_Test_1.4.4.1.zip" }, "vendored_frameworks": "AgoraRtmKit.framework", "frameworks": [ "CoreTelephony", "SystemConfiguration" ], "libraries": [ "c++", "resolv" ], "requires_arc": true }
302
2,322
/* * browseui - Internet Explorer / Windows Explorer standard UI * * Copyright 2001 <NAME> (for CodeWeavers) * Copyright 2004 <NAME> (for CodeWeavers) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include <stdarg.h> #include <stdio.h> #define COBJMACROS #include "wine/debug.h" #include "windef.h" #include "winbase.h" #include "winreg.h" #include "shlwapi.h" #include "shlguid.h" #include "rpcproxy.h" #include "wine/heap.h" #include "browseui.h" #include "initguid.h" DEFINE_GUID(CLSID_CompCatCacheDaemon, 0x8C7461EF, 0x2b13, 0x11d2, 0xbe, 0x35, 0x30, 0x78, 0x30, 0x2c, 0x20, 0x30); WINE_DEFAULT_DEBUG_CHANNEL(browseui); LONG BROWSEUI_refCount = 0; HINSTANCE BROWSEUI_hinstance = 0; typedef HRESULT (*LPFNCONSTRUCTOR)(IUnknown *pUnkOuter, IUnknown **ppvOut); static const struct { REFCLSID clsid; LPFNCONSTRUCTOR ctor; } ClassesTable[] = { {&CLSID_ACLMulti, ACLMulti_Constructor}, {&CLSID_ProgressDialog, ProgressDialog_Constructor}, {&CLSID_CompCatCacheDaemon, CompCatCacheDaemon_Constructor}, {&CLSID_ACListISF, ACLShellSource_Constructor}, {NULL, NULL} }; typedef struct tagClassFactory { IClassFactory IClassFactory_iface; LONG ref; LPFNCONSTRUCTOR ctor; } ClassFactory; static inline ClassFactory *impl_from_IClassFactory(IClassFactory *iface) { return CONTAINING_RECORD(iface, ClassFactory, IClassFactory_iface); } static void ClassFactory_Destructor(ClassFactory *This) { TRACE("Destroying class factory %p\n", This); heap_free(This); InterlockedDecrement(&BROWSEUI_refCount); } static HRESULT WINAPI ClassFactory_QueryInterface(IClassFactory *iface, REFIID riid, LPVOID *ppvOut) { *ppvOut = NULL; if (IsEqualIID(riid, &IID_IClassFactory) || IsEqualIID(riid, &IID_IUnknown)) { IClassFactory_AddRef(iface); *ppvOut = iface; return S_OK; } WARN("Unknown interface %s\n", debugstr_guid(riid)); return E_NOINTERFACE; } static ULONG WINAPI ClassFactory_AddRef(IClassFactory *iface) { ClassFactory *This = impl_from_IClassFactory(iface); return InterlockedIncrement(&This->ref); } static ULONG WINAPI ClassFactory_Release(IClassFactory *iface) { ClassFactory *This = impl_from_IClassFactory(iface); ULONG ret = InterlockedDecrement(&This->ref); if (ret == 0) ClassFactory_Destructor(This); return ret; } static HRESULT WINAPI ClassFactory_CreateInstance(IClassFactory *iface, IUnknown *punkOuter, REFIID iid, LPVOID *ppvOut) { ClassFactory *This = impl_from_IClassFactory(iface); HRESULT ret; IUnknown *obj; TRACE("(%p, %p, %s, %p)\n", iface, punkOuter, debugstr_guid(iid), ppvOut); ret = This->ctor(punkOuter, &obj); if (FAILED(ret)) return ret; ret = IUnknown_QueryInterface(obj, iid, ppvOut); IUnknown_Release(obj); return ret; } static HRESULT WINAPI ClassFactory_LockServer(IClassFactory *iface, BOOL fLock) { ClassFactory *This = impl_from_IClassFactory(iface); TRACE("(%p)->(%x)\n", This, fLock); if(fLock) InterlockedIncrement(&BROWSEUI_refCount); else InterlockedDecrement(&BROWSEUI_refCount); return S_OK; } static const IClassFactoryVtbl ClassFactoryVtbl = { /* IUnknown */ ClassFactory_QueryInterface, ClassFactory_AddRef, ClassFactory_Release, /* IClassFactory*/ ClassFactory_CreateInstance, ClassFactory_LockServer }; static HRESULT ClassFactory_Constructor(LPFNCONSTRUCTOR ctor, LPVOID *ppvOut) { ClassFactory *This = heap_alloc(sizeof(ClassFactory)); This->IClassFactory_iface.lpVtbl = &ClassFactoryVtbl; This->ref = 1; This->ctor = ctor; *ppvOut = &This->IClassFactory_iface; TRACE("Created class factory %p\n", This); InterlockedIncrement(&BROWSEUI_refCount); return S_OK; } /************************************************************************* * BROWSEUI DllMain */ BOOL WINAPI DllMain(HINSTANCE hinst, DWORD fdwReason, LPVOID fImpLoad) { TRACE("%p 0x%x %p\n", hinst, fdwReason, fImpLoad); switch (fdwReason) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hinst); BROWSEUI_hinstance = hinst; break; } return TRUE; } /************************************************************************* * DllCanUnloadNow (BROWSEUI.@) */ HRESULT WINAPI DllCanUnloadNow(void) { return BROWSEUI_refCount ? S_FALSE : S_OK; } /*********************************************************************** * DllGetVersion (BROWSEUI.@) */ HRESULT WINAPI DllGetVersion(DLLVERSIONINFO *info) { if(info->cbSize == sizeof(DLLVERSIONINFO) || info->cbSize == sizeof(DLLVERSIONINFO2)) { /* this is what IE6 on Windows 98 reports */ info->dwMajorVersion = 6; info->dwMinorVersion = 0; info->dwBuildNumber = 2600; info->dwPlatformID = DLLVER_PLATFORM_WINDOWS; if(info->cbSize == sizeof(DLLVERSIONINFO2)) { DLLVERSIONINFO2 *info2 = (DLLVERSIONINFO2*) info; info2->dwFlags = 0; info2->ullVersion = MAKEDLLVERULL(info->dwMajorVersion, info->dwMinorVersion, info->dwBuildNumber, 0); /* FIXME: correct hotfix number */ } return S_OK; } WARN("wrong DLLVERSIONINFO size from app.\n"); return E_INVALIDARG; } /*********************************************************************** * DllGetClassObject (BROWSEUI.@) */ HRESULT WINAPI DllGetClassObject(REFCLSID clsid, REFIID iid, LPVOID *ppvOut) { int i; *ppvOut = NULL; if (!IsEqualIID(iid, &IID_IUnknown) && !IsEqualIID(iid, &IID_IClassFactory)) return E_NOINTERFACE; for (i = 0; ClassesTable[i].clsid != NULL; i++) if (IsEqualCLSID(ClassesTable[i].clsid, clsid)) { return ClassFactory_Constructor(ClassesTable[i].ctor, ppvOut); } FIXME("CLSID %s not supported\n", debugstr_guid(clsid)); return CLASS_E_CLASSNOTAVAILABLE; } /*********************************************************************** * DllInstall (BROWSEUI.@) */ HRESULT WINAPI DllInstall(BOOL bInstall, LPCWSTR cmdline) { FIXME("(%s, %s): stub\n", bInstall ? "TRUE" : "FALSE", debugstr_w(cmdline)); return S_OK; }
2,903
27,066
package com.xkcoding.websocket.socketio.config; /** * <p> * 事件常量 * </p> * * @author yangkai.shen * @date Created in 2018-12-18 19:36 */ public interface Event { /** * 聊天事件 */ String CHAT = "chat"; /** * 广播消息 */ String BROADCAST = "broadcast"; /** * 群聊 */ String GROUP = "group"; /** * 加入群聊 */ String JOIN = "join"; }
228
852
<reponame>ckamtsikis/cmssw import argparse import subprocess import signal, fcntl import sys, os, time # dup and close stdin/stdout stdin_ = os.dup(sys.stdin.fileno()) stdout_ = os.dup(sys.stdout.fileno()) sys.stdin.close() sys.stdout.close() class Timeout(IOError): pass def alarm_handler(signum, frame): if signum != 14: return raise Timeout("Timeout reached.") signal.signal(signal.SIGALRM, alarm_handler) def log(s): sys.stderr.write("watchdog: " + s + "\n"); sys.stderr.flush() def launch(args): fd, wd = os.pipe() def preexec(): os.close(fd) env = os.environ env["WATCHDOG_FD"] = str(wd) p = subprocess.Popen(args.pargs, preexec_fn=preexec, stdin=stdin_, stdout=stdout_) os.close(wd) while True: try: signal.alarm(args.t) ch = os.read(fd, 1024) signal.alarm(0) if not ch: os.close(fd) return False, p.wait() # normal exit log("Received: %s, timer reset." % repr(ch)) except Timeout as t: signal.alarm(0) log("Timeout reached, taking action.") if p.poll() is None: p.send_signal(args.action) os.close(fd) return True, p.wait() for p in open_procs_: if p.poll() is None: p.send_signal(sig) def main(args): while True: killed, ret = launch(args) log("Program exitted, killed: %s, code: %d." % (killed, ret, )) if killed and args.restart: log("Restarting.") continue break parser = argparse.ArgumentParser(description="Kill/restart the child process if it doesn't out the required string.") parser.add_argument("-t", type=int, default="2", help="Timeout in seconds.") parser.add_argument("-s", type=int, default="2000", help="Signal to send.") parser.add_argument("-r", "--restart", action="store_true", default=False, help="Restart the process after killing it.") parser.add_argument("pargs", nargs=argparse.REMAINDER) group = parser.add_mutually_exclusive_group() group.add_argument('--term', action='store_const', dest="action", const=signal.SIGTERM, default=signal.SIGTERM) group.add_argument('--kill', action='store_const', dest="action", const=signal.SIGKILL) if __name__ == "__main__": args = parser.parse_args() #log("Args: %s." % str(args)) main(args)
1,119
14,668
<filename>chrome/credential_provider/gaiacp/gaia_credential_provider_module.h<gh_stars>1000+ // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_CREDENTIAL_PROVIDER_GAIACP_GAIA_CREDENTIAL_PROVIDER_MODULE_H_ #define CHROME_CREDENTIAL_PROVIDER_GAIACP_GAIA_CREDENTIAL_PROVIDER_MODULE_H_ // Due to windows include file ordering, this needs to remain first. #include "chrome/credential_provider/gaiacp/stdafx.h" #include "chrome/credential_provider/gaiacp/gaia_credential_provider_i.h" #include "chrome/credential_provider/gaiacp/scoped_handle.h" #include "base/at_exit.h" namespace base { class AtExitManager; } namespace credential_provider { // Declaration of Afx module class for this DLL. class CGaiaCredentialProviderModule : public ATL::CAtlDllModuleT<CGaiaCredentialProviderModule> { public: CGaiaCredentialProviderModule(); ~CGaiaCredentialProviderModule() override; DECLARE_LIBID(LIBID_GaiaCredentialProviderLib) // This class implements UpdateRegistryAppId() directly instead of using the // the DECLARE_REGISTRY_APPID_RESOURCEID so that it can use additional rgs // file variable substitutions. static HRESULT WINAPI UpdateRegistryAppId(BOOL do_register) throw(); // Called from DLL entry point to handle attaching and detaching from // processes and threads. BOOL DllMain(HINSTANCE hinstance, DWORD reason, LPVOID reserved); // Indicates if the instance is running in a test. void set_is_testing(bool is_testing) { is_testing_ = is_testing; } // Performs a one time refresh of all valid token handles to ensure their // validity is up to date. void RefreshTokenHandleValidity(); // Fires a thread and checks the status of GCPW extensioon and runs it if not // running. void CheckGCPWExtension(); // Initializes the crash reporting for the module. Initialization happens only // once even if the function is called multiple times. void InitializeCrashReporting(); // Logs the details of the module such as version, loading process. void LogProcessDetails(); private: std::unique_ptr<base::AtExitManager> exit_manager_; bool is_testing_ = false; bool token_handle_validity_refreshed_ = false; base::win::ScopedHandle::Handle gcpw_extension_checker_thread_handle_; volatile long gcpw_extension_check_performed_; volatile long crashpad_initialized_ = 0; }; } // namespace credential_provider #endif // CHROME_CREDENTIAL_PROVIDER_GAIACP_GAIA_CREDENTIAL_PROVIDER_MODULE_H_
826
7,482
<reponame>Davidfind/rt-thread /*""FILE COMMENT""******************************************************* * System Name : Voltage detection circuit API for RX62Nxx * File Name : r_pdl_lvd.h * Version : 1.02 * Contents : LVD API header * Customer : * Model : * Order : * CPU : RX * Compiler : RXC * OS : Nothing * Programmer : * Note : ************************************************************************ * Copyright, 2011. Renesas Electronics Corporation * and Renesas Solutions Corporation ************************************************************************ * History : 2011.04.08 * : Ver 1.02 * : CS-5 release. *""FILE COMMENT END""**************************************************/ #ifndef R_PDL_LVD_H #define R_PDL_LVD_H #include "r_pdl_common_defs_RX62Nxx.h" /* Function prototypes */ bool LVD_Control( uint8_t ); /* LVD2 and LVD1 control */ #define PDL_LVD_VDET2_DISABLE_VDET1_DISABLE 0x01u #define PDL_LVD_VDET2_DISABLE_VDET1_RESET 0x02u #define PDL_LVD_VDET2_DISABLE_VDET1_INTERRUPT 0x04u #define PDL_LVD_VDET2_RESET_VDET1_DISABLE 0x08u #define PDL_LVD_VDET2_INTERRUPT_VDET1_DISABLE 0x10u #define PDL_LVD_VDET2_INTERRUPT_VDET1_RESET 0x20u #endif /* End of file */
474
348
{"nom":"Saunières","circ":"3ème circonscription","dpt":"Saône-et-Loire","inscrits":72,"abs":35,"votants":37,"blancs":6,"nuls":0,"exp":31,"res":[{"nuance":"REM","nom":"<NAME>","voix":21},{"nuance":"LR","nom":"M. <NAME>","voix":10}]}
98
1,408
/* * Copyright (c) 2016, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef PMU_H #define PMU_H /* Allocate sp reginon in pmusram */ #define PSRAM_SP_SIZE 0x80 #define PSRAM_SP_BOTTOM (PSRAM_SP_TOP - PSRAM_SP_SIZE) /***************************************************************************** * pmu con,reg *****************************************************************************/ #define PMU_WKUP_CFG0 0x0 #define PMU_WKUP_CFG1 0x4 #define PMU_WKUP_CFG2 0x8 #define PMU_TIMEOUT_CNT 0x7c #define PMU_PWRDN_CON 0xc #define PMU_PWRDN_ST 0x10 #define PMU_CORE_PWR_ST 0x38 #define PMU_PWRMD_CORE 0x14 #define PMU_PWRMD_COM 0x18 #define PMU_SFT_CON 0x1c #define PMU_BUS_IDE_REQ 0x3c #define PMU_BUS_IDE_ST 0x40 #define PMU_OSC_CNT 0x48 #define PMU_PLLLOCK_CNT 0x4c #define PMU_PLLRST_CNT 0x50 #define PMU_STABLE_CNT 0x54 #define PMU_DDRIO_PWR_CNT 0x58 #define PMU_WKUPRST_CNT 0x5c enum pmu_powermode_core { pmu_mdcr_global_int_dis = 0, pmu_mdcr_core_src_gt, pmu_mdcr_clr_cci, pmu_mdcr_cpu0_pd, pmu_mdcr_clr_clst_l = 4, pmu_mdcr_clr_core, pmu_mdcr_scu_l_pd, pmu_mdcr_core_pd, pmu_mdcr_l2_idle = 8, pmu_mdcr_l2_flush }; /* * the shift of bits for cores status */ enum pmu_core_pwrst_shift { clstl_cpu_wfe = 2, clstl_cpu_wfi = 6, clstb_cpu_wfe = 12, clstb_cpu_wfi = 16 }; enum pmu_pdid { PD_CPUL0 = 0, PD_CPUL1, PD_CPUL2, PD_CPUL3, PD_SCUL, PD_CPUB0 = 5, PD_CPUB1, PD_CPUB2, PD_CPUB3, PD_SCUB = 9, PD_PERI = 13, PD_VIDEO, PD_VIO, PD_GPU0, PD_GPU1, PD_END }; enum pmu_bus_ide { bus_ide_req_clst_l = 0, bus_ide_req_clst_b, bus_ide_req_gpu, bus_ide_req_core, bus_ide_req_bus = 4, bus_ide_req_dma, bus_ide_req_peri, bus_ide_req_video, bus_ide_req_vio = 8, bus_ide_req_res0, bus_ide_req_cxcs, bus_ide_req_alive, bus_ide_req_pmu = 12, bus_ide_req_msch, bus_ide_req_cci, bus_ide_req_cci400 = 15, bus_ide_req_end }; enum pmu_powermode_common { pmu_mode_en = 0, pmu_mode_res0, pmu_mode_bus_pd, pmu_mode_wkup_rst, pmu_mode_pll_pd = 4, pmu_mode_pwr_off, pmu_mode_pmu_use_if, pmu_mode_pmu_alive_use_if, pmu_mode_osc_dis = 8, pmu_mode_input_clamp, pmu_mode_sref_enter, pmu_mode_ddrc_gt, pmu_mode_ddrio_ret = 12, pmu_mode_ddrio_ret_deq, pmu_mode_clr_pmu, pmu_mode_clr_alive, pmu_mode_clr_bus = 16, pmu_mode_clr_dma, pmu_mode_clr_msch, pmu_mode_clr_peri, pmu_mode_clr_video = 20, pmu_mode_clr_vio, pmu_mode_clr_gpu, pmu_mode_clr_mcu, pmu_mode_clr_cxcs = 24, pmu_mode_clr_cci400, pmu_mode_res1, pmu_mode_res2, pmu_mode_res3 = 28, pmu_mode_mclst }; enum pmu_core_power_st { clst_l_cpu_wfe = 2, clst_l_cpu_wfi = 6, clst_b_l2_flsh_done = 10, clst_b_l2_wfi = 11, clst_b_cpu_wfe = 12, clst_b_cpu_wfi = 16, mcu_sleeping = 20, }; enum pmu_sft_con { pmu_sft_acinactm_clst_b = 5, pmu_sft_l2flsh_clst_b, pmu_sft_glbl_int_dis_b = 9, pmu_sft_ddrio_ret_cfg = 11, }; enum pmu_wkup_cfg2 { pmu_cluster_l_wkup_en = 0, pmu_cluster_b_wkup_en, pmu_gpio_wkup_en, pmu_sdio_wkup_en, pmu_sdmmc_wkup_en, pmu_sim_wkup_en, pmu_timer_wkup_en, pmu_usbdev_wkup_en, pmu_sft_wkup_en, pmu_wdt_mcu_wkup_en, pmu_timeout_wkup_en, }; enum pmu_bus_idle_st { pmu_idle_ack_cluster_l = 0, pmu_idle_ack_cluster_b, pmu_idle_ack_gpu, pmu_idle_ack_core, pmu_idle_ack_bus, pmu_idle_ack_dma, pmu_idle_ack_peri, pmu_idle_ack_video, pmu_idle_ack_vio, pmu_idle_ack_cci = 10, pmu_idle_ack_msch, pmu_idle_ack_alive, pmu_idle_ack_pmu, pmu_idle_ack_cxcs, pmu_idle_ack_cci400, pmu_inactive_cluster_l, pmu_inactive_cluster_b, pmu_idle_gpu, pmu_idle_core, pmu_idle_bus, pmu_idle_dma, pmu_idle_peri, pmu_idle_video, pmu_idle_vio, pmu_idle_cci = 26, pmu_idle_msch, pmu_idle_alive, pmu_idle_pmu, pmu_active_cxcs, pmu_active_cci, }; #define PM_PWRDM_CPUSB_MSK (0xf << 5) #define CKECK_WFE_MSK 0x1 #define CKECK_WFI_MSK 0x10 #define CKECK_WFEI_MSK 0x11 #define PD_CTR_LOOP 500 #define CHK_CPU_LOOP 500 #define MAX_WAIT_CONUT 1000 #endif /* PMU_H */
2,280
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.beaninfo.editors; import java.beans.PropertyEditorSupport; // bugfix# 9219 for attachEnv() method import org.openide.explorer.propertysheet.ExPropertyEditor; import org.openide.explorer.propertysheet.PropertyEnv; import java.beans.FeatureDescriptor; import org.openide.nodes.Node; import org.openide.util.NbBundle; /** * A property editor for String class. * @author <NAME> */ public class StringEditor extends PropertyEditorSupport implements ExPropertyEditor { private static boolean useRaw = Boolean.getBoolean("netbeans.stringEditor.useRawCharacters"); // bugfix# 9219 added editable field and isEditable() "getter" to be used in StringCustomEditor private boolean editable=true; /** gets information if the text in editor should be editable or not */ public boolean isEditable(){ return (editable); } @Override public String getAsText() { Object value = getValue(); if (value != null) { return value.toString(); } else { return nullValue != null ? nullValue : NbBundle.getMessage(StringEditor.class, "CTL_NullValue"); } } /** sets new value */ @Override public void setAsText(String s) { if ( "null".equals( s ) && getValue() == null ) // NOI18N return; if (nullValue != null && nullValue.equals (s)) { setValue (null); return; } setValue(s); } @Override public String getJavaInitializationString () { String s = (String) getValue (); return "\"" + toAscii(s) + "\""; // NOI18N } @Override public boolean supportsCustomEditor () { return customEd; } @Override public java.awt.Component getCustomEditor () { Object val = getValue(); String s = ""; // NOI18N if (val != null) { s = val instanceof String ? (String) val : val.toString(); } return new StringCustomEditor (s, isEditable(), oneline, instructions, this, env); } private static String toAscii(String str) { StringBuilder buf = new StringBuilder(str.length() * 6); // x -> \u1234 char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; switch (c) { case '\b': buf.append("\\b"); break; // NOI18N case '\t': buf.append("\\t"); break; // NOI18N case '\n': buf.append("\\n"); break; // NOI18N case '\f': buf.append("\\f"); break; // NOI18N case '\r': buf.append("\\r"); break; // NOI18N case '\"': buf.append("\\\""); break; // NOI18N // case '\'': buf.append("\\'"); break; // NOI18N case '\\': buf.append("\\\\"); break; // NOI18N default: if (c >= 0x0020 && (useRaw || c <= 0x007f)) buf.append(c); else { buf.append("\\u"); // NOI18N String hex = Integer.toHexString(c); for (int j = 0; j < 4 - hex.length(); j++) buf.append('0'); buf.append(hex); } } } return buf.toString(); } private String instructions=null; private boolean oneline=false; private boolean customEd=false; // until PropertyEnv is attached private PropertyEnv env; /** null or name to use for null value */ private String nullValue; // bugfix# 9219 added attachEnv() method checking if the user canWrite in text box @Override public void attachEnv(PropertyEnv env) { this.env = env; readEnv(env.getFeatureDescriptor()); } /*@VisibleForTesting*/ void readEnv (FeatureDescriptor desc) { if (desc instanceof Node.Property){ Node.Property prop = (Node.Property)desc; editable = prop.canWrite(); //enh 29294 - support one-line editor & suppression of custom //editor instructions = (String) prop.getValue ("instructions"); //NOI18N oneline = Boolean.TRUE.equals (prop.getValue ("oneline")); //NOI18N customEd = !Boolean.TRUE.equals (prop.getValue ("suppressCustomEditor")); //NOI18N } Object obj = desc.getValue(ObjectEditor.PROP_NULL); if (Boolean.TRUE.equals(obj)) { nullValue = NbBundle.getMessage(StringEditor.class, "CTL_NullValue"); } else { if (obj instanceof String) { nullValue = (String)obj; } else { nullValue = null; } } } }
2,329
892
<filename>advisories/unreviewed/2022/05/GHSA-w7r2-35m5-84qx/GHSA-w7r2-35m5-84qx.json { "schema_version": "1.2.0", "id": "GHSA-w7r2-35m5-84qx", "modified": "2022-05-02T03:50:02Z", "published": "2022-05-02T03:50:02Z", "aliases": [ "CVE-2009-3945" ], "details": "Unspecified vulnerability in the Front-End Editor in the com_content component in Joomla! before 1.5.15 allows remote authenticated users, with Author privileges, to replace the articles of an arbitrary user via unknown vectors.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2009-3945" }, { "type": "WEB", "url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/54161" }, { "type": "WEB", "url": "http://developer.joomla.org/security/news/305-20091103-core-front-end-editor-issue-.html" }, { "type": "WEB", "url": "http://osvdb.org/59801" }, { "type": "WEB", "url": "http://secunia.com/advisories/37262" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
551
747
// // mgsort.c // Algorithms - Merge sort // // Created by YourtionGuo on 11/05/2017. // Copyright © 2017 Yourtion. All rights reserved. // #include <stdlib.h> #include <string.h> #include "sort.h" #pragma mark - Private /** 将两个有序集合并成一个有序集 @param data 数据数组 @param esize 每个元素的大小 @param i 元素分区起点 @param j 元素中间元素位置 @param k 元素分区终点 @param compare 函数指针,用于比较两个成员大小(大于返回 1,小于返回 -1,等于返回 0) @return 成功返回 0;否则返回 -1 */ static int merge(void *data, int esize, int i, int j, int k, int (*compare)(const void *key1, const void *key2)) { char *a = data, *m; int ipos, jpos, mpos; /// 初始化合并过程使用的计数器 ipos = i; jpos = j + 1; mpos = 0; /// 创建用于合并数组的空间 if ((m = (char *)malloc(esize * ((k - i) + 1))) == NULL) return -1; /// 执行合并直到没有数据 while (ipos <= j || jpos <= k) { if (ipos > j) { /// 左半部分还有元素 while (jpos <= k) { memcpy(&m[mpos * esize], &a[jpos * esize], esize); jpos++; mpos++; } continue; } else if (jpos > k) { /// 右半部分还有元素 while (ipos <= j) { memcpy(&m[mpos * esize], &a[ipos * esize], esize); ipos++; mpos++; } continue; } /// 添加下一个元素到已排序数组 if (compare(&a[ipos * esize], &a[jpos * esize]) < 0) { memcpy(&m[mpos * esize], &a[ipos * esize], esize); ipos++; mpos++; } else { memcpy(&m[mpos * esize], &a[jpos * esize], esize); jpos++; mpos++; } } /// 将已排序数据放回 memcpy(&a[i * esize], m, esize * ((k - i) + 1)); /// 销毁用于排序的临时空间 free(m); return 0; } #pragma mark - Public int mgsort(void *data, int size, int esize, int i, int k, int (*compare)(const void *key1, const void *key2)) { int j; /// 当没有元素可以分割则停止递归 if (i < k) { /// 确定元素分割点 j = (int)(((i + k - 1)) / 2); /// 递归对两部分执行归并排序 if (mgsort(data, size, esize, i, j, compare) < 0) return -1; if (mgsort(data, size, esize, j + 1, k, compare) < 0) return -1; /// 合并两个已排序白部分 if (merge(data, esize, i, j, k, compare) < 0) return -1; } return 0; } int mgsrt(void *data, int size, int esize, int (*compare)(const void *key1, const void *key2)) { return mgsort(data, size, esize, 0, size - 1, compare); }
1,461
1,762
/* * Copyright (C) 2007-2008 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * * File Name: omxVCM4P10_TransformQuant_LumaDC.c * OpenMAX DL: v1.0.2 * Revision: 9641 * Date: Thursday, February 7, 2008 * * * * Description: * This function will calculate 4x4 hadamard transform of luma DC coefficients * and quantization * */ #include "omxtypes.h" #include "armOMX.h" #include "omxVC.h" #include "armCOMM.h" #include "armVC.h" /** * Function: omxVCM4P10_TransformQuant_LumaDC (6.3.5.6.2) * * Description: * This function performs a 4x4 Hadamard transform of luma DC coefficients * and then quantizes the coefficients. * * Input Arguments: * * pSrcDst - Pointer to the 4x4 array of luma DC coefficients. 16-byte * alignment required. * iQP - Quantization parameter; must be in the range [0,51]. * * Output Arguments: * * pSrcDst - Pointer to transformed and quantized coefficients. 16-byte * alignment required. * * Return Value: * * OMX_Sts_NoErr - no error * OMX_Sts_BadArgErr - bad arguments; returned if any of the following * conditions are true: * - at least one of the following pointers is NULL: pSrcDst * - pSrcDst is not aligned on an 16-byte boundary * */ OMXResult omxVCM4P10_TransformQuant_LumaDC( OMX_S16* pSrcDst, OMX_U32 iQP ) { OMX_INT i, j; OMX_S32 m1[4][4], m2[4][4]; OMX_S32 Value; OMX_U32 QbitsPlusOne, Two_f, MF; /* Check for argument error */ armRetArgErrIf(pSrcDst == NULL, OMX_Sts_BadArgErr); armRetArgErrIf(armNot16ByteAligned(pSrcDst), OMX_Sts_BadArgErr); armRetArgErrIf(iQP > 51, OMX_Sts_BadArgErr); /* Hadamard Transform for 4x4 block */ /* Horizontal Hadamard */ for (i = 0; i < 4; i++) { j = i * 4; m1[i][0] = pSrcDst[j + 0] + pSrcDst[j + 2]; /* a+c */ m1[i][1] = pSrcDst[j + 1] + pSrcDst[j + 3]; /* b+d */ m1[i][2] = pSrcDst[j + 0] - pSrcDst[j + 2]; /* a-c */ m1[i][3] = pSrcDst[j + 1] - pSrcDst[j + 3]; /* b-d */ m2[i][0] = m1[i][0] + m1[i][1]; /* a+b+c+d */ m2[i][1] = m1[i][2] + m1[i][3]; /* a+b-c-d */ m2[i][2] = m1[i][2] - m1[i][3]; /* a-b-c+d */ m2[i][3] = m1[i][0] - m1[i][1]; /* a-b+c-d */ } /* Vertical */ for (i = 0; i < 4; i++) { m1[0][i] = m2[0][i] + m2[2][i]; m1[1][i] = m2[1][i] + m2[3][i]; m1[2][i] = m2[0][i] - m2[2][i]; m1[3][i] = m2[1][i] - m2[3][i]; m2[0][i] = m1[0][i] + m1[1][i]; m2[1][i] = m1[2][i] + m1[3][i]; m2[2][i] = m1[2][i] - m1[3][i]; m2[3][i] = m1[0][i] - m1[1][i]; } /* Quantization */ QbitsPlusOne = ARM_M4P10_Q_OFFSET + 1 + (iQP / 6); /*floor (QP/6)*/ Two_f = (1 << QbitsPlusOne) / 3; /* 3->INTRA, 6->INTER */ MF = armVCM4P10_MFMatrix [iQP % 6][0]; /* Scaling */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { Value = (armAbs((m2[j][i]/* + 1*/) / 2) * MF + Two_f) >> QbitsPlusOne; pSrcDst[j * 4 + i] = (OMX_S16)((m2[j][i] < 0) ? -Value : Value); } } return OMX_Sts_NoErr; } /***************************************************************************** * END OF FILE *****************************************************************************/
1,908
506
// https://cses.fi/problemset/task/1196/ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef tuple<ll,ll>ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vii> vvii; typedef priority_queue<ii,vii,greater<ii>> pq; int main() { ios::sync_with_stdio(0); cin.tie(0); int n,m,k; cin>>n>>m>>k; vvii g(n); for(int i=0;i<m;i++){ int u,v,w; cin>>u>>v>>w; u--;v--; g[u].push_back({w,v}); } int c=0; vi b(n,0); pq q; q.push({0,0}); while(true){ ll w,u; tie(w,u)=q.top(); q.pop(); if(b[u]>k)continue; if(u==n-1){ c++; cout<<w<<" \n"[c==k]; if(c==k)break; } b[u]++; for(auto z:g[u]){ ll x,v; tie(x,v)=z; if (b[v]>k)continue; q.push({w+x,v}); } } }
471
2,151
<filename>device/fido/device_response_converter.h // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef DEVICE_FIDO_DEVICE_RESPONSE_CONVERTER_H_ #define DEVICE_FIDO_DEVICE_RESPONSE_CONVERTER_H_ #include <stdint.h> #include <vector> #include "base/component_export.h" #include "base/optional.h" #include "device/fido/authenticator_get_assertion_response.h" #include "device/fido/authenticator_get_info_response.h" #include "device/fido/authenticator_make_credential_response.h" #include "device/fido/fido_constants.h" // Converts response from authenticators to CTAPResponse objects. If the // response of the authenticator does not conform to format specified by the // CTAP protocol, null optional is returned. namespace device { // Parses response code from response received from the authenticator. If // unknown response code value is received, then CTAP2_ERR_OTHER is returned. COMPONENT_EXPORT(DEVICE_FIDO) CtapDeviceResponseCode GetResponseCode(base::span<const uint8_t> buffer); // De-serializes CBOR encoded response, checks for valid CBOR map formatting, // and converts response to AuthenticatorMakeCredentialResponse object with // CBOR map keys that conform to format of attestation object defined by the // WebAuthN spec : https://w3c.github.io/webauthn/#fig-attStructs COMPONENT_EXPORT(DEVICE_FIDO) base::Optional<AuthenticatorMakeCredentialResponse> ReadCTAPMakeCredentialResponse(base::span<const uint8_t> buffer); // De-serializes CBOR encoded response to AuthenticatorGetAssertion / // AuthenticatorGetNextAssertion request to AuthenticatorGetAssertionResponse // object. COMPONENT_EXPORT(DEVICE_FIDO) base::Optional<AuthenticatorGetAssertionResponse> ReadCTAPGetAssertionResponse( base::span<const uint8_t> buffer); // De-serializes CBOR encoded response to AuthenticatorGetInfo request to // AuthenticatorGetInfoResponse object. COMPONENT_EXPORT(DEVICE_FIDO) base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer); } // namespace device #endif // DEVICE_FIDO_DEVICE_RESPONSE_CONVERTER_H_
689
311
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://appsec-schema.datadoghq.com/jsonschema/raw/contexts/_definitions/service/service_0.1.0.json", "type": "object", "properties": { "name": { "type": "string" }, "environment": { "type": ["string", "null"] }, "version": { "type": ["string", "null"] } }, "required": [ "name" ] }
189
526
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.conformance.beans; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; import java.util.Date; import java.util.List; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; /** * OpenMetadataConformanceTestLabSummary is a bean for collating the summarized results from a specific test lab. * A test lab contains multiple workbenches. */ @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) public class OpenMetadataConformanceTestLabSummary implements Serializable { private static final long serialVersionUID = 1L; private Date testRunDate = new Date(); private List<OpenMetadataConformanceWorkbenchSummary> testSummariesFromWorkbenches = null; /** * Default constructor */ public OpenMetadataConformanceTestLabSummary() { super(); } /** * Return date that the test was run. * * @return date object */ public Date getTestRunDate() { return testRunDate; } /** * Set up the date of the test. * * @param testRunDate date object */ public void setTestRunDate(Date testRunDate) { this.testRunDate = testRunDate; } /** * Return the list of test summaries from each workbench. * * @return list of workbench summaries */ public List<OpenMetadataConformanceWorkbenchSummary> getTestSummariesFromWorkbenches() { return testSummariesFromWorkbenches; } /** * Set up the list of test summaries from each workbench. * * @param testSummariesFromWorkbenches list of workbench summaries */ public void setTestSummariesFromWorkbenches(List<OpenMetadataConformanceWorkbenchSummary> testSummariesFromWorkbenches) { this.testSummariesFromWorkbenches = testSummariesFromWorkbenches; } /** * toString() JSON-style * * @return string description */ @Override public String toString() { return "OpenMetadataConformanceTestLabSummary{" + "testRunDate=" + testRunDate + ", testSummariesFromWorkbenches=" + testSummariesFromWorkbenches + '}'; } }
1,002
5,939
/* Copyright 2015 Twitter, Inc. */ package com.twitter.finagle.thrift.service; import scala.PartialFunction; import org.junit.Test; import com.twitter.finagle.service.ReqRep; import com.twitter.finagle.service.ResponseClass; public class ThriftResponseClassifierCompilationTest { @Test public void testThriftExceptionsAsFailures() { PartialFunction<ReqRep, ResponseClass> classifier = ThriftResponseClassifier.ThriftExceptionsAsFailures(); } }
149
575
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h" #include <utility> #include "base/bind.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h" namespace blink { namespace scheduler { NonMainThreadSchedulerImpl::NonMainThreadSchedulerImpl( base::sequence_manager::SequenceManager* manager, TaskType default_task_type) : helper_(manager, this, default_task_type) {} NonMainThreadSchedulerImpl::~NonMainThreadSchedulerImpl() = default; // static std::unique_ptr<NonMainThreadSchedulerImpl> NonMainThreadSchedulerImpl::Create( ThreadType thread_type, base::sequence_manager::SequenceManager* sequence_manager, WorkerSchedulerProxy* proxy) { return std::make_unique<WorkerThreadScheduler>(thread_type, sequence_manager, proxy); } scoped_refptr<NonMainThreadTaskQueue> NonMainThreadSchedulerImpl::CreateTaskQueue(const char* name) { helper_.CheckOnValidThread(); return helper_.NewTaskQueue(base::sequence_manager::TaskQueue::Spec(name) .SetShouldMonitorQuiescence(true) .SetTimeDomain(nullptr)); } void NonMainThreadSchedulerImpl::RunIdleTask(Thread::IdleTask task, base::TimeTicks deadline) { std::move(task).Run(deadline); } void NonMainThreadSchedulerImpl::PostIdleTask(const base::Location& location, Thread::IdleTask task) { IdleTaskRunner()->PostIdleTask( location, base::BindOnce(&NonMainThreadSchedulerImpl::RunIdleTask, std::move(task))); } void NonMainThreadSchedulerImpl::PostNonNestableIdleTask( const base::Location& location, Thread::IdleTask task) { IdleTaskRunner()->PostNonNestableIdleTask( location, base::BindOnce(&NonMainThreadSchedulerImpl::RunIdleTask, std::move(task))); } void NonMainThreadSchedulerImpl::PostDelayedIdleTask( const base::Location& location, base::TimeDelta delay, Thread::IdleTask task) { IdleTaskRunner()->PostDelayedIdleTask( location, delay, base::BindOnce(&NonMainThreadSchedulerImpl::RunIdleTask, std::move(task))); } std::unique_ptr<WebAgentGroupScheduler> NonMainThreadSchedulerImpl::CreateAgentGroupScheduler() { NOTREACHED(); return nullptr; } WebAgentGroupScheduler* NonMainThreadSchedulerImpl::GetCurrentAgentGroupScheduler() { NOTREACHED(); return nullptr; } std::unique_ptr<NonMainThreadSchedulerImpl::RendererPauseHandle> NonMainThreadSchedulerImpl::PauseScheduler() { return nullptr; } base::TimeTicks NonMainThreadSchedulerImpl::MonotonicallyIncreasingVirtualTime() { return base::TimeTicks::Now(); } scoped_refptr<base::SingleThreadTaskRunner> NonMainThreadSchedulerImpl::ControlTaskRunner() { return helper_.ControlNonMainThreadTaskQueue()->task_runner(); } void NonMainThreadSchedulerImpl::RegisterTimeDomain( base::sequence_manager::TimeDomain* time_domain) { return helper_.RegisterTimeDomain(time_domain); } void NonMainThreadSchedulerImpl::UnregisterTimeDomain( base::sequence_manager::TimeDomain* time_domain) { return helper_.UnregisterTimeDomain(time_domain); } base::sequence_manager::TimeDomain* NonMainThreadSchedulerImpl::GetActiveTimeDomain() { return helper_.real_time_domain(); } const base::TickClock* NonMainThreadSchedulerImpl::GetTickClock() { return helper_.GetClock(); } scoped_refptr<base::SingleThreadTaskRunner> NonMainThreadSchedulerImpl::DeprecatedDefaultTaskRunner() { return DefaultTaskRunner(); } void NonMainThreadSchedulerImpl::AttachToCurrentThread() { helper_.AttachToCurrentThread(); } } // namespace scheduler } // namespace blink
1,517
342
package me.zq.youjoin.fragment; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.VolleyError; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import me.zq.youjoin.R; import me.zq.youjoin.YouJoinApplication; import me.zq.youjoin.activity.UserInfoActivity; import me.zq.youjoin.adapter.FriendListAdapter; import me.zq.youjoin.model.FriendsInfo; import me.zq.youjoin.network.NetworkManager; import me.zq.youjoin.network.ResponseListener; import me.zq.youjoin.utils.Md5Utils; import me.zq.youjoin.utils.StringUtils; import me.zq.youjoin.widget.sidebar.CustomEditText; import me.zq.youjoin.widget.sidebar.SideBar; /** * A simple {@link Fragment} subclass. */ public class AroundFragment extends BaseFragment implements SideBar.OnTouchingLetterChangedListener, TextWatcher { @Bind(R.id.refresher) SwipeRefreshLayout refresher; @Bind(R.id.search_input) CustomEditText searchInput; @Bind(R.id.friend_list) ListView friendList; @Bind(R.id.friend_dialog) TextView friendDialog; @Bind(R.id.friend_sidebar) SideBar friendSidebar; private FriendListAdapter adapter; private List<FriendsInfo.FriendsEntity> dataList = new ArrayList<>(); private LocationManager locationManager; private String provider; private static String baseLocation = ""; private static double size = 0.001; private static int len = 3; public AroundFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.yj_fragment_around, container, false); ButterKnife.bind(this, view); initView(); return view; } private void initView() { friendSidebar.setTextView(friendDialog); friendSidebar.setOnTouchingLetterChangedListener(this); searchInput.addTextChangedListener(this); adapter = new FriendListAdapter(friendList, dataList); friendList.setAdapter(adapter); friendList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { UserInfoActivity.actionStart(getActivity(), UserInfoActivity.TYPE_OTHER_USER, dataList.get(position).getId()); } }); refresher.setColorSchemeResources(R.color.colorPrimary); refresher.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getLocation(); } }); getLocation(); } private void getLocation() { locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); List<String> providerList = locationManager.getProviders(true); if (providerList.contains(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else { Toast.makeText(getActivity(), "No Location Provider to Use", Toast.LENGTH_SHORT).show(); return; } try { Location location = locationManager.getLastKnownLocation(provider); if (location != null) { onGetLocation(location); }else{ refresher.setRefreshing(false); Toast.makeText(getActivity(), "Can not get location", Toast.LENGTH_SHORT).show(); } locationManager.requestLocationUpdates(provider, 5000, 1, locationListener); } catch (SecurityException e) { e.printStackTrace(); } } LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { //更新当前设备位置信息 onGetLocation(location); } }; private void onGetLocation(Location location) { double longitude = location.getLongitude(); double latitude = location.getLatitude(); String[] locationString = { StringUtils.double2String(longitude, len) + StringUtils.double2String(latitude, len), StringUtils.double2String(longitude + size, len) + StringUtils.double2String(latitude, len), StringUtils.double2String(longitude, len) + StringUtils.double2String(latitude + size, len), StringUtils.double2String(longitude + size, len) + StringUtils.double2String(latitude + size, len) }; if (locationString[0].equals(baseLocation)) { NetworkManager.postRequestAround(Integer.toString(YouJoinApplication.getCurrUser().getId()), false, null, new ResponseListener<FriendsInfo>() { @Override public void onErrorResponse(VolleyError volleyError) { if(refresher != null){ refresher.setRefreshing(false); } } @Override public void onResponse(FriendsInfo info) { if(refresher != null){ refresher.setRefreshing(false); Log.d(TAG, info.getResult()); dataList.clear(); dataList.addAll(info.getFriends()); adapter.refresh(dataList); searchInput.setText(""); } } }); }else{ baseLocation = locationString[0]; List<String> locationKeyList = new ArrayList<>(); for (String s : locationString) { locationKeyList.add(Md5Utils.MD5_secure(s)); } NetworkManager.postRequestAround(Integer.toString(YouJoinApplication.getCurrUser().getId()), true, locationKeyList, new ResponseListener<FriendsInfo>() { @Override public void onErrorResponse(VolleyError volleyError) { if(refresher != null){ refresher.setRefreshing(false); } } @Override public void onResponse(FriendsInfo info) { if(refresher != null){ refresher.setRefreshing(false); Log.d(TAG, info.getResult()); dataList.clear(); dataList.addAll(info.getFriends()); adapter.refresh(dataList); searchInput.setText(""); } } }); } } @Override public void onTouchingLetterChanged(String s){ int position = 0; //该字母首次出现的位置 if(adapter != null){ position = adapter.getPositionForSection(s.charAt(0)); } if(position != -1){ friendList.setSelection(position); }else if(s.contains("#")){ friendList.setSelection(0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { List<FriendsInfo.FriendsEntity> temp = new ArrayList<>(); temp.addAll(dataList); if(!searchInput.getText().toString().equals("")){ for (FriendsInfo.FriendsEntity data : dataList) { if (data.getNickname().contains(s) || data.getPinyin().contains(s)) { } else { temp.remove(data); } } } if (adapter != null) { adapter.refresh(temp); } } @Override public void afterTextChanged(Editable s) { } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
4,464
10,225
package io.quarkus.logging.gelf.graal; import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; import biz.paluch.logging.gelf.intern.GelfSender; import biz.paluch.logging.gelf.intern.GelfSenderConfiguration; @TargetClass(className = "biz.paluch.logging.gelf.intern.sender.KafkaGelfSenderProvider") public final class KafkaGelfSenderProviderSubstitution { @Substitute public GelfSender create(GelfSenderConfiguration configuration) { return null; } }
194
2,151
// Copyright (c) 2011 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 <sstream> #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/range/range.h" #include "ui/gfx/range/range_f.h" namespace { template <typename T> class RangeTest : public testing::Test { }; typedef testing::Types<gfx::Range, gfx::RangeF> RangeTypes; TYPED_TEST_CASE(RangeTest, RangeTypes); template <typename T> void TestContainsAndIntersects(const T& r1, const T& r2, const T& r3) { EXPECT_TRUE(r1.Intersects(r1)); EXPECT_TRUE(r1.Contains(r1)); EXPECT_EQ(T(10, 12), r1.Intersect(r1)); EXPECT_FALSE(r1.Intersects(r2)); EXPECT_FALSE(r1.Contains(r2)); EXPECT_TRUE(r1.Intersect(r2).is_empty()); EXPECT_FALSE(r2.Intersects(r1)); EXPECT_FALSE(r2.Contains(r1)); EXPECT_TRUE(r2.Intersect(r1).is_empty()); EXPECT_TRUE(r1.Intersects(r3)); EXPECT_TRUE(r3.Intersects(r1)); EXPECT_TRUE(r3.Contains(r1)); EXPECT_FALSE(r1.Contains(r3)); EXPECT_EQ(T(10, 12), r1.Intersect(r3)); EXPECT_EQ(T(10, 12), r3.Intersect(r1)); EXPECT_TRUE(r2.Intersects(r3)); EXPECT_TRUE(r3.Intersects(r2)); EXPECT_FALSE(r3.Contains(r2)); EXPECT_FALSE(r2.Contains(r3)); EXPECT_EQ(T(5, 8), r2.Intersect(r3)); EXPECT_EQ(T(5, 8), r3.Intersect(r2)); } } // namespace TYPED_TEST(RangeTest, EmptyInit) { TypeParam r; EXPECT_EQ(0U, r.start()); EXPECT_EQ(0U, r.end()); EXPECT_EQ(0U, r.length()); EXPECT_FALSE(r.is_reversed()); EXPECT_TRUE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(0U, r.GetMin()); EXPECT_EQ(0U, r.GetMax()); } TYPED_TEST(RangeTest, StartEndInit) { TypeParam r(10, 15); EXPECT_EQ(10U, r.start()); EXPECT_EQ(15U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_FALSE(r.is_reversed()); EXPECT_FALSE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(10U, r.GetMin()); EXPECT_EQ(15U, r.GetMax()); } TYPED_TEST(RangeTest, StartEndReversedInit) { TypeParam r(10, 5); EXPECT_EQ(10U, r.start()); EXPECT_EQ(5U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_TRUE(r.is_reversed()); EXPECT_FALSE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(5U, r.GetMin()); EXPECT_EQ(10U, r.GetMax()); } TYPED_TEST(RangeTest, PositionInit) { TypeParam r(12); EXPECT_EQ(12U, r.start()); EXPECT_EQ(12U, r.end()); EXPECT_EQ(0U, r.length()); EXPECT_FALSE(r.is_reversed()); EXPECT_TRUE(r.is_empty()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(12U, r.GetMin()); EXPECT_EQ(12U, r.GetMax()); } TYPED_TEST(RangeTest, InvalidRange) { TypeParam r(TypeParam::InvalidRange()); EXPECT_EQ(0U, r.length()); EXPECT_EQ(r.start(), r.end()); EXPECT_EQ(r.GetMax(), r.GetMin()); EXPECT_FALSE(r.is_reversed()); EXPECT_TRUE(r.is_empty()); EXPECT_FALSE(r.IsValid()); EXPECT_EQ(r, TypeParam::InvalidRange()); EXPECT_TRUE(r.EqualsIgnoringDirection(TypeParam::InvalidRange())); } TYPED_TEST(RangeTest, Equality) { TypeParam r1(10, 4); TypeParam r2(10, 4); TypeParam r3(10, 2); EXPECT_EQ(r1, r2); EXPECT_NE(r1, r3); EXPECT_NE(r2, r3); TypeParam r4(11, 4); EXPECT_NE(r1, r4); EXPECT_NE(r2, r4); EXPECT_NE(r3, r4); TypeParam r5(12, 5); EXPECT_NE(r1, r5); EXPECT_NE(r2, r5); EXPECT_NE(r3, r5); } TYPED_TEST(RangeTest, EqualsIgnoringDirection) { TypeParam r1(10, 5); TypeParam r2(5, 10); EXPECT_TRUE(r1.EqualsIgnoringDirection(r2)); } TYPED_TEST(RangeTest, SetStart) { TypeParam r(10, 20); EXPECT_EQ(10U, r.start()); EXPECT_EQ(10U, r.length()); r.set_start(42); EXPECT_EQ(42U, r.start()); EXPECT_EQ(20U, r.end()); EXPECT_EQ(22U, r.length()); EXPECT_TRUE(r.is_reversed()); } TYPED_TEST(RangeTest, SetEnd) { TypeParam r(10, 13); EXPECT_EQ(10U, r.start()); EXPECT_EQ(3U, r.length()); r.set_end(20); EXPECT_EQ(10U, r.start()); EXPECT_EQ(20U, r.end()); EXPECT_EQ(10U, r.length()); } TYPED_TEST(RangeTest, SetStartAndEnd) { TypeParam r; r.set_end(5); r.set_start(1); EXPECT_EQ(1U, r.start()); EXPECT_EQ(5U, r.end()); EXPECT_EQ(4U, r.length()); EXPECT_EQ(1U, r.GetMin()); EXPECT_EQ(5U, r.GetMax()); } TYPED_TEST(RangeTest, ReversedRange) { TypeParam r(10, 5); EXPECT_EQ(10U, r.start()); EXPECT_EQ(5U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_TRUE(r.is_reversed()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(5U, r.GetMin()); EXPECT_EQ(10U, r.GetMax()); } TYPED_TEST(RangeTest, SetReversedRange) { TypeParam r(10, 20); r.set_start(25); EXPECT_EQ(25U, r.start()); EXPECT_EQ(20U, r.end()); EXPECT_EQ(5U, r.length()); EXPECT_TRUE(r.is_reversed()); EXPECT_TRUE(r.IsValid()); r.set_end(21); EXPECT_EQ(25U, r.start()); EXPECT_EQ(21U, r.end()); EXPECT_EQ(4U, r.length()); EXPECT_TRUE(r.IsValid()); EXPECT_EQ(21U, r.GetMin()); EXPECT_EQ(25U, r.GetMax()); } TYPED_TEST(RangeTest, ContainAndIntersect) { { SCOPED_TRACE("contain and intersect"); TypeParam r1(10, 12); TypeParam r2(1, 8); TypeParam r3(5, 12); TestContainsAndIntersects(r1, r2, r3); } { SCOPED_TRACE("contain and intersect: reversed"); TypeParam r1(12, 10); TypeParam r2(8, 1); TypeParam r3(12, 5); TestContainsAndIntersects(r1, r2, r3); } // Invalid rect tests TypeParam r1(10, 12); TypeParam r2(8, 1); TypeParam invalid = r1.Intersect(r2); EXPECT_FALSE(invalid.IsValid()); EXPECT_FALSE(invalid.Contains(invalid)); EXPECT_FALSE(invalid.Contains(r1)); EXPECT_FALSE(invalid.Intersects(invalid)); EXPECT_FALSE(invalid.Intersects(r1)); EXPECT_FALSE(r1.Contains(invalid)); EXPECT_FALSE(r1.Intersects(invalid)); } TEST(RangeTest, RangeFConverterTest) { gfx::RangeF range_f(1.2f, 3.9f); gfx::Range range = range_f.Floor(); EXPECT_EQ(1U, range.start()); EXPECT_EQ(3U, range.end()); range = range_f.Ceil(); EXPECT_EQ(2U, range.start()); EXPECT_EQ(4U, range.end()); range = range_f.Round(); EXPECT_EQ(1U, range.start()); EXPECT_EQ(4U, range.end()); // Test for negative values. range_f.set_start(-1.2f); range_f.set_end(-3.8f); range = range_f.Floor(); EXPECT_EQ(0U, range.start()); EXPECT_EQ(0U, range.end()); range = range_f.Ceil(); EXPECT_EQ(0U, range.start()); EXPECT_EQ(0U, range.end()); range = range_f.Round(); EXPECT_EQ(0U, range.start()); EXPECT_EQ(0U, range.end()); } TEST(RangeTest, ToString) { gfx::Range range(4, 7); EXPECT_EQ("{4,7}", range.ToString()); range = gfx::Range::InvalidRange(); std::ostringstream expected; expected << "{" << range.start() << "," << range.end() << "}"; EXPECT_EQ(expected.str(), range.ToString()); }
3,186
403
package com.camunda.consulting.demo.incident; import org.camunda.bpm.BpmPlatform; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.impl.incident.DefaultIncidentHandler; import org.camunda.bpm.engine.impl.incident.IncidentContext; import org.camunda.bpm.engine.runtime.Incident; import org.camunda.bpm.engine.variable.VariableMap; import org.camunda.bpm.engine.variable.Variables; public class ProcessIncidentHandler extends DefaultIncidentHandler { public ProcessIncidentHandler(String type){ super(type); } @Override public String getIncidentHandlerType() { return super.getIncidentHandlerType(); } @Override public Incident handleIncident(IncidentContext context, String message) { Incident incident = super.handleIncident(context, message); VariableMap variables = Variables.createVariables() .putValue("incidentId", incident.getId()) .putValue("incidentMessage", incident.getIncidentMessage()) .putValue("incidentExecutionId", incident.getExecutionId()); BpmPlatform.getDefaultProcessEngine().getRuntimeService() .startProcessInstanceByKey("IncidentManagementProcess", variables); return incident; } }
379
5,169
<filename>Specs/iOSSolarMapOverlay/1.0.0/iOSSolarMapOverlay.podspec.json { "name": "iOSSolarMapOverlay", "version": "1.0.0", "summary": "A Solar Terminator Overlay for iOS.", "homepage": "https://github.com/DABSquared/iOSSolarMapOverlay", "license": "MIT", "authors": { "DABSquared": "<EMAIL>" }, "source": { "git": "https://github.com/DABSquared/iOSSolarMapOverlay.git", "tag": "1.0.0" }, "platforms": { "ios": "6.0" }, "source_files": [ "SolarTerminator/Classes", "SolarTerminator/Classes/*.{h,m}" ], "exclude_files": "SolarTerminator/Classes/Exclude", "frameworks": [ "Foundation", "UIKit", "MapKit", "CoreLocation", "CoreGraphics" ], "libraries": [ "iconv", "charset" ], "requires_arc": true }
348
1,178
<gh_stars>1000+ # Copyright 2020 Makani Technologies LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Scoring functions used by this batch simulation.""" from makani.config import mconfig from makani.control import system_types from makani.lib.python import c_helpers from makani.lib.python import wing_flag from makani.lib.python.batch_sim import scoring_functions from makani.lib.python.batch_sim.scoring_functions import aero from makani.lib.python.batch_sim.scoring_functions import buoy from makani.lib.python.batch_sim.scoring_functions import crosswind from makani.lib.python.batch_sim.scoring_functions import gs02 from makani.lib.python.batch_sim.scoring_functions import hover from makani.lib.python.batch_sim.scoring_functions import kinematics from makani.lib.python.batch_sim.scoring_functions import loads from makani.lib.python.batch_sim.scoring_functions import power from makani.lib.python.batch_sim.scoring_functions import rotors from makani.lib.python.batch_sim.scoring_functions import software from makani.lib.python.batch_sim.scoring_functions import tether from makani.lib.python.batch_sim.scoring_functions import trans_in import numpy as np _FLIGHT_PLAN_HELPER = c_helpers.EnumHelper('FlightPlan', system_types, prefix='kFlightPlan') _WING_MODEL_HELPER = c_helpers.EnumHelper('WingModel', system_types, prefix='kWingModel') def LimitsHelper(limits, offsets): """Add offsets to lower/upper limit params for passing to scoring functions. Args: limits: Iterable of len 1 or 2 that contains the lower and/or upper limit. offsets: Iterable, twice the length of limits, that will be added to the limits. Returns: good_bad_limits: List of the limit values with the offsets applied. Example: LimitsHelper([110., 190.], [5., 10., -10., -5.]) returns: [115., 120., 180., 185.] """ assert len(limits) == len(offsets)/2, 'Check input types, see doc string.' good_bad_limits = [] for ii, limit in enumerate(limits): good_bad_limits.append(limit + offsets[0 + 2*ii]) good_bad_limits.append(limit + offsets[1 + 2*ii]) return good_bad_limits class CrosswindSweepsParameters(object): """Common parameters to the client and worker for this batch sim. Attributes: scoring_functions: List of scoring functions. """ def __init__(self, only_steady_flight=False, steady_flight_mode_time=20, flight_plan='kFlightPlanTurnKey', offshore=False, wing_model=system_types.kWingModelYm600): """Initalize the crosswind batch sim scoring functions. Args: only_steady_flight: Boolean that describes whether the test should only be run in steady crosswind flight, or whether it should include the transient from transition-in. Note that some scores, such as airspeed and radius error, are only applied in steady crosswind in either case. steady_flight_mode_time: Time [s] after which transients from transition-in have gone away. This may be used to test the performance of the crosswind controller under steady conditions. flight_plan: String or Enum that defines the flight plan used in a given batch simulation run. offshore: Flag indicating an offshore scenario. wing_model: String or Enum that defines the wing model to score. """ flight_plan = _FLIGHT_PLAN_HELPER.ShortName(flight_plan) wing_config_name = wing_flag.WingModelToConfigName(wing_model) assert wing_config_name in ['m600', 'oktoberkite'] # Time [s] to end simulation. if flight_plan not in ['TurnKey', 'HighHover']: assert False, 'Unsupported flight plan: %s' % flight_plan # Flight mode time threshold [s] used by default. common_flight_mode_time_threshold = (steady_flight_mode_time if only_steady_flight else 0.0) mconfig.WING_MODEL = wing_config_name # TODO: Allow the score limits to depend on test site. overrides = { 'system': { 'flight_plan': _FLIGHT_PLAN_HELPER.Value(flight_plan) } } params = mconfig.MakeParams('common.all_params', overrides=overrides, override_method='derived') limits = params['system']['limits'] # TODO: Move params only needed for scoring functions out of # the main config files (wing.py, crosswind.py, etc) and to # separate, dedicated scoring config file. if wing_model == 'm600': # TODO: Move these params to the config once values for # Oktoberkite are set. # For the MaxTailMomentScoringFunction scoring function. tail_moment_limits = { 'x': [-17.352, -14.341, 14.341, 17.352], 'y': [-74.250, -61.364, 53.760, 65.013], 'z': [-81.675, -67.500, 67.500, 81.675], } self.scoring_functions = ( # Rubric for assigning severity is as follows: # 0- Informational scores, don't contribute to aggregate score. # 1- Minimal (or negligible) impact to mission or performance # (~3% performance reduction). # 2- Small reduction in mission return or performance # (~10% performance reduction). # 3- Moderate reduction in mission return or performance # (~30% performance reduction). # 4- Significant reduction in mission return or performance # (~60% performance reduction). Potentially indicating end of flight. # 5- Mission failure/vehicle loss/ground station loss. # All crash scoring functions are assigned severity=5. ########################################### # Crash-specific scoring functions. ########################################### # Min height above ground level. Checks for basic condition of kite # making contact with the ground in all modes of flight. The tail is # expected to be 3.2 meters above the ground when the kite is on the # perch. We set the "good" limit to 2.0 meters. The bad limit is # equivalent to zero clearance to the ground indicating contact. # The sphere of contact is defined by a radius from the kite body origin # to the center of pressure of the elevator (or to the tip of the tail # spike, if it exists). This does not fully envelop the wing tips, but # it is assumed unlikely that a wingtip can contact the ground without # subsequent reduced clearance that would be captured by this function # (e.g. an uncontrolled descent). scoring_functions.CrashScoringFunction( kinematics.KiteHeightAglScoringFunctionWrapper( kinematics.MinKiteHeightAglScoringFunction(2.0, 0.0, severity=5))), # Airspeed at the rotors should maintain margin from the vortex ring # state (VRS) threshold. Each rotor is scored from 0 (not at risk of # VRS) to 1 (fully in VRS) and all rotors are summed. Nearly half the # rotors in VRS (3.5/8) or all rotors partially in VRS shall be the # limit, and non-zero values begin when any individual rotor is at # risk of VRS. scoring_functions.CrashScoringFunction( rotors.VortexRingStateScoringFunction(0.0, 3.5, severity=5)), # Breaker applies a 30 minute thermal time constant. # 225 amps is 100% breaker rating. # Discussion here: https://goo.gl/NfkRMi scoring_functions.CrashScoringFunction( power.BreakerCurrentScoringFunction(0.8 * 225.0, 225.0, severity=5)), # Maximum power motoring [kW]. 900 can be sustained for # 3 hours based on breaker rating. 1120 kW can be sustained # for 30 minutes. 600 seconds for 1.25 * rating. scoring_functions.CrashScoringFunction( power.PowerConsumedMaxScoringFunction(1120.0, 1400.0, severity=5)), # Maximum power generated [kW]. # The load bank can sink up to 1.5 MW peak (up to an estimated 240 # seconds) and 1.0 MW continuously. This limit is set by the 1200A # 480VAC load bank breaker. # We try to maintain at least 300 kW of load on the Aggreko at all times # so the loadbank will attempt to dissipate 300 kW plus any power # generated by the kite. Analysis of crosswind flights in PR shows that # the loadbank tracking is good enough to maintain at least 200 kW of # load on the Aggreko except when power transients exceed 1 MW/s. # 950 kW of generation (1.25 MW load bank dissipation) can be sustained # for an estimated 300 seconds. Limit peak generation to 1150 kW. # These limits assume that the kite will not generate an average power # of more than 600 kW. If this changes, we'll need to upgrade the # load bank breaker rating or reduce the Aggreko minimum load. # TODO(b/146362655): Add load bank breaker current scoring function. scoring_functions.CrashScoringFunction( power.PowerGeneratedMaxScoringFunction(950.0, 1150.0, severity=5)), # Maximum rate of power change [kW/sec]. # 500 kW / sec slew rate was the request to the controls team. # 1000.0 kW / sec was about what we saw during the crash. # The microgrid has been hardened significantly, but testing is # limited due to lack of hardware and money to build a fully rated # power simulation. For now, the upper limit is set at the crash # value since we don't have the ability to validate a higher limit. scoring_functions.CrashScoringFunction( power.PowerTransientScoringFunction(500.0, 1000.0, severity=5)), ) if wing_model == 'm600': # Max allowable combination of aerodynamic lift and inertial loads in # kite -Z direction. Returns non-dimensional failure index based on an # aerodynamic lift limit between 258 and 500 kN (based on HALB & THT # wing design load cases https://goo.gl/ePwZ7S), with knockdown for # roll acceleration that causes a change in lift distribution that # increases bending moments in the center of the wing and a kite body # acceleration limit of 85.9 m/s^2 (based on RPX-09 max kite body # acceleration at time of mid-air breakup). A value of 1.0 indicates # structural failure; limits of 0.608 & 0.733 are limit load- and proof # load-equivalent failure indexes. Source derivation for limits and # interaction equation here: https://goo.gl/qUjCgy self.scoring_functions += ( scoring_functions.CrashScoringFunction( loads.MaxWingBendingFailureIndex( 0.608, 0.733, severity=5, aero_tension_limit=500e3, accel_limit=85.9, domega_limit=5.79)), ) # Maximum wing/fuselage junction moment [N-m]. The limits were set # during the integrated fuselage proof-test (https://goo.gl/YDzcj9). # -My limits were determined by FEA of the LAHB case with My reversed # (-207 kN-m) multiplying by the 1st applicable eigenvalue (0.45) and # dividing by a safety factor of 1.518 (buckling, extreme) # (https://goo.gl/JXGWLR) = 61.364 kN-m The good limits are the limit # loads and the bad limits are the proof loads (kN-m). for ax, lims in tail_moment_limits.items(): self.scoring_functions += ( scoring_functions.CrashScoringFunction( loads.MaxTailMomentScoringFunction(ax, *lims, severity=5)), ) self.scoring_functions += ( # Maximum servo hinge moments [N-m] should be # less than 140 N-m and should never exceed 176.0 N-m which would # damage any one actuator. Limits are from servo tests shown here: # https://goo.gl/aoWts4 scoring_functions.CrashScoringFunction( loads.MaxServoMoment(140.0, 176.0, severity=5)), # Maximum rotor resultant in-plane moment [N-m]. # It should not exceed 1230 N-m before the pylons may break. Non-zero # values shall begin at 1016 N-m which is 1230 / (1.1 * 1.1) to account # for the safety factors on this value. # TODO(b/124793226): The sim commonly reports rotor in-plane moments # greater than 4000 N-m which, according to the limits of this scoring # function, would break the pylons. Investigate if the limits are # over-conservative or if the scoring function is incorrect. scoring_functions.CrashScoringFunction( loads.MaxRotorInPlaneMoment(1016.0, 1230.0, severity=5)), # At the Parker Ranch test site, the command center is located at # 45 deg azimuth. We do not want to fly within 45 deg of this # azimuth. Bad scores start in this zone, and are full red # when >=5 deg inside this zone. # For offshore sims, we do not evaluate azi no-go scores, and handle # this risk through operational procedures. # b/137571714 scoring_functions.CrashScoringFunction( scoring_functions.PayoutFilter( kinematics.AzimuthDegNoGoZoneScoringFunction( 0.0, 90.0, 5.0, -180.0, 180.0, severity=5), min_payout=50.0)), # The tether elevation is -7.8 deg right before ascend. # The kite can ascend by 3.0 m on the panel; however, with a steady # state hover attitude, the kite has to pitch back by 24 deg, leading to # tail-side fuselage hitting the panel. Analysis shows that with a perch # peg that is compressed by 30%, the maximum ascent distance on the # panel without the risk of hitting the fuselage is 1.6 m. # Given that the length of the boom is 7.892 m, the maximum increase in # tether elevation during HoverAscend is 11.6 deg. This means a nominal # range of [-7.8, 3.8] deg. For the upper bound, the good/bad limits are # softened to [2.8, 4.8] deg. For the lower bound, the good/bad limits # are softened to [-9.8, -7.8] deg to account for false positives # introduced by sim's contactor modeling. See b/137197170. scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverAscend', hover.TetherElevationScoringFunction( -9.8, -7.8, 2.8, 4.8, severity=5, transform_stages=None, sustained_duration=None))), # After nominal perching, the tether elevation sometimes goes to # -8.8 deg. It is different from ascent likely due to the contactor # interaction modeling in the sim. With the same tether elevation # window size as ascent, the nominal range is then [-8.8, 2.8]. The # limits are then softened following the same logic as in ascent. scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverDescend', hover.TetherElevationScoringFunction( -10.8, -8.8, 1.8, 3.8, severity=5, transform_stages=None, sustained_duration=None))), scoring_functions.CrashScoringFunction( scoring_functions.PerchingFilter( hover.TetherElevationScoringFunction( -10.8, -8.8, 1.8, 3.8, severity=5, transform_stages=None, sustained_duration=None))), scoring_functions.CrashScoringFunction( scoring_functions.PerchingFilter( hover.PanelAzimuthTrackingScoringFunction( 84.55, 86.55, 90.47, 92.47, severity=5))), # The near perch tether elevation window should be the same as the # ascent/descent tether elevation window, to make sure the kite does # not hit the panel, and the peg is able to engage the panel if the # kite reels in. scoring_functions.CrashScoringFunction( scoring_functions.PayoutFilter( hover.TetherElevationScoringFunction( -9.8, -7.8, 13.0, 15.0, severity=5, transform_stages=None, sustained_duration=0.5), min_payout=0.0, max_payout=6.0, flight_mode_filter='PayOut')), scoring_functions.CrashScoringFunction( scoring_functions.PayoutFilter( hover.TetherElevationScoringFunction( -10.8, -8.8, 12.0, 14.0, severity=5, transform_stages=None, sustained_duration=0.5), min_payout=0.0, max_payout=6.0, flight_mode_filter='ReelIn')), # Tether elevation limits in reel modes. See b/117169069, # b/117995426, and b/123407643 for details on the limits and # design of this scoring function. scoring_functions.CrashScoringFunction( scoring_functions.PayoutFilter( hover.TetherElevationScoringFunction( -2.0, 1.0, 12.0, 18.0, severity=5, transform_stages=None, sustained_duration=0.5), min_payout=6.0, flight_mode_filter='PayOut')), scoring_functions.CrashScoringFunction( scoring_functions.PayoutFilter( hover.TetherElevationScoringFunction( -2.0, 1.0, 12.0, 18.0, severity=5, transform_stages=None, sustained_duration=0.5), min_payout=6.0, flight_mode_filter='ReelIn')), # Tether elevation should be well-controlled during the transforms. # Note that when transforming from high-tension to reel mode, the # transform stages proceed in the sequence of [0, 1, 2, 3, 4]. The # sequence is [0, 4, 3, 2, 1] when transforming from reel to # high-tension mode. # # When transforming from high-tension to reel, the tether # elevation should fall within [0, 17] deg before and during the azimuth # slew (stages 1 and 2) to avoid touching the levelwind or its bump # block and the panel. Conventionally, there is a +/- 2 deg of margin # (1 deg for encoders and 1 for extra safety), therefore the new window # for tranform is [2, 15]. # The limits in stage 4 are the same as reel. # Stage 3 is the transition stage between 2 and 4. # # References: # go/makani-tether-elevation-control. # go/makani-levelwind-bumpblock. # During stage 1, the drum rotates to move the GSG from the # upper position to the lower position. Because the tether is # on the GSG at this point, tether elevation control is not # critical. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsUp', hover.TetherElevationScoringFunction( 2.0, 3.0, 14.0, 15.0, severity=1, transform_stages=[1], extra_system_labels=['experimental'])), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsUp', hover.TetherElevationScoringFunction( 2.0, 3.0, 14.0, 15.0, severity=5, transform_stages=[2]))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsUp', hover.TetherElevationScoringFunction( 2.0, 3.0, 12.0, 18.0, severity=5, transform_stages=[3]))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsUp', hover.TetherElevationScoringFunction( -2.0, 1.0, 12.0, 18.0, severity=5, transform_stages=[0, 4]))), scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsDown', hover.TetherElevationScoringFunction( 2.0, 3.0, 14.0, 15.0, severity=0, transform_stages=[0, 1], extra_system_labels=['experimental'])), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsDown', hover.TetherElevationScoringFunction( 2.0, 3.0, 14.0, 15.0, severity=5, transform_stages=[2]))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsDown', hover.TetherElevationScoringFunction( 2.0, 3.0, 12.0, 18.0, severity=5, transform_stages=[3]))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsDown', hover.TetherElevationScoringFunction( -2.0, 1.0, 12.0, 18.0, severity=5, transform_stages=[4]))), ) if flight_plan == 'TurnKey': # We apply a crosswind filter to the MaxWingBendingFailureIndex and # MaxTailMoments scoring function to help isolate issues occurring # during the crosswind flight modes from the ones occurring during # hover. # NOTE: Since we expect these scoring functions to # trigger during crosswind, the present implementation makes it # difficult to isolate bad events occurring in hover in the same log. if wing_model == 'm600': self.scoring_functions += ( scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeCrosswindNormal', 'kFlightModeCrosswindPrepTransOut'], loads.MaxWingBendingFailureIndex( 0.608, 0.733, severity=5, aero_tension_limit=500e3, accel_limit=85.9, domega_limit=5.79), filter_name_prefix='Crosswind - ')), ) for ax, lims in tail_moment_limits.items(): self.scoring_functions += ( scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeCrosswindNormal', 'kFlightModeCrosswindPrepTransOut'], loads.MaxTailMomentScoringFunction( ax, *lims, severity=5), filter_name_prefix='Crosswind - ')), ) self.scoring_functions += ( # The tether must maintain some minimum height [m] off of the ground # (minimum height is 1 meter AGL to account for bushes). We restrict # this scoring function to high tension modes and we exclude Crosswind # for which the kite height AGL serves as a proxy. # NOTE: This scoring function assumes that the terrain at the test # site is flat (see b/70640378#comment8) scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverFullLength', tether.TetherHeightAglMinScoringFunction(4.0, 1.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown'], tether.TetherHeightAglMinScoringFunction(4.0, 1.0, severity=5), filter_name_prefix='HoverTransOut')), # The kite must not deviate too far from the tether sphere during # CrosswindNormal (see analysis based on RPX-06, 07, 08 and 09: # b/78361234). # The initial transients following TransIn are ignored. scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( kinematics.TetherSphereDeviationScoringFunction( 2.5, 5.0, severity=5, mean_tether_tension=100e3), flight_mode_time_threshold=steady_flight_mode_time)), # Tether pitch scoring functions with high tension threshold, used to # evaluate how close the bridles are to a collision with the pylons. scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeTransIn', tether.PitchDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_hover_pitch_rom']), [5.0, 10.0, -2.0, -1.0]), severity=5, tension_threshold=( limits['tether_pitch_tension_threshold'])))), scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( tether.PitchDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_crosswind_pitch_rom']), [5.0, 10.0, -2.0, -1.0]), severity=5, tension_threshold=( limits['tether_pitch_tension_threshold'])))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', tether.PitchDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_crosswind_pitch_rom']), [5.0, 10.0, -2.0, -1.0]), severity=5, tension_threshold=( limits['tether_pitch_tension_threshold'])))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', tether.PitchDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_hover_pitch_rom']), [5.0, 10.0, -2.0, -1.0]), severity=5, tension_threshold=( limits['tether_pitch_tension_threshold'])))), # Tether roll scoring functions with low tension threshold, used to # evaluate how close the system is to a collapse of the bridle point. scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeTransIn', tether.RollDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_hover_roll_rom']), [5.0, 15.0, -15.0, -5.0]), severity=5, tension_threshold=1000.0))), scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( tether.RollDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_crosswind_roll_rom']), [5.0, 15.0, -15.0, -5.0]), severity=5, tension_threshold=1000.0))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', tether.RollDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_crosswind_roll_rom']), [5.0, 15.0, -15.0, -5.0]), severity=5, tension_threshold=1000.0))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown'], tether.RollDegScoringFunction( *LimitsHelper( np.rad2deg(limits['tether_hover_roll_rom']), [5.0, 15.0, -15.0, -5.0]), severity=5, tension_threshold=1000.0), filter_name_prefix='HoverTransOut')), # Max airspeed [m/s] allowed during steady crosswind. This # score should only be applied after the transient from # transition-in has died. scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( aero.AirspeedMaxScoringFunction( *LimitsHelper( [params['control']['crosswind']['power'][ 'max_airspeed']], [-10.0, -5.0]), severity=5), flight_mode_time_threshold=steady_flight_mode_time)), # Maximum tension [kN] that the tether is allowed to see # during crosswind flight is 234 kN, based on http://b/64933954. # The crash criteria "good" value corresponds to the red # indicator limit on the flight test monitors (234 kN) and the "bad" # value corresponds to the tether proof load (263 kN). scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( tether.TensionMaxScoringFunction(234.0, 263.0, severity=5))), # Rotor max advance ratio margin. When negative, the max instantaneous # advance ratio of one (or more) rotors exceeded the limit, which # means the rotor is stalled according to the rotor tables. The bad # score is set slightly negative so small fluctuations are not # considered a crash. scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( rotors.RotorStallScoringFunction(0.0, -0.05, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', rotors.RotorStallScoringFunction(0.0, -0.05, severity=5))), # Ground-side Gimbal (GSG) Yoke and Termination angles [deg]. These # angles are physically limited by GSG geometry as referenced in # b/78529394. The gsg yoke was designed to have a Range of Motion of # +/-105 degrees (see https://goo.gl/kWMBRz) which was later reduced # to +/-73 degrees with the introduction of MV cables and slip ring # hardware. A "guard band" of ~10% is included with these functions # to warn of flight conditions where GSG limits are almost exceeded. # TODO: Use a drum angle filter for GSG angles. # See b/138462894 for more details. scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsUp', scoring_functions.Gs02TransformStageFilter( 1, gs02.GsgYokeAnglesScoringFunction( -73.0, -65.0, 65.0, 73.0, severity=5)))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsUp', scoring_functions.Gs02TransformStageFilter( [1, 2, 3], gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5)))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeHoverFullLength', 'kFlightModeHoverAccel'], gs02.GsgYokeAnglesScoringFunction(-73.0, -65.0, 65.0, 73.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeHoverFullLength', 'kFlightModeHoverAccel'], gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeTransIn', gs02.GsgYokeAnglesScoringFunction(-73.0, -65.0, 65.0, 73.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeTransIn', gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( gs02.GsgYokeAnglesScoringFunction(-73.0, -65.0, 65.0, 73.0, severity=5), flight_mode_time_threshold= common_flight_mode_time_threshold)), scoring_functions.CrashScoringFunction( scoring_functions.CrosswindFilter( gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5), flight_mode_time_threshold= common_flight_mode_time_threshold)), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', gs02.GsgYokeAnglesScoringFunction(-73.0, -65.0, 65.0, 73.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown'], gs02.GsgYokeAnglesScoringFunction(-73.0, -65.0, 65.0, 73.0, severity=5), filter_name_prefix='HoverTransOut')), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown'], gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5), filter_name_prefix='HoverTransOut')), # TODO: Use a drum angle filter for GSG angles. scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsDown', scoring_functions.Gs02TransformStageFilter( [0, 1], gs02.GsgYokeAnglesScoringFunction( -73.0, -65.0, 65.0, 73.0, severity=5)))), scoring_functions.CrashScoringFunction( scoring_functions.FlightModeFilter( 'kFlightModeHoverTransformGsDown', scoring_functions.Gs02TransformStageFilter( [0, 1, 2, 3], gs02.GsgTerminationAnglesScoringFunction(-34.0, -31.0, 31.0, 34.0, severity=5)))), # Relative to the nominal kite perched position (perched_wing_pos_p), # the kite can translate 0.335 m or 0.755 m towards the port or # starboard sides, respectively, before falling-off the perch panel # (see b/137225712). # Adding a 4.5 cm margin to account for radial position change, the # kite will always be on the perch if the difference between launch # and land positions is less than 0.38 m (good value), and it will be # always off the perch if it is greater than 0.80 m (bad value). scoring_functions.CrashScoringFunction( hover.PerchedPositionScoringFunction( 0.38, 0.80, severity=5)), # Max tether twists, in continuous number of revolutions. gs02.GSTetherTwistScoringFunction(-10.0, -2.0, 2.0, 10.0, severity=4), ) self.scoring_functions += ( ########################################### # Hover scoring functions. ########################################### # TODO: Add in hover position and angle scoring functions for # when we are near perch. These can be added once the sim is upgraded # Max rotor speed [rad/s] from perch to crosswind and from crosswind to # perch. scoring_functions.FlightModeFilter( ['kFlightModeHoverAscend', 'kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength', 'kFlightModeHoverAccel'], rotors.MaxRotorSpeedsScoringFunction(215.0, 225.0, severity=2), 0.0, 'Hover - Perch to CW'), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn', 'kFlightModeHoverDescend'], rotors.MaxRotorSpeedsScoringFunction(215.0, 225.0, severity=2), 0.0, 'Hover - CW to Perch'), # Max rotors thrust saturation duration [s] from perch to crosswind and # from crosswind to perch. scoring_functions.FlightModeFilter( ['kFlightModeHoverAscend', 'kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength'], rotors.ThrustMomentSaturationDurationScoringFunction( 'thrust', 0.5, 1.0, severity=4), flight_mode_time_threshold=0.0, filter_name_prefix='Hover - Perch to CW'), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn', 'kFlightModeHoverDescend'], rotors.ThrustMomentSaturationDurationScoringFunction( 'thrust', 0.5, 1.0, severity=4), flight_mode_time_threshold=0.0, filter_name_prefix='Hover - CW to Perch'), # Max rotors pitching moment saturation duration [s] from perch to # crosswind and from crosswind to perch. scoring_functions.FlightModeFilter( ['kFlightModeHoverAscend', 'kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength'], rotors.ThrustMomentSaturationDurationScoringFunction( 'moment_y', 0.5, 1.0, severity=4), flight_mode_time_threshold=0.0, filter_name_prefix='Hover - Perch to CW'), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn', 'kFlightModeHoverDescend'], rotors.ThrustMomentSaturationDurationScoringFunction( 'moment_y', 0.5, 1.0, severity=4), flight_mode_time_threshold=0.0, filter_name_prefix='Hover - CW to Perch'), # Max rotors yawing moment saturation duration [s] from perch to # crosswind and from crosswind to perch. scoring_functions.FlightModeFilter( ['kFlightModeHoverAscend', 'kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength'], rotors.ThrustMomentSaturationDurationScoringFunction( 'moment_z', 0.5, 1.0, severity=4), flight_mode_time_threshold=0.0, filter_name_prefix='Hover - Perch to CW'), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn', 'kFlightModeHoverDescend'], rotors.ThrustMomentSaturationDurationScoringFunction( 'moment_z', 0.5, 1.0, severity=4), flight_mode_time_threshold=0.0, filter_name_prefix='Hover - CW to Perch'), # The tether tension [kN] must be high enough during reel-in and # reel-out modes to prevent the tether from coming out of the # level-wind. scoring_functions.FlightModeFilter( ['kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp'], tether.TensionMinScoringFunction( 2.0, 1.0, severity=4), 0.0, 'Hover - Perch to Transform'), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn'], tether.TensionMinScoringFunction( 2.0, 1.0, severity=4), 0.0, 'Hover - Transform to Perch'), # Tether Tension should follow the tension command. scoring_functions.FlightModeFilter( ['kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn'], scoring_functions.PayoutFilter( hover.HoverTensionControlScoringFunction( 2.0, 5.0, severity=1), 7.0), flight_mode_time_threshold=0.0, filter_name_prefix=None), # Tether Tension should not oscillate. Limits [kN] and # cut-off frequency [Hz] are chosen from CW01-CW03 flight data. # See b/128534501. scoring_functions.PayoutFilter( scoring_functions.FlightModeFilter( ['kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength'], tether.TetherTensionOscillationScoringFunction( 1.0, 1.2, severity=4, cut_off_freq=1.0/20.0), 0.0, 'Hover - Perch to Accel'), 5.0), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut'], tether.TetherTensionOscillationScoringFunction( 3.0, 5.0, severity=3, cut_off_freq=1.0/5.0), 0.0, 'HoverTransout'), scoring_functions.PayoutFilter( scoring_functions.FlightModeFilter( ['kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn'], tether.TetherTensionOscillationScoringFunction( 1.0, 1.2, severity=4, cut_off_freq=1.0/20.0), 0.0, 'Hover - PrepTransformDn to Perch'), 5.0), # Tether elevation should not oscillate. Limits [deg] and # cut-off frequency [Hz] are chosen from CW01 and CW02 flight data. # See b/119215536. scoring_functions.PayoutFilter( hover.TetherElevationOscillationScoringFunction( 1.0, 2.0, severity=4, cut_off_freq=1.0/20.0), min_payout=6.0, flight_mode_filter='PayOut'), scoring_functions.PayoutFilter( hover.TetherElevationOscillationScoringFunction( 1.0, 2.0, severity=4, cut_off_freq=1.0/20.0), min_payout=6.0, flight_mode_filter='ReelIn'), # Tether pitch in hover must remain small enough to ensure effective # bridle roll stiffening. The lower "good" limit was determined from # flight testing (see https://goo.gl/UMnMLd). The upper limit is driven # by bridle interference with the starboard pylon. scoring_functions.FlightModeFilter( ['kFlightModeHoverAscend', 'kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength'], tether.SustainedPitchDegScoringFunction(-55.0, -50.0, 16.0, 17.0, severity=4, sustained_duration=1.0), filter_name_prefix='Hover - Perch to Accel'), scoring_functions.FlightModeFilter( ['kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn', 'kFlightModeHoverDescend'], tether.SustainedPitchDegScoringFunction(-55.0, -50.0, 16.0, 17.0, severity=4, sustained_duration=1.0), filter_name_prefix='Hover - TransOut to Perch'), # The period [s] of the roll mode in hover must stay below an acceptable # threshold, indicating sufficient roll bridle stiffening. The allowable # threshold was determined following the High-Hover-01 flight test. scoring_functions.FlightModeFilter( ['kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength'], tether.RollPeriodScoringFunction(10.0, 12.0, severity=4), filter_name_prefix='Hover - Perch to CW'), scoring_functions.FlightModeFilter( ['kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn'], tether.RollPeriodScoringFunction(10.0, 12.0, severity=4), filter_name_prefix='Hover - CW to Perch'), scoring_functions.FlightModeFilter( 'kFlightModeHoverDescend', tether.TensionMinScoringFunction(2.0, 1.0, severity=4)), scoring_functions.FlightModeFilter( 'kFlightModeHoverAscend', tether.TensionMinScoringFunction(2.0, 1.0, severity=4)), ) if flight_plan == 'TurnKey': self.scoring_functions += ( ########################################### # HoverAccel and TransIn scoring functions. ########################################### # Must spend some minimum time [s] in the hoverAccel flight mode. scoring_functions.FlightModeFilter( 'kFlightModeHoverAccel', scoring_functions.DurationScoringFunction(1.5, 3.0, 10.0, 15.0, severity=1)), # Must spend some minimum time [s] in the TransIn flight mode. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', scoring_functions.DurationScoringFunction(5.0, 6.0, 20.0, 25.0, severity=1)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', trans_in.TransInPitchForwardDurationScoringFunction(5.0, 3.0, 5.0, severity=1)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', aero.MinAlphaDegScoringFunction( -10.0, -8.0, np.rad2deg( limits['trans_in_pitched_forward_alpha']) - 1.0, np.rad2deg(limits['trans_in_pitched_forward_alpha']), severity=2)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', trans_in.AfterPitchForwardScoringFunction( np.rad2deg(limits['trans_in_pitched_forward_alpha']), aero.AlphaDegScoringFunction( *np.rad2deg(limits['crosswind_alpha_limits']), severity=2))), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', trans_in.AfterPitchForwardScoringFunction( np.rad2deg(limits['trans_in_pitched_forward_alpha']), aero.BetaDegScoringFunction( *np.rad2deg(limits['trans_in_beta_limits']), severity=2))), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', trans_in.TransInFinalLateralVelocityErrorScoringFunction( 5.0, 10.0, severity=2)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', trans_in.FinalAirspeedScoringFunction(25.0, 20.0, severity=2)), # TODO: This should be increased when trans-in tension # application is improved. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', tether.TensionMaxScoringFunction(10.0, 5.0, severity=2)), # The simulated tether pitch has very brief transients (<0.5 s) where # it peaks outside of "good" limits. This is a simulator artifact # which is ignored by looking for occurrences of sustained tether # pitch outside of limits. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', tether.SustainedPitchDegScoringFunction(-55.0, -50.0, 10.0, 17.0, severity=3, sustained_duration=0.5)), # Tether roll scoring function with high tension threshold, driven by # structural loads limits (see load cases RPX HEHR and RPX HELR in # go/makanienvelope). scoring_functions.FlightModeFilter( 'kFlightModeTransIn', tether.RollDegScoringFunction(-11.5, -9.5, 23.8, 25.8, severity=3, tension_threshold=200e3)), # Maximum motor speed [rad/s] should nominally be in the range # [200, 210] rad/s in trans-in. It should not exceed 220 rad/s. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', rotors.MaxRotorSpeedsScoringFunction(210.0, 220.0, severity=2)), # Maximum rotor thrust [N] allowed in hover-accel and trans-in. The # good value corresponds to the maximum thrust that the controller # is allowed to command. The bad value is the peak thrust defining the # load case HA (see go/makani-gen3-rotor-loads). scoring_functions.FlightModeFilter( 'kFlightModeHoverAccel', rotors.MaxRotorThrustScoringFunction(3800.0, 4400.0, severity=2)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', rotors.MaxRotorThrustScoringFunction(3800.0, 4400.0, severity=2)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', trans_in.AfterPitchForwardScoringFunction( np.rad2deg(limits['trans_in_pitched_forward_alpha']), tether.PitchMomentCoefficientScoringFunction( -2.0, -1.0, 0.1, 0.2, severity=1))), # Key control surface saturations are shown with a non-zero score if # the surface is saturated during trans-in. # TODO: Once we have implemented flight quality metrics these # limits should be determined based on the percent time [%] that each # control surface was saturated during trans-in in flight tests. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', aero.SurfaceSaturationScoringFunction(['Ele'], 0.0, 100.0, severity=4)), scoring_functions.FlightModeFilter( 'kFlightModeTransIn', aero.SurfaceSaturationScoringFunction(['Rud'], 0.0, 100.0, severity=4)), # Max distance [m] wing overflies the GS into the wind during # trans-in. See b/117102168 for discussion of limits and severity. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', kinematics.MaxWingOverflyGSScoringFunction(0.0, 45.0, severity=4)), # Trans-in pitch rate scoring function. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', kinematics.PitchRateScoringFunction(0.75, 1.25, severity=2)), # Maximum servo hinge moments [N-m] of elevator should be # less than 135 N-m to allow for redundant actuation, and should never # exceed 281.6 N-m which is the limit for paired actuation, as # documented in go/makani_servo_limits. scoring_functions.FlightModeFilter( 'kFlightModeTransIn', loads.MaxElevatorServoMoment(135.0, 281.6, severity=2)), ########################################### # Crosswind scoring functions. ########################################### # Must spend some minimum time [s] in the crosswind flight mode. scoring_functions.CrosswindFilter( scoring_functions.DurationScoringFunction(30.0, 60.0, 10000.0, 15000.0, severity=1), flight_mode_time_threshold=common_flight_mode_time_threshold), # Azimuth error scoring function. This scoring function checks that # the computed azimuth error in the GS02 high tension controller stays # within design limits. See https://goo.gl/L7W9Yw section 3.1. scoring_functions.CrosswindFilter( gs02.GsAzimuthErrorScoringFunction( -23.0, -20.0, 20.0, 23.0, severity=3), flight_mode_time_threshold=common_flight_mode_time_threshold), # Angle-of-attack [deg] limits. # The MainWingAlphaScoringFunction evaluates the alpha [deg] of each # airfoil seen along the span of the main wing, as evaluated by the # Super Simple Aero Model (SSAM). # We include separate scoring functions for the entire crosswind # flight, including the initial transients, and the steady crosswind # flight. scoring_functions.CrosswindFilter( aero.MainWingAlphaScoringFunction( *np.rad2deg(limits['crosswind_alpha_limits']), severity=2, airspeed_threshold=20.0), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.MainWingAlphaScoringFunction( *np.rad2deg(limits['crosswind_alpha_limits']), severity=3, airspeed_threshold=20.0, steady_flight=True), flight_mode_time_threshold=steady_flight_mode_time), # Angle-of-sideslip [deg] limits. # We include separate scoring functions for the entire crosswind # flight, including the initial transients, and the steady crosswind # flight. scoring_functions.CrosswindFilter( aero.BetaDegScoringFunction( *np.rad2deg(limits['crosswind_beta_limits']), severity=1, airspeed_threshold=20.0), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.BetaDegScoringFunction( *np.rad2deg(limits['crosswind_beta_limits']), severity=3, airspeed_threshold=20.0, steady_flight=True), flight_mode_time_threshold=steady_flight_mode_time), # Root-mean-square error of alpha [deg], beta [deg], and airspeed # [m/s] during steady crosswind. scoring_functions.CrosswindFilter( aero.AlphaRmsScoringFunction(0.0, 2.0, severity=0), flight_mode_time_threshold=steady_flight_mode_time), scoring_functions.CrosswindFilter( aero.BetaRmsScoringFunction(0.0, 5.0, severity=0), flight_mode_time_threshold=steady_flight_mode_time), scoring_functions.CrosswindFilter( aero.AirspeedRmsScoringFunction(0.0, 1.0, severity=0), flight_mode_time_threshold=steady_flight_mode_time), # Aero angles error [deg] allowed during steady crosswind (applied # after the transient from transition-in has died). The limits of the # scoring functions are somewhat arbitrary and based on flight # testing. scoring_functions.CrosswindFilter( aero.AlphaDegErrorScoringFunction(2.0, 4.0, severity=3, steady_flight=True), flight_mode_time_threshold=steady_flight_mode_time), scoring_functions.CrosswindFilter( aero.BetaDegErrorScoringFunction(3.0, 6.0, severity=4, steady_flight=True), flight_mode_time_threshold=steady_flight_mode_time), # Min airspeed [m/s] allowed during steady crosswind. This # score should only be applied after the transient from # transition-in has died. scoring_functions.CrosswindFilter( aero.AirspeedMinScoringFunction( *LimitsHelper( [params['control']['crosswind']['power']['min_airspeed']], [10.0, 5.0]), severity=4), flight_mode_time_threshold=steady_flight_mode_time), # Airspeed error [m/s] allowed during steady crosswind. This # score should only be applied after the transient from # transition-in has died. scoring_functions.CrosswindFilter( crosswind.AirspeedErrorScoringFunction(5.0, 10.0, severity=2), flight_mode_time_threshold=steady_flight_mode_time), # Radius error [m] allowed during steady crosswind. This # score should only be applied after the transient from # transition-in has died. scoring_functions.CrosswindFilter( crosswind.RadiusErrorScoringFunction(-50.0, -25.0, 50.0, 100.0, severity=1), flight_mode_time_threshold=steady_flight_mode_time), # Low tension tether pitch scoring function, used to evaluate how # close the system is to an interference between the bridle release # mechanism and the wing (bending of the release starts at approx. # -30 to -40 deg, but is acceptable at low tensions up to -50 deg # tether pitch). The upper "good" limit is driven by bridle # interference with the starboard pylon (at tether pitch=17.7 deg). scoring_functions.CrosswindFilter( tether.PitchDegScoringFunction(-55.0, -50.0, 16.0, 17.0, severity=1, tension_threshold=1000.0), flight_mode_time_threshold=common_flight_mode_time_threshold), # High tension tether roll scoring function, used to evaluate how # close the controller is to exceeding structural load limits. Roll # limits are based around the RPX HEHR and RPX HELR cases in # go/makanienvelope, as it is impossible to fly with the tighter # limits in the original specification. scoring_functions.CrosswindFilter( tether.RollDegScoringFunction(-11.5, -9.5, 23.8, 25.8, severity=2, tension_threshold=200e3), flight_mode_time_threshold=common_flight_mode_time_threshold), # Minimum tension [kN] allowed during steady crosswind. The limits are # discussed in b/117490377. scoring_functions.CrosswindFilter( tether.TensionMinScoringFunction(25.0, 20.0, severity=3), flight_mode_time_threshold=steady_flight_mode_time), # Maximum motor speed [rad/s] should nominally be in the range # [220, 240] rad/s in steady crosswind flight. It should not # exceed 250 rad/s (see b/67742392). scoring_functions.CrosswindFilter( rotors.MaxRotorSpeedsScoringFunction(240.0, 250.0, severity=2), flight_mode_time_threshold=common_flight_mode_time_threshold), # Maximum motor torque [N-m] in steady crosswind flight should # peak below 850 N-m. It should not exceed 900 N-m. # see "Makani Gen2.3 key motor parameters with 850V.pdf" on Drive) scoring_functions.CrosswindFilter( rotors.MaxMotorTorqueScoringFunction(850.0, 900.0, severity=2), flight_mode_time_threshold=common_flight_mode_time_threshold), # Yb-acceleration range [m/s^2] allowed during entire crosswind. The # limits are based around the rpxHAHB and rpxHALB load cases in # go/makanienvelope. scoring_functions.CrosswindFilter( loads.YbAccelerationScoringFunction(-79.0, -42.0, 20.0, 25.0, severity=0), flight_mode_time_threshold=common_flight_mode_time_threshold), # Key control surface saturations are shown with a non-zero score if # the surface is saturated during a particular loop of crosswind. # The SurfaceSaturationScoringFunction is written such that while in a # crosswind configuration, the maximum percentage time spent saturated # during any particular loop is what is returned as a score. The # choice of an upper limit of 2.5 percent is the equivalent of saying # the kite should not go open loop for more than a total of 9 degrees # within any single loop, i.e. 360 degrees*0.025 = 9 degrees scoring_functions.CrosswindFilter( aero.SurfaceSaturationScoringFunction(['A1'], 0.0, 2.5, severity=4), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.SurfaceSaturationScoringFunction(['A2'], 0.0, 2.5, severity=4), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.SurfaceSaturationScoringFunction(['A7'], 0.0, 2.5, severity=4), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.SurfaceSaturationScoringFunction(['A8'], 0.0, 2.5, severity=4), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.SurfaceSaturationScoringFunction(['Ele'], 0.0, 2.5, severity=4), flight_mode_time_threshold=common_flight_mode_time_threshold), scoring_functions.CrosswindFilter( aero.SurfaceSaturationScoringFunction(['Rud'], 0.0, 2.5, severity=4), flight_mode_time_threshold=common_flight_mode_time_threshold), # Check minimum reasonable altitude [m] in crosswind flight. scoring_functions.CrosswindFilter( kinematics.KiteHeightAglScoringFunctionWrapper( kinematics.MinKiteHeightAglScoringFunction( *LimitsHelper( [limits['min_altitude']], [-10.0, -25.0]), severity=3))), # Average generated power [kW] in crosswind. scoring_functions.CrosswindFilter( power.PowerGeneratedMeanScoringFunction(600.0, 0.0, severity=1)), ########################################### # CrosswindPrepTransOut scoring functions. ########################################### # Must spend some minimum time [s] in the prep-trans-out flight mode. scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', scoring_functions.DurationScoringFunction(1.0, 3.0, 180.0, 300.0, severity=1)), # The kite must not deviate too far from the tether sphere during # CrosswindPrepTransOut. The limits [m] are selected based on flight # test experience (see b/147883975). scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', kinematics.TetherSphereDeviationScoringFunction( 2.0, 4.0, severity=4, mean_tether_tension=100e3)), # The max TransOut airspeed command immediately before and after # the flare is 40 m/s. We restrict the scoring of Alpha and Beta in # CrosswindPrepTransOut to airspeeds above this threshold. All limits # are the same as in CrosswindNormal except the good limits for beta # are changed to -10, 10 degrees based on flight test results. # See b/77638038 for details. scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', aero.MainWingAlphaScoringFunction( *np.rad2deg(limits['crosswind_alpha_limits']), severity=2, airspeed_threshold=40.0)), scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', aero.BetaDegScoringFunction( *np.rad2deg(limits['prep_trans_out_beta_limits']), severity=1, airspeed_threshold=40.0)), # Radius error [m] allowed during prep-trans-out. scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', crosswind.RadiusErrorScoringFunction(-50.0, -25.0, 50.0, 100.0, severity=2)), # Maximum servo hinge moments [N-m] of elevator should be # less than 135 N-m to allow for redundant actuation, and should never # exceed 281.6 N-m which is the limit for paired actuation, as # documented in go/makani_servo_limits. scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', loads.MaxElevatorServoMoment(135.0, 281.6, severity=4)), # Rudder surface saturations are shown with a non-zero score if # the surface is saturated during CrosswindPrepTransOut. # TODO: Once we have implemented flight quality metrics these # limits should be determined based on the percent time [%] that each # control surface was saturated during crosswind in flight tests. scoring_functions.FlightModeFilter( 'kFlightModeCrosswindPrepTransOut', aero.SurfaceSaturationScoringFunction(['Rud'], 0.0, 100.0, severity=2)), # Maximum rotor thrust [N] allowed in trans-out. The limits are equal # to the ones set in hover-accel and trans-in. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', rotors.MaxRotorThrustScoringFunction(3800.0, 4400.0, severity=2)), ########################################### # HoverTransOut scoring functions. ########################################### # Must spend some minimum time [s] in the Hover-trans-out flight mode. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', scoring_functions.DurationScoringFunction(1.0, 5.0, 10000.0, 15000.0, severity=1)), # The kite must not deviate too far from the tether sphere during # TransOut. The limits [m] are selected based on flight test # experience (see b/147883975). scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', kinematics.TetherSphereDeviationScoringFunction( 5.0, 8.0, severity=4, mean_tether_tension=100e3)), # Based on experience from flight testing (see go/makani-ecr-480), the # kite must trans-out within a safe range of altitudes above ground # level [m] in order to prevent very high hover (upper limit) and a # sideway trans-out maneuver (lower limit). The lower limit depends on # the height of the last loop in CrosswindPrepTransOut. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', kinematics.KiteHeightAglScoringFunctionWrapper( kinematics.KiteHeightAglScoringFunction( 100.0, 120.0, 190.0, 220.0, severity=3))), # The maximum pitch rate should not exceed 1.25 rad/s because # of gyroscopic loads on the pylons. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', kinematics.PitchRateScoringFunction(0.75, 1.25, severity=1)), # Sustained tether pitch scoring function. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', tether.SustainedPitchDegScoringFunction(-55.0, -50.0, 10.0, 17.0, severity=1, sustained_duration=3.0)), # Maximum servo hinge moments [N-m] of elevator should be # less than 135 N-m to allow for redundant actuation, and should never # exceed 281.6 N-m which is the limit for paired actuation, as # documented in go/makani_servo_limits. scoring_functions.FlightModeFilter( 'kFlightModeHoverTransOut', loads.MaxElevatorServoMoment(135.0, 281.6, severity=0)), ########################################### # HoverDescend scoring functions. ########################################### # Duration [s] of HoverDescend flight mode. This scoring function is # used to verify that the kite has progressed to this flight mode. The # upper good limit is set intentionally high because the flight mode # will run as long as the simulation does. scoring_functions.FlightModeFilter( 'kFlightModeHoverDescend', scoring_functions.DurationScoringFunction( -1.0, 0.0, 500.0, 1000.0, severity=1, extra_system_labels=['experimental'])), ) ########################################### # GS02-specific scoring functions. ########################################### self.scoring_functions += ( scoring_functions.FlightModeFilter( 'kFlightModeHoverPrepTransformGsUp', scoring_functions.DurationScoringFunction(0.0, 20.0, 45.0, 300.0, severity=1)), scoring_functions.FlightModeFilter( 'kFlightModeHoverPrepTransformGsDown', scoring_functions.DurationScoringFunction(0.0, 20.0, 45.0, 300.0, severity=1)), # The tether azimuth must be within a certain range during descend # to track the perch panel. The nominal azimuth window in platform # frame is [84.55, 92.47] deg according to b/137225712. scoring_functions.FlightModeFilter( 'kFlightModeHoverAscend', hover.PanelAzimuthTrackingScoringFunction( 84.55, 86.55, 90.47, 92.47, severity=4)), scoring_functions.FlightModeFilter( 'kFlightModeHoverDescend', hover.PanelAzimuthTrackingScoringFunction( 84.55, 86.55, 90.47, 92.47, severity=4)), # Check whether the kite is being hit by the panel by examining the # vertical acceleration. # See b/137227472. scoring_functions.FlightModeFilter( 'kFlightModeHoverAscend', loads.ZgAccelerationScoringFunction( -10.0, -15.0, severity=4)), scoring_functions.FlightModeFilter( 'kFlightModeHoverDescend', loads.ZgAccelerationScoringFunction( -10.0, -15.0, severity=4)), ) self.scoring_functions += ( # There is no explicit requirement on the size of detwist command jumps, # but if the command scheme is implemented sensibly, then command jumps # across flight modes should not be too large. scoring_functions.FlightModeFilter( ['kFlightModeHoverFullLength', 'kFlightModeHoverAccel', 'kFlightModeTransIn', 'kFlightModeCrosswindNormal', 'kFlightModeCrosswindPrepTransOut', 'kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown'], gs02.GsDetwistCommandJumpScoringFunction(45.0, 90.0, severity=1), filter_name_prefix='HighTension'), ) self.scoring_functions += ( # Limit on detwist command rate [deg/s]. Limit is 1.257 rad/s # (72 deg/s). scoring_functions.FlightModeFilter( ['kFlightModeHoverFullLength', 'kFlightModeHoverAccel', 'kFlightModeTransIn', 'kFlightModeCrosswindNormal', 'kFlightModeCrosswindPrepTransOut', 'kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown'], gs02.GsDetwistCommandRateScoringFunction(60.0, 72.0, severity=1), filter_name_prefix='HighTension'), ) self.scoring_functions += ( # Main to side lobe ratio in dB. Current limits of -10 and -6 dB are # based on observation from prior flights and simulation. scoring_functions.FlightModeFilter( ['kFlightModeTransIn', 'kFlightModeCrosswindNormal', 'kFlightModeCrosswindPrepTransOut', 'kFlightModeHoverTransOut'], gs02.GsDetwistOscillationsScoringFunction(-10.0, -6.0, severity=3), filter_name_prefix='Crosswind - '), ) ########################################### # Software performance scoring functions. ########################################### self.scoring_functions += ( # Maximum absolute difference [s] between the sampling time parameter # and the first difference of the time telemetry. software.MaxSampleTimeErrorScoringFunction(0.0, 1e-6, severity=1), ) ########################################### # Offshore scoring functions. ########################################### if offshore: self.scoring_functions += ( # Distance from water line on the buoy to a threshold. The threshold # is the location of the top deck, as specified by the variable # 'top_deck_pos_z_v' in config/m600/buoy.py, measured from the origin # of the vessel frame (positive downwards). buoy.BuoyWaterLineScoringFunction(6.3, 5.3, severity=3), ) self.scoring_functions += ( # Peak yaw angle of the buoy wrt the rest (equilibrium) azimuth, as # defined by the mooring line systemin the file # config/m600/sim/buoy_sim.py. buoy.BuoyYawAngleScoringFunction(60.0, 90.0, severity=3), ) self.scoring_functions += ( # Peak acceleration of the vessel frame origin, measured in gs. buoy.BuoyVesselOriginAccelScoringFunction(1.0, 2.0, severity=2), ) ########################################### # Other Oktoberkite scores. ########################################### if wing_model == 'oktoberkite': # Duration in each flight mode flight_modes = [ 'kFlightModeHoverAscend', 'kFlightModeHoverPayOut', 'kFlightModeHoverPrepTransformGsUp', 'kFlightModeHoverTransformGsUp', 'kFlightModeHoverFullLength', 'kFlightModeHoverAccel', 'kFlightModeTransIn', 'kFlightModeCrosswindNormal', 'kFlightModeCrosswindPrepTransOut', 'kFlightModeHoverTransOut', 'kFlightModeHoverPrepTransformGsDown', 'kFlightModeHoverTransformGsDown', 'kFlightModeHoverReelIn', 'kFlightModeHoverDescend', ] for ii, flight_mode in enumerate(flight_modes): if flight_mode == 'kFlightModeCrosswindNormal': good_lower = 500.0 else: good_lower = 250.0 self.scoring_functions += ( scoring_functions.FlightModeFilter( [flight_modes[ii]], scoring_functions.DurationScoringFunction( 0.1, good_lower, 10000.0, 15000.0, severity=1, extra_system_labels='experimental'), filter_name_prefix=flight_mode.lstrip('kFlightMode')+' Basic'), ) # Make sure there is no conflicting names. assert len(set(sf.GetName() for sf in self.scoring_functions)) == len( self.scoring_functions), ( 'One or more scoring function names are not unique.')
37,048
335
<gh_stars>100-1000 { "word": "Claudication", "definitions": [ "Limping.", "A condition in which cramping pain in the leg is induced by exercise, typically caused by obstruction of the arteries." ], "parts-of-speech": "Noun" }
98
1,405
<reponame>jarekankowski/pegasus_spyware package com.lenovo.safecenterwidget; import android.content.Context; import android.util.Log; import com.lenovo.lps.reaper.sdk.AnalyticsTracker; /* loaded from: classes.dex */ public class TrackEvent { static final String CATEGORY_APP_RMISSION = "appPerm"; private static final String CATEGORY_CHARGE_SHIELD = "ChargeShield"; static final String CATEGORY_FIVE_PROTECT = "FiveProtectSwitch"; static final String CATEGORY_HARASS_INTERCEPT = "HarassIntercept"; private static final String CATEGORY_HEALTH_CHECKUP = "health_checkup"; static final String CATEGORY_PRIVACY = "privacy"; static final String CATEGORY_SUPERTOOL = "supertool"; static final String OTHER = "other"; static final String TAG = "wu0wu"; private static AnalyticsTracker tracker; public static void initialize(Context context) { try { tracker = AnalyticsTracker.getInstance(); tracker.initialize(context); } catch (Exception e) { Log.i(TAG, "TrackEvent initialize Exception:" + e.toString()); } } public static void shutdown() { try { tracker.shutdown(); } catch (Exception e) { Log.i(TAG, "TrackEvent shutdown Exception:" + e.toString()); } } public static AnalyticsTracker get(Context context) { if (tracker == null) { Log.i(TAG, "tracker==null"); initialize(context); } return tracker; } public static void trackPause(Context context) { try { get(context).trackPause(context); } catch (Exception e) { Log.i(TAG, "TrackEvent trackPause Exception:" + e.toString()); } } public static void trackResume(Context context) { try { get(context).trackResume(context); } catch (Exception e) { Log.i(TAG, "TrackEvent trackResume Exception:" + e.toString()); } } public static void reportOneKeyHealthCheckup() { if (tracker == null) { Log.i(TAG, "reportOneKeyHealthCheckup tracker == null"); } else { tracker.trackEvent(CATEGORY_HEALTH_CHECKUP, "OneKeyHealthCheckup", null, 0); } } public static void reportCancelHealthCheckup() { if (tracker == null) { Log.i(TAG, "reportCancelHealthCheckup tracker == null"); } else { tracker.trackEvent(CATEGORY_HEALTH_CHECKUP, "cancelHealthCheckup", null, 0); } } public static void reportHealthOptimizeImmediately() { if (tracker == null) { Log.i(TAG, "reportHealthOptimizeImmediately tracker == null"); } else { tracker.trackEvent(CATEGORY_HEALTH_CHECKUP, "HealthOptimizeImmediately", null, 0); } } public static void reportProtectTrafficSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportProtectTrafficSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_CHARGE_SHIELD, "protect_traffic_switch_change", String.valueOf(isOn), 0); } } public static void reportSendSmsOnBackgroud(String packageName) { if (tracker == null) { Log.i(TAG, "reportSendSmsOnBackgroud tracker == null"); } else { tracker.trackEvent(CATEGORY_CHARGE_SHIELD, "SendSmsOnBackgroud", packageName, 0); } } public static void reportCallOnBackgroud(String packageName) { if (tracker == null) { Log.i(TAG, "reportCallOnBackgroud tracker == null"); } else { tracker.trackEvent(CATEGORY_CHARGE_SHIELD, "CallOnBackgroud", packageName, 0); } } public static void reportProtectPeepSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportProtectPeepSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_PRIVACY, "Protect_Peep_Switch_change", String.valueOf(isOn), 0); } } public static void reportProtectHarassSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportProtectHarassSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_HARASS_INTERCEPT, "Protect_Harass_Switch_change", String.valueOf(isOn), 0); } } public static void reportInterceptGarbageSMS() { if (tracker == null) { Log.i(TAG, "reportInterceptGarbageSMS tracker == null"); } else { tracker.trackEvent(CATEGORY_HARASS_INTERCEPT, "InterceptGarbageSMS", null, 0); } } public static void reportInterceptHarassCalls() { if (tracker == null) { Log.i(TAG, "reportInterceptHarassCalls tracker == null"); } else { tracker.trackEvent(CATEGORY_HARASS_INTERCEPT, "InterceptHarassCall", null, 0); } } public static void reportUninstallApp(String packageName) { if (tracker == null) { Log.i(TAG, "reportUninstallApp tracker == null"); } else { tracker.trackEvent(CATEGORY_APP_RMISSION, "UninstallApp", packageName, 0); } } public static void reportChildModeSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportChildModeSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_SUPERTOOL, "child_mode_switch_change", String.valueOf(isOn), 0); } } public static void reportGuestModeSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportGuestModeSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_SUPERTOOL, "guest_mode_switch_change", String.valueOf(isOn), 0); } } public static void reportEntryPrivacySpaceCount(int count) { if (tracker == null) { Log.i(TAG, "reportEntryPrivacySpaceCount tracker == null"); } else { tracker.trackEvent(CATEGORY_PRIVACY, "Entry_Privacy_Space_Count", String.valueOf(count), 0); } } public static void reportProtectThiefSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportProtectThiefSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_SUPERTOOL, "Protect_Thief_Switch_change", String.valueOf(isOn), 0); } } public static void reportsafePay(boolean isOn) { if (tracker == null) { Log.i(TAG, "reportsafePay tracker == null"); } else { tracker.trackEvent(CATEGORY_SUPERTOOL, "safepaymen_on", String.valueOf(isOn), 0); } } public static void reportSafeInputMethod(boolean isOn) { if (tracker == null) { Log.i(TAG, "reportSafeInputMethod tracker == null"); } else { tracker.trackEvent(CATEGORY_SUPERTOOL, "SafeInputMethod_on", String.valueOf(isOn), 0); } } public static void reportEntryLeCloudSync() { if (tracker == null) { Log.i(TAG, "reportStartLeCloudSync tracker == null"); } else { tracker.trackEvent(CATEGORY_SUPERTOOL, "EntryLeCloudSync", null, 0); } } public static void reportCleanMemory() { if (tracker == null) { Log.i(TAG, "reportCleanMemory tracker == null"); } else { tracker.trackEvent(OTHER, "CleanMemory", null, 0); } } public static void reportDisableBootStartApp(String packageName) { if (tracker == null) { Log.i(TAG, "reportDisableBootStartApp tracker == null"); } else { tracker.trackEvent(OTHER, "DisableBootStartApp", packageName, 0); } } public static void reportProtectVirusSwitchChange(Boolean isOn) { if (tracker == null) { Log.i(TAG, "reportProtectVirusSwitchChange tracker == null"); } else { tracker.trackEvent(CATEGORY_FIVE_PROTECT, "Protect_Virus_Switch_change", String.valueOf(isOn), 0); } } public static void reportEntrySafeCenterCount(int count) { if (tracker == null) { Log.i(TAG, "reportEntrySafeCenterCount tracker == null"); } else { tracker.trackEvent("home_page", "Entry_Safe_Center_Count", String.valueOf(count), 0); } } public static void reportClickOneKeyEndTaskCount(int count) { if (tracker == null) { Log.i(TAG, "reportClickOneKeyEndTaskCount tracker == null"); } else { tracker.trackEvent("app_manager", "Click_One_Key_End_Task_Count", String.valueOf(count), 0); } } public static void reportTrustApp(String packageName) { if (tracker == null) { Log.i(TAG, "reportClickOneKeyEndTaskCount tracker == null"); } else { tracker.trackEvent("app_permission_manager", "trust_app_packageName", packageName, 0); } } public static void reportWidgetKillOneApp(String packageName) { if (tracker == null) { Log.i(TAG, "reportWidgetKillOneApp tracker == null"); } else { tracker.trackEvent("app_widget", "kill_one_app", packageName, 0); } } public static void reportWidgetKillAllApp() { if (tracker == null) { Log.i(TAG, "reportWidgetKillAllApp tracker == null"); } else { tracker.trackEvent("app_widget", "kill_all_app", null, 0); } } public static void reportWidgetRefresh() { if (tracker == null) { Log.i(TAG, "reportWidgetRefresh tracker == null"); } else { tracker.trackEvent("app_widget", "refresh", null, 0); } } public static void reportWidgetEntrySafeCenter() { if (tracker == null) { Log.i(TAG, "reportWidgetEntrySafeCenter tracker == null"); } else { tracker.trackEvent("app_widget", "entry_safecenter", null, 0); } } }
4,352
696
<reponame>hwang-pku/Strata /* * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.data.scenario; import static com.opengamma.strata.collect.TestHelper.coverBeanEquals; import static com.opengamma.strata.collect.TestHelper.coverImmutableBean; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.opengamma.strata.collect.array.DoubleArray; /** * Test {@link DoubleScenarioArray}. */ public class DoubleScenarioArrayTest { @Test public void create() { DoubleArray values = DoubleArray.of(1, 2, 3); DoubleScenarioArray test = DoubleScenarioArray.of(values); assertThat(test.getValues()).isEqualTo(values); assertThat(test.getScenarioCount()).isEqualTo(3); assertThat(test.get(0)).isEqualTo(1d); assertThat(test.get(1)).isEqualTo(2d); assertThat(test.get(2)).isEqualTo(3); assertThat(test.stream().collect(toList())).containsExactly(1d, 2d, 3d); } @Test public void create_fromList() { List<Double> values = ImmutableList.of(1d, 2d, 3d); DoubleScenarioArray test = DoubleScenarioArray.of(values); assertThat(test.getValues()).isEqualTo(DoubleArray.of(1d, 2d, 3d)); assertThat(test.getScenarioCount()).isEqualTo(3); assertThat(test.get(0)).isEqualTo(1d); assertThat(test.get(1)).isEqualTo(2d); assertThat(test.get(2)).isEqualTo(3); assertThat(test.stream().collect(toList())).containsExactly(1d, 2d, 3d); } @Test public void create_fromFunction() { List<Double> values = ImmutableList.of(1d, 2d, 3d); DoubleScenarioArray test = DoubleScenarioArray.of(3, i -> values.get(i)); assertThat(test.getValues()).isEqualTo(DoubleArray.of(1d, 2d, 3d)); assertThat(test.getScenarioCount()).isEqualTo(3); assertThat(test.get(0)).isEqualTo(1d); assertThat(test.get(1)).isEqualTo(2d); assertThat(test.get(2)).isEqualTo(3); assertThat(test.stream().collect(toList())).containsExactly(1d, 2d, 3d); } //------------------------------------------------------------------------- @Test public void coverage() { DoubleArray values = DoubleArray.of(1, 2, 3); DoubleScenarioArray test = DoubleScenarioArray.of(values); coverImmutableBean(test); DoubleArray values2 = DoubleArray.of(1, 2, 3); DoubleScenarioArray test2 = DoubleScenarioArray.of(values2); coverBeanEquals(test, test2); } }
970
23,901
<filename>student_mentor_dataset_cleaning/training/datasets/mnist.py # coding=utf-8 # Copyright 2021 The Google Research 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. """Class to load the MNIST dataset from Tensorflow Datasets.""" from absl import logging import tensorflow as tf import tensorflow_datasets as tfds import student_mentor_dataset_cleaning.training.datasets as datasets def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`. Args: image: input image with uint8 values in [0, 255]. label: the label to assign to the image. Returns: A tuple of: The image cast to float and normalized to [0.0, 1.0]. The input label. """ return tf.cast(image, tf.float32) / 255., label def create_dataset(student_train_portion, student_validation_portion, mentor_portion, noise_rate, target_distribution_parameter, shuffle_files=True): """Creates an MNIST data set from TFDS. The dataset will have three splits: student training, student validation and mentor training. The training split will be distorted by adding noise and resampling to change the class distribution to an exponential distribution. The data will be normalized to be within the [0.0, 1.0] range. Args: student_train_portion: The fraction of the dataset used for student training. student_validation_portion: The fraction of the dataset used for student validation. mentor_portion: The fraction of the dataset used for mentor training. noise_rate: Fraction of the data points whose labels will be randomized. target_distribution_parameter: Parameter controlling the steepness of the exponential distribution used for resamling the training split. shuffle_files: Whether to shuffle the input data. Returns: A list containing the three dataset splits as tf.data.Dataset. """ logging.info('Start loading the data') portions = [ 0, student_train_portion, student_train_portion + student_validation_portion, student_train_portion + student_validation_portion + mentor_portion ] split = [ tfds.core.ReadInstruction( 'train', from_=portions[i - 1], to=portions[i], unit='%') for i in range(1, len(portions)) ] dataset_splits = tfds.load( 'mnist', split=split, shuffle_files=shuffle_files, as_supervised=True, with_info=False) dataset_splits = [ split.map( normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE) for split in dataset_splits ] logging.info('Adding noise to the data set') dataset_splits[0] = datasets.corrupt_dataset( dataset_splits[0], noise_rate=noise_rate, target_distribution_parameter=target_distribution_parameter) logging.info('Finished loading the data') return dataset_splits
1,167
776
package act.crypto; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import act.session.JWT; import org.osgl.util.Codec; import org.osgl.util.E; import org.osgl.util.S; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.Charset; import java.security.MessageDigest; import java.util.HashMap; import java.util.Map; public class HMAC { public enum Algorithm { SHA256, SHA384, SHA512 ; private final String javaName; private final String jwtName; Algorithm() { this.javaName = S.concat("Hmac", name()); this.jwtName = S.concat("HS", name().substring(3)); } Mac macOf(String key) { try { SecretKeySpec spec = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), javaName); Mac mac = Mac.getInstance(javaName); mac.init(spec); return mac; } catch (Exception e) { throw E.unexpected(e); } } public String jwtName() { return jwtName; } } private Mac mac; private String algoName; protected Algorithm algo; private final Charset UTF_8 = Charset.forName("UTF-8"); protected HMAC(String algoKey) { algo = algoLookup.get(algoKey.toUpperCase()); E.illegalArgumentIf(null == algo, "Algorithm not found"); algoName = algo.jwtName(); } protected HMAC(Algorithm algo) { this.algoName = algo.jwtName(); this.algo = algo; } public HMAC(String key, String algoKey) { this(algoKey); mac = algo.macOf(key); } public HMAC(String key, Algorithm algo) { this(algo); mac = algo.macOf(key); } public String toString(JWT.Token token) { token.header(JWT.Header.ALGO, algoName); String headers = token.headerJsonString(); String payloads = token.payloadJsonString(); String encodedHeaders = encodePart(headers); String encodedPayloads = encodePart(payloads); StringBuilder buf = new StringBuilder(encodedHeaders) .append(".") .append(encodedPayloads); String hash = hash(buf.toString()); return buf.append(".").append(hash).toString(); } public String hash(String text) { return hash(text.getBytes(UTF_8)); } public String hash(byte[] bytes) { byte[] hashed = doHash(bytes); return encodePart(hashed); } protected byte[] doHash(byte[] bytes) { return doHash(bytes, mac()); } protected final byte[] doHash(byte[] bytes, Mac mac) { return mac.doFinal(bytes); } public boolean verifyHash(String content, String hash) { int len = hash.length(); int padding = 4 - len % 4; if (padding > 0) { hash = S.concat(hash, S.times(Codec.URL_SAFE_BASE64_PADDING_CHAR, padding)); } byte[] yourHash = Codec.decodeUrlSafeBase64(hash); return verifyHash(content.getBytes(UTF_8), yourHash); } protected boolean verifyHash(byte[] payload, byte[] hash) { return verifyHash(payload, hash, mac()); } protected final boolean verifyHash(byte[] payload, byte[] hash, Mac mac) { byte[] myHash = doHash(payload, mac); return MessageDigest.isEqual(myHash, hash); } public boolean verifyArgo(String algoName) { Algorithm algorithm = algoLookup.get(algoName); return null != algorithm && S.eq(this.algoName, algorithm.jwtName()); } private static final ThreadLocal<Mac> curMac = new ThreadLocal<>(); private Mac mac() { Mac mac = curMac.get(); if (null == mac) { mac = newMac(); curMac.set(mac); } return mac; } private Mac newMac() { try { return (Mac) mac.clone(); } catch (CloneNotSupportedException e) { throw E.unsupport("mac not clonable"); } } private static Map<String, Algorithm> algoLookup; static { algoLookup = new HashMap<>(); for (Algorithm algo : Algorithm.values()) { algoLookup.put(algo.javaName.toUpperCase(), algo); algoLookup.put(algo.name().toUpperCase(), algo); algoLookup.put(algo.jwtName().toUpperCase(), algo); } } protected static String encodePart(String part) { return Codec.encodeUrlSafeBase64(part); } protected static String encodePart(byte[] part) { return Codec.encodeUrlSafeBase64(part); } }
2,230
755
class SomeClass: y = 4 def func(self, g): print(g) c = SomeClass() c.func("member function call on class")
49
2,329
<filename>shenyu-plugin/shenyu-plugin-cache/shenyu-plugin-cache-redis/src/main/java/org/apache/shenyu/plugin/cache/redis/RedisCache.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.shenyu.plugin.cache.redis; import org.apache.shenyu.plugin.cache.ICache; import org.apache.shenyu.plugin.cache.redis.serializer.ShenyuRedisSerializationContext; import org.springframework.data.redis.connection.ReactiveRedisConnection; import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; import org.springframework.data.redis.core.ReactiveRedisTemplate; import java.time.Duration; import java.util.Objects; /** * RedisCache. */ public final class RedisCache implements ICache { private final ReactiveRedisTemplate<String, byte[]> redisTemplate; public RedisCache(final RedisConfigProperties redisConfigProperties) { this.redisTemplate = new ReactiveRedisTemplate<>(new RedisConnectionFactory(redisConfigProperties).getLettuceConnectionFactory(), ShenyuRedisSerializationContext.bytesSerializationContext()); } /** * Cache the data with the key. * @param key the cache key * @param bytes the data * @param timeoutSeconds value valid time * @return success or not */ @Override public boolean cacheData(final String key, final byte[] bytes, final long timeoutSeconds) { this.redisTemplate.opsForValue().set(key, bytes, Duration.ofSeconds(timeoutSeconds)).subscribe(); return true; } /** * Check the cache is existed or not. * @param key the cache key * @return true exist */ @Override public boolean isExist(final String key) { return Boolean.TRUE.equals(this.redisTemplate.hasKey(key).block()); } /** * Get data with the key. * @param key the cache key * @return the data */ @Override public byte[] getData(final String key) { return this.redisTemplate.opsForValue().get(key).block(); } /** * close the redis cache. */ @Override public void close() { if (Objects.isNull(this.redisTemplate)) { return; } final ReactiveRedisConnectionFactory connectionFactory = this.redisTemplate.getConnectionFactory(); try { ReactiveRedisConnection connection = connectionFactory.getReactiveConnection(); connection.close(); connection = connectionFactory.getReactiveClusterConnection(); connection.close(); } catch (Exception ignored) { } } }
1,122
302
<gh_stars>100-1000 //**************************************************************************** //** //** fsys.cpp //** -Virtual File System //** //**************************************************************************** //============================================================================ // IMPLEMENTATION HEADERS //============================================================================ #include "fsys.h" #include "../Include/string.h" //============================================================================ // IMPLEMENTATION PRIVATE DEFINITIONS / ENUMERATIONS / SIMPLE TYPEDEFS //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE CLASS PROTOTYPES / EXTERNAL CLASS REFERENCES //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE STRUCTURES / UTILITY CLASSES //============================================================================ //============================================================================ // IMPLEMENTATION REQUIRED EXTERNAL REFERENCES (AVOID) //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE DATA //============================================================================ #define DEVICE_MAX 26 //! File system list PFILESYSTEM _FileSystems[DEVICE_MAX]; //============================================================================ // INTERFACE DATA //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE FUNCTION PROTOTYPES //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE FUNCTIONS //============================================================================ //============================================================================ // INTERFACE FUNCTIONS //============================================================================ /** * Opens a file */ FILE volOpenFile(const char *fname) { if (fname) { //! default to device 'a' unsigned char device = 'a'; //! filename char *filename = (char *)fname; //! in all cases, if fname[1]==':' then the first character must be device letter //! FIXME: Using fname[2] do to BUG 2. Please see main.cpp for info if (fname[2] == ':') { device = fname[0]; filename += 3; //strip it from pathname } //! call filesystem if (_FileSystems[device - 'a']) { //! set volume specific information and return file FILE file = _FileSystems[device - 'a']->Open(filename); file.deviceID = device; return file; } } //! return invalid file FILE file; file.flags = FS_INVALID; return file; } /** * Reads file */ void volReadFile(PFILE file, unsigned char *Buffer, unsigned int Length) { if (file) if (_FileSystems[file->deviceID - 'a']) _FileSystems[file->deviceID - 'a']->Read(file, Buffer, Length); } /** * Close file */ void volCloseFile(PFILE file) { if (file) if (_FileSystems[file->deviceID - 'a']) _FileSystems[file->deviceID - 'a']->Close(file); } /** * Registers a filesystem */ void volRegisterFileSystem(PFILESYSTEM fsys, unsigned int deviceID) { static int i = 0; if (i < DEVICE_MAX) if (fsys) { _FileSystems[deviceID] = fsys; i++; } } /** * Unregister file system */ void volUnregisterFileSystem(PFILESYSTEM fsys) { for (int i = 0; i < DEVICE_MAX; i++) if (_FileSystems[i] == fsys) _FileSystems[i] = 0; } /** * Unregister file system */ void volUnregisterFileSystemByID(unsigned int deviceID) { if (deviceID < DEVICE_MAX) _FileSystems[deviceID] = 0; } //============================================================================ // INTERFACE CLASS BODIES //============================================================================ //**************************************************************************** //** //** END[fsys.cpp] //** //****************************************************************************
1,082
1,771
<filename>demo.py #coding:utf-8 import thulac thu1 = thulac.thulac(seg_only=True, model_path="请查看README下载相关模型放到thulac根目录或在这里写路径") #设置模式为行分词模式 a = thu1.cut("我爱北京天安门") print(a)
157
335
{ "word": "Cultivation", "definitions": [ "The action of cultivating land, or the state of being cultivated.", "The process of trying to acquire or develop a quality or skill.", "Refinement and good education." ], "parts-of-speech": "Noun" }
103
3,296
#ifndef _GUARD_async_h_ #define _GUARD_async_h_ // it tries to maintain a FIFO order, but it may not be the case sometimes void main_async_f(void* context, void (*cb)(void*)); void main_async_init(void); void main_async_start(EV_P); void main_async_destroy(void); #endif
106
973
/*_########################################################################## _## _## Copyright (C) 2016 Pcap4J.org _## _########################################################################## */ package org.pcap4j.packet; import java.nio.ByteOrder; import org.pcap4j.packet.RadiotapPacket.RadiotapData; import org.pcap4j.util.ByteArrays; /** * Radiotap Channel field. Tx/Rx frequency in MHz and flags. * * @see <a href="http://www.radiotap.org/defined-fields/Rate">Radiotap</a> * @author <NAME> * @since pcap4j 1.6.5 */ public final class RadiotapDataChannel implements RadiotapData { /** */ private static final long serialVersionUID = 3645927613193110605L; private static final int LENGTH = 4; private final short frequency; private final boolean lsbOfFlags; private final boolean secondLsbOfFlags; private final boolean thirdLsbOfFlags; private final boolean fourthLsbOfFlags; private final boolean turbo; private final boolean cck; private final boolean ofdm; private final boolean twoGhzSpectrum; private final boolean fiveGhzSpectrum; private final boolean onlyPassiveScan; private final boolean dynamicCckOfdm; private final boolean gfsk; private final boolean gsm; private final boolean staticTurbo; private final boolean halfRate; private final boolean quarterRate; /** * A static factory method. This method validates the arguments by {@link * ByteArrays#validateBounds(byte[], int, int)}, which may throw exceptions undocumented here. * * @param rawData rawData * @param offset offset * @param length length * @return a new RadiotapChannel object. * @throws IllegalRawDataException if parsing the raw data fails. */ public static RadiotapDataChannel newInstance(byte[] rawData, int offset, int length) throws IllegalRawDataException { ByteArrays.validateBounds(rawData, offset, length); return new RadiotapDataChannel(rawData, offset, length); } private RadiotapDataChannel(byte[] rawData, int offset, int length) throws IllegalRawDataException { if (length < LENGTH) { StringBuilder sb = new StringBuilder(200); sb.append("The data is too short to build a RadiotapChannel (") .append(LENGTH) .append(" bytes). data: ") .append(ByteArrays.toHexString(rawData, " ")) .append(", offset: ") .append(offset) .append(", length: ") .append(length); throw new IllegalRawDataException(sb.toString()); } this.frequency = ByteArrays.getShort(rawData, offset, ByteOrder.LITTLE_ENDIAN); this.lsbOfFlags = (rawData[offset + 2] & 0x01) != 0; this.secondLsbOfFlags = (rawData[offset + 2] & 0x02) != 0; this.thirdLsbOfFlags = (rawData[offset + 2] & 0x04) != 0; this.fourthLsbOfFlags = (rawData[offset + 2] & 0x08) != 0; this.turbo = (rawData[offset + 2] & 0x10) != 0; this.cck = (rawData[offset + 2] & 0x20) != 0; this.ofdm = (rawData[offset + 2] & 0x40) != 0; this.twoGhzSpectrum = (rawData[offset + 2] & 0x80) != 0; this.fiveGhzSpectrum = (rawData[offset + 3] & 0x01) != 0; this.onlyPassiveScan = (rawData[offset + 3] & 0x02) != 0; this.dynamicCckOfdm = (rawData[offset + 3] & 0x04) != 0; this.gfsk = (rawData[offset + 3] & 0x08) != 0; this.gsm = (rawData[offset + 3] & 0x10) != 0; this.staticTurbo = (rawData[offset + 3] & 0x20) != 0; this.halfRate = (rawData[offset + 3] & 0x40) != 0; this.quarterRate = (rawData[offset + 3] & 0x80) != 0; } private RadiotapDataChannel(Builder builder) { if (builder == null) { throw new NullPointerException("builder is null."); } this.frequency = builder.frequency; this.lsbOfFlags = builder.lsbOfFlags; this.secondLsbOfFlags = builder.secondLsbOfFlags; this.thirdLsbOfFlags = builder.thirdLsbOfFlags; this.fourthLsbOfFlags = builder.fourthLsbOfFlags; this.turbo = builder.turbo; this.cck = builder.cck; this.ofdm = builder.ofdm; this.twoGhzSpectrum = builder.twoGhzSpectrum; this.fiveGhzSpectrum = builder.fiveGhzSpectrum; this.onlyPassiveScan = builder.onlyPassiveScan; this.dynamicCckOfdm = builder.dynamicCckOfdm; this.gfsk = builder.gfsk; this.gsm = builder.gsm; this.staticTurbo = builder.staticTurbo; this.halfRate = builder.halfRate; this.quarterRate = builder.quarterRate; } /** * Tx/Rx frequency in MHz * * @return frequency (unit: MHz) */ public short getFrequency() { return frequency; } /** * Tx/Rx frequency in MHz * * @return frequency (unit: MHz) */ public int getFrequencyAsInt() { return frequency & 0xFFFF; } /** @return true if the LSB of the flags field is set to 1; otherwise false. */ public boolean getLsbOfFlags() { return lsbOfFlags; } /** @return true if the second LSB of the flags field is set to 1; otherwise false. */ public boolean getSecondLsbOfFlags() { return secondLsbOfFlags; } /** @return true if the third LSB of the flags field is set to 1; otherwise false. */ public boolean getThirdLsbOfFlags() { return thirdLsbOfFlags; } /** @return true if the fourth LSB of the flags field is set to 1; otherwise false. */ public boolean getFourthLsbOfFlags() { return fourthLsbOfFlags; } /** @return turbo */ public boolean isTurbo() { return turbo; } /** @return cck */ public boolean isCck() { return cck; } /** @return ofdm */ public boolean isOfdm() { return ofdm; } /** @return twoGhzSpectrum */ public boolean isTwoGhzSpectrum() { return twoGhzSpectrum; } /** @return fiveGhzSpectrum */ public boolean isFiveGhzSpectrum() { return fiveGhzSpectrum; } /** @return onlyPassiveScan */ public boolean isOnlyPassiveScan() { return onlyPassiveScan; } /** @return dynamicCckOfdm */ public boolean isDynamicCckOfdm() { return dynamicCckOfdm; } /** @return gfsk */ public boolean isGfsk() { return gfsk; } /** @return gsm */ public boolean isGsm() { return gsm; } /** @return staticTurbo */ public boolean isStaticTurbo() { return staticTurbo; } /** @return halfRate */ public boolean isHalfRate() { return halfRate; } /** @return quarterRate */ public boolean isQuarterRate() { return quarterRate; } @Override public int length() { return LENGTH; } @Override public byte[] getRawData() { byte[] data = new byte[4]; System.arraycopy( ByteArrays.toByteArray(frequency, ByteOrder.LITTLE_ENDIAN), 0, data, 0, ByteArrays.SHORT_SIZE_IN_BYTES); if (lsbOfFlags) { data[2] |= 0x01; } if (secondLsbOfFlags) { data[2] |= 0x02; } if (thirdLsbOfFlags) { data[2] |= 0x04; } if (fourthLsbOfFlags) { data[2] |= 0x08; } if (turbo) { data[2] |= 0x10; } if (cck) { data[2] |= 0x20; } if (ofdm) { data[2] |= 0x40; } if (twoGhzSpectrum) { data[2] |= 0x80; } if (fiveGhzSpectrum) { data[3] |= 0x01; } if (onlyPassiveScan) { data[3] |= 0x02; } if (dynamicCckOfdm) { data[3] |= 0x04; } if (gfsk) { data[3] |= 0x08; } if (gsm) { data[3] |= 0x10; } if (staticTurbo) { data[3] |= 0x20; } if (halfRate) { data[3] |= 0x40; } if (quarterRate) { data[3] |= 0x80; } return data; } /** @return a new Builder object populated with this object's fields. */ public Builder getBuilder() { return new Builder(this); } @Override public String toString() { return toString(""); } @Override public String toString(String indent) { StringBuilder sb = new StringBuilder(); String ls = System.getProperty("line.separator"); sb.append(indent) .append("Channel: ") .append(ls) .append(indent) .append(" Frequency: ") .append(getFrequencyAsInt()) .append(" MHz") .append(ls) .append(indent) .append(" LSB of flags: ") .append(lsbOfFlags) .append(ls) .append(indent) .append(" 2nd LSB of flags: ") .append(secondLsbOfFlags) .append(ls) .append(indent) .append(" 3rd LSB of flags: ") .append(thirdLsbOfFlags) .append(ls) .append(indent) .append(" 4th LSB of flags: ") .append(fourthLsbOfFlags) .append(ls) .append(indent) .append(" Turbo: ") .append(turbo) .append(ls) .append(indent) .append(" CCK: ") .append(cck) .append(ls) .append(indent) .append(" OFDM: ") .append(ofdm) .append(ls) .append(indent) .append(" 2 GHz spectrum: ") .append(twoGhzSpectrum) .append(ls) .append(indent) .append(" 5 GHz spectrum: ") .append(fiveGhzSpectrum) .append(ls) .append(indent) .append(" Only passive scan: ") .append(onlyPassiveScan) .append(ls) .append(indent) .append(" Dynamic CCK-OFDM: ") .append(dynamicCckOfdm) .append(ls) .append(indent) .append(" GFSK: ") .append(gfsk) .append(ls) .append(indent) .append(" GSM: ") .append(gsm) .append(ls) .append(indent) .append(" Static Turbo: ") .append(staticTurbo) .append(ls) .append(indent) .append(" Half rate: ") .append(halfRate) .append(ls) .append(indent) .append(" Quarter rate: ") .append(quarterRate) .append(ls); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cck ? 1231 : 1237); result = prime * result + (dynamicCckOfdm ? 1231 : 1237); result = prime * result + (fiveGhzSpectrum ? 1231 : 1237); result = prime * result + (fourthLsbOfFlags ? 1231 : 1237); result = prime * result + frequency; result = prime * result + (gfsk ? 1231 : 1237); result = prime * result + (gsm ? 1231 : 1237); result = prime * result + (halfRate ? 1231 : 1237); result = prime * result + (lsbOfFlags ? 1231 : 1237); result = prime * result + (ofdm ? 1231 : 1237); result = prime * result + (onlyPassiveScan ? 1231 : 1237); result = prime * result + (quarterRate ? 1231 : 1237); result = prime * result + (secondLsbOfFlags ? 1231 : 1237); result = prime * result + (staticTurbo ? 1231 : 1237); result = prime * result + (thirdLsbOfFlags ? 1231 : 1237); result = prime * result + (turbo ? 1231 : 1237); result = prime * result + (twoGhzSpectrum ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RadiotapDataChannel other = (RadiotapDataChannel) obj; if (cck != other.cck) return false; if (dynamicCckOfdm != other.dynamicCckOfdm) return false; if (fiveGhzSpectrum != other.fiveGhzSpectrum) return false; if (fourthLsbOfFlags != other.fourthLsbOfFlags) return false; if (frequency != other.frequency) return false; if (gfsk != other.gfsk) return false; if (gsm != other.gsm) return false; if (halfRate != other.halfRate) return false; if (lsbOfFlags != other.lsbOfFlags) return false; if (ofdm != other.ofdm) return false; if (onlyPassiveScan != other.onlyPassiveScan) return false; if (quarterRate != other.quarterRate) return false; if (secondLsbOfFlags != other.secondLsbOfFlags) return false; if (staticTurbo != other.staticTurbo) return false; if (thirdLsbOfFlags != other.thirdLsbOfFlags) return false; if (turbo != other.turbo) return false; if (twoGhzSpectrum != other.twoGhzSpectrum) return false; return true; } /** * @author <NAME> * @since pcap4j 1.6.5 */ public static final class Builder { private short frequency; private boolean lsbOfFlags; private boolean secondLsbOfFlags; private boolean thirdLsbOfFlags; private boolean fourthLsbOfFlags; private boolean turbo; private boolean cck; private boolean ofdm; private boolean twoGhzSpectrum; private boolean fiveGhzSpectrum; private boolean onlyPassiveScan; private boolean dynamicCckOfdm; private boolean gfsk; private boolean gsm; private boolean staticTurbo; private boolean halfRate; private boolean quarterRate; /** */ public Builder() {} private Builder(RadiotapDataChannel obj) { this.frequency = obj.frequency; this.lsbOfFlags = obj.lsbOfFlags; this.secondLsbOfFlags = obj.secondLsbOfFlags; this.thirdLsbOfFlags = obj.thirdLsbOfFlags; this.fourthLsbOfFlags = obj.fourthLsbOfFlags; this.turbo = obj.turbo; this.cck = obj.cck; this.ofdm = obj.ofdm; this.twoGhzSpectrum = obj.twoGhzSpectrum; this.fiveGhzSpectrum = obj.fiveGhzSpectrum; this.onlyPassiveScan = obj.onlyPassiveScan; this.dynamicCckOfdm = obj.dynamicCckOfdm; this.gfsk = obj.gfsk; this.gsm = obj.gsm; this.staticTurbo = obj.staticTurbo; this.halfRate = obj.halfRate; this.quarterRate = obj.quarterRate; } /** * @param frequency frequency * @return this Builder object for method chaining. */ public Builder frequency(short frequency) { this.frequency = frequency; return this; } /** * @param lsbOfFlags lsbOfFlags * @return this Builder object for method chaining. */ public Builder lsbOfFlags(boolean lsbOfFlags) { this.lsbOfFlags = lsbOfFlags; return this; } /** * @param secondLsbOfFlags secondLsbOfFlags * @return this Builder object for method chaining. */ public Builder secondLsbOfFlags(boolean secondLsbOfFlags) { this.secondLsbOfFlags = secondLsbOfFlags; return this; } /** * @param thirdLsbOfFlags thirdLsbOfFlags * @return this Builder object for method chaining. */ public Builder thirdLsbOfFlags(boolean thirdLsbOfFlags) { this.thirdLsbOfFlags = thirdLsbOfFlags; return this; } /** * @param fourthLsbOfFlags fourthLsbOfFlags * @return this Builder object for method chaining. */ public Builder fourthLsbOfFlags(boolean fourthLsbOfFlags) { this.fourthLsbOfFlags = fourthLsbOfFlags; return this; } /** * @param turbo turbo * @return this Builder object for method chaining. */ public Builder turbo(boolean turbo) { this.turbo = turbo; return this; } /** * @param cck cck * @return this Builder object for method chaining. */ public Builder cck(boolean cck) { this.cck = cck; return this; } /** * @param ofdm ofdm * @return this Builder object for method chaining. */ public Builder ofdm(boolean ofdm) { this.ofdm = ofdm; return this; } /** * @param twoGhzSpectrum twoGhzSpectrum * @return this Builder object for method chaining. */ public Builder twoGhzSpectrum(boolean twoGhzSpectrum) { this.twoGhzSpectrum = twoGhzSpectrum; return this; } /** * @param fiveGhzSpectrum fiveGhzSpectrum * @return this Builder object for method chaining. */ public Builder fiveGhzSpectrum(boolean fiveGhzSpectrum) { this.fiveGhzSpectrum = fiveGhzSpectrum; return this; } /** * @param onlyPassiveScan onlyPassiveScan * @return this Builder object for method chaining. */ public Builder onlyPassiveScan(boolean onlyPassiveScan) { this.onlyPassiveScan = onlyPassiveScan; return this; } /** * @param dynamicCckOfdm dynamicCckOfdm * @return this Builder object for method chaining. */ public Builder dynamicCckOfdm(boolean dynamicCckOfdm) { this.dynamicCckOfdm = dynamicCckOfdm; return this; } /** * @param gfsk gfsk * @return this Builder object for method chaining. */ public Builder gfsk(boolean gfsk) { this.gfsk = gfsk; return this; } /** * @param gsm gsm * @return this Builder object for method chaining. */ public Builder gsm(boolean gsm) { this.gsm = gsm; return this; } /** * @param staticTurbo staticTurbo * @return this Builder object for method chaining. */ public Builder staticTurbo(boolean staticTurbo) { this.staticTurbo = staticTurbo; return this; } /** * @param halfRate halfRate * @return this Builder object for method chaining. */ public Builder halfRate(boolean halfRate) { this.halfRate = halfRate; return this; } /** * @param quarterRate quarterRate * @return this Builder object for method chaining. */ public Builder quarterRate(boolean quarterRate) { this.quarterRate = quarterRate; return this; } /** @return a new RadiotapChannel object. */ public RadiotapDataChannel build() { return new RadiotapDataChannel(this); } } }
7,148
5,169
{ "name": "TagLayout", "version": "0.1.0", "summary": "Library allowing easily showing of text tags in UICollectionView", "description": "'A subclass of UICollectionViewLayout to achieve tags in CollectionView. Easy to integrate and use. Written in Swift and works with UIKit.", "homepage": "https://github.com/udbhateja/TagLayout", "screenshots": [ "https://github.com/udbhateja/TagLayout/raw/master/Screenshots/1.png", "https://github.com/udbhateja/TagLayout/raw/master/Screenshots/2.png" ], "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "udbhateja": "<EMAIL>" }, "source": { "git": "https://github.com/udbhateja/TagLayout.git", "tag": "0.1.0" }, "social_media_url": "https://twitter.com/udbhateja", "platforms": { "ios": "9.0" }, "swift_versions": [ "5.1", "5.2", "5.3" ], "source_files": "Sources/*.{swift}", "frameworks": "UIKit", "swift_version": "5.3" }
395
655
#include <StdAfx.h> #include <UI/Controls/SortList/SingleMAPIPropListCtrl.h> #include <core/mapi/columnTags.h> #include <UI/Dialogs/MFCUtilityFunctions.h> #include <UI/UIFunctions.h> #include <UI/MySecInfo.h> #include <core/interpret/guid.h> #include <UI/file/FileDialogEx.h> #include <core/utility/import.h> #include <core/mapi/mapiProgress.h> #include <core/mapi/cache/namedProps.h> #include <core/smartview/SmartView.h> #include <core/PropertyBag/PropertyBag.h> #include <core/PropertyBag/MAPIPropPropertyBag.h> #include <core/PropertyBag/RowPropertyBag.h> #include <core/utility/strings.h> #include <core/mapi/cache/globalCache.h> #include <UI/Dialogs/Editors/Editor.h> #include <UI/Dialogs/Editors/RestrictEditor.h> #include <UI/Dialogs/Editors/StreamEditor.h> #include <UI/Dialogs/Editors/TagArrayEditor.h> #include <UI/Dialogs/Editors/propeditor/ipropeditor.h> #include <UI/Dialogs/Editors/PropertyTagEditor.h> #include <core/mapi/cache/mapiObjects.h> #include <core/mapi/mapiMemory.h> #include <UI/addinui.h> #include <core/mapi/mapiOutput.h> #include <core/utility/registry.h> #include <core/interpret/proptags.h> #include <core/interpret/proptype.h> #include <core/utility/output.h> #include <core/mapi/mapiFunctions.h> #include <core/property/parseProperty.h> namespace controls::sortlistctrl { static std::wstring CLASS = L"CSingleMAPIPropListCtrl"; // 26 columns should be enough for anybody #define MAX_SORT_COLS 26 CSingleMAPIPropListCtrl::CSingleMAPIPropListCtrl( _In_ CWnd* pCreateParent, _In_ dialog::CBaseDialog* lpHostDlg, _In_ std::shared_ptr<cache::CMapiObjects> lpMapiObjects) : m_lpMapiObjects(lpMapiObjects), m_lpHostDlg(lpHostDlg) { TRACE_CONSTRUCTOR(CLASS); Create(pCreateParent, LVS_SINGLESEL, IDC_LIST_CTRL, true); if (m_lpHostDlg) m_lpHostDlg->AddRef(); for (ULONG i = 0; i < columns::PropColumns.size(); i++) { const auto szHeaderName = strings::loadstring(columns::PropColumns[i].uidName); InsertColumnW(i, szHeaderName); } const auto lpMyHeader = GetHeaderCtrl(); // Column orders are stored as lowercase letters // bacdefghi would mean the first two columns are swapped if (lpMyHeader && !registry::propertyColumnOrder.empty()) { auto bSetCols = false; const auto nColumnCount = lpMyHeader->GetItemCount(); const auto cchOrder = registry::propertyColumnOrder.length() - 1; if (nColumnCount == static_cast<int>(cchOrder)) { auto order = std::vector<int>(nColumnCount); for (auto i = 0; i < nColumnCount; i++) { order[i] = registry::propertyColumnOrder[i] - L'a'; } if (SetColumnOrderArray(static_cast<int>(order.size()), order.data())) { bSetCols = true; } } // If we didn't like the reg key, clear it so we don't see it again if (!bSetCols) registry::propertyColumnOrder.clear(); } AutoSizeColumns(false); } CSingleMAPIPropListCtrl::~CSingleMAPIPropListCtrl() { TRACE_DESTRUCTOR(CLASS); if (m_sptExtraProps) MAPIFreeBuffer(m_sptExtraProps); if (m_lpHostDlg) m_lpHostDlg->Release(); } BEGIN_MESSAGE_MAP(CSingleMAPIPropListCtrl, CSortListCtrl) #pragma warning(push) #pragma warning(disable : 26454) ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk) #pragma warning(pop) ON_WM_KEYDOWN() ON_WM_CONTEXTMENU() ON_MESSAGE(WM_MFCMAPI_SAVECOLUMNORDERLIST, msgOnSaveColumnOrder) END_MESSAGE_MAP() LRESULT CSingleMAPIPropListCtrl::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_ERASEBKGND: if (!m_lpPropBag) { return true; } break; case WM_PAINT: if (!m_lpPropBag) { ui::DrawHelpText(m_hWnd, IDS_HELPTEXTNOPROPS); return true; } break; } return CSortListCtrl::WindowProc(message, wParam, lParam); } // WM_MFCMAPI_SAVECOLUMNORDERLIST _Check_return_ LRESULT CSingleMAPIPropListCtrl::msgOnSaveColumnOrder(WPARAM /*wParam*/, LPARAM /*lParam*/) { const auto lpMyHeader = GetHeaderCtrl(); if (lpMyHeader) { const auto columnCount = lpMyHeader->GetItemCount(); if (columnCount && columnCount <= MAX_SORT_COLS) { auto columns = std::vector<int>(columnCount); registry::propertyColumnOrder.clear(); EC_B_S(GetColumnOrderArray(columns.data(), columnCount)); for (const auto column : columns) { registry::propertyColumnOrder.push_back(static_cast<wchar_t>(L'a' + column)); } } } return S_OK; } // namespace sortlistctrl void CSingleMAPIPropListCtrl::InitMenu(_In_ CMenu* pMenu) const { if (pMenu) { const auto bHasSource = m_lpPropBag != nullptr; const auto bPropSelected = GetSelectedPropModelData() != nullptr; const auto ulStatus = cache::CGlobalCache::getInstance().GetBufferStatus(); const auto lpEIDsToCopy = cache::CGlobalCache::getInstance().GetMessagesToCopy(); pMenu->EnableMenuItem( ID_PASTE_PROPERTY, DIM(bHasSource && (ulStatus & BUFFER_PROPTAG) && (ulStatus & BUFFER_SOURCEPROPOBJ))); pMenu->EnableMenuItem(ID_COPYTO, DIM(bHasSource && (ulStatus & BUFFER_SOURCEPROPOBJ))); pMenu->EnableMenuItem( ID_PASTE_NAMEDPROPS, DIM(bHasSource && (ulStatus & BUFFER_MESSAGES) && lpEIDsToCopy && 1 == lpEIDsToCopy->cValues)); pMenu->EnableMenuItem(ID_COPY_PROPERTY, DIM(bHasSource)); pMenu->EnableMenuItem( ID_DISPLAYPROPERTYASSECURITYDESCRIPTORPROPSHEET, DIM(bHasSource && bPropSelected && import::pfnEditSecurity)); pMenu->EnableMenuItem(ID_EDITPROPASBINARYSTREAM, DIM(bHasSource && bPropSelected)); pMenu->EnableMenuItem(ID_EDITPROPERTY, DIM(bPropSelected)); pMenu->EnableMenuItem(ID_EDITPROPERTYASASCIISTREAM, DIM(bHasSource && bPropSelected)); pMenu->EnableMenuItem(ID_EDITPROPERTYASUNICODESTREAM, DIM(bHasSource && bPropSelected)); pMenu->EnableMenuItem(ID_EDITPROPERTYASPRRTFCOMPRESSEDSTREAM, DIM(bHasSource && bPropSelected)); pMenu->EnableMenuItem(ID_OPEN_PROPERTY, DIM(bPropSelected)); pMenu->EnableMenuItem(ID_SAVEPROPERTIES, DIM(bHasSource)); pMenu->EnableMenuItem(ID_EDITGIVENPROPERTY, DIM(bHasSource)); pMenu->EnableMenuItem(ID_OPENPROPERTYASTABLE, DIM(bHasSource)); pMenu->EnableMenuItem(ID_FINDALLNAMEDPROPS, DIM(bHasSource)); pMenu->EnableMenuItem(ID_COUNTNAMEDPROPS, DIM(bHasSource)); if (m_lpHostDlg) { for (ULONG ulMenu = ID_ADDINPROPERTYMENU;; ulMenu++) { const auto lpAddInMenu = ui::addinui::GetAddinMenuItem(m_lpHostDlg->m_hWnd, ulMenu); if (!lpAddInMenu) break; pMenu->EnableMenuItem(ulMenu, DIM(bPropSelected)); } } const bool bCanDelete = bPropSelected && m_lpPropBag && m_lpPropBag->CanDelete(); pMenu->EnableMenuItem(ID_DELETEPROPERTY, DIM(bCanDelete)); } } _Check_return_ bool CSingleMAPIPropListCtrl::HandleMenu(WORD wMenuSelect) { output::DebugPrint( output::dbgLevel::Menu, L"CSingleMAPIPropListCtrl::HandleMenu wMenuSelect = 0x%X = %u\n", wMenuSelect, wMenuSelect); switch (wMenuSelect) { case ID_COPY_PROPERTY: OnCopyProperty(); return true; case ID_COPYTO: OnCopyTo(); return true; case ID_DELETEPROPERTY: OnDeleteProperty(); return true; case ID_DISPLAYPROPERTYASSECURITYDESCRIPTORPROPSHEET: OnDisplayPropertyAsSecurityDescriptorPropSheet(); return true; case ID_EDITGIVENPROPERTY: OnEditGivenProperty(); return true; case ID_EDITPROPERTY: OnEditProp(); return true; case ID_EDITPROPASBINARYSTREAM: OnEditPropAsStream(PT_BINARY, false); return true; case ID_EDITPROPERTYASASCIISTREAM: OnEditPropAsStream(PT_STRING8, false); return true; case ID_EDITPROPERTYASUNICODESTREAM: OnEditPropAsStream(PT_UNICODE, false); return true; case ID_EDITPROPERTYASPRRTFCOMPRESSEDSTREAM: OnEditPropAsStream(PT_BINARY, true); return true; case ID_FINDALLNAMEDPROPS: FindAllNamedProps(); return true; case ID_COUNTNAMEDPROPS: CountNamedProps(); return true; case ID_MODIFYEXTRAPROPS: OnModifyExtraProps(); return true; case ID_OPEN_PROPERTY: OnOpenProperty(); return true; case ID_OPENPROPERTYASTABLE: OnOpenPropertyAsTable(); return true; case ID_PASTE_NAMEDPROPS: OnPasteNamedProps(); return true; case ID_PASTE_PROPERTY: OnPasteProperty(); return true; case ID_SAVEPROPERTIES: SavePropsToXML(); return true; } return HandleAddInMenu(wMenuSelect); } _Check_return_ std::shared_ptr<sortlistdata::propModelData> CSingleMAPIPropListCtrl::GetSelectedPropModelData() const { const auto iItem = GetNextItem(-1, LVNI_FOCUSED | LVNI_SELECTED); if (-1 != iItem) { const auto lpListData = reinterpret_cast<sortlistdata::sortListData*>(GetItemData(iItem)); if (lpListData) { return lpListData->cast<sortlistdata::propModelData>(); } } return {}; } // Call GetProps with NULL to get a list of (almost) all properties. // Parse this list and render them in the control. // Add any extra props we've asked for through the UI void CSingleMAPIPropListCtrl::LoadMAPIPropList() { if (!m_lpPropBag) return; CWaitCursor Wait; // Change the mouse to an hourglass while we work. auto models = std::vector<std::shared_ptr<model::mapiRowModel>>{}; if (!registry::onlyAdditionalProperties) { models = m_lpPropBag->GetAllModels(); } // Now check if the user has given us any other properties to add and get them one at a time if (m_sptExtraProps) { for (ULONG i = 0; i < m_sptExtraProps->cValues; i++) { models.emplace_back(m_lpPropBag->GetOneModel(mapi::getTag(m_sptExtraProps, i))); } } // Add our props to the view if (!models.empty()) { // Set the item count to speed up the addition of items SetItemCount(static_cast<int>(models.size())); // get each model in turn and add it to the list ULONG ulCurListBoxRow = 0; for (const auto model : models) { AddPropToListBox(ulCurListBoxRow++, model); } } if (m_lpHostDlg) { // This flag may be set by a GetProps call, so we make this check AFTER we get our props if (m_lpPropBag->IsBackedByGetProps()) { m_lpHostDlg->UpdateStatusBarText(statusPane::infoText, IDS_PROPSFROMGETPROPS); } else { m_lpHostDlg->UpdateStatusBarText(statusPane::infoText, IDS_PROPSFROMROW); } } output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"LoadMAPIPropList", L"added %u properties\n", models.size()); SortClickedColumn(); } void CSingleMAPIPropListCtrl::RefreshMAPIPropList() { output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"RefreshMAPIPropList", L"\n"); // Turn off redraw while we work on the window MySetRedraw(false); auto MyPos = GetFirstSelectedItemPosition(); const auto iSelectedItem = GetNextSelectedItem(MyPos); EC_B_S(DeleteAllItems()); if (m_lpPropBag) { LoadMAPIPropList(); } SetItemState(iSelectedItem, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); EnsureVisible(iSelectedItem, false); // Turn redraw back on to update our view MySetRedraw(true); if (m_lpHostDlg) m_lpHostDlg->UpdateStatusBarText(statusPane::data2, IDS_STATUSTEXTNUMPROPS, GetItemCount()); } void CSingleMAPIPropListCtrl::AddPropToExtraProps(ULONG ulPropTag, bool bRefresh) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"AddPropToExtraProps", L"adding proptag 0x%X\n", ulPropTag); // Cache this proptag so we continue to request it in this view // We've got code to refresh any props cached in m_sptExtraProps...let's add to that. SPropTagArray sptSingleProp = {1, ulPropTag}; AddPropsToExtraProps(&sptSingleProp, bRefresh); } void CSingleMAPIPropListCtrl::AddPropsToExtraProps(_In_ LPSPropTagArray lpPropsToAdd, bool bRefresh) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"AddPropsToExtraProps", L"adding prop array %p\n", lpPropsToAdd); const auto lpNewExtraProps = mapi::ConcatSPropTagArrays(m_sptExtraProps, lpPropsToAdd); MAPIFreeBuffer(m_sptExtraProps); m_sptExtraProps = lpNewExtraProps; if (bRefresh) { RefreshMAPIPropList(); } } static TypeIcon _PropTypeIcons[] = { {PT_UNSPECIFIED, sortIcon::ptUnspecified}, {PT_NULL, sortIcon::ptNull}, {PT_I2, sortIcon::ptI2}, {PT_LONG, sortIcon::ptLong}, {PT_R4, sortIcon::ptR4}, {PT_DOUBLE, sortIcon::ptDouble}, {PT_CURRENCY, sortIcon::ptCurrency}, {PT_APPTIME, sortIcon::ptAppTime}, {PT_ERROR, sortIcon::ptError}, {PT_BOOLEAN, sortIcon::ptBoolean}, {PT_OBJECT, sortIcon::ptObject}, {PT_I8, sortIcon::ptI8}, {PT_STRING8, sortIcon::ptString8}, {PT_UNICODE, sortIcon::ptUnicode}, {PT_SYSTIME, sortIcon::ptSysTime}, {PT_CLSID, sortIcon::ptClsid}, {PT_BINARY, sortIcon::ptBinary}, {PT_MV_I2, sortIcon::mvI2}, {PT_MV_LONG, sortIcon::mvLong}, {PT_MV_R4, sortIcon::mvR4}, {PT_MV_DOUBLE, sortIcon::mvDouble}, {PT_MV_CURRENCY, sortIcon::mvCurrency}, {PT_MV_APPTIME, sortIcon::mvAppTime}, {PT_MV_SYSTIME, sortIcon::mvSysTime}, {PT_MV_STRING8, sortIcon::mvString8}, {PT_MV_BINARY, sortIcon::mvBinary}, {PT_MV_UNICODE, sortIcon::mvUnicode}, {PT_MV_CLSID, sortIcon::mvClsid}, {PT_MV_I8, sortIcon::mvI8}, {PT_SRESTRICTION, sortIcon::sRestriction}, {PT_ACTIONS, sortIcon::actions}, }; // Render the row model in the list. void CSingleMAPIPropListCtrl::AddPropToListBox(int iRow, const std::shared_ptr<model::mapiRowModel>& model) { if (!model) return; auto ulPropTag = model->ulPropTag(); auto image = sortIcon::siDefault; for (const auto& _PropTypeIcon : _PropTypeIcons) { if (_PropTypeIcon.objType == PROP_TYPE(ulPropTag)) { image = _PropTypeIcon.image; break; } } auto lpData = InsertRow(iRow, L"", 0, image); // Data used to refer to specific property tags. See GetSelectedPropTag. if (lpData) { sortlistdata::propModelData::init(lpData, model); } SetItemText(iRow, columns::pcPROPBESTGUESS, model->name()); SetItemText(iRow, columns::pcPROPOTHERNAMES, model->otherName()); SetItemText(iRow, columns::pcPROPTAG, model->tag()); SetItemText(iRow, columns::pcPROPTYPE, model->propType()); SetItemText(iRow, columns::pcPROPVAL, model->value()); SetItemText(iRow, columns::pcPROPVALALT, model->altValue()); SetItemText(iRow, columns::pcPROPSMARTVIEW, model->smartView()); SetItemText(iRow, columns::pcPROPNAMEDNAME, model->namedPropName()); SetItemText(iRow, columns::pcPROPNAMEDGUID, model->namedPropGuid()); } _Check_return_ bool CSingleMAPIPropListCtrl::IsModifiedPropVals() const { return m_lpPropBag && m_lpPropBag->IsModified(); } void CSingleMAPIPropListCtrl::SetDataSource( _In_opt_ LPMAPIPROP lpMAPIProp, _In_opt_ sortlistdata::sortListData* lpListData, bool bIsAB) { output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"SetDataSource", L"setting new data source\n"); if (lpMAPIProp) { return SetDataSource(std::make_shared<propertybag::mapiPropPropertyBag>(lpMAPIProp, lpListData, bIsAB)); } else if (lpListData) { return SetDataSource(std::make_shared<propertybag::rowPropertyBag>(lpListData, bIsAB)); } return SetDataSource(nullptr); } // Clear the current property list from the control. // Load a new list from the IMAPIProp or lpSourceProps object passed in // Most calls to this will come through CBaseDialog::OnUpdateSingleMAPIPropListCtrl, which will preserve the current bIsAB // Exceptions will be where we need to set a specific bIsAB void CSingleMAPIPropListCtrl::SetDataSource(const std::shared_ptr<propertybag::IMAPIPropertyBag> lpPropBag) { output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"SetDataSource", L"setting new data source\n"); // if nothing to do...do nothing if (lpPropBag && lpPropBag->IsEqual(m_lpPropBag)) { return; } m_lpPropBag = lpPropBag; // Turn off redraw while we work on the window MySetRedraw(false); RefreshMAPIPropList(); // Reset our header widths if weren't showing anything before and are now if (!m_bHaveEverDisplayedSomething && m_lpPropBag && GetItemCount()) { m_bHaveEverDisplayedSomething = true; auto lpMyHeader = GetHeaderCtrl(); if (lpMyHeader) { // This fixes a ton of flashing problems lpMyHeader->SetRedraw(true); for (auto iCurCol = 0; iCurCol < static_cast<int>(columns::PropColumns.size()); iCurCol++) { SetColumnWidth(iCurCol, LVSCW_AUTOSIZE_USEHEADER); if (GetColumnWidth(iCurCol) > 200) SetColumnWidth(iCurCol, 200); } lpMyHeader->SetRedraw(false); } } // Turn redraw back on to update our view MySetRedraw(true); } const std::shared_ptr<propertybag::IMAPIPropertyBag> CSingleMAPIPropListCtrl::GetDataSource() { return m_lpPropBag; } std::wstring binPropToXML(UINT uidTag, const std::wstring str, int iIndent) { auto toks = strings::tokenize(str); if (toks.count(L"lpb")) { auto attr = property::Attributes(); if (toks.count(L"cb")) { attr.AddAttribute(L"cb", toks[L"cb"]); } auto parsing = property::Parsing(toks[L"lpb"], true, attr); return parsing.toXML(uidTag, iIndent); } return strings::emptystring; } // Parse this for XML: // Err: 0x00040380=MAPI_W_ERRORS_RETURNED std::wstring errPropToXML(UINT uidTag, const std::wstring str, int iIndent) { auto toks = strings::tokenize(str); if (toks.count(L"Err")) { auto err = strings::split(toks[L"Err"], L'='); if (err.size() == 2) { auto attr = property::Attributes(); attr.AddAttribute(L"err", err[0]); auto parsing = property::Parsing(err[1], true, attr); return parsing.toXML(uidTag, iIndent); } } return strings::emptystring; } void CSingleMAPIPropListCtrl::SavePropsToXML() { auto szFileName = file::CFileDialogExW::SaveAs( L"xml", // STRING_OK L"props.xml", // STRING_OK OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strings::loadstring(IDS_XMLFILES), this); if (!szFileName.empty()) { const auto fProps = output::MyOpenFile(szFileName, true); if (fProps) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"SavePropsToXML", L"saving to %ws\n", szFileName.c_str()); // Force a sort on the tag column to make output consistent FakeClickColumn(columns::pcPROPTAG, false); const auto iItemCount = GetItemCount(); output::OutputToFile(fProps, output::g_szXMLHeader); output::OutputToFile(fProps, L"<properties listtype=\"propertypane\">\n"); for (auto iRow = 0; iRow < iItemCount; iRow++) { const auto szTag = GetItemText(iRow, columns::pcPROPTAG); const auto szType = GetItemText(iRow, columns::pcPROPTYPE); const auto szBestGuess = GetItemText(iRow, columns::pcPROPBESTGUESS); const auto szOther = GetItemText(iRow, columns::pcPROPOTHERNAMES); const auto szNameGuid = GetItemText(iRow, columns::pcPROPNAMEDGUID); const auto szNameName = GetItemText(iRow, columns::pcPROPNAMEDNAME); output::OutputToFilef( fProps, L"\t<property tag = \"%ws\" type = \"%ws\" >\n", szTag.c_str(), szType.c_str()); if (szNameName.empty() && !strings::beginsWith(szBestGuess, L"0x")) { output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPBESTGUESS].uidName, szBestGuess, false, 2); } output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPOTHERNAMES].uidName, szOther, false, 2); output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPNAMEDGUID].uidName, szNameGuid, false, 2); output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPNAMEDNAME].uidName, szNameName, false, 2); const auto lpListData = reinterpret_cast<sortlistdata::sortListData*>(GetItemData(iRow)); auto ulPropType = PT_NULL; if (lpListData) { const auto prop = lpListData->cast<sortlistdata::propModelData>(); if (prop) { ulPropType = PROP_TYPE(prop->getPropTag()); } } const auto szVal = GetItemText(iRow, columns::pcPROPVAL); const auto szAltVal = GetItemText(iRow, columns::pcPROPVALALT); switch (ulPropType) { case PT_STRING8: case PT_UNICODE: { output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPVAL].uidName, szVal, true, 2); const auto binXML = binPropToXML(columns::PropXMLNames[columns::pcPROPVALALT].uidName, szAltVal, 2); output::Output(output::dbgLevel::NoDebug, fProps, false, binXML); } break; case PT_BINARY: { const auto binXML = binPropToXML(columns::PropXMLNames[columns::pcPROPVAL].uidName, szVal, 2); output::Output(output::dbgLevel::NoDebug, fProps, false, binXML); output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPVALALT].uidName, szAltVal, true, 2); } break; case PT_ERROR: { const auto errXML = errPropToXML(columns::PropXMLNames[columns::pcPROPVAL].uidName, szVal, 2); output::Output(output::dbgLevel::NoDebug, fProps, false, errXML); } break; default: output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPVAL].uidName, szVal, false, 2); output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPVALALT].uidName, szAltVal, false, 2); break; } const auto szSmartView = GetItemText(iRow, columns::pcPROPSMARTVIEW); output::OutputXMLValueToFile( fProps, columns::PropXMLNames[columns::pcPROPSMARTVIEW].uidName, szSmartView, true, 2); output::OutputToFile(fProps, L"\t</property>\n"); } output::OutputToFile(fProps, L"</properties>"); output::CloseFile(fProps); } } } void CSingleMAPIPropListCtrl::OnDblclk(_In_ NMHDR* /*pNMHDR*/, _In_ LRESULT* pResult) { output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"OnDblclk", L"calling OnEditProp\n"); OnEditProp(); *pResult = 0; } void CSingleMAPIPropListCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { output::DebugPrintEx(output::dbgLevel::Menu, CLASS, L"OnKeyDown", L"0x%X\n", nChar); const auto bCtrlPressed = GetKeyState(VK_CONTROL) < 0; const auto bShiftPressed = GetKeyState(VK_SHIFT) < 0; const auto bMenuPressed = GetKeyState(VK_MENU) < 0; if (!bMenuPressed) { if ('X' == nChar && bCtrlPressed && !bShiftPressed) { OnDeleteProperty(); } else if (VK_DELETE == nChar) { OnDeleteProperty(); } else if ('S' == nChar && bCtrlPressed) { SavePropsToXML(); } else if ('E' == nChar && bCtrlPressed) { OnEditProp(); } else if ('C' == nChar && bCtrlPressed && !bShiftPressed) { OnCopyProperty(); } else if ('V' == nChar && bCtrlPressed && !bShiftPressed) { OnPasteProperty(); } else if (VK_F5 == nChar) { RefreshMAPIPropList(); } else if (VK_RETURN == nChar) { if (!bCtrlPressed) { output::DebugPrintEx(output::dbgLevel::Menu, CLASS, L"OnKeyDown", L"calling OnEditProp\n"); OnEditProp(); } else { output::DebugPrintEx(output::dbgLevel::Menu, CLASS, L"OnKeyDown", L"calling OnOpenProperty\n"); OnOpenProperty(); } } else if (!m_lpHostDlg || !m_lpHostDlg->HandleKeyDown(nChar, bShiftPressed, bCtrlPressed, bMenuPressed)) { CSortListCtrl::OnKeyDown(nChar, nRepCnt, nFlags); } } } void CSingleMAPIPropListCtrl::OnContextMenu(_In_ CWnd* pWnd, CPoint pos) { if (pWnd && -1 == pos.x && -1 == pos.y) { POINT point = {0}; const auto iItem = GetNextItem(-1, LVNI_SELECTED); GetItemPosition(iItem, &point); ::ClientToScreen(pWnd->m_hWnd, &point); pos = point; } ui::DisplayContextMenu(IDR_MENU_PROPERTY_POPUP, IDR_MENU_MESSAGE_POPUP, m_lpHostDlg->m_hWnd, pos.x, pos.y); } void CSingleMAPIPropListCtrl::FindAllNamedProps() { if (!m_lpPropBag) return; output::DebugPrintEx( output::dbgLevel::NamedProp, CLASS, L"FindAllNamedProps", L"Calling GetNamesFromIDs with a NULL\n"); const auto names = cache::GetNamesFromIDs(m_lpPropBag->GetMAPIProp(), nullptr, 0); if (names.size() > 0) { for (const auto& name : names) { AddPropToExtraProps(PROP_TAG(NULL, name->getPropID()), false); } // Refresh the display RefreshMAPIPropList(); } } void CSingleMAPIPropListCtrl::CountNamedProps() { if (!m_lpPropBag) return; output::DebugPrintEx( output::dbgLevel::NamedProp, CLASS, L"CountNamedProps", L"Searching for the highest named prop mapping\n"); ULONG ulHighestKnown = cache::FindHighestNamedProp(m_lpPropBag->GetMAPIProp()); dialog::editor::CEditor MyResult(this, IDS_COUNTNAMEDPROPS, IDS_COUNTNAMEDPROPSPROMPT, CEDITOR_BUTTON_OK); if (ulHighestKnown) { const auto ulPropTag = PROP_TAG(NULL, ulHighestKnown); const auto name = cache::GetNameFromID(m_lpPropBag->GetMAPIProp(), ulPropTag, NULL); if (cache::namedPropCacheEntry::valid(name)) { output::DebugPrintEx( output::dbgLevel::NamedProp, CLASS, L"CountNamedProps", L"Found a named property at 0x%04X.\n", ulHighestKnown); } MyResult.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_HIGHESTNAMEDPROPTOTAL, true)); MyResult.SetDecimal(0, ulHighestKnown - 0x8000); MyResult.AddPane(viewpane::TextPane::CreateMultiLinePane(1, IDS_HIGHESTNAMEDPROPNUM, true)); if (cache::namedPropCacheEntry::valid(name)) { const auto namePropNames = cache::NameIDToStrings(ulPropTag, nullptr, name->getMapiNameId(), nullptr, false); MyResult.SetStringW( 1, strings::formatmessage( IDS_HIGHESTNAMEDPROPNAME, ulHighestKnown, namePropNames.name.c_str(), namePropNames.guid.c_str())); } } else { MyResult.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_HIGHESTNAMEDPROPTOTAL, true)); MyResult.LoadString(0, IDS_HIGHESTNAMEDPROPNOTFOUND); } static_cast<void>(MyResult.DisplayDialog()); } // Delete the selected property void CSingleMAPIPropListCtrl::OnDeleteProperty() { if (!m_lpPropBag || m_lpPropBag->GetType() == propertybag::propBagType::Row) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us const auto propModelData = GetSelectedPropModelData(); if (!propModelData) return; dialog::editor::CEditor Query( this, IDS_DELETEPROPERTY, IDS_DELETEPROPERTYPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); if (Query.DisplayDialog()) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnDeleteProperty", L"deleting property 0x%08X\n", propModelData->getPropTag()); const auto hRes = EC_H(lpPropBag->DeleteProp(propModelData->getPropTag(), propModelData->getName())); if (SUCCEEDED(hRes)) { // Refresh the display RefreshMAPIPropList(); } } } // Display the selected property as a security descriptor using a property sheet void CSingleMAPIPropListCtrl::OnDisplayPropertyAsSecurityDescriptorPropSheet() const { if (!m_lpPropBag || !import::pfnEditSecurity) return; const auto propModelData = GetSelectedPropModelData(); if (!propModelData) return; output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnDisplayPropertyAsSecurityDescriptorPropSheet", L"interpreting 0x%X as Security Descriptor\n", propModelData->getPropTag()); const auto mySecInfo = std::make_shared<mapi::mapiui::CMySecInfo>(m_lpPropBag->GetMAPIProp(), propModelData->getPropTag()); EC_B_S(import::pfnEditSecurity(m_hWnd, mySecInfo.get())); } void CSingleMAPIPropListCtrl::OnEditProp() { if (!m_lpPropBag) return; const auto propModelData = GetSelectedPropModelData(); if (!propModelData) return; OnEditGivenProp(propModelData->getPropTag(), propModelData->getName()); } void CSingleMAPIPropListCtrl::OnEditPropAsRestriction(ULONG ulPropTag) { if (!m_lpPropBag || !ulPropTag || PT_SRESTRICTION != PROP_TYPE(ulPropTag)) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us auto lpEditProp = lpPropBag->GetOneProp(ulPropTag, {}); // TODO: Should I have a name here? LPSRestriction lpResIn = nullptr; if (lpEditProp) { lpResIn = reinterpret_cast<LPSRestriction>(lpEditProp->Value.lpszA); } output::DebugPrint(output::dbgLevel::Generic, L"Source restriction before editing:\n"); output::outputRestriction(output::dbgLevel::Generic, nullptr, lpResIn, lpPropBag->GetMAPIProp()); dialog::editor::CRestrictEditor MyResEditor( this, nullptr, // No alloc parent - we must MAPIFreeBuffer the result lpResIn); if (MyResEditor.DisplayDialog()) { const auto lpModRes = MyResEditor.DetachModifiedSRestriction(); if (lpModRes) { output::DebugPrint(output::dbgLevel::Generic, L"Modified restriction:\n"); output::outputRestriction(output::dbgLevel::Generic, nullptr, lpModRes, lpPropBag->GetMAPIProp()); // need to merge the data we got back from the CRestrictEditor with our current prop set // so that we can free lpModRes SPropValue ResProp = {}; if (lpEditProp) { ResProp.ulPropTag = lpEditProp->ulPropTag; } else { ResProp.ulPropTag = ulPropTag; } ResProp.Value.lpszA = reinterpret_cast<LPSTR>(lpModRes); const auto hRes = EC_H(lpPropBag->SetProp(&ResProp, ulPropTag, L"")); // Remember, we had no alloc parent - this is safe to free MAPIFreeBuffer(lpModRes); if (SUCCEEDED(hRes)) { // refresh RefreshMAPIPropList(); } } } lpPropBag->FreeBuffer(lpEditProp); } void CSingleMAPIPropListCtrl::OnEditGivenProp(ULONG ulPropTag, const std::wstring& name) { LPSPropValue lpEditProp = nullptr; if (!m_lpPropBag) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us // Explicit check since TagToString is expensive if (fIsSet(output::dbgLevel::Generic)) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnEditGivenProp", L"editing property 0x%X (= %ws = %ws)\n", ulPropTag, name.c_str(), proptags::TagToString(ulPropTag, lpPropBag->GetMAPIProp(), lpPropBag->IsAB(), true).c_str()); } ulPropTag = PT_ERROR == PROP_TYPE(ulPropTag) ? CHANGE_PROP_TYPE(ulPropTag, PT_UNSPECIFIED) : ulPropTag; if (PT_SRESTRICTION == PROP_TYPE(ulPropTag)) { OnEditPropAsRestriction(ulPropTag); return; } if (PT_OBJECT == PROP_TYPE(ulPropTag)) { EC_H_S(DisplayTable(lpPropBag->GetMAPIProp(), ulPropTag, dialog::objectType::otDefault, m_lpHostDlg)); return; } const auto lpSourceObj = lpPropBag->GetMAPIProp(); auto bUseStream = false; if (PROP_ID(PR_RTF_COMPRESSED) == PROP_ID(ulPropTag)) { bUseStream = true; } else { lpEditProp = lpPropBag->GetOneProp(ulPropTag, name); } if (lpEditProp && PROP_TYPE(lpEditProp->ulPropTag) == PT_ERROR && lpEditProp->Value.err == MAPI_E_NOT_ENOUGH_MEMORY) { bUseStream = true; } if (bUseStream) { dialog::editor::CStreamEditor MyEditor( this, IDS_PROPEDITOR, IDS_STREAMEDITORPROMPT, lpSourceObj, ulPropTag, true, // Guess the type of stream to use lpPropBag->IsAB(), false, false, NULL, NULL, NULL); if (MyEditor.DisplayDialog()) { RefreshMAPIPropList(); } } else { if (PROP_TYPE(ulPropTag) == PT_UNSPECIFIED && lpEditProp) ulPropTag = lpEditProp->ulPropTag; const auto propEditor = dialog::editor::DisplayPropertyEditor( this, IDS_PROPEDITOR, name, lpPropBag->IsAB(), lpSourceObj, ulPropTag, false, lpEditProp); if (propEditor) { const auto lpModProp = propEditor->getValue(); if (lpModProp) { // If we didn't have a source object, we need to shove our results back in to the property bag if (!lpSourceObj) { // SetProp does not take ownership of memory EC_H_S(lpPropBag->SetProp(lpModProp, ulPropTag, name)); } RefreshMAPIPropList(); } } } lpPropBag->FreeBuffer(lpEditProp); } // Display the selected property as a stream using CStreamEditor void CSingleMAPIPropListCtrl::OnEditPropAsStream(ULONG ulType, bool bEditAsRTF) { if (!m_lpPropBag) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us const auto propModelData = GetSelectedPropModelData(); if (!propModelData) return; auto ulPropTag = propModelData->getPropTag(); // Explicit check since TagToString is expensive if (fIsSet(output::dbgLevel::Generic)) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnEditPropAsStream", L"editing property 0x%X (= %ws) as stream, ulType = 0x%08X, bEditAsRTF = 0x%X\n", ulPropTag, proptags::TagToString(ulPropTag, lpPropBag->GetMAPIProp(), lpPropBag->IsAB(), true).c_str(), ulType, bEditAsRTF); } ulPropTag = CHANGE_PROP_TYPE(ulPropTag, ulType); auto bUseWrapEx = false; ULONG ulRTFFlags = NULL; ULONG ulInCodePage = NULL; ULONG ulOutCodePage = CP_ACP; // Default to ANSI - check if this is valid for UNICODE builds if (bEditAsRTF) { dialog::editor::CEditor MyPrompt( this, IDS_USEWRAPEX, IDS_USEWRAPEXPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyPrompt.AddPane(viewpane::CheckPane::Create(0, IDS_USEWRAPEX, true, false)); if (!MyPrompt.DisplayDialog()) return; if (MyPrompt.GetCheck(0)) { bUseWrapEx = true; const auto lpProp = lpPropBag->GetOneProp(PR_INTERNET_CPID, {}); if (lpProp && PT_LONG == PROP_TYPE(lpProp[0].ulPropTag)) { ulInCodePage = lpProp[0].Value.l; } lpPropBag->FreeBuffer(lpProp); dialog::editor::CEditor MyPrompt2( this, IDS_WRAPEXFLAGS, IDS_WRAPEXFLAGSPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyPrompt2.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_WRAPEXFLAGS, false)); MyPrompt2.SetHex(0, MAPI_NATIVE_BODY); MyPrompt2.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_ULINCODEPAGE, false)); MyPrompt2.SetDecimal(1, ulInCodePage); MyPrompt2.AddPane(viewpane::TextPane::CreateSingleLinePane(2, IDS_ULOUTCODEPAGE, false)); MyPrompt2.SetDecimal(2, CP_UNICODE); if (!MyPrompt2.DisplayDialog()) return; ulRTFFlags = MyPrompt2.GetHex(0); ulInCodePage = MyPrompt2.GetDecimal(1); ulOutCodePage = MyPrompt2.GetDecimal(2); } } dialog::editor::CStreamEditor MyEditor( this, IDS_PROPEDITOR, IDS_STREAMEDITORPROMPT, lpPropBag->GetMAPIProp(), ulPropTag, false, // No stream guessing lpPropBag->IsAB(), bEditAsRTF, bUseWrapEx, ulRTFFlags, ulInCodePage, ulOutCodePage); if (MyEditor.DisplayDialog()) { RefreshMAPIPropList(); } } void CSingleMAPIPropListCtrl::OnCopyProperty() const { cache::CGlobalCache::getInstance().SetPropertyToCopy(GetSelectedPropModelData(), m_lpPropBag); } void CSingleMAPIPropListCtrl::OnPasteProperty() { if (!m_lpHostDlg || !m_lpPropBag) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us const auto sourceProp = cache::CGlobalCache::getInstance().GetPropertyToCopy(); const auto sourcePropBag = cache::CGlobalCache::getInstance().GetSourcePropBag(); const auto ulSourcePropTag = sourceProp->getPropTag(); auto lpSourcePropObj = sourcePropBag->GetMAPIProp(); if (!lpSourcePropObj) { // If we don't have a source prop object, try setting the prop back to the prop bag const auto sourceName = sourceProp->getName(); const auto lpSourceProp = sourcePropBag->GetOneProp(ulSourcePropTag, sourceName); EC_H(lpPropBag->SetProp(lpSourceProp, ulSourcePropTag, sourceName)); this->RefreshMAPIPropList(); return; } auto hRes = S_OK; LPSPropProblemArray lpProblems = nullptr; SPropTagArray TagArray = {1, ulSourcePropTag}; dialog::editor::CEditor MyData( this, IDS_PASTEPROP, IDS_PASTEPROPPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); UINT uidDropDown[] = {IDS_DDCOPYPROPS, IDS_DDGETSETPROPS, IDS_DDCOPYSTREAM}; MyData.AddPane(viewpane::DropDownPane::Create(0, IDS_COPYSTYLE, _countof(uidDropDown), uidDropDown, true)); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_SOURCEPROP, false)); MyData.SetHex(1, ulSourcePropTag); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(2, IDS_TARGETPROP, false)); MyData.SetHex(2, ulSourcePropTag); if (!MyData.DisplayDialog()) return; const auto ulSourceTag = MyData.GetHex(1); auto ulTargetTag = MyData.GetHex(2); mapi::setTag(TagArray, 0) = ulSourceTag; if (PROP_TYPE(ulTargetTag) != PROP_TYPE(ulSourceTag)) ulTargetTag = CHANGE_PROP_TYPE(ulTargetTag, PROP_TYPE(ulSourceTag)); switch (MyData.GetDropDown(0)) { case 0: { dialog::editor::CEditor MyCopyData( this, IDS_PASTEPROP, IDS_COPYPASTEPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); const auto szGuid = guid::GUIDToStringAndName(&IID_IMAPIProp); MyCopyData.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_INTERFACE, szGuid, false)); MyCopyData.AddPane(viewpane::TextPane::CreateSingleLinePane(1, IDS_FLAGS, false)); MyCopyData.SetHex(1, MAPI_DIALOG); if (!MyCopyData.DisplayDialog()) return; auto MyGUID = guid::StringToGUID(MyCopyData.GetStringW(0)); auto lpProgress = mapi::mapiui::GetMAPIProgress(L"IMAPIProp::CopyProps", m_lpHostDlg->m_hWnd); // STRING_OK auto ulCopyFlags = MyCopyData.GetHex(1); if (lpProgress) ulCopyFlags |= MAPI_DIALOG; hRes = EC_MAPI(lpSourcePropObj->CopyProps( &TagArray, lpProgress ? reinterpret_cast<ULONG_PTR>(m_lpHostDlg->m_hWnd) : NULL, // ui param lpProgress, // progress &MyGUID, lpPropBag->GetMAPIProp(), ulCopyFlags, &lpProblems)); if (lpProgress) lpProgress->Release(); } break; case 1: { ULONG ulValues = NULL; LPSPropValue lpSourceProp = nullptr; hRes = EC_MAPI(lpSourcePropObj->GetProps(&TagArray, fMapiUnicode, &ulValues, &lpSourceProp)); if (SUCCEEDED(hRes) && ulValues && lpSourceProp && PT_ERROR != lpSourceProp->ulPropTag) { lpSourceProp->ulPropTag = ulTargetTag; hRes = EC_H(lpPropBag->SetProps(ulValues, lpSourceProp)); } } break; case 2: hRes = EC_H(mapi::CopyPropertyAsStream(lpSourcePropObj, lpPropBag->GetMAPIProp(), ulSourceTag, ulTargetTag)); break; } EC_PROBLEMARRAY(lpProblems); MAPIFreeBuffer(lpProblems); if (SUCCEEDED(hRes)) { hRes = EC_H(lpPropBag->Commit()); if (SUCCEEDED(hRes)) { // refresh RefreshMAPIPropList(); } } lpSourcePropObj->Release(); } void CSingleMAPIPropListCtrl::OnCopyTo() { // for now, we only copy from objects - copying from rows would be difficult to generalize if (!m_lpHostDlg || !m_lpPropBag) return; auto lpSourcePropObj = cache::CGlobalCache::getInstance().GetSourcePropObject(); if (!lpSourcePropObj) return; const auto hRes = EC_H(mapi::CopyTo( m_lpHostDlg->m_hWnd, lpSourcePropObj, m_lpPropBag->GetMAPIProp(), &IID_IMAPIProp, nullptr, m_lpPropBag->IsAB(), true)); if (SUCCEEDED(hRes)) { EC_H_S(m_lpPropBag->Commit()); // refresh RefreshMAPIPropList(); } lpSourcePropObj->Release(); } // Open a binary property as an entry ID void CSingleMAPIPropListCtrl::OnOpenProperty() const { auto hRes = S_OK; if (!m_lpHostDlg) return; const auto propModelData = GetSelectedPropModelData(); if (!propModelData) return; const auto ulPropTag = propModelData->getPropTag(); output::DebugPrintEx(output::dbgLevel::Generic, CLASS, L"OnOpenProperty", L"asked to open 0x%X\n", ulPropTag); LPSPropValue lpProp = nullptr; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us if (lpPropBag) { lpProp = lpPropBag->GetOneProp(ulPropTag, {}); // TODO: Should I have a name here } if (SUCCEEDED(hRes) && lpProp) { if (lpPropBag && PT_OBJECT == PROP_TYPE(lpProp->ulPropTag)) { EC_H_S(DisplayTable( lpPropBag->GetMAPIProp(), lpProp->ulPropTag, dialog::objectType::otDefault, m_lpHostDlg)); } else if (PT_BINARY == PROP_TYPE(lpProp->ulPropTag) || PT_MV_BINARY == PROP_TYPE(lpProp->ulPropTag)) { switch (PROP_TYPE(lpProp->ulPropTag)) { case PT_BINARY: output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnOpenProperty", L"property is PT_BINARY\n"); m_lpHostDlg->OnOpenEntryID(mapi::getBin(lpProp)); break; case PT_MV_BINARY: output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnOpenProperty", L"property is PT_MV_BINARY\n"); if (hRes == S_OK && lpProp && PT_MV_BINARY == PROP_TYPE(lpProp->ulPropTag)) { output::DebugPrintEx( output::dbgLevel::Generic, CLASS, L"OnOpenProperty", L"opened MV structure. There are 0x%X binaries in it.\n", lpProp->Value.MVbin.cValues); for (ULONG i = 0; i < lpProp->Value.MVbin.cValues; i++) { m_lpHostDlg->OnOpenEntryID(lpProp->Value.MVbin.lpbin[i]); } } break; } } } if (lpPropBag) { lpPropBag->FreeBuffer(lpProp); } } void CSingleMAPIPropListCtrl::OnModifyExtraProps() { cache::CGlobalCache::getInstance().MAPIInitialize(NULL); dialog::editor::CTagArrayEditor MyTagArrayEditor( this, IDS_EXTRAPROPS, NULL, nullptr, m_sptExtraProps, m_lpPropBag ? m_lpPropBag->IsAB() : false, m_lpPropBag ? m_lpPropBag->GetMAPIProp() : nullptr); if (!MyTagArrayEditor.DisplayDialog()) return; const auto lpNewTagArray = MyTagArrayEditor.DetachModifiedTagArray(); if (lpNewTagArray) { MAPIFreeBuffer(m_sptExtraProps); m_sptExtraProps = lpNewTagArray; } RefreshMAPIPropList(); } void CSingleMAPIPropListCtrl::OnEditGivenProperty() { if (!m_lpPropBag) return; // Display a dialog to get a property number. dialog::editor::CPropertyTagEditor MyPropertyTag( IDS_EDITGIVENPROP, NULL, // prompt NULL, m_lpPropBag->IsAB(), m_lpPropBag->GetMAPIProp(), this); if (MyPropertyTag.DisplayDialog()) { OnEditGivenProp(MyPropertyTag.GetPropertyTag(), {}); } } void CSingleMAPIPropListCtrl::OnOpenPropertyAsTable() { if (!m_lpPropBag) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us // Display a dialog to get a property number. dialog::editor::CPropertyTagEditor MyPropertyTag( IDS_OPENPROPASTABLE, NULL, // prompt NULL, lpPropBag->IsAB(), lpPropBag->GetMAPIProp(), this); if (!MyPropertyTag.DisplayDialog()) return; dialog::editor::CEditor MyData( this, IDS_OPENPROPASTABLE, IDS_OPENPROPASTABLEPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); MyData.AddPane(viewpane::CheckPane::Create(0, IDS_OPENASEXTABLE, false, false)); if (!MyData.DisplayDialog()) return; if (MyData.GetCheck(0)) { EC_H_S(DisplayExchangeTable( lpPropBag->GetMAPIProp(), CHANGE_PROP_TYPE(MyPropertyTag.GetPropertyTag(), PT_OBJECT), dialog::objectType::otDefault, m_lpHostDlg)); } else { EC_H_S(DisplayTable( lpPropBag->GetMAPIProp(), CHANGE_PROP_TYPE(MyPropertyTag.GetPropertyTag(), PT_OBJECT), dialog::objectType::otDefault, m_lpHostDlg)); } } void CSingleMAPIPropListCtrl::OnPasteNamedProps() { if (!m_lpPropBag) return; auto lpPropBag = m_lpPropBag; // Hold the prop bag so it doesn't get deleted under us const auto lpSourceMsgEID = cache::CGlobalCache::getInstance().GetMessagesToCopy(); if (cache::CGlobalCache::getInstance().GetBufferStatus() & BUFFER_MESSAGES && lpSourceMsgEID && 1 == lpSourceMsgEID->cValues) { dialog::editor::CEditor MyData( this, IDS_PASTENAMEDPROPS, IDS_PASTENAMEDPROPSPROMPT, CEDITOR_BUTTON_OK | CEDITOR_BUTTON_CANCEL); const auto szGuid = guid::GUIDToStringAndName(&PS_PUBLIC_STRINGS); MyData.AddPane(viewpane::TextPane::CreateSingleLinePane(0, IDS_GUID, szGuid, false)); MyData.AddPane(viewpane::CheckPane::Create(1, IDS_MAPIMOVE, false, false)); MyData.AddPane(viewpane::CheckPane::Create(2, IDS_MAPINOREPLACE, false, false)); if (!MyData.DisplayDialog()) return; ULONG ulObjType = 0; auto propSetGUID = guid::StringToGUID(MyData.GetStringW(0)); auto lpSource = mapi::CallOpenEntry<LPMAPIPROP>( nullptr, nullptr, cache::CGlobalCache::getInstance().GetSourceParentFolder(), nullptr, lpSourceMsgEID->lpbin, nullptr, MAPI_BEST_ACCESS, &ulObjType); if (ulObjType == MAPI_MESSAGE && lpSource) { auto hRes = EC_H(mapi::CopyNamedProps( lpSource, &propSetGUID, MyData.GetCheck(1), MyData.GetCheck(2), lpPropBag->GetMAPIProp(), m_lpHostDlg->m_hWnd)); if (SUCCEEDED(hRes)) { hRes = EC_H(lpPropBag->Commit()); } if (SUCCEEDED(hRes)) { RefreshMAPIPropList(); } lpSource->Release(); } } } _Check_return_ bool CSingleMAPIPropListCtrl::HandleAddInMenu(WORD wMenuSelect) const { if (wMenuSelect < ID_ADDINPROPERTYMENU) return false; CWaitCursor Wait; // Change the mouse to an hourglass while we work. const auto lpAddInMenu = ui::addinui::GetAddinMenuItem(m_lpHostDlg->m_hWnd, wMenuSelect); if (!lpAddInMenu) return false; _AddInMenuParams MyAddInMenuParams = {nullptr}; MyAddInMenuParams.lpAddInMenu = lpAddInMenu; MyAddInMenuParams.ulAddInContext = MENU_CONTEXT_PROPERTY; MyAddInMenuParams.hWndParent = m_hWnd; MyAddInMenuParams.lpMAPIProp = m_lpPropBag->GetMAPIProp(); if (m_lpMapiObjects) { MyAddInMenuParams.lpMAPISession = m_lpMapiObjects->GetSession(); // do not release MyAddInMenuParams.lpMDB = m_lpMapiObjects->GetMDB(); // do not release MyAddInMenuParams.lpAdrBook = m_lpMapiObjects->GetAddrBook(false); // do not release } if (m_lpPropBag) { const auto lpRowPropBag = std::dynamic_pointer_cast<propertybag::rowPropertyBag>(m_lpPropBag); if (lpRowPropBag) { SRow MyRow = {0}; static_cast<void>(lpRowPropBag->GetAllProps(&MyRow.cValues, &MyRow.lpProps)); // No need to free MyAddInMenuParams.lpRow = &MyRow; MyAddInMenuParams.ulCurrentFlags |= MENU_FLAGS_ROW; } } const auto propModelData = GetSelectedPropModelData(); if (propModelData) { MyAddInMenuParams.ulPropTag = propModelData->getPropTag(); } ui::addinui::InvokeAddInMenu(&MyAddInMenuParams); return true; } } // namespace controls::sortlistctrl
19,815
343
<reponame>devtayls/elixir { "blurb": "Named functions may declare default values for one or more of their arguments.", "authors": [ "neenjaw" ], "contributors": [ "angelikatyborska" ] }
81
14,668
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_BLUETOOTH_BLUETOOTH_REMOTE_GATT_UTILS_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_BLUETOOTH_BLUETOOTH_REMOTE_GATT_UTILS_H_ #include "third_party/blink/renderer/core/typed_arrays/dom_data_view.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { class BluetoothRemoteGATTUtils final { STATIC_ONLY(BluetoothRemoteGATTUtils); public: static DOMDataView* ConvertWTFVectorToDataView(const WTF::Vector<uint8_t>&); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BLUETOOTH_BLUETOOTH_REMOTE_GATT_UTILS_H_
333
406
{ "name": "gluestick-packages", "scripts": { "lerna": "lerna", "yarn:install": "lerna exec --concurrency=1 -- yarn install", "yarn:install:ci": "lerna exec --concurrency=1 -- yarn install --frozen-lockfile", "install:npm": "npm install && npm run build && lerna bootstrap", "install:yarn": "yarn install && yarn run build && yarn run yarn:install && lerna bootstrap --concurrency=1", "install:yarn:ci": "yarn install --frozen-lockfile && yarn run build && yarn run yarn:install:ci && lerna bootstrap --concurrency=1", "clean": "lerna clean --yes", "test": "jest", "test:watch": "jest --watch", "test-coverage": "npm run test -- --coverage", "lint": "eslint ./packages", "flow": "flow", "ci": "npm run lint && npm run flow && npm run test-coverage", "publish": "npm run build && ./scripts/deploy.js", "e2e": "./scripts/e2e/runner.js", "build": "node ./scripts/build.js", "docs:clean": "rm -rf _book", "docs:prepare": "gitbook install", "docs:watch": "npm run docs:prepare && gitbook serve", "docs:build": "npm run docs:prepare && gitbook build -g TrueCar/gluestick" }, "dependencies": { "flow-typed": "2.1.5", "gitbook": "^3.2.3", "gitbook-cli": "^2.3.2", "gitbook-plugin-anchorjs": "^1.1.1", "gitbook-plugin-edit-link": "^2.0.2", "gitbook-plugin-github": "2.0.0", "gitbook-plugin-prism": "^2.3.0", "jest": "23.5.0", "lerna": "2.0.0-rc.5" }, "devDependencies": { "babel-core": "^6.24.1", "babel-eslint": "^7.2.3", "babel-plugin-transform-decorators-legacy": "1.3.4", "babel-plugin-transform-flow-strip-types": "^6.22.0", "babel-preset-env": "^1.6.0", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-preset-stage-0": "^6.24.1", "eslint": "^4.2.0", "eslint-config-airbnb": "^15.0.2", "eslint-config-prettier": "^2.3.0", "eslint-plugin-import": "^2.2.0", "eslint-plugin-jsx-a11y": "^6.0.2", "eslint-plugin-prettier": "^2.1.2", "eslint-plugin-react": "^7.1.0", "flow-bin": "^0.50.0", "flow-copy-source": "^1.2.0", "glob": "^7.1.2", "mkdirp": "0.5.1", "node-fetch": "^1.7.1", "prettier": "^1.5.3", "rimraf": "2.6.1", "traverse": "0.6.6" }, "jest": { "notify": true, "roots": [ "packages" ], "transform": { "\\.js$": "<rootDir>/jestTransform.js" }, "testRegex": "(src|shared)/(.*/)?__tests__/.*\\.test\\.js$", "moduleNameMapper": { "^application-config$": "<rootDir>/packages/gluestick/src/__tests__/mocks/applicationConfig.js", "^entry-wrapper$": "<rootDir>/packages/gluestick/src/__tests__/mocks/EntryWrapper.js", "^gluestick-hooks$": "<rootDir>/packages/gluestick/src/__tests__/mocks/gluestickHooks.js", "^redux-middlewares$": "<rootDir>/packages/gluestick/src/__tests__/mocks/reduxMiddlewares.js", "^project-entries$": "<rootDir>/packages/gluestick/src/__tests__/mocks/projectEntries.js", "^project-entries-config$": "<rootDir>/packages/gluestick/src/__tests__/mocks/projectEntriesConfig.js" } }, "private": true, "workspaces": [ "packages/*" ], "npmClient": "yarn", "useWorkspaces": true }
1,537
2,053
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouter.xtra.http; import scouter.agent.error.ASYNC_SERVLET_TIMEOUT; import scouter.agent.proxy.IHttpTrace; import scouter.agent.trace.TraceContext; import scouter.agent.trace.TraceContextManager; import scouter.agent.trace.TraceMain; import scouter.agent.trace.TransferMap; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static scouter.agent.AgentCommonConstant.REQUEST_ATTRIBUTE_ALL_DISPATCHED_TRACE_CONTEXT; import static scouter.agent.AgentCommonConstant.REQUEST_ATTRIBUTE_ASYNC_DISPATCH; import static scouter.agent.AgentCommonConstant.REQUEST_ATTRIBUTE_CALLER_TRANSFER_MAP; import static scouter.agent.AgentCommonConstant.REQUEST_ATTRIBUTE_INITIAL_TRACE_CONTEXT; import static scouter.agent.AgentCommonConstant.REQUEST_ATTRIBUTE_SELF_DISPATCHED; import static scouter.agent.AgentCommonConstant.REQUEST_ATTRIBUTE_TRACE_CONTEXT; public class HttpTrace3 extends HttpTrace implements IHttpTrace { public void addAsyncContextListener(Object ac) { TraceContext traceContext = TraceContextManager.getContext(); if(traceContext == null) return; AsyncContext actx = (AsyncContext)ac; if(actx.getRequest().getAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH) == null) { actx.getRequest().setAttribute(REQUEST_ATTRIBUTE_INITIAL_TRACE_CONTEXT, traceContext); actx.getRequest().setAttribute(REQUEST_ATTRIBUTE_TRACE_CONTEXT, traceContext); actx.getRequest().setAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH, 1); } else { int dispatchCount = (Integer) actx.getRequest().getAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH); actx.getRequest().setAttribute(REQUEST_ATTRIBUTE_TRACE_CONTEXT, traceContext); actx.getRequest().setAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH, ++dispatchCount); } List<TraceContext> dispatchedContexts = (List<TraceContext>)actx.getRequest().getAttribute(REQUEST_ATTRIBUTE_ALL_DISPATCHED_TRACE_CONTEXT); if(dispatchedContexts == null) { dispatchedContexts = new ArrayList<TraceContext>(); actx.getRequest().setAttribute(REQUEST_ATTRIBUTE_ALL_DISPATCHED_TRACE_CONTEXT, dispatchedContexts); } if(!dispatchedContexts.contains(traceContext)) { dispatchedContexts.add(traceContext); } actx.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent asyncEvent) throws IOException { // System.out.println("[scouter][asynccontext]onComplete:count: " + asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH) + " => " + this.toString()); // System.out.println("[scouter][asynccontext]onComplete:thread: " + Thread.currentThread().getName()); List<TraceContext> traceContextList = (List<TraceContext>) asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ALL_DISPATCHED_TRACE_CONTEXT); Iterator<TraceContext> iter = traceContextList.iterator(); while(iter.hasNext()) { TraceContext ctx = iter.next(); TraceMain.endHttpServiceFinal(ctx, asyncEvent.getSuppliedRequest(), asyncEvent.getSuppliedResponse(), ctx.asyncThrowable); TraceContextManager.completeDeferred(ctx); } } @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException { // System.out.println("[scouter][asynccontext]onTimeout:count:" + asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH) + " => " + this.toString()); // System.out.println("[scouter][asynccontext]onTimeout:thread: " + Thread.currentThread().getName()); List<TraceContext> traceContextList = (List<TraceContext>) asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ALL_DISPATCHED_TRACE_CONTEXT); Iterator<TraceContext> iter = traceContextList.iterator(); while(iter.hasNext()) { TraceContext ctx = iter.next(); ctx.asyncThrowable = new ASYNC_SERVLET_TIMEOUT("exceed async servlet timeout! : " + asyncEvent.getAsyncContext().getTimeout() + "ms"); } } @Override public void onError(AsyncEvent asyncEvent) throws IOException { // System.out.println("[scouter][asynccontext]onError:count:" + asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH) + " => " + this.toString()); // System.out.println("[scouter][asynccontext]onError:thread: " + Thread.currentThread().getName()); List<TraceContext> traceContextList = (List<TraceContext>) asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ALL_DISPATCHED_TRACE_CONTEXT); Iterator<TraceContext> iter = traceContextList.iterator(); while(iter.hasNext()) { TraceContext ctx = iter.next(); ctx.asyncThrowable = asyncEvent.getThrowable(); } } @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException { // System.out.println("[scouter][asynccontext]onStartAsync:count:" + asyncEvent.getSuppliedRequest().getAttribute(REQUEST_ATTRIBUTE_ASYNC_DISPATCH) + " => " + this.toString()); // System.out.println("[scouter][asynccontext]onStartAsync:thread: " + Thread.currentThread().getName()); } }); } public TraceContext getTraceContextFromAsyncContext(Object oAsyncContext) { AsyncContext asyncContext = (AsyncContext) oAsyncContext; TraceContext currentTraceContext = (TraceContext)asyncContext.getRequest().getAttribute(REQUEST_ATTRIBUTE_TRACE_CONTEXT); return currentTraceContext; } public void setDispatchTransferMap(Object oAsyncContext, long gxid, long caller, long callee, byte xType) { AsyncContext asyncContext = (AsyncContext) oAsyncContext; asyncContext.getRequest().setAttribute(REQUEST_ATTRIBUTE_CALLER_TRANSFER_MAP, new TransferMap.ID(gxid, caller, callee, xType)); } public void setSelfDispatch(Object oAsyncContext, boolean self) { AsyncContext asyncContext = (AsyncContext) oAsyncContext; asyncContext.getRequest().setAttribute(REQUEST_ATTRIBUTE_SELF_DISPATCHED, self); } public boolean isSelfDispatch(Object oAsyncContext) { AsyncContext asyncContext = (AsyncContext) oAsyncContext; return Boolean.TRUE.equals(asyncContext.getRequest().getAttribute(REQUEST_ATTRIBUTE_SELF_DISPATCHED)); } }
2,944
2,221
/* * 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.flume.source; import java.util.ArrayList; import java.util.List; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.DatagramSocket; import com.google.common.base.Charsets; import org.apache.flume.Channel; import org.apache.flume.ChannelSelector; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.Transaction; import org.apache.flume.channel.ChannelProcessor; import org.apache.flume.channel.MemoryChannel; import org.apache.flume.channel.ReplicatingChannelSelector; import org.apache.flume.conf.Configurables; import org.junit.Assert; import org.junit.Test; import org.slf4j.LoggerFactory; public class TestNetcatUdpSource { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TestNetcatUdpSource.class); private NetcatUdpSource source; private Channel channel; private static final int TEST_NETCAT_PORT = 0; private final String shortString = "Lorem ipsum dolor sit amet."; private final String mediumString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Nunc maximus rhoncus viverra. Nunc a metus."; private void init() { source = new NetcatUdpSource(); channel = new MemoryChannel(); Configurables.configure(channel, new Context()); List<Channel> channels = new ArrayList<Channel>(); channels.add(channel); ChannelSelector rcs = new ReplicatingChannelSelector(); rcs.setChannels(channels); source.setChannelProcessor(new ChannelProcessor(rcs)); Context context = new Context(); context.put("port", String.valueOf(TEST_NETCAT_PORT)); source.configure(context); } /** Tests the keepFields configuration parameter (enabled or disabled) using SyslogUDPSource.*/ private void runUdpTest(String data1) throws IOException { init(); source.start(); // Write some message to the port DatagramSocket socket; DatagramPacket datagramPacket; datagramPacket = new DatagramPacket(data1.getBytes(), data1.getBytes().length, InetAddress.getLocalHost(), source.getSourcePort()); for (int i = 0; i < 10 ; i++) { socket = new DatagramSocket(); socket.send(datagramPacket); socket.close(); } List<Event> channelEvents = new ArrayList<Event>(); Transaction txn = channel.getTransaction(); txn.begin(); for (int i = 0; i < 10; i++) { Event e = channel.take(); Assert.assertNotNull(e); channelEvents.add(e); } try { txn.commit(); } catch (Throwable t) { txn.rollback(); } finally { txn.close(); } source.stop(); for (Event e : channelEvents) { Assert.assertNotNull(e); String str = new String(e.getBody(), Charsets.UTF_8); logger.info(str); Assert.assertArrayEquals(data1.getBytes(), e.getBody()); } } @Test public void testLargePayload() throws Exception { init(); source.start(); // Write some message to the netcat port byte[] largePayload = getPayload(1000).getBytes(); DatagramSocket socket; DatagramPacket datagramPacket; datagramPacket = new DatagramPacket(largePayload, 1000, InetAddress.getLocalHost(), source.getSourcePort()); for (int i = 0; i < 10 ; i++) { socket = new DatagramSocket(); socket.send(datagramPacket); socket.close(); } List<Event> channelEvents = new ArrayList<Event>(); Transaction txn = channel.getTransaction(); txn.begin(); for (int i = 0; i < 10; i++) { Event e = channel.take(); Assert.assertNotNull(e); channelEvents.add(e); } try { txn.commit(); } catch (Throwable t) { txn.rollback(); } finally { txn.close(); } source.stop(); for (Event e : channelEvents) { Assert.assertNotNull(e); Assert.assertArrayEquals(largePayload, e.getBody()); } } @Test public void testShortString() throws IOException { runUdpTest(shortString); } @Test public void testMediumString() throws IOException { runUdpTest(mediumString); } private String getPayload(int length) { StringBuilder payload = new StringBuilder(length); for (int n = 0; n < length; ++n) { payload.append("x"); } return payload.toString(); } }
1,855
435
<filename>pybay-2017/videos/moshe-zadka-and-kurt-b-rose-moving-towards-best-practices-in-legacy-code-bases-pybay2017.json { "description": "When a company is young, getting the product out the door is the most important thing. Time to market and lopsided hiring of inexperienced developers often ends up delivering a product that works, but is riddled with Python anti-patterns. How to move towards best practices while maintaining development velocity and product stability?\n\n**Abstract**\n\nReal life is messy. Real companies doubly so. While, of course, the decision to use Python is a good one, often developers are hired who are either inexperienced or are new to Python. Following best practices, or even learning what they are, or even avoiding replicating Java/C++ in Python, are treated as luxuries reserved for bigger companies.\n\nAfter enough pain-- in the form of production outages-- is experienced, it is often possible to convince companies that efforts need to be made to bring their code up to date. What is the best way to achieve that?\n\nWe will talk about practices to update to the newest version of Python, and the newest versions of libraries, while avoiding (most) risk. We will cover techniques to introduce static analysis, and better unit testing, to reduce the chance of customer-facing problems. We will also cover how to refactor large mono-repos into manageable pieces using pip, pants and pex. Finally, we will cover how to introduce a microservice architecture gradually, in order to isolate faults.\n\n**Bios**\n\nMoshe is a core Twisted contributor, and has contributed to core Python. He has building and deploying web applications since 2001.\n\n<NAME> has been developing in Python since 2008 in the areas of web, networking, and security at Samsung, PayPal, and several startups.", "language": "eng", "recorded": "2017-08-12", "speakers": [ "<NAME>", "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/liXwz9ygeIk/hqdefault.jpg", "title": "Moving Towards Best Practices in Legacy Code Bases", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=liXwz9ygeIk" } ] }
588
348
<reponame>chamberone/Leaflet.PixiOverlay<gh_stars>100-1000 {"nom":"Cotignac","circ":"8ème circonscription","dpt":"Var","inscrits":1790,"abs":919,"votants":871,"blancs":63,"nuls":16,"exp":792,"res":[{"nuance":"REM","nom":"<NAME>","voix":514},{"nuance":"FN","nom":"<NAME>","voix":278}]}
118
777
<filename>services/ui/display/screen_manager_ozone.cc // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/display/screen_manager_ozone.h" #include <string> #include <utility> #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/system/devicemode.h" #include "services/service_manager/public/cpp/interface_registry.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/display/manager/chromeos/display_change_observer.h" #include "ui/display/manager/chromeos/touch_transform_controller.h" #include "ui/display/manager/display_layout_store.h" #include "ui/display/manager/display_manager_utilities.h" #include "ui/display/screen.h" #include "ui/display/screen_base.h" #include "ui/display/types/display_snapshot.h" #include "ui/display/types/fake_display_controller.h" #include "ui/display/types/native_display_delegate.h" #include "ui/gfx/geometry/rect.h" #include "ui/ozone/public/ozone_platform.h" namespace display { namespace { // Needed for DisplayConfigurator::ForceInitialConfigure. const SkColor kChromeOsBootColor = SkColorSetRGB(0xfe, 0xfe, 0xfe); // Recursively swaps the displays in a DisplayLayout to change the primary // display but keep the same relative display layout. // TODO(kylechar): This is copied from WindowTreeHostManager. The concept of // getting the same relative display layout with a different primary display id // should become a function on DisplayLayout itself to avoid reimplementing it // here. void SwapRecursive(const std::map<int64_t, DisplayPlacement*>& id_to_placement, int64_t current_primary_id, int64_t display_id) { if (display_id == current_primary_id) return; DCHECK(id_to_placement.count(display_id)); DisplayPlacement* placement = id_to_placement.at(display_id); DCHECK(placement); SwapRecursive(id_to_placement, current_primary_id, placement->parent_display_id); placement->Swap(); } } // namespace // static std::unique_ptr<ScreenManager> ScreenManager::Create() { return base::MakeUnique<ScreenManagerOzone>(); } ScreenManagerOzone::ScreenManagerOzone() {} ScreenManagerOzone::~ScreenManagerOzone() { // We are shutting down and don't want to make anymore display changes. fake_display_controller_ = nullptr; touch_transform_controller_.reset(); if (display_manager_) display_manager_->RemoveObserver(this); if (display_change_observer_) { display_configurator_.RemoveObserver(display_change_observer_.get()); display_change_observer_.reset(); } if (display_manager_) display_manager_.reset(); } void ScreenManagerOzone::SetPrimaryDisplayId(int64_t display_id) { DCHECK_NE(kInvalidDisplayId, display_id); if (primary_display_id_ == display_id) return; const Display& new_primary_display = display_manager_->GetDisplayForId(display_id); if (!new_primary_display.is_valid()) { LOG(ERROR) << "Invalid or non-existent display is requested:" << new_primary_display.ToString(); return; } int64_t old_primary_display_id = primary_display_id_; const DisplayLayout& layout = display_manager_->GetCurrentDisplayLayout(); // The requested primary id can be same as one in the stored layout // when the primary id is set after new displays are connected. // Only update the layout if it is requested to swap primary display. if (layout.primary_id != new_primary_display.id()) { std::unique_ptr<DisplayLayout> swapped_layout(layout.Copy()); std::map<int64_t, DisplayPlacement*> id_to_placement; for (auto& placement : swapped_layout->placement_list) id_to_placement[placement.display_id] = &placement; SwapRecursive(id_to_placement, primary_display_id_, new_primary_display.id()); std::sort(swapped_layout->placement_list.begin(), swapped_layout->placement_list.end(), [](const DisplayPlacement& d1, const DisplayPlacement& d2) { return d1.display_id < d2.display_id; }); swapped_layout->primary_id = new_primary_display.id(); DisplayIdList list = display_manager_->GetCurrentDisplayIdList(); display_manager_->layout_store()->RegisterLayoutForDisplayIdList( list, std::move(swapped_layout)); } primary_display_id_ = new_primary_display.id(); screen_->display_list().UpdateDisplay(new_primary_display, DisplayList::Type::PRIMARY); // Force updating display bounds for new primary display. display_manager_->set_force_bounds_changed(true); display_manager_->UpdateDisplays(); display_manager_->set_force_bounds_changed(false); DVLOG(1) << "Primary display changed from " << old_primary_display_id << " to " << primary_display_id_; delegate_->OnPrimaryDisplayChanged(primary_display_id_); } void ScreenManagerOzone::AddInterfaces( service_manager::InterfaceRegistry* registry) { registry->AddInterface<mojom::DisplayController>(this); registry->AddInterface<mojom::TestDisplayController>(this); } void ScreenManagerOzone::Init(ScreenManagerDelegate* delegate) { DCHECK(delegate); delegate_ = delegate; // Tests may inject a NativeDisplayDelegate, otherwise get it from // OzonePlatform. if (!native_display_delegate_) { native_display_delegate_ = ui::OzonePlatform::GetInstance()->CreateNativeDisplayDelegate(); } // The FakeDisplayController gives us a way to make the NativeDisplayDelegate // pretend something display related has happened. if (!chromeos::IsRunningAsSystemCompositor()) { fake_display_controller_ = native_display_delegate_->GetFakeDisplayController(); } // Create a new Screen instance. std::unique_ptr<ScreenBase> screen = base::MakeUnique<ScreenBase>(); Screen::SetScreenInstance(screen.get()); screen_ = screen.get(); // Configure display manager. ScreenManager acts as an observer to find out // display changes and as a delegate to find out when changes start/stop. display_manager_ = base::MakeUnique<DisplayManager>(std::move(screen)); display_manager_->set_configure_displays(true); display_manager_->AddObserver(this); display_manager_->set_delegate(this); // DisplayChangeObserver observes DisplayConfigurator and sends updates to // DisplayManager. display_change_observer_ = base::MakeUnique<DisplayChangeObserver>( &display_configurator_, display_manager_.get()); // We want display configuration to happen even off device to keep the control // flow similar. display_configurator_.set_configure_display(true); display_configurator_.AddObserver(display_change_observer_.get()); display_configurator_.set_state_controller(display_change_observer_.get()); display_configurator_.set_mirroring_controller(display_manager_.get()); // Perform initial configuration. display_configurator_.Init(std::move(native_display_delegate_), false); display_configurator_.ForceInitialConfigure(kChromeOsBootColor); touch_transform_controller_ = base::MakeUnique<TouchTransformController>( &display_configurator_, display_manager_.get()); } void ScreenManagerOzone::RequestCloseDisplay(int64_t display_id) { if (!fake_display_controller_) return; // Tell the NDD to remove the display. ScreenManager will get an update // that the display configuration has changed and the display will be gone. fake_display_controller_->RemoveDisplay(display_id); } int64_t ScreenManagerOzone::GetPrimaryDisplayId() const { return primary_display_id_; } void ScreenManagerOzone::ToggleAddRemoveDisplay() { if (!fake_display_controller_) return; DVLOG(1) << "ToggleAddRemoveDisplay"; int num_displays = display_manager_->GetNumDisplays(); if (num_displays == 1) { const gfx::Size& pixel_size = display_manager_->GetDisplayInfo(display_manager_->GetDisplayAt(0).id()) .bounds_in_native() .size(); fake_display_controller_->AddDisplay(pixel_size); } else if (num_displays > 1) { DisplayIdList displays = display_manager_->GetCurrentDisplayIdList(); fake_display_controller_->RemoveDisplay(displays.back()); } } void ScreenManagerOzone::ToggleDisplayResolution() { if (primary_display_id_ == kInvalidDisplayId) return; // Internal displays don't have alternate resolutions. if (Display::HasInternalDisplay() && primary_display_id_ == Display::InternalDisplayId()) return; DVLOG(1) << "ToggleDisplayResolution"; const ManagedDisplayInfo& info = display_manager_->GetDisplayInfo(primary_display_id_); scoped_refptr<ManagedDisplayMode> mode = GetDisplayModeForNextResolution(info, true); // Loop back to first mode from last. if (mode->size() == info.bounds_in_native().size()) mode = info.display_modes()[0]; // Set mode only if it's different from current. if (mode->size() != info.bounds_in_native().size()) display_manager_->SetDisplayMode(primary_display_id_, mode); } void ScreenManagerOzone::IncreaseInternalDisplayZoom() { if (Display::HasInternalDisplay()) display_manager_->ZoomInternalDisplay(false); } void ScreenManagerOzone::DecreaseInternalDisplayZoom() { if (Display::HasInternalDisplay()) display_manager_->ZoomInternalDisplay(true); } void ScreenManagerOzone::ResetInternalDisplayZoom() { if (Display::HasInternalDisplay()) display_manager_->ResetInternalDisplayZoom(); } void ScreenManagerOzone::RotateCurrentDisplayCW() { NOTIMPLEMENTED(); } void ScreenManagerOzone::SwapPrimaryDisplay() { // Can't swap if there is only 1 display and swapping isn't supported for 3 or // more displays. if (display_manager_->GetNumDisplays() != 2) return; DVLOG(1) << "SwapPrimaryDisplay()"; DisplayIdList display_ids = display_manager_->GetCurrentDisplayIdList(); // Find the next primary display. if (primary_display_id_ == display_ids[0]) SetPrimaryDisplayId(display_ids[1]); else SetPrimaryDisplayId(display_ids[0]); } void ScreenManagerOzone::ToggleMirrorMode() { NOTIMPLEMENTED(); } void ScreenManagerOzone::SetDisplayWorkArea(int64_t display_id, const gfx::Size& size, const gfx::Insets& insets) { // TODO(kylechar): Check the size of the display matches the current size. display_manager_->UpdateWorkAreaOfDisplay(display_id, insets); } void ScreenManagerOzone::OnDisplayAdded(const Display& display) { ViewportMetrics metrics = GetViewportMetricsForDisplay(display); DVLOG(1) << "OnDisplayAdded: " << display.ToString() << "\n " << metrics.ToString(); screen_->display_list().AddDisplay(display, DisplayList::Type::NOT_PRIMARY); delegate_->OnDisplayAdded(display.id(), metrics); } void ScreenManagerOzone::OnDisplayRemoved(const Display& display) { // TODO(kylechar): If we're removing the primary display we need to first set // a new primary display. This will crash until then. DVLOG(1) << "OnDisplayRemoved: " << display.ToString(); screen_->display_list().RemoveDisplay(display.id()); delegate_->OnDisplayRemoved(display.id()); } void ScreenManagerOzone::OnDisplayMetricsChanged(const Display& display, uint32_t changed_metrics) { ViewportMetrics metrics = GetViewportMetricsForDisplay(display); DVLOG(1) << "OnDisplayModified: " << display.ToString() << "\n " << metrics.ToString(); screen_->display_list().UpdateDisplay(display); delegate_->OnDisplayModified(display.id(), metrics); } ViewportMetrics ScreenManagerOzone::GetViewportMetricsForDisplay( const Display& display) { const ManagedDisplayInfo& managed_info = display_manager_->GetDisplayInfo(display.id()); ViewportMetrics metrics; metrics.bounds = display.bounds(); metrics.work_area = display.work_area(); metrics.pixel_size = managed_info.bounds_in_native().size(); metrics.rotation = display.rotation(); metrics.touch_support = display.touch_support(); metrics.device_scale_factor = display.device_scale_factor(); metrics.ui_scale_factor = managed_info.configured_ui_scale(); return metrics; } void ScreenManagerOzone::CreateOrUpdateMirroringDisplay( const DisplayInfoList& display_info_list) { NOTIMPLEMENTED(); } void ScreenManagerOzone::CloseMirroringDisplayIfNotNecessary() { NOTIMPLEMENTED(); } void ScreenManagerOzone::PreDisplayConfigurationChange(bool clear_focus) { DVLOG(1) << "PreDisplayConfigurationChange"; } void ScreenManagerOzone::PostDisplayConfigurationChange( bool must_clear_window) { // Set primary display if not set yet. if (primary_display_id_ == kInvalidDisplayId) { const Display& primary_display = display_manager_->GetPrimaryDisplayCandidate(); if (primary_display.is_valid()) { primary_display_id_ = primary_display.id(); DVLOG(1) << "Set primary display to " << primary_display_id_; screen_->display_list().UpdateDisplay(primary_display, DisplayList::Type::PRIMARY); delegate_->OnPrimaryDisplayChanged(primary_display_id_); } } touch_transform_controller_->UpdateTouchTransforms(); DVLOG(1) << "PostDisplayConfigurationChange"; } DisplayConfigurator* ScreenManagerOzone::display_configurator() { return &display_configurator_; } void ScreenManagerOzone::Create( const service_manager::Identity& remote_identity, mojom::DisplayControllerRequest request) { controller_bindings_.AddBinding(this, std::move(request)); } void ScreenManagerOzone::Create( const service_manager::Identity& remote_identity, mojom::TestDisplayControllerRequest request) { test_bindings_.AddBinding(this, std::move(request)); } } // namespace display
4,673
2,151
#!/usr/bin/env python2.7 # Copyright 2015 gRPC 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. import argparse import glob import os import shutil import sys import tempfile import multiprocessing sys.path.append( os.path.join( os.path.dirname(sys.argv[0]), '..', 'run_tests', 'python_utils')) assert sys.argv[1:], 'run generate_projects.sh instead of this directly' import jobset os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '..', '..')) argp = argparse.ArgumentParser() argp.add_argument('build_files', nargs='+', default=[]) argp.add_argument('--templates', nargs='+', default=[]) argp.add_argument('--output_merged', default=None, type=str) argp.add_argument('--jobs', '-j', default=multiprocessing.cpu_count(), type=int) argp.add_argument('--base', default='.', type=str) args = argp.parse_args() json = args.build_files test = {} if 'TEST' in os.environ else None plugins = sorted(glob.glob('tools/buildgen/plugins/*.py')) templates = args.templates if not templates: for root, dirs, files in os.walk('templates'): for f in files: templates.append(os.path.join(root, f)) pre_jobs = [] base_cmd = [sys.executable, 'tools/buildgen/mako_renderer.py'] cmd = base_cmd[:] for plugin in plugins: cmd.append('-p') cmd.append(plugin) for js in json: cmd.append('-d') cmd.append(js) cmd.append('-w') preprocessed_build = '.preprocessed_build' cmd.append(preprocessed_build) if args.output_merged is not None: cmd.append('-M') cmd.append(args.output_merged) pre_jobs.append( jobset.JobSpec(cmd, shortname='preprocess', timeout_seconds=None)) jobs = [] for template in reversed(sorted(templates)): root, f = os.path.split(template) if os.path.splitext(f)[1] == '.template': out_dir = args.base + root[len('templates'):] out = out_dir + '/' + os.path.splitext(f)[0] if not os.path.exists(out_dir): os.makedirs(out_dir) cmd = base_cmd[:] cmd.append('-P') cmd.append(preprocessed_build) cmd.append('-o') if test is None: cmd.append(out) else: tf = tempfile.mkstemp() test[out] = tf[1] os.close(tf[0]) cmd.append(test[out]) cmd.append(args.base + '/' + root + '/' + f) jobs.append(jobset.JobSpec(cmd, shortname=out, timeout_seconds=None)) jobset.run(pre_jobs, maxjobs=args.jobs) jobset.run(jobs, maxjobs=args.jobs) if test is not None: for s, g in test.iteritems(): if os.path.isfile(g): assert 0 == os.system('diff %s %s' % (s, g)), s os.unlink(g) else: assert 0 == os.system('diff -r %s %s' % (s, g)), s shutil.rmtree(g, ignore_errors=True)
1,349
9,156
/** * 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.pulsar.structuredeventlog; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; /** * Structured Logged Event interface. * * This interface is used to add context information to the log event and eventually log. */ public interface Event { /** * Create a new child event. The child event will inherit the trace ID of the event * from which it was created. The child event parentId will be the ID of the event * from which it was created. * The child will inherit resources from its parent event, but not attributes. * * @return a new child event */ Event newChildEvent(); /** * Set the trace ID of the event. Normally this will be inherited from the parent * event. In the case of a root event, the trace ID will be automatically generated. * This method only needs to be used if a traceID has been received from elsewhere, * such as from a user request. * @param traceId the traceId * @return this */ Event traceId(String traceId); /** * Set the parent ID of the event. Normally this is set automatically for child events. * For root events, it is normally empty unless provided by some other means, such * as via a user request. * @param parentId the parentId * @return this */ Event parentId(String parentId); /** * Mark this event as timed. * Timed events will measure the duration between #timed() being called * and logged being called. The duration will be in milliseconds. * * <pre> * Event e = logger.newRootEvent().timed(); * // do something that takes time. * e.log(Events.SOME_EVENT); * </pre> * * @return this */ Event timed(); /** * Mark this event as sampled. * Sampled events will only log once per specified duration. * The sampling key is used to scope the rate limit. All events using the * same sampling key will observe the same rate limit. * Sampled events are most useful in the data plane, where, if there is an * error for one event, there's likely to be a lot of other events which are * almost identical. * * @param samplingKey a key by which to scope the rate limiting * @param duration the duration for which one event will be logged * @param unit the duration unit * @return this */ Event sampled(Object samplingKey, int duration, TimeUnit unit); /** * Add resources for the event from an EventResources object. * @see #resource(java.lang.String,java.lang.Object) * @return this */ Event resources(EventResources attrs); /** * Add a resource for the event. Resources are inherited by * child events. * @param key the key to identify the resource * @param value the value which will be logged for the resource. * This is converted to a string before logging. * @return this */ Event resource(String key, Object value); /** * Add a resource for the event using a supplier. The supplier is * used in the case that generating the string from the object is * expensive or we want to generate a custom string. * @param key the key to identify the resource * @param value a supplier which returns the value to be logged for * this resource * @see #resource(java.lang.String,java.lang.Object) */ Event resource(String key, Supplier<String> value); /** * Add an attribute for the event. Attributes are not inherited * by child events. * @param key the key to identify the attribute * @param value the value which will be logged for the attribute. * This is converted to a string, using Object#toString() before logging. * @return this */ Event attr(String key, Object value); /** * Add an attribute for the event using a supplier. * @param key the key to identify the attribute * @param value a supplier which returns the value to be logged for * this attribute * @return this */ Event attr(String key, Supplier<String> value); /** * Attach an exception to the event. * @param t the exception * @return this */ Event exception(Throwable t); /** * Log this event at the error level. * @return this */ Event atError(); /** * Log this event at the info level (the default). * @return this */ Event atInfo(); /** * Log this event at the warn level. * @return this */ Event atWarn(); /** * Log the event, using an enum as the message. * Logging with a enum allows documentation and annotations, such as subcomponent * to be attached to the message. * @param event the event message, in enum form */ void log(Enum<?> event); /** * Log the event, using a string. * @param event the event message. */ void log(String event); /** * Stash this log event to bridge across an unmodifiable API call. * @see StructuredEventLog#unstash() */ void stash(); }
1,950
892
<filename>advisories/unreviewed/2022/04/GHSA-j3j5-x3ff-v276/GHSA-j3j5-x3ff-v276.json { "schema_version": "1.2.0", "id": "GHSA-j3j5-x3ff-v276", "modified": "2022-04-22T00:24:18Z", "published": "2022-04-22T00:24:18Z", "aliases": [ "CVE-2011-3631" ], "details": "Hardlink before 0.1.2 has multiple integer overflows leading to heap-based buffer overflows because of the way string lengths concatenation is done in the calculation of the required memory space to be used. A remote attacker could provide a specially-crafted directory tree and trick the local user into consolidating it, leading to hardlink executable crash or potentially arbitrary code execution with user privileges.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2011-3631" }, { "type": "WEB", "url": "https://access.redhat.com/security/cve/cve-2011-3631" }, { "type": "WEB", "url": "https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=645516" }, { "type": "WEB", "url": "https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2011-3631" }, { "type": "WEB", "url": "https://security-tracker.debian.org/tracker/CVE-2011-3631" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
593
27,470
// Copyright 2019 <NAME>. // // This file is part of GitStatus. // // GitStatus is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // GitStatus 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 GitStatus. If not, see <https://www.gnu.org/licenses/>. #ifndef ROMKATV_GITSTATUS_BITS_H_ #define ROMKATV_GITSTATUS_BITS_H_ #include <cstddef> namespace gitstatus { inline size_t NextPow2(size_t n) { return n < 2 ? 1 : (~size_t{0} >> __builtin_clzll(n - 1)) + 1; } } // namespace gitstatus #endif // ROMKATV_GITSTATUS_BITS_H_
313
918
<filename>gobblin-example/src/test/java/org/apache/gobblin/example/TestOneShotRunner.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.gobblin.example; import java.net.URL; import org.apache.hadoop.fs.Path; import org.testng.Assert; import org.testng.annotations.Test; import org.apache.gobblin.example.generic.OneShotRunner; import org.apache.gobblin.runtime.api.Configurable; public class TestOneShotRunner { @Test public void testConfiguration() { OneShotRunner runner = new OneShotRunner(); URL appConfResource = getClass().getClassLoader().getResource("appConf.conf"); URL baseConfResource = getClass().getClassLoader().getResource("baseConf.conf"); runner.appConf("file://" + appConfResource.getFile()); runner.baseConf("file://" + baseConfResource.getFile()); Assert.assertEquals(runner.getJobFile().get(), new Path("file://" + appConfResource.getPath())); Configurable resolvedSysConfig = runner.getSysConfig(); Assert.assertEquals(resolvedSysConfig.getConfig().getString("test.key1"), "value1"); Assert.assertEquals(resolvedSysConfig.getConfig().getString("test.key2"), "value2"); } }
557
489
from __future__ import absolute_import, print_function import json import numpy as np import tensorflow as tf from gym import spaces from rltools import log, util from rltools.algos.policyopt import TRPO, SamplingPolicyOptimizer, ConcurrentPolicyOptimizer from rltools.baselines.linear import LinearFeatureBaseline from rltools.baselines.mlp import MLPBaseline from rltools.baselines.zero import ZeroBaseline from rltools.policy.categorical import CategoricalMLPPolicy, CategoricalGRUPolicy from rltools.policy.gaussian import GaussianGRUPolicy, GaussianMLPPolicy from rltools.samplers.parallel import ParallelSampler from rltools.samplers.serial import DecSampler, SimpleSampler, ConcSampler from runners import tonamedtuple def rltools_envpolicy_parser(env, args): if isinstance(args, dict): args = tonamedtuple(args) # XXX # Should be handled in the environment? # shape mucking is incorrect for image envs if args.control == 'centralized': obs_space = spaces.Box(low=env.agents[0].observation_space.low[0], high=env.agents[0].observation_space.high[0], shape=(env.agents[0].observation_space.shape[0] * len(env.agents),)) action_space = spaces.Box(low=env.agents[0].observation_space.low[0], high=env.agents[0].observation_space.high[0], shape=(env.agents[0].action_space.shape[0] * len(env.agents),)) else: obs_space = env.agents[0].observation_space action_space = env.agents[0].action_space if args.recurrent: if args.recurrent == 'gru': if isinstance(action_space, spaces.Box): if args.control == 'concurrent': policies = [ GaussianGRUPolicy(env.agents[agid].observation_space, env.agents[agid].action_space, hidden_spec=args.policy_hidden_spec, min_stdev=args.min_std, init_logstdev=0., enable_obsnorm=args.enable_obsnorm, state_include_action=False, varscope_name='policy_{}'.format(agid)) for agid in range(len(env.agents)) ] policy = GaussianGRUPolicy(obs_space, action_space, hidden_spec=args.policy_hidden_spec, min_stdev=args.min_std, init_logstdev=0., enable_obsnorm=args.enable_obsnorm, state_include_action=False, varscope_name='policy') elif isinstance(action_space, spaces.Discrete): if args.control == 'concurrent': policies = [ CategoricalGRUPolicy(env.agents[agid].observation_space, env.agents[agid].action_space, hidden_spec=args.policy_hidden_spec, enable_obsnorm=args.enable_obsnorm, state_include_action=False, varscope_name='policy_{}'.format(agid)) for agid in range(len(env.agents)) ] policy = CategoricalGRUPolicy(obs_space, action_space, hidden_spec=args.policy_hidden_spec, enable_obsnorm=args.enable_obsnorm, state_include_action=False, varscope_name='policy') elif isinstance(action_space, spaces.Discrete): raise NotImplementedError(args.recurrent) else: raise NotImplementedError() else: if isinstance(action_space, spaces.Box): if args.control == 'concurrent': policies = [ GaussianMLPPolicy(env.agents[agid].observation_space, env.agents[agid].action_space, hidden_spec=args.policy_hidden_spec, min_stdev=args.min_std, init_logstdev=0., enable_obsnorm=args.enable_obsnorm, varscope_name='{}_policy'.format(agid)) for agid in range(len(env.agents)) ] policy = GaussianMLPPolicy(obs_space, action_space, hidden_spec=args.policy_hidden_spec, min_stdev=args.min_std, init_logstdev=0., enable_obsnorm=args.enable_obsnorm, varscope_name='policy') elif isinstance(action_space, spaces.Discrete): if args.control == 'concurrent': policies = [ CategoricalMLPPolicy(env.agents[agid].observation_space, env.agents[agid].action_space, hidden_spec=args.policy_hidden_spec, enable_obsnorm=args.enable_obsnorm, varscope_name='policy_{}'.format(agid)) for agid in range(len(env.agents)) ] policy = CategoricalMLPPolicy(obs_space, action_space, hidden_spec=args.policy_hidden_spec, enable_obsnorm=args.enable_obsnorm, varscope_name='policy') else: raise NotImplementedError() if args.control == 'concurrent': return env, policies, policy else: return env, None, policy class RLToolsRunner(object): def __init__(self, env, args): self.args = args env, policies, policy = rltools_envpolicy_parser(env, args) if args.baseline_type == 'linear': if args.control == 'concurrent': baselines = [ LinearFeatureBaseline(env.agents[agid].observation_space, enable_obsnorm=args.enable_obsnorm, varscope_name='baseline_{}'.format(agid)) for agid in range(len(env.agents)) ] else: baseline = LinearFeatureBaseline(policy.observation_space, enable_obsnorm=args.enable_obsnorm, varscope_name='baseline') elif args.baseline_type == 'mlp': if args.control == 'concurrent': baselines = [ MLPBaseline(env.agents[agid].observation_space, hidden_spec=args.baseline_hidden_spec, enable_obsnorm=args.enable_obsnorm, enable_vnorm=args.enable_vnorm, max_kl=args.vf_max_kl, damping=args.vf_cg_damping, time_scale=1. / args.max_traj_len, varscope_name='{}_baseline'.format(agid)) for agid in range(len(env.agents)) ] else: baseline = MLPBaseline(policy.observation_space, hidden_spec=args.baseline_hidden_spec, enable_obsnorm=args.enable_obsnorm, enable_vnorm=args.enable_vnorm, max_kl=args.vf_max_kl, damping=args.vf_cg_damping, time_scale=1. / args.max_traj_len, varscope_name='baseline') elif args.baseline_type == 'zero': if args.control == 'concurrent': baselines = [ ZeroBaseline(env.agents[agid].observation_space) for agid in range(len(env.agents)) ] else: baseline = ZeroBaseline(policy.observation_space) else: raise NotImplementedError() if args.sampler == 'simple': if args.control == 'centralized': sampler_cls = SimpleSampler elif args.control == 'decentralized': sampler_cls = DecSampler elif args.control == 'concurrent': sampler_cls = ConcSampler else: raise NotImplementedError() sampler_args = dict(max_traj_len=args.max_traj_len, n_timesteps=args.n_timesteps, n_timesteps_min=args.n_timesteps_min, n_timesteps_max=args.n_timesteps_max, timestep_rate=args.timestep_rate, adaptive=args.adaptive_batch, enable_rewnorm=args.enable_rewnorm) elif args.sampler == 'parallel': sampler_cls = ParallelSampler sampler_args = dict(max_traj_len=args.max_traj_len, n_timesteps=args.n_timesteps, n_timesteps_min=args.n_timesteps_min, n_timesteps_max=args.n_timesteps_max, timestep_rate=args.timestep_rate, adaptive=args.adaptive_batch, enable_rewnorm=args.enable_rewnorm, n_workers=args.sampler_workers, mode=args.control, discard_extra=False) else: raise NotImplementedError() step_func = TRPO(max_kl=args.max_kl) if args.control == 'concurrent': self.algo = ConcurrentPolicyOptimizer(env=env, policies=policies, baselines=baselines, step_func=step_func, discount=args.discount, gae_lambda=args.gae_lambda, sampler_cls=sampler_cls, sampler_args=sampler_args, n_iter=args.n_iter, target_policy=policy, interp_alpha=args.interp_alpha) else: self.algo = SamplingPolicyOptimizer(env=env, policy=policy, baseline=baseline, step_func=step_func, discount=args.discount, gae_lambda=args.gae_lambda, sampler_cls=sampler_cls, sampler_args=sampler_args, n_iter=args.n_iter) argstr = json.dumps(vars(args), separators=(',', ':'), indent=2) util.header(argstr) self.log_f = log.TrainingLog(args.log, [('args', argstr)], debug=args.debug) def __call__(self): with tf.Session() as sess: sess.run(tf.initialize_all_variables()) summary_writer = tf.train.SummaryWriter(self.args.tblog, graph=sess.graph) self.algo.train(sess, self.log_f, self.args.save_freq, blend_freq=self.args.blend_freq, keep_kmax=self.args.keep_kmax, blend_eval_trajs=self.args.blend_eval_trajs)
6,654
868
/* * 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.activemq.artemis.jms.example; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.naming.InitialContext; import java.util.Hashtable; public class CamelExample { public static void main(final String[] args) throws Exception { Connection connection = null; InitialContext ic = null; try { // Step 1. - we create an initial context for looking up JNDI Hashtable<String, Object> properties = new Hashtable<>(); properties.put("java.naming.factory.initial", "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory"); properties.put("connectionFactory.ConnectionFactory", "tcp://127.0.0.1:61616"); properties.put("queue.queue/sausage-factory", "sausage-factory"); properties.put("queue.queue/mincing-machine", "mincing-machine"); ic = new InitialContext(properties); // Step 2. - we look up the sausage-factory queue from node 0 Queue sausageFactory = (Queue) ic.lookup("queue/sausage-factory"); Queue mincingMachine = (Queue) ic.lookup("queue/mincing-machine"); // Step 3. - we look up a JMS ConnectionFactory object from node 0 ConnectionFactory cf = (ConnectionFactory) ic.lookup("ConnectionFactory"); // Step 4. We create a JMS Connection connection which is a connection to server 0 connection = cf.createConnection(); // Step 5. We create a JMS Session on server 0 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Step 6. We start the connection to ensure delivery occurs on them connection.start(); // Step 7. We create JMS MessageConsumer object MessageConsumer consumer = session.createConsumer(mincingMachine); // Step 8. We create a JMS MessageProducer object MessageProducer producer = session.createProducer(sausageFactory); // Step 9. We create and send a message to the sausage-factory Message message = session.createMessage(); producer.send(message); System.out.println("Sent message to sausage-factory"); // Step 10. - we successfully receive the message from the mincing-machine. Message receivedMessage = consumer.receive(5000); if (receivedMessage == null) { throw new IllegalStateException(); } System.out.println("Received message from mincing-machine"); } finally { // Step 15. Be sure to close our resources! if (connection != null) { connection.close(); } if (ic != null) { ic.close(); } } } }
1,248
937
<gh_stars>100-1000 package cyclops.data; import com.oath.cyclops.types.persistent.PersistentIndexed; import cyclops.control.Option; import cyclops.function.Function1; import cyclops.reactive.ReactiveSeq; import lombok.AllArgsConstructor; import java.util.List; import java.util.function.Supplier; public interface Enumeration<E> { Option<E> toEnum(int e); int fromEnum(E a); default E toEnumOrElse(int e, E value){ return toEnum(e).orElse(value); } default E toEnumOrElseGet(int e, Supplier<? extends E> value){ return toEnum(e).orElse(value.get()); } default E succOrElse(E e,E value){ return toEnumOrElse(fromEnum(e)+1,value); } default E predOrElse(E e, E value){ return toEnumOrElse(fromEnum(e)-1,value); } default E succOrElseGet(E e,Supplier<? extends E> value){ return toEnumOrElseGet(fromEnum(e)+1,value); } default E predOrElseGet(E e, Supplier<? extends E> value){ return toEnumOrElseGet(fromEnum(e)-1,value); } default Option<E> succ(E e){ return toEnum(fromEnum(e)+1); } default Option<E> pred(E e){ return toEnum(fromEnum(e)-1); } static <E extends Enum<E>> Enumeration<E> enums(E... values){ return new EnumerationByEnum<E>(values); } static <E extends Enum<E>> Enumeration<E> enums(Class<E> c){ return new EnumerationByEnum<E>(c.getEnumConstants()); } static Enumeration<Integer> ints(){ return new Enumeration<Integer>() { @Override public Option<Integer> toEnum(int e) { return Option.some(e); } @Override public int fromEnum(Integer a) { return a; } }; } static <E> Enumeration<E> enums(PersistentIndexed<E> seq){ return new EnumerationByIndexed<E>(seq); } static <E> Enumeration<E> enumsList(List<E> seq){ return new EnumerationByIndexed<E>(Seq.fromIterable(seq)); } @AllArgsConstructor static class EnumerationByEnum<E extends Enum<E>> implements Enumeration<E>{ private final E[] values; final Function1<E,Integer> memo = this::calcFromEnum; public Option<E> toEnum(int a){ return a>-1 && a< values.length ? Option.some(values[a]) : Option.none(); } public E toEnumOrElse(int a,E e){ return a>-1 && a< values.length ? values[a] : e; } public E toEnumOrElseGet(int a,Supplier<? extends E> e){ return a>-1 && a< values.length ? values[a] : e.get(); } public Function1<E,Integer> fromEnumMemoized(){ Function1<E,Integer> fn = this::fromEnum; return fn.memoize(); } @Override public int fromEnum(E e) { return memo.apply(e); } public int calcFromEnum(E e) { for(int i=0;i<values.length;i++){ if(values[i]==e){ return i; } } return -1; } } @AllArgsConstructor static class EnumerationByIndexed<E> implements Enumeration<E>{ private final PersistentIndexed<E> seq; final Function1<E,Integer> memo = this::calcFromEnum; @Override public Option<E> toEnum(int e) { return seq.get(e); } @Override public E toEnumOrElse(int e, E value) { return seq.getOrElse(e,value); } @Override public E toEnumOrElseGet(int e, Supplier<? extends E> value) { return seq.getOrElseGet(e,value); } @Override public int fromEnum(E a) { return memo.apply(a); } public int calcFromEnum(E e) { for(int i=0;i<seq.size();i++){ if(seq.get(i)==e){ return i; } } return -1; } } default ReactiveSeq<E> streamTo(E e,E end){ return ReactiveSeq.range(fromEnum(e),fromEnum(end)).map(this::toEnum) .takeWhile(Option::isPresent) .filter(Option::isPresent).flatMap(Option::stream); } default ReactiveSeq<E> streamThenTo(E e,E next,E end){ int start= fromEnum(e); int step = fromEnum(next)-start; return ReactiveSeq.range(start,step,fromEnum(end)).map(this::toEnum) .takeWhile(Option::isPresent) .filter(Option::isPresent).flatMap(Option::stream); } default ReactiveSeq<E> stream(E e){ return ReactiveSeq.range(fromEnum(e),Integer.MAX_VALUE).map(this::toEnum) .takeWhile(Option::isPresent) .filter(Option::isPresent).flatMap(Option::stream); } default Seq<E> seq(E e){ return stream(e) .to().seq(); } default LazySeq<E> lazySeq(E e){ return stream(e) .to().lazySeq(); } }
2,459
364
<filename>doc/quickbook/oalplus/quickref/device.hpp /* * Copyright 2014-2019 <NAME>. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ //[oalplus_device_common namespace tag { struct Playback {}; struct Capture {}; } // namespace tag class DevCommonOps { public: DevCommonOps(DevCommonOps&&) = default; static __Range<__StrCRef> Extensions(); /*< Returns a range of ALC extension strings for [^this] devices. See [alcfunc GetString], [alcconst EXTENSIONS]. >*/ }; template <typename DeviceTag> class DeviceOps; //] //[oalplus_device_playback_ops template <> class DeviceOps<tag::Playback> : public DevCommonOps { public: __StrCRef Specifier() const; /*< Returns the device specifier string. See [alcfunc GetString], [alcconst DEVICE_SPECIFIER]. >*/ static __Range<__StrCRef> Specifiers(); /*< Returns a range of specifier strings for available audio playback devices. See [alcfunc GetString], [alcconst DEVICE_SPECIFIER]. >*/ }; //] //[oalplus_device_capture_ops template <> class DeviceOps<tag::Capture> : public DevCommonOps { public: __StrCRef Specifier() const; /*< Returns the device specifier string. See [alcfunc GetString], [alcconst CAPTURE_DEVICE_SPECIFIER]. >*/ static __Range<__StrCRef> Specifiers(); /*< Returns a range of specifier strings for available audio capture devices. See [alcfunc GetString], [alcconst CAPTURE_DEVICE_SPECIFIER]. >*/ void Start(); /*< Starts audio capture on [^this] device. See [alcfunc CaptureStart]. >*/ void Stop(); /*< Stops audio capture on [^this] device. See [alcfunc CaptureStop]. >*/ ALCsizei Samples() const; /*< Gets the number of samples captured on [^this] device. See [alcfunc GetInteger], [alcconst CAPTURE_SAMPLES]. >*/ void Samples(ALCvoid* buffer, ALCsizei samples) const; /*< Gets the samples captured on [^this] device. See [alcfunc CaptureSamples]. >*/ }; //] //[oalplus_playback_device class Device : public DeviceOps<tag::Playback> { public: Device(); /*< Constructs an object referencing the default audio playback device. See [alcfunc OpenDevice]. >*/ Device(__StrCRef dev_spec); /*< Constructs an object referencing the specified audio device. See [alcfunc OpenDevice]. >*/ }; //] //[oalplus_capture_device class CaptureDevice : public DeviceOps<tag::Capture> { public: CaptureDevice( ALCuint frequency, __DataFormat format, ALCsizei bufsize); /*< Constructs an object referencing the default audio capture device. See [alcfunc CaptureOpenDevice]. >*/ CaptureDevice( StrCRef dev_spec, ALCuint frequency, __DataFormat format, ALCsizei bufsize); /*< Constructs an object referencing the specified audio capture device. See [alcfunc CaptureOpenDevice]. >*/ }; //]
1,337
892
{ "schema_version": "1.2.0", "id": "GHSA-248v-73qf-wh7x", "modified": "2022-01-20T00:02:53Z", "published": "2022-01-11T00:01:39Z", "aliases": [ "CVE-2021-20048" ], "details": "A Stack-based buffer overflow in the SonicOS SessionID HTTP response header allows a remote authenticated attacker to cause Denial of Service (DoS) and potentially results in code execution in the firewall. This vulnerability affected SonicOS Gen 5, Gen 6 and Gen 7 firmware versions.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-20048" }, { "type": "WEB", "url": "https://psirt.global.sonicwall.com/vuln-detail/SNWLID-2021-0028" } ], "database_specific": { "cwe_ids": [ "CWE-787" ], "severity": "HIGH", "github_reviewed": false } }
373
32,544
<gh_stars>1000+ package com.baeldung.spring.data.gemfire.repository; import com.baeldung.spring.data.gemfire.function.FunctionExecution; import com.baeldung.spring.data.gemfire.function.GemfireConfiguration; import com.baeldung.spring.data.gemfire.model.Employee; import com.google.common.collect.Lists; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import java.util.List; import static junit.framework.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class) public class EmployeeRepositoryIntegrationTest { @Autowired private EmployeeRepository employeeRepository; @Autowired private FunctionExecution execution; @Test public void whenEmployeeIsSaved_ThenAbleToRead(){ Employee employee=new Employee("<NAME>",4550.00); employeeRepository.save(employee); List<Employee> employees= Lists.newArrayList(employeeRepository.findAll()); assertEquals(1, employees.size()); } @Test public void whenSalaryGreaterThan_ThenEmployeeFound(){ Employee employee=new Employee("<NAME>",4550.00); Employee employee1=new Employee("<NAME>",3500.00); Employee employee2=new Employee("<NAME>",5600.00); employeeRepository.save(employee); employeeRepository.save(employee1); employeeRepository.save(employee2); List<Employee> employees= Lists.newArrayList(employeeRepository.findBySalaryGreaterThan(4000.00)); assertEquals(2,employees.size()); } @Test public void whenSalaryLessThan_ThenEmployeeFound(){ Employee employee=new Employee("<NAME>",4550.00); Employee employee1=new Employee("<NAME>",3500.00); Employee employee2=new Employee("<NAME>",5600.00); employeeRepository.save(employee); employeeRepository.save(employee1); employeeRepository.save(employee2); List<Employee> employees= Lists.newArrayList(employeeRepository.findBySalaryLessThan(4000)); assertEquals(1,employees.size()); } @Test public void whenSalaryBetween_ThenEmployeeFound(){ Employee employee=new Employee("<NAME>",4550.00); Employee employee1=new Employee("<NAME>",3500.00); Employee employee2=new Employee("<NAME>",5600.00); employeeRepository.save(employee); employeeRepository.save(employee1); employeeRepository.save(employee2); List<Employee> employees= Lists.newArrayList(employeeRepository.findBySalaryGreaterThanAndSalaryLessThan(3500,5000)); assertEquals(1,employees.size()); } @Test public void whenFunctionExecutedFromClient_ThenFunctionExecutedOnServer(){ execution.execute("Hello World"); } @After public void cleanup(){ employeeRepository.deleteAll(); } }
1,159
852
<reponame>malbouis/cmssw<gh_stars>100-1000 #include "L1Trigger/L1TMuonOverlap/interface/GhostBuster.h" #include <algorithm> #include <sstream> #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "L1Trigger/L1TMuonOverlap/interface/OMTFConfiguration.h" namespace { int phiGMT(int phiAlgo) { return phiAlgo * 437 / pow(2, 12); } } // namespace std::vector<AlgoMuon> GhostBuster::select(std::vector<AlgoMuon> refHitCands, int charge) { std::vector<AlgoMuon> refHitCleanCands; // Sort candidates with decreased goodness, // where goodness definied in < operator of AlgoMuon std::sort(refHitCands.rbegin(), refHitCands.rend()); for (std::vector<AlgoMuon>::iterator it1 = refHitCands.begin(); it1 != refHitCands.end(); ++it1) { bool isGhost = false; for (std::vector<AlgoMuon>::iterator it2 = refHitCleanCands.begin(); it2 != refHitCleanCands.end(); ++it2) { //do not accept candidates with similar phi (any charge combination) //veto window 5deg(=half of logic cone)=5/360*5760=80"logic strips" //veto window 5 degree in GMT scale is 5/360*576=8 units if (std::abs(phiGMT(it1->getPhi()) - phiGMT(it2->getPhi())) < 8) { // if(std::abs(it1->getPhi() - it2->getPhi())<5/360.0*nPhiBins){ isGhost = true; break; //which one candidate is killed depends only on the order in the refHitCands (the one with smaller index is taken), and this order is assured by the sort above //TODO here the candidate that is killed does not kill other candidates - check if the firmware does the same (KB) } } if (it1->getQ() > 0 && !isGhost) refHitCleanCands.push_back(*it1); } refHitCleanCands.resize(3, AlgoMuon(0, 999, 9999, 0, 0, 0, 0, 0)); //FIXME //refHitCleanCands.resize( 3, AlgoMuon() ); std::stringstream myStr; bool hasCandidates = false; for (unsigned int iRefHit = 0; iRefHit < refHitCands.size(); ++iRefHit) { if (refHitCands[iRefHit].getQ()) { hasCandidates = true; break; } } for (unsigned int iRefHit = 0; iRefHit < refHitCands.size(); ++iRefHit) { if (refHitCands[iRefHit].getQ()) myStr << "Ref hit: " << iRefHit << " " << refHitCands[iRefHit] << std::endl; } myStr << "Selected Candidates with charge: " << charge << std::endl; for (unsigned int iCand = 0; iCand < refHitCleanCands.size(); ++iCand) { myStr << "Cand: " << iCand << " " << refHitCleanCands[iCand] << std::endl; } if (hasCandidates) edm::LogInfo("OMTF Sorter") << myStr.str(); // update refHitCands with refHitCleanCands return refHitCleanCands; }
1,098
937
package cyclops.monads.transformers.seq; import com.oath.cyclops.types.AbstractTraversableTest; import com.oath.cyclops.types.traversable.Traversable; import cyclops.monads.AnyMs; import cyclops.monads.Witness.reactiveSeq; import cyclops.reactive.ReactiveSeq; public class StreamTSeqTraversableTest extends AbstractTraversableTest { @Override public <T> Traversable<T> of(T... elements) { return AnyMs.liftM(ReactiveSeq.of(elements), reactiveSeq.ITERATIVE); } @Override public <T> Traversable<T> empty() { return ReactiveSeq.<T>empty() .to(AnyMs::<reactiveSeq,T>liftM) .apply(reactiveSeq.ITERATIVE); } }
305
416
<filename>iPhoneOS11.2.sdk/System/Library/Frameworks/HealthKit.framework/Headers/HKCorrelationQuery.h // // HKCorrelationQuery.h // HealthKit // // Copyright (c) 2014 Apple Inc. All rights reserved. // #import <HealthKit/HKQuery.h> NS_ASSUME_NONNULL_BEGIN @class HKCorrelationType; @class HKCorrelation; /*! @class HKCorrelationQuery @abstract A query to find HKCorrelations @discussion Correlations are HKSamples that contain a set of correlated samples. HKCorrelationQuery accepts a predicate to filter HKCorrelations and a dictionary of predicates to filter the correlated samples. */ HK_EXTERN API_AVAILABLE(ios(8.0), watchos(2.0)) @interface HKCorrelationQuery : HKQuery @property (readonly, copy) HKCorrelationType *correlationType; /*! @property samplePredicates @abstract A dictionary of predicates for the HKCorrelation's objects @discussion samplePredicates maps HKSampleTypes to NSPredicates. The predicate value will apply to objects of the key type. */ @property (readonly, copy, nullable) NSDictionary<__kindof HKSampleType *, NSPredicate *> *samplePredicates; /*! @method initWithTypes:predicate:samplePredicate:completion: @abstract The designated initializer for HKCorrelationQuery. @param correlationType The type of correlation that is being queried for @param predicate The predicate for scoping which HKCorrelations are returned @param samplePredicates A dictionary mapping HKSampleTypes to NSPredicates. If no predicate for a particular type is provided, it is assumed to be a nil predicate and objects of that type will not be filtered. */ - (instancetype)initWithType:(HKCorrelationType *)correlationType predicate:(nullable NSPredicate *)predicate samplePredicates:(nullable NSDictionary<HKSampleType *, NSPredicate *> *)samplePredicates completion:(void(^)(HKCorrelationQuery *query, NSArray<HKCorrelation *> * _Nullable correlations, NSError * _Nullable error))completion; @end NS_ASSUME_NONNULL_END
775
2,236
// Authored by : seastar105 // Co-authored by : - // Link : https://www.acmicpc.net/source/share/628806951c694c76a58fa0c5e510d10f #include<bits/stdc++.h> using namespace std; int dy[4] = {-1, 1, 0, 0}; int dx[4] = {0, 0, -1, 1}; int N; int a[55][55]; bool vis[55][55]; int L, R; bool valid(int y, int x) { return 0 <= y && y < N && 0 <= x && x < N; } bool bfs() { bool flag = false; queue<pair<int,int>> q; vector<vector<pair<int,int>>> comp; vector<int> comp_pop; memset(vis, false, sizeof(vis)); // bfs for(int i=0;i<N;++i) { for(int j=0;j<N;++j) { if(vis[i][j]) continue; vector<pair<int,int>> cur; int sum = 0; q.emplace(i, j); vis[i][j] = true; while(!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); sum += a[y][x]; cur.emplace_back(y, x); for(int k=0;k<4;++k) { int ny = y + dy[k]; int nx = x + dx[k]; int diff = abs(a[y][x] - a[ny][nx]); if(!valid(ny, nx) || vis[ny][nx]) continue; if(diff > R || diff < L) continue; flag = true; vis[ny][nx] = true; q.emplace(ny, nx); } } comp.push_back(cur); comp_pop.push_back(sum); } } if(!flag) return false; // population moving for(int i=0;i<comp.size();++i) { int pop = comp_pop[i] / comp[i].size(); for(pair<int, int> p : comp[i]) a[p.first][p.second] = pop; } return true; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cin >> N >> L >> R; for(int i=0;i<N;++i) { for(int j=0;j<N;++j) { cin >> a[i][j]; } } int ans = 0; while(bfs()) ++ans; cout << ans << '\n'; return 0; }
837
2,989
<filename>databus-core/databus-core-schemas/src/main/java/com/linkedin/databus2/schemas/SchemaId.java package com.linkedin.databus2.schemas; /* * * Copyright 2013 LinkedIn Corp. 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. * */ import java.util.Arrays; import org.apache.avro.Schema; import org.apache.commons.codec.binary.Hex; import com.linkedin.databus.core.DbusEvent; import com.linkedin.databus2.schemas.utils.Utils; /** * This class contains a byte-array that is used as a unique identifier for an Avro schema. * The byte array is of size 16 (if we use MD5 hash) or 4 (if we use CRC32). * * "Borrowed" largely from com.linkedin.avro.SchemaId */ public class SchemaId { private final byte[] _idBytes; public SchemaId(byte[] newIdBytes) { super(); Utils.notNull(newIdBytes); // As of now, we support either MD5 or CRC32. //restrict byte sequences to either handle 128 bits or 32 bits if((newIdBytes.length != DbusEvent.MD5_DIGEST_LEN) && (newIdBytes.length != DbusEvent.CRC32_DIGEST_LEN)) { throw new IllegalArgumentException("schema id is of length is " + newIdBytes.length + " Expected length: " + DbusEvent.CRC32_DIGEST_LEN + " or " + DbusEvent.MD5_DIGEST_LEN); } _idBytes = newIdBytes.clone(); } /** * Create a schema ID with an MD5 for a given Avro schema. */ public static SchemaId createWithMd5(Schema schema) { return new SchemaId(Utils.md5(Utils.utf8(schema.toString(false)))); } public static SchemaId createWithMd5(String schema) { return createWithMd5(Schema.parse(schema)); } @Override public boolean equals(Object obj) { if(obj == null || !(obj instanceof SchemaId)) return false; if (this == obj) return true; //shortcut SchemaId id = (SchemaId) obj; return Arrays.equals(_idBytes, id._idBytes); } @Override public int hashCode() { return Arrays.hashCode(_idBytes); } @Override public String toString() { return Hex.encodeHexString(_idBytes); } public byte[] getByteArray() { return _idBytes; } }
949
6,989
from __future__ import unicode_literals from collections import deque from functools import wraps __all__ = ( 'SimpleCache', 'FastDictCache', 'memoized', ) class SimpleCache(object): """ Very simple cache that discards the oldest item when the cache size is exceeded. :param maxsize: Maximum size of the cache. (Don't make it too big.) """ def __init__(self, maxsize=8): assert isinstance(maxsize, int) and maxsize > 0 self._data = {} self._keys = deque() self.maxsize = maxsize def get(self, key, getter_func): """ Get object from the cache. If not found, call `getter_func` to resolve it, and put that on the top of the cache instead. """ # Look in cache first. try: return self._data[key] except KeyError: # Not found? Get it. value = getter_func() self._data[key] = value self._keys.append(key) # Remove the oldest key when the size is exceeded. if len(self._data) > self.maxsize: key_to_remove = self._keys.popleft() if key_to_remove in self._data: del self._data[key_to_remove] return value def clear(self): " Clear cache. " self._data = {} self._keys = deque() class FastDictCache(dict): """ Fast, lightweight cache which keeps at most `size` items. It will discard the oldest items in the cache first. The cache is a dictionary, which doesn't keep track of access counts. It is perfect to cache little immutable objects which are not expensive to create, but where a dictionary lookup is still much faster than an object instantiation. :param get_value: Callable that's called in case of a missing key. """ # NOTE: This cache is used to cache `prompt_toolkit.layout.screen.Char` and # `prompt_toolkit.Document`. Make sure to keep this really lightweight. # Accessing the cache should stay faster than instantiating new # objects. # (Dictionary lookups are really fast.) # SimpleCache is still required for cases where the cache key is not # the same as the arguments given to the function that creates the # value.) def __init__(self, get_value=None, size=1000000): assert callable(get_value) assert isinstance(size, int) and size > 0 self._keys = deque() self.get_value = get_value self.size = size def __missing__(self, key): # Remove the oldest key when the size is exceeded. if len(self) > self.size: key_to_remove = self._keys.popleft() if key_to_remove in self: del self[key_to_remove] result = self.get_value(*key) self[key] = result self._keys.append(key) return result def memoized(maxsize=1024): """ Momoization decorator for immutable classes and pure functions. """ cache = SimpleCache(maxsize=maxsize) def decorator(obj): @wraps(obj) def new_callable(*a, **kw): def create_new(): return obj(*a, **kw) key = (a, tuple(kw.items())) return cache.get(key, create_new) return new_callable return decorator
1,420