max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,754
<reponame>leonard84/ratpack<gh_stars>1000+ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 ratpack.exec.util.internal; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ratpack.func.Exceptions; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ThreadFactory; public abstract class TransportDetector { private static final Logger LOGGER = LoggerFactory.getLogger(TransportDetector.class); private static final Transport TRANSPORT = determineTransport(); private static Transport determineTransport() { Transport transport = new NativeTransport("io.netty.channel.epoll", "Epoll"); if (transport.isAvailable()) { LOGGER.debug("Using epoll transport"); return transport; } transport = new NativeTransport("io.netty.channel.kqueue", "KQueue"); if (transport.isAvailable()) { LOGGER.debug("Using kqueue transport"); return transport; } LOGGER.debug("Using nio transport"); return new NioTransport(); } public static Class<? extends ServerSocketChannel> getServerSocketChannelImpl() { return TRANSPORT.getServerSocketChannelImpl(); } public static Class<? extends SocketChannel> getSocketChannelImpl() { return TRANSPORT.getSocketChannelImpl(); } public static Class<? extends DatagramChannel> getDatagramChannelImpl() { return TRANSPORT.getDatagramChannelImpl(); } public static EventLoopGroup eventLoopGroup(int nThreads, ThreadFactory threadFactory) { return TRANSPORT.eventLoopGroup(nThreads, threadFactory); } private interface Transport { boolean isAvailable(); Class<? extends ServerSocketChannel> getServerSocketChannelImpl(); Class<? extends SocketChannel> getSocketChannelImpl(); Class<? extends DatagramChannel> getDatagramChannelImpl(); EventLoopGroup eventLoopGroup(int nThreads, ThreadFactory threadFactory); } private static class NioTransport implements Transport { @Override public boolean isAvailable() { return true; } @Override public Class<? extends ServerSocketChannel> getServerSocketChannelImpl() { return NioServerSocketChannel.class; } @Override public Class<? extends SocketChannel> getSocketChannelImpl() { return NioSocketChannel.class; } @Override public Class<? extends DatagramChannel> getDatagramChannelImpl() { return NioDatagramChannel.class; } @Override public EventLoopGroup eventLoopGroup(int nThreads, ThreadFactory threadFactory) { return new NioEventLoopGroup(nThreads, threadFactory); } } private static class NativeTransport implements Transport { private final NativeTransportImpl impl; NativeTransport(String packageName, String classPrefix) { String property = "ratpack." + classPrefix.toLowerCase() + ".disable"; boolean disabled = Boolean.getBoolean(property); if (disabled || !isAvailable(packageName, classPrefix)) { this.impl = null; } else { this.impl = loadImpl(packageName, classPrefix); } } @Override public boolean isAvailable() { return impl != null; } @Override public Class<? extends ServerSocketChannel> getServerSocketChannelImpl() { return impl.serverSocketChannelClass; } @Override public Class<? extends SocketChannel> getSocketChannelImpl() { return impl.socketChannelClass; } @Override public Class<? extends DatagramChannel> getDatagramChannelImpl() { return impl.datagramChannelClass; } @Override public EventLoopGroup eventLoopGroup(int nThreads, ThreadFactory threadFactory) { return impl.eventLoopGroup(nThreads, threadFactory); } private static NativeTransportImpl loadImpl(String packageName, String classPrefix) { try { Class<? extends ServerSocketChannel> serverSocketChannelClass = loadClass(ServerSocketChannel.class, packageName, classPrefix, ServerSocketChannel.class.getSimpleName()); Class<? extends SocketChannel> socketChannelClass = loadClass(SocketChannel.class, packageName, classPrefix, SocketChannel.class.getSimpleName()); Class<? extends DatagramChannel> datagramChannelClass = loadClass(DatagramChannel.class, packageName, classPrefix, DatagramChannel.class.getSimpleName()); Class<? extends EventLoopGroup> eventLoopGroupClass = loadClass(EventLoopGroup.class, packageName, classPrefix, EventLoopGroup.class.getSimpleName()); Constructor<? extends EventLoopGroup> constructor = eventLoopGroupClass.getConstructor(int.class, ThreadFactory.class); return new NativeTransportImpl(serverSocketChannelClass, socketChannelClass, datagramChannelClass, constructor); } catch (ReflectiveOperationException e) { LOGGER.debug("Failed to load {}", classPrefix, e); return null; } } private static boolean isAvailable(String packageName, String classPrefix) { try { Class<?> clazz = loadClass(Object.class, packageName, classPrefix, null); return invokeIsAvailable(clazz); } catch (ClassNotFoundException e) { LOGGER.debug("{} was not found", packageName); return false; } catch (Exception e) { LOGGER.debug("{} failed to load", packageName, e); return false; } } private static <T> Class<? extends T> loadClass(Class<T> type, String packageName, String classPrefix, String classType) throws ClassNotFoundException { String name = packageName + "." + classPrefix; if (classType != null) { name += classType; } Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(name); if (type.isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") Class<? extends T> cast = (Class<? extends T>) clazz; return cast; } else { throw new ClassCastException("Cannot assign " + clazz + " to " + type); } } private static boolean invokeIsAvailable(Class<?> clazz) { Object result; try { result = clazz.getMethod("isAvailable").invoke(null); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { LOGGER.debug("{}.isAvailable failed", clazz.getName(), e); return false; } if (result instanceof Boolean) { Boolean isAvailable = (Boolean) result; if (!isAvailable && LOGGER.isDebugEnabled()) { Object unavailabilityCause; try { unavailabilityCause = clazz.getMethod("unavailabilityCause").invoke(null); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { LOGGER.debug("{}.unavailabilityCause() failed", clazz.getName(), e); return false; } if (unavailabilityCause instanceof Throwable) { //noinspection VerifyFormattedMessage LOGGER.debug("{} unavailability cause", clazz.getName(), unavailabilityCause); } } return isAvailable; } else { LOGGER.debug("{}.isAvailable returned {}", clazz.getName(), result); return false; } } } private static class NativeTransportImpl { private final Class<? extends ServerSocketChannel> serverSocketChannelClass; private final Class<? extends SocketChannel> socketChannelClass; private final Class<? extends DatagramChannel> datagramChannelClass; private final Constructor<? extends EventLoopGroup> constructor; NativeTransportImpl( Class<? extends ServerSocketChannel> serverSocketChannelClass, Class<? extends SocketChannel> socketChannelClass, Class<? extends DatagramChannel> datagramChannelClass, Constructor<? extends EventLoopGroup> constructor ) { this.serverSocketChannelClass = serverSocketChannelClass; this.socketChannelClass = socketChannelClass; this.datagramChannelClass = datagramChannelClass; this.constructor = constructor; } EventLoopGroup eventLoopGroup(int nThreads, ThreadFactory threadFactory) { try { return constructor.newInstance(nThreads, threadFactory); } catch (ReflectiveOperationException e) { throw Exceptions.uncheck(e); } } } }
3,056
3,294
<reponame>BaruaSourav/docs // System::Net::WebPermission::WebPermission(PermissionState);System::Net::WebPermission::Copy; /** * This program demonstrates the WebPermission(PermissionState) constructor and * Copy method of the WebPermission class . * It creates a WebPermission instance with Permissionstate set to None and * sets the access right to one pair of URLs. * Then it uses the Copy method to create another instance of WebPermission class * Finally, the attributes , values and childrens of both the XML encoded instances * are displayed. */ #using <System.dll> using namespace System; using namespace System::Net; using namespace System::Security; using namespace System::Security::Permissions; using namespace System::Collections; public ref class CopyWebPermission { public: void CreateCopy() { // <Snippet1> // Create a WebPermission instance. WebPermission^ myWebPermission1 = gcnew WebPermission( PermissionState::None ); // Allow access to the first set of URL's. myWebPermission1->AddPermission( NetworkAccess::Connect, "http://www.microsoft.com/default.htm" ); myWebPermission1->AddPermission( NetworkAccess::Connect, "http://www.msn.com" ); // Check whether all callers higher in the call stack have been granted the permissionor not. myWebPermission1->Demand(); // </Snippet1> // <Snippet2> // Create another WebPermission instance that is the copy of the above WebPermission instance. WebPermission^ myWebPermission2 = (WebPermission^)(myWebPermission1->Copy()); // Check whether all callers higher in the call stack have been granted the permissionor not. myWebPermission2->Demand(); // </Snippet2> Console::WriteLine( "The Attributes and Values are :\n" ); // Display the Attributes, Values and Children of the XML encoded instance. PrintKeysAndValues( myWebPermission1->ToXml()->Attributes, myWebPermission1->ToXml()->Children ); Console::WriteLine( "\nCopied Instance Attributes and Values are:\n" ); // Display the Attributes, Values and Children of the XML encoded copied instance. PrintKeysAndValues( myWebPermission2->ToXml()->Attributes, myWebPermission2->ToXml()->Children ); } private: void PrintKeysAndValues( Hashtable^ myHashtable, IEnumerable^ myList ) { // Gets the enumerator that can iterate through Hashtable. IDictionaryEnumerator^ myEnumerator = myHashtable->GetEnumerator(); Console::WriteLine( "\t-KEY-\t-VALUE-" ); while ( myEnumerator->MoveNext() ) { Console::WriteLine( "\t {0}:\t {1}", myEnumerator->Key, myEnumerator->Value ); } Console::WriteLine(); IEnumerator^ myEnumerator1 = myList->GetEnumerator(); Console::WriteLine( "The Children are: " ); while ( myEnumerator1->MoveNext() ) { Console::Write( "\t {0}", myEnumerator1->Current ); } } }; int main() { try { CopyWebPermission^ myCopyWebPermission = gcnew CopyWebPermission; myCopyWebPermission->CreateCopy(); } catch ( SecurityException^ e ) { Console::WriteLine( "SecurityException: {0}", e->Message ); } catch ( Exception^ e ) { Console::WriteLine( "Exception: {0}", e->Message ); } }
1,133
2,577
<reponame>mlehotsky13/camunda-bpm-platform /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.impl.runtime; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import org.junit.Before; import org.junit.Test; public class DefaultDeserializationTypeValidatorTest { private static final String ANOTHER_CLASS = "another.class.Class"; private static final String ANOTHER_PACKAGE = "another.class"; private static final String SOME_CLASS = "some.class.Class"; private static final String SOME_PACKAGE = "some.class"; protected DefaultDeserializationTypeValidator validator; @Before public void setUp() { validator = new DefaultDeserializationTypeValidator(); } // SETTERS @Test public void shouldAcceptNullListOfAllowedClasses() { // when validator.setAllowedClasses(null); // then assertThat(validator.allowedClasses).isEmpty(); } @Test public void shouldAcceptEmptyListOfAllowedClasses() { // when validator.setAllowedClasses(""); // then assertThat(validator.allowedClasses).isEmpty(); } @Test public void shouldAcceptListOfEmptyAllowedClasses() { // when validator.setAllowedClasses("\r\n , \t , ,,\n,\r"); // then assertThat(validator.allowedClasses).isEmpty(); } @Test public void shouldAcceptSingleStringOfAllowedClasses() { // when validator.setAllowedClasses("some.Class"); // then assertThat(validator.allowedClasses).containsExactly("some.Class"); } @Test public void shouldAcceptStringListOfAllowedClasses() { // when validator.setAllowedClasses(" some.class.Class , another.class.Class "); // then assertThat(validator.allowedClasses).containsExactlyInAnyOrder(SOME_CLASS, ANOTHER_CLASS); } @Test public void shouldOverrideAllowedClasses() { // given validator.setAllowedClasses(SOME_CLASS); // when validator.setAllowedClasses(ANOTHER_CLASS); // then assertThat(validator.allowedClasses).containsExactly(ANOTHER_CLASS); } @Test public void shouldClearAllowedClasses() { // given validator.setAllowedClasses(SOME_CLASS); // when validator.setAllowedClasses(null); // then assertThat(validator.allowedClasses).isEmpty(); } @Test public void shouldAcceptNullListOfAllowedPackages() { // when validator.setAllowedPackages(null); // then assertThat(validator.allowedPackages).isEmpty(); } @Test public void shouldAcceptEmptyListOfAllowedPackages() { // when validator.setAllowedPackages(""); // then assertThat(validator.allowedPackages).isEmpty(); } @Test public void shouldAcceptListOfEmptyAllowedPackages() { // when validator.setAllowedPackages("\r\n , \t , ,,\n,\r"); // then assertThat(validator.allowedPackages).isEmpty(); } @Test public void shouldAcceptSingleStringOfAllowedPackages() { // when validator.setAllowedPackages("some."); // then assertThat(validator.allowedPackages).containsExactly("some."); } @Test public void shouldAcceptStringListOfAllowedPackages() { // when validator.setAllowedPackages(" some.class , another.class "); // then assertThat(validator.allowedPackages).containsExactlyInAnyOrder("some.class", "another.class"); } @Test public void shouldOverrideAllowedPackages() { // given validator.setAllowedPackages(SOME_PACKAGE); // when validator.setAllowedPackages(ANOTHER_PACKAGE); // then assertThat(validator.allowedPackages).containsExactly(ANOTHER_PACKAGE); } @Test public void shouldClearAllowedPackages() { // given validator.setAllowedPackages(SOME_PACKAGE); // when validator.setAllowedPackages(null); // then assertThat(validator.allowedPackages).isEmpty(); } // EMPTY WHITELIST @Test public void shouldForbidUnknownClassOnEmptyWhitelist() { // then assertThat(validator.validate(SOME_CLASS)).isFalse(); } @Test public void shouldAllowJavaLangClassOnEmptyWhitelist() { // then assertThat(validator.validate(Number.class.getName())).isTrue(); } @Test public void shouldAllowJavaUtilContainerClassesOnEmptyWhitelist() { // then assertThat(validator.validate(ArrayList.class.getName())).isTrue(); assertThat(validator.validate(HashMap.class.getName())).isTrue(); assertThat(validator.validate(Arrays.asList("a", "n").getClass().getName())).isTrue(); } // ALLOWED CLASS(ES) @Test public void shouldAllowClassOnWhitelistedClass() { // given validator.setAllowedClasses(SOME_CLASS); // then assertThat(validator.validate(SOME_CLASS)).isTrue(); } @Test public void shouldAllowClassOnWhitelistedClasses() { // given validator.setAllowedClasses(SOME_CLASS + "," + ANOTHER_CLASS); // then assertThat(validator.validate(SOME_CLASS)).isTrue(); } @Test public void shouldForbidClassOnNonWhitelistedClass() { // given validator.setAllowedClasses(SOME_CLASS); // then assertThat(validator.validate(ANOTHER_CLASS)).isFalse(); } @Test public void shouldForbidClassOnNonWhitelistedClasses() { // given validator.setAllowedClasses(SOME_CLASS + "," + ANOTHER_CLASS); // then assertThat(validator.validate("different.Class")).isFalse(); } @Test public void shouldForbidClassOnEmptyClasses() { // given validator.setAllowedClasses(", ,,"); // then assertThat(validator.validate(SOME_CLASS)).isFalse(); } // ALLOWED PACKAGE(S) @Test public void shouldAllowClassOnWhitelistedPackage() { // given validator.setAllowedPackages(SOME_PACKAGE); // then assertThat(validator.validate(SOME_CLASS)).isTrue(); } @Test public void shouldAllowClassOnWhitelistedPackages() { // given validator.setAllowedPackages(SOME_PACKAGE + "," + ANOTHER_PACKAGE); // then assertThat(validator.validate(SOME_CLASS)).isTrue(); } @Test public void shouldForbidClassOnNonWhitelistedPackage() { // given validator.setAllowedPackages(SOME_PACKAGE); // then assertThat(validator.validate(ANOTHER_CLASS)).isFalse(); } @Test public void shouldForbidClassOnNonWhitelistedPackages() { // given validator.setAllowedPackages(SOME_PACKAGE + "," + ANOTHER_PACKAGE); // then assertThat(validator.validate("different.Class")).isFalse(); } @Test public void shouldForbidClassOnEmptyPackages() { // given validator.setAllowedPackages(", ,,"); // then assertThat(validator.validate(SOME_CLASS)).isFalse(); } // ALLOWED CLASS(ES) AND PACKAGE(S) @Test public void shouldAllowClassOnWhitelistedClassAndNonWhitelistedPackage() { // given validator.setAllowedClasses(SOME_CLASS); validator.setAllowedPackages(ANOTHER_PACKAGE); // then assertThat(validator.validate(SOME_CLASS)).isTrue(); } @Test public void shouldAllowClassOnNonWhitelistedClassAndWhitelistedPackage() { // given validator.setAllowedClasses(ANOTHER_CLASS); validator.setAllowedPackages(SOME_PACKAGE); // then assertThat(validator.validate(SOME_CLASS)).isTrue(); } @Test public void shouldForbidClassOnNonWhitelistedClassAndNonWhitelistedPackage() { // given validator.setAllowedPackages(SOME_PACKAGE); validator.setAllowedClasses(SOME_CLASS); // then assertThat(validator.validate(ANOTHER_CLASS)).isFalse(); } }
2,888
855
import pytest from kopf._cogs.structs.references import EVERYTHING, Selector @pytest.mark.parametrize('kw', ['kind', 'plural', 'singular', 'shortcut', 'category', 'any_name']) def test_repr_with_names(kw): selector = Selector(**{kw: 'name1'}) selector_repr = repr(selector) assert selector_repr == f"Selector({kw}='name1')" @pytest.mark.parametrize('group', ['group1', 'group1.example.com', 'v1nonconventional']) def test_repr_with_group(group): selector = Selector(group=group, any_name='name1') selector_repr = repr(selector) assert selector_repr == f"Selector(group='{group}', any_name='name1')" @pytest.mark.parametrize('kw', ['kind', 'plural', 'singular', 'shortcut', 'any_name']) def test_is_specific_with_names(kw): selector = Selector(**{kw: 'name1'}) assert selector.is_specific @pytest.mark.parametrize('kw', ['category']) def test_is_not_specific_with_categories(kw): selector = Selector(**{kw: 'name1'}) assert not selector.is_specific @pytest.mark.parametrize('kw', ['category']) def test_is_not_specific_with_categories(kw): selector = Selector(EVERYTHING) assert not selector.is_specific @pytest.mark.parametrize('kw', ['category']) def test_is_not_specific_with_categories(kw): selector = Selector(**{kw: 'name1'}) assert not selector.is_specific
511
17,275
package jenkins.security; import hudson.model.User; import hudson.security.SecurityRealm; import hudson.security.UserMayOrMayNotExistException2; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * {@link UserDetailsService} for those {@link SecurityRealm} * that doesn't allow query of other users. * * When the backend responds with {@link UserMayOrMayNotExistException2}, we try to replace that with * information stored in {@link LastGrantedAuthoritiesProperty}. * * @author <NAME> */ public class ImpersonatingUserDetailsService2 implements UserDetailsService { private final UserDetailsService base; public ImpersonatingUserDetailsService2(UserDetailsService base) { this.base = base; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { return base.loadUserByUsername(username); } catch (UserMayOrMayNotExistException2 e) { return attemptToImpersonate(username, e); } } protected UserDetails attemptToImpersonate(String username, RuntimeException e) { // this backend cannot tell if the user name exists or not. so substitute by what we know User u = User.getById(username, false); if (u != null) { LastGrantedAuthoritiesProperty p = u.getProperty(LastGrantedAuthoritiesProperty.class); if (p != null) { return new org.springframework.security.core.userdetails.User(username, "", true, true, true, true, p.getAuthorities2()); } } throw e; } }
598
2,663
{ "type": "Claim Votes", "definition": { "text": "In general terms, Claim Votes allow you to support the claims of other users. The term Claim Votes is a generalization referring to either or all of the existing types: Position Claim Vote, Feature Claim Vote, and Asset Claim Vote nodes.", "updated": 1630343978470 }, "paragraphs": [ { "style": "Block", "text": "Content", "updated": 1624781429515 }, { "style": "Callout", "text": "In general terms, Claim Votes allow you to support the claims of other users. The term Claim Votes is a generalization referring to either or all of the existing particular types: Position Claim Vote, Feature Claim Vote, and Asset Claim Vote nodes.", "updated": 1630343984130 } ] }
316
3,102
#define THROUGH3 int through3(int);
13
2,740
<filename>mlmodel/src/MILBlob/Blob/StorageWriter.cpp // Copyright (c) 2021, Apple Inc. All rights reserved. // // Use of this source code is governed by a BSD-3-clause license that can be // found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause #include "MILBlob/Blob/FileWriter.hpp" #include "MILBlob/Blob/StorageFormat.hpp" #include "MILBlob/Blob/StorageWriter.hpp" #include "MILBlob/Fp16.hpp" #include "MILBlob/Util/Span.hpp" #include "MILBlob/Util/SpanCast.hpp" #include <string> #include <unordered_map> using namespace MILBlob; using namespace MILBlob::Blob; namespace { template <typename T> Util::Span<uint8_t> CastAndMakeSpan(T& x) { return Util::Span<uint8_t>(reinterpret_cast<uint8_t*>(&x), sizeof(x)); } } // anonymous namespace class StorageWriter::Impl final { public: Impl(const Impl&) = delete; Impl(Impl&&) = delete; Impl& operator=(const Impl&) = delete; Impl& operator=(Impl&&) = delete; ~Impl() = default; Impl(const std::string& filePath, bool truncateFile) : m_fileWriter(std::make_unique<FileWriter>(filePath, truncateFile)) { if (truncateFile) { m_fileWriter->WriteData(CastAndMakeSpan(m_header), 0); } else { auto fileSize = m_fileWriter->GetFileSize(); if (fileSize == 0) { // File exists and is empty m_fileWriter->WriteData(CastAndMakeSpan(m_header), 0); } else if (static_cast<size_t>(fileSize) >= sizeof(m_header)) { m_fileWriter->ReadData(0, CastAndMakeSpan(m_header)); if (m_header.version != 2) { // File exists and header is incorrect // File is not empty, please use truncate option throw std::runtime_error( "[MIL StorageWriter]: Incorrect file header, please use truncateFile=true"); } } else { // File is not empty, please use truncate option throw std::runtime_error("[MIL StorageWriter]: Incorrect file header, please use truncateFile=true"); } } } template <typename T> uint64_t WriteData(Util::Span<const T> data); private: std::unique_ptr<FileWriter> m_fileWriter; storage_header m_header; }; template <typename T> uint64_t StorageWriter::Impl::WriteData(Util::Span<const T> data) { // 1. Write data blob_metadata metadata; metadata.mil_dtype = BlobDataTypeTraits<typename std::remove_const<T>::type>::DataType; metadata.sizeInBytes = data.Size() * sizeof(T); // Get offset for data auto metadataOffset = m_fileWriter->GetNextAlignedOffset(); // metadata is 64 bit aligned. auto dataOffset = metadataOffset + sizeof(metadata); MILVerifyIsTrue(dataOffset % DefaultStorageAlignment == 0, std::runtime_error, "[MIL StorageWriter]: dataOffset is expected to be 64 bits aligned."); metadata.offset = dataOffset; // We don't expect m_fileWriter to produce different offset for metadata and data auto actualMetadataOffset = m_fileWriter->AppendData(CastAndMakeSpan(metadata)); MILVerifyIsTrue(metadataOffset == actualMetadataOffset, std::runtime_error, "[MIL StorageWriter]: Metadata written to different offset than expected."); auto actualDataOffset = m_fileWriter->AppendData(Util::SpanCast<const uint8_t>(data)); MILVerifyIsTrue(dataOffset == actualDataOffset, std::runtime_error, "[MIL StorageWriter]: Metadata written to different offset than expected."); // 2. Update count in header m_header.count++; // Write header with new count m_fileWriter->WriteData(CastAndMakeSpan(m_header), 0); // return offset in file to blob_metadata return metadataOffset; } // -------------------------------------------------------------------------------------- StorageWriter::~StorageWriter() = default; StorageWriter::StorageWriter(const std::string& filePath, bool truncateFile) : m_impl(std::make_unique<Impl>(filePath, truncateFile)) {} template <> uint64_t StorageWriter::WriteData<uint8_t>(Util::Span<const uint8_t> data) { return m_impl->WriteData(data); } template <> uint64_t StorageWriter::WriteData<Fp16>(Util::Span<const Fp16> data) { return m_impl->WriteData(data); } template <> uint64_t StorageWriter::WriteData<float>(Util::Span<const float> data) { return m_impl->WriteData(data); }
1,814
3,066
<gh_stars>1000+ /* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.blob; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.IOUtils; import org.elasticsearch.action.ActionListenerResponseHandler; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportRequestOptions; import org.elasticsearch.transport.TransportResponse; import org.elasticsearch.transport.TransportService; import io.crate.blob.exceptions.BlobAlreadyExistsException; import io.crate.blob.exceptions.DigestMismatchException; import io.crate.blob.transfer.BlobHeadRequestHandler; import io.crate.blob.transfer.BlobInfoRequest; import io.crate.blob.transfer.BlobTransferInfoResponse; import io.crate.blob.transfer.GetBlobHeadRequest; import io.crate.blob.v2.BlobIndicesService; import io.crate.blob.v2.BlobShard; import io.crate.common.unit.TimeValue; public class BlobTransferTarget { private static final Logger LOGGER = LogManager.getLogger(BlobTransferTarget.class); private final ConcurrentMap<UUID, BlobTransferStatus> activeTransfers = ConcurrentCollections.newConcurrentMap(); private final BlobIndicesService blobIndicesService; private final ThreadPool threadPool; private final TransportService transportService; private final ClusterService clusterService; private CountDownLatch getHeadRequestLatch; private CompletableFuture<CountDownLatch> getHeadRequestLatchFuture; private final ConcurrentLinkedQueue<UUID> activePutHeadChunkTransfers; private CountDownLatch activePutHeadChunkTransfersLatch; private volatile boolean recoveryActive = false; private final Object lock = new Object(); private final List<UUID> finishedUploads = new ArrayList<>(); private final TimeValue STATE_REMOVAL_DELAY; @Inject public BlobTransferTarget(BlobIndicesService blobIndicesService, ThreadPool threadPool, TransportService transportService, ClusterService clusterService) { String property = System.getProperty("tests.short_timeouts"); if (property == null) { STATE_REMOVAL_DELAY = new TimeValue(40, TimeUnit.SECONDS); } else { STATE_REMOVAL_DELAY = new TimeValue(2, TimeUnit.SECONDS); } this.blobIndicesService = blobIndicesService; this.threadPool = threadPool; this.transportService = transportService; this.clusterService = clusterService; this.getHeadRequestLatchFuture = new CompletableFuture<>(); this.activePutHeadChunkTransfers = new ConcurrentLinkedQueue<>(); } public BlobTransferStatus getActiveTransfer(UUID transferId) { return activeTransfers.get(transferId); } public void startTransfer(StartBlobRequest request, StartBlobResponse response) { LOGGER.debug("startTransfer {} {}", request.transferId(), request.isLast()); BlobShard blobShard = blobIndicesService.blobShardSafe(request.shardId()); File existing = blobShard.blobContainer().getFile(request.id()); long size = existing.length(); if (existing.exists()) { // the file exists response.status(RemoteDigestBlob.Status.EXISTS); response.size(size); return; } DigestBlob digestBlob = blobShard.blobContainer().createBlob(request.id(), request.transferId()); digestBlob.addContent(request.content(), request.isLast()); response.size(digestBlob.size()); if (request.isLast()) { try { digestBlob.commit(); blobShard.incrementStats(digestBlob.size()); response.status(RemoteDigestBlob.Status.FULL); } catch (DigestMismatchException e) { response.status(RemoteDigestBlob.Status.MISMATCH); } catch (BlobAlreadyExistsException e) { response.size(digestBlob.size()); response.status(RemoteDigestBlob.Status.EXISTS); } catch (Exception e) { response.status(RemoteDigestBlob.Status.FAILED); } } else { BlobTransferStatus status = new BlobTransferStatus( request.shardId(), request.transferId(), digestBlob ); activeTransfers.put(request.transferId(), status); response.status(RemoteDigestBlob.Status.PARTIAL); } LOGGER.debug("startTransfer finished {} {}", response.status(), response.size()); } public void continueTransfer(PutChunkReplicaRequest request, PutChunkResponse response) { BlobTransferStatus status = activeTransfers.get(request.transferId); if (status == null) { status = restoreTransferStatus(request); } addContent(request, response, status); } public void continueTransfer(PutChunkRequest request, PutChunkResponse response) { BlobTransferStatus status = activeTransfers.get(request.transferId()); if (status == null) { LOGGER.error("No context for transfer: {} Dropping request", request.transferId()); response.status(RemoteDigestBlob.Status.PARTIAL); return; } addContent(request, response, status); } private BlobTransferStatus restoreTransferStatus(PutChunkReplicaRequest request) { LOGGER.trace("Restoring transferContext for PutChunkReplicaRequest with transferId {}", request.transferId); DiscoveryNodes nodes = clusterService.state().getNodes(); DiscoveryNode recipientNodeId = nodes.get(request.sourceNodeId); String senderNodeId = nodes.getLocalNodeId(); var listener = new PlainActionFuture<BlobTransferInfoResponse>(); transportService.sendRequest( recipientNodeId, BlobHeadRequestHandler.Actions.GET_TRANSFER_INFO, new BlobInfoRequest(senderNodeId, request.transferId), TransportRequestOptions.EMPTY, new ActionListenerResponseHandler<>(listener, BlobTransferInfoResponse::new) ); BlobTransferInfoResponse transferInfoResponse = listener.actionGet(); BlobShard blobShard = blobIndicesService.blobShardSafe(request.shardId()); DigestBlob digestBlob = DigestBlob.resumeTransfer( blobShard.blobContainer(), transferInfoResponse.digest, request.transferId, request.currentPos ); assert digestBlob != null : "DigestBlob couldn't be restored"; BlobTransferStatus status; status = new BlobTransferStatus(request.shardId(), request.transferId, digestBlob); activeTransfers.put(request.transferId, status); LOGGER.trace("Restored transferStatus for digest {} transferId: {}", transferInfoResponse.digest, request.transferId ); var getBlobHeadListener = new PlainActionFuture<>(); transportService.sendRequest( recipientNodeId, BlobHeadRequestHandler.Actions.GET_BLOB_HEAD, new GetBlobHeadRequest(senderNodeId, request.transferId(), request.currentPos), TransportRequestOptions.EMPTY, new ActionListenerResponseHandler<>(getBlobHeadListener, in -> TransportResponse.Empty.INSTANCE) ); getBlobHeadListener.actionGet(); return status; } private void addContent(IPutChunkRequest request, PutChunkResponse response, BlobTransferStatus status) { DigestBlob digestBlob = status.digestBlob(); try { digestBlob.addContent(request.content(), request.isLast()); } catch (BlobWriteException e) { IOUtils.closeWhileHandlingException(activeTransfers.remove(status.transferId())); throw e; } response.size(digestBlob.size()); if (request.isLast()) { digestBlob.waitForHead(); try { digestBlob.commit(); BlobShard blobShard = blobIndicesService.blobShardSafe(status.shardId()); blobShard.incrementStats(digestBlob.size()); response.status(RemoteDigestBlob.Status.FULL); } catch (DigestMismatchException e) { response.status(RemoteDigestBlob.Status.MISMATCH); } catch (BlobAlreadyExistsException e) { response.size(digestBlob.size()); response.status(RemoteDigestBlob.Status.EXISTS); } catch (Exception e) { response.status(RemoteDigestBlob.Status.FAILED); } finally { removeTransferAfterRecovery(status.transferId()); } LOGGER.debug("transfer finished digest:{} status:{} size:{} chunks:{}", status.transferId(), response.status(), response.size(), digestBlob.chunks()); } else { response.status(RemoteDigestBlob.Status.PARTIAL); } } private void removeTransferAfterRecovery(UUID transferId) { boolean toSchedule = false; synchronized (lock) { if (recoveryActive) { /** * the recovery target node might request the transfer context. So it is * necessary to keep the state until the recovery is done. */ finishedUploads.add(transferId); } else { toSchedule = true; } } if (toSchedule) { LOGGER.debug("finished transfer {}, removing state", transferId); /** * there might be a race condition that the recoveryActive flag is still false although a * recovery has been started. * * delay the state removal a bit and re-check the recoveryActive flag in order to not remove * states which might still be needed. */ threadPool.schedule(new StateRemoval(transferId), STATE_REMOVAL_DELAY, ThreadPool.Names.GENERIC); } } private class StateRemoval implements Runnable { private final UUID transferId; private StateRemoval(UUID transferId) { this.transferId = transferId; } @Override public void run() { synchronized (lock) { if (recoveryActive) { finishedUploads.add(transferId); } else { BlobTransferStatus transferStatus = activeTransfers.remove(transferId); IOUtils.closeWhileHandlingException(transferStatus); } } } } /** * creates a countDownLatch from the activeTransfers. * This is the number of "GetHeadRequests" that are expected from the target node * The actual number of GetHeadRequests that will be received might be lower * than the number that is expected. */ public void createActiveTransfersSnapshot() { getHeadRequestLatch = new CountDownLatch(activeTransfers.size()); /** * the future is used because {@link #gotAGetBlobHeadRequest(org.elasticsearch.common.UUID)} * might be called before this method und there is a .get() call that blocks and waits */ getHeadRequestLatchFuture.complete(getHeadRequestLatch); } /** * wait until the expected number of GetHeadRequests was received or at most * num / timeUnit. * <p> * The number of GetHeadRequests that are expected is set when * {@link #createActiveTransfersSnapshot()} is called */ public void waitForGetHeadRequests(int num, TimeUnit timeUnit) { try { getHeadRequestLatch.await(num, timeUnit); } catch (InterruptedException e) { Thread.interrupted(); } } public void waitUntilPutHeadChunksAreFinished() { try { activePutHeadChunkTransfersLatch.await(); } catch (InterruptedException e) { Thread.interrupted(); } } public void gotAGetBlobHeadRequest(UUID transferId) { /** * this method might be called before the getHeadRequestLatch is initialized * the future is used here to wait until it is initialized. */ if (getHeadRequestLatch == null) { try { getHeadRequestLatch = getHeadRequestLatchFuture.get(); activePutHeadChunkTransfers.add(transferId); getHeadRequestLatch.countDown(); } catch (InterruptedException | ExecutionException e) { LOGGER.error("can't retrieve getHeadRequestLatch", e); } } } public void createActivePutHeadChunkTransfersSnapshot() { activePutHeadChunkTransfersLatch = new CountDownLatch(activePutHeadChunkTransfers.size()); } public void putHeadChunkTransferFinished(UUID transferId) { activePutHeadChunkTransfers.remove(transferId); if (activePutHeadChunkTransfersLatch != null) { activePutHeadChunkTransfersLatch.countDown(); } } public void startRecovery() { recoveryActive = true; } public void stopRecovery() { synchronized (lock) { recoveryActive = false; for (UUID finishedUpload : finishedUploads) { LOGGER.debug("finished transfer and recovery for {}, removing state", finishedUpload); BlobTransferStatus transferStatus = activeTransfers.remove(finishedUpload); IOUtils.closeWhileHandlingException(transferStatus); } } } }
6,079
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_ #define __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <threadhelp/threadhelpbase.hxx> #include <macros/generic.hxx> #include <macros/xinterface.hxx> #include <macros/xtypeprovider.hxx> //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #include <com/sun/star/task/XStatusIndicator.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/lang/XComponent.hpp> //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #include <rtl/ustring.hxx> #include <cppuhelper/implbase1.hxx> #include <vector> namespace framework { class StatusIndicatorInterfaceWrapper : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XStatusIndicator> { public: StatusIndicatorInterfaceWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& rStatusIndicatorImpl ); virtual ~StatusIndicatorInterfaceWrapper(); //--------------------------------------------------------------------------------------------------------- // XStatusIndicator //--------------------------------------------------------------------------------------------------------- virtual void SAL_CALL start ( const ::rtl::OUString& sText , sal_Int32 nRange ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL end ( ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL reset ( ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setText ( const ::rtl::OUString& sText ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setValue( sal_Int32 nValue ) throw( ::com::sun::star::uno::RuntimeException ); private: StatusIndicatorInterfaceWrapper(); ::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent > m_xStatusIndicatorImpl; }; } #endif // __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
1,074
713
<filename>core/src/test/java/org/infinispan/api/SimpleCacheTest.java package org.infinispan.api; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.util.function.BiConsumer; import org.infinispan.Cache; import org.infinispan.cache.impl.AbstractDelegatingCache; import org.infinispan.cache.impl.SimpleCacheImpl; import org.infinispan.commons.CacheConfigurationException; import org.infinispan.configuration.CustomInterceptorConfigTest; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.container.entries.CacheEntry; import org.infinispan.interceptors.AsyncInterceptorChain; import org.infinispan.interceptors.BaseCustomAsyncInterceptor; import org.infinispan.interceptors.impl.InvocationContextInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.stats.Stats; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.transaction.TransactionMode; import org.testng.annotations.Test; /** * @author <NAME> &lt;<EMAIL>&gt; */ @Test(groups = "functional", testName = "api.SimpleCacheTest") public class SimpleCacheTest extends APINonTxTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.simpleCache(true); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(cb); cache = AbstractDelegatingCache.unwrapCache(cm.getCache()); assertTrue(cache instanceof SimpleCacheImpl); return cm; } @Test(expectedExceptions = UnsupportedOperationException.class) public void testAddInterceptor() { cache().getAdvancedCache().getAsyncInterceptorChain() .addInterceptor(new CustomInterceptorConfigTest.DummyInterceptor(), 0); } public void testFindInterceptor() { AsyncInterceptorChain interceptorChain = cache().getAdvancedCache().getAsyncInterceptorChain(); assertNotNull(interceptorChain); assertNull(interceptorChain.findInterceptorExtending(InvocationContextInterceptor.class)); } @Test(expectedExceptions = CacheConfigurationException.class) public void testTransactions() { new ConfigurationBuilder().simpleCache(true) .transaction().transactionMode(TransactionMode.TRANSACTIONAL).build(); } @Test(expectedExceptions = CacheConfigurationException.class) public void testCustomInterceptors() { new ConfigurationBuilder().simpleCache(true) .customInterceptors().addInterceptor().interceptor(new BaseCustomAsyncInterceptor()) .build(); } @Test(expectedExceptions = CacheConfigurationException.class) public void testBatching() { new ConfigurationBuilder().simpleCache(true).invocationBatching().enable(true).build(); } @Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN000381: This configuration is not supported for simple cache") public void testIndexing() { new ConfigurationBuilder().simpleCache(true).indexing().enable().build(); } @Test(expectedExceptions = CacheConfigurationException.class) public void testStoreAsBinary() { new ConfigurationBuilder().simpleCache(true).memory().storageType(StorageType.BINARY).build(); } @Test(dataProvider = "lockedStreamActuallyLocks", expectedExceptions = UnsupportedOperationException.class) @Override public void testLockedStreamActuallyLocks(BiConsumer<Cache<Object, Object>, CacheEntry<Object, Object>> consumer, boolean forEachOrInvokeAll) throws Throwable { super.testLockedStreamActuallyLocks(consumer, forEachOrInvokeAll); } @Test(expectedExceptions = UnsupportedOperationException.class) @Override public void testLockedStreamSetValue() { super.testLockedStreamSetValue(); } @Test(expectedExceptions = UnsupportedOperationException.class) @Override public void testLockedStreamWithinLockedStream() { super.testLockedStreamWithinLockedStream(); } @Test(expectedExceptions = UnsupportedOperationException.class) @Override public void testLockedStreamInvokeAllFilteredSet() { super.testLockedStreamInvokeAllFilteredSet(); } @Test(expectedExceptions = UnsupportedOperationException.class) @Override public void testLockedStreamInvokeAllPut() { super.testLockedStreamInvokeAllPut(); } public void testStatistics() { Configuration cfg = new ConfigurationBuilder().simpleCache(true).jmxStatistics().enabled(true).build(); String name = "statsCache"; cacheManager.defineConfiguration(name, cfg); Cache<Object, Object> cache = cacheManager.getCache(name); assertEquals(0L, cache.getAdvancedCache().getStats().getStores()); cache.put("key", "value"); assertEquals(1L, cache.getAdvancedCache().getStats().getStores()); } public void testEvictionWithStatistics() { int KEY_COUNT = 5; Configuration cfg = new ConfigurationBuilder() .simpleCache(true) .memory().size(1) .jmxStatistics().enable() .build(); String name = "evictionCache"; cacheManager.defineConfiguration(name, cfg); Cache<Object, Object> cache = cacheManager.getCache(name); for (int i = 0; i < KEY_COUNT; i++) { cache.put("key" + i, "value"); } Stats stats = cache.getAdvancedCache().getStats(); assertEquals(1, stats.getCurrentNumberOfEntriesInMemory()); assertEquals(KEY_COUNT, stats.getStores()); assertEquals(KEY_COUNT - 1, stats.getEvictions()); } }
1,971
848
/*- * Copyright (c) 2015 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * $FreeBSD$ */ #ifndef _ATKBDC_H_ #define _ATKBDC_H_ #define KBD_DATA_PORT 0x60 #define KBD_STS_CTL_PORT 0x64 #define KBDC_RESET 0xfe #define KBD_DEV_IRQ 1 #define AUX_DEV_IRQ 12 /* controller commands */ #define KBDC_SET_COMMAND_BYTE 0x60 #define KBDC_GET_COMMAND_BYTE 0x20 #define KBDC_DISABLE_AUX_PORT 0xa7 #define KBDC_ENABLE_AUX_PORT 0xa8 #define KBDC_TEST_AUX_PORT 0xa9 #define KBDC_TEST_CTRL 0xaa #define KBDC_TEST_KBD_PORT 0xab #define KBDC_DISABLE_KBD_PORT 0xad #define KBDC_ENABLE_KBD_PORT 0xae #define KBDC_READ_INPORT 0xc0 #define KBDC_READ_OUTPORT 0xd0 #define KBDC_WRITE_OUTPORT 0xd1 #define KBDC_WRITE_KBD_OUTBUF 0xd2 #define KBDC_WRITE_AUX_OUTBUF 0xd3 #define KBDC_WRITE_TO_AUX 0xd4 /* controller command byte (set by KBDC_SET_COMMAND_BYTE) */ #define KBD_TRANSLATION 0x40 #define KBD_SYS_FLAG_BIT 0x04 #define KBD_DISABLE_KBD_PORT 0x10 #define KBD_DISABLE_AUX_PORT 0x20 #define KBD_ENABLE_AUX_INT 0x02 #define KBD_ENABLE_KBD_INT 0x01 #define KBD_KBD_CONTROL_BITS (KBD_DISABLE_KBD_PORT | KBD_ENABLE_KBD_INT) #define KBD_AUX_CONTROL_BITS (KBD_DISABLE_AUX_PORT | KBD_ENABLE_AUX_INT) /* controller status bits */ #define KBDS_KBD_BUFFER_FULL 0x01 #define KBDS_SYS_FLAG 0x04 #define KBDS_CTRL_FLAG 0x08 #define KBDS_AUX_BUFFER_FULL 0x20 /* controller output port */ #define KBDO_KBD_OUTFULL 0x10 #define KBDO_AUX_OUTFULL 0x20 #define RAMSZ 32 #define FIFOSZ 15 #define CTRL_CMD_FLAG 0x8000 struct vmctx; struct kbd_dev { bool irq_active; int irq; uint8_t buffer[FIFOSZ]; int brd, bwr; int bcnt; }; struct aux_dev { bool irq_active; int irq; }; struct atkbdc_base { struct vmctx *ctx; pthread_mutex_t mtx; struct ps2kbd_info *ps2kbd; struct ps2mouse_info *ps2mouse; uint8_t status; /* status register */ uint8_t outport; /* controller output port */ uint8_t ram[RAMSZ]; /* byte0 = controller config */ uint32_t curcmd; /* current command for next byte */ uint32_t ctrlbyte; struct kbd_dev kbd; struct aux_dev aux; }; void atkbdc_init(struct vmctx *ctx); void atkbdc_deinit(struct vmctx *ctx); void atkbdc_event(struct atkbdc_base *base, int iskbd); #endif /* _ATKBDC_H_ */
1,447
311
package com.sec.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; /** * @author 0range */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Dependencies { String[] value() default {}; public static class Utils { public static String[] getDependencies(AnnotatedElement annotated) { Dependencies deps = annotated.getAnnotation(Dependencies.class); if (deps != null && deps.value() != null) { return deps.value(); } else { return new String[0]; } } public static String[] getDependenciesSimple(AnnotatedElement annotated) { String[] deps = getDependencies(annotated); String[] simple = new String[deps.length]; for (int i = 0; i < simple.length; i++) { simple[i] = deps[i].split(":", 2)[1]; } return simple; } } }
477
2,151
<reponame>fugu-helper/android_external_swiftshader //===-- llvm/Support/COFF.h -------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains an definitions used in Windows COFF Files. // // Structures and enums defined within this file where created using // information from Microsoft's publicly available PE/COFF format document: // // Microsoft Portable Executable and Common Object File Format Specification // Revision 8.1 - February 15, 2008 // // As of 5/2/2010, hosted by Microsoft at: // http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_WIN_COFF_H #define LLVM_SUPPORT_WIN_COFF_H #include "llvm/Support/DataTypes.h" #include <cstring> namespace llvm { namespace COFF { // Sizes in bytes of various things in the COFF format. enum { HeaderSize = 20, NameSize = 8, SymbolSize = 18, SectionSize = 40, RelocationSize = 10 }; struct header { uint16_t Machine; uint16_t NumberOfSections; uint32_t TimeDateStamp; uint32_t PointerToSymbolTable; uint32_t NumberOfSymbols; uint16_t SizeOfOptionalHeader; uint16_t Characteristics; }; enum MachineTypes { IMAGE_FILE_MACHINE_I386 = 0x14C, IMAGE_FILE_MACHINE_AMD64 = 0x8664 }; struct symbol { char Name[NameSize]; uint32_t Value; uint16_t Type; uint8_t StorageClass; uint16_t SectionNumber; uint8_t NumberOfAuxSymbols; }; enum SymbolFlags { SF_TypeMask = 0x0000FFFF, SF_TypeShift = 0, SF_ClassMask = 0x00FF0000, SF_ClassShift = 16, SF_WeakExternal = 0x01000000 }; enum SymbolSectionNumber { IMAGE_SYM_DEBUG = -2, IMAGE_SYM_ABSOLUTE = -1, IMAGE_SYM_UNDEFINED = 0 }; /// Storage class tells where and what the symbol represents enum SymbolStorageClass { IMAGE_SYM_CLASS_END_OF_FUNCTION = -1, ///< Physical end of function IMAGE_SYM_CLASS_NULL = 0, ///< No symbol IMAGE_SYM_CLASS_AUTOMATIC = 1, ///< Stack variable IMAGE_SYM_CLASS_EXTERNAL = 2, ///< External symbol IMAGE_SYM_CLASS_STATIC = 3, ///< Static IMAGE_SYM_CLASS_REGISTER = 4, ///< Register variable IMAGE_SYM_CLASS_EXTERNAL_DEF = 5, ///< External definition IMAGE_SYM_CLASS_LABEL = 6, ///< Label IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7, ///< Undefined label IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8, ///< Member of structure IMAGE_SYM_CLASS_ARGUMENT = 9, ///< Function argument IMAGE_SYM_CLASS_STRUCT_TAG = 10, ///< Structure tag IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11, ///< Member of union IMAGE_SYM_CLASS_UNION_TAG = 12, ///< Union tag IMAGE_SYM_CLASS_TYPE_DEFINITION = 13, ///< Type definition IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14, ///< Undefined static IMAGE_SYM_CLASS_ENUM_TAG = 15, ///< Enumeration tag IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16, ///< Member of enumeration IMAGE_SYM_CLASS_REGISTER_PARAM = 17, ///< Register parameter IMAGE_SYM_CLASS_BIT_FIELD = 18, ///< Bit field /// ".bb" or ".eb" - beginning or end of block IMAGE_SYM_CLASS_BLOCK = 100, /// ".bf" or ".ef" - beginning or end of function IMAGE_SYM_CLASS_FUNCTION = 101, IMAGE_SYM_CLASS_END_OF_STRUCT = 102, ///< End of structure IMAGE_SYM_CLASS_FILE = 103, ///< File name /// Line number, reformatted as symbol IMAGE_SYM_CLASS_SECTION = 104, IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105, ///< Duplicate tag /// External symbol in dmert public lib IMAGE_SYM_CLASS_CLR_TOKEN = 107 }; enum SymbolBaseType { IMAGE_SYM_TYPE_NULL = 0, ///< No type information or unknown base type. IMAGE_SYM_TYPE_VOID = 1, ///< Used with void pointers and functions. IMAGE_SYM_TYPE_CHAR = 2, ///< A character (signed byte). IMAGE_SYM_TYPE_SHORT = 3, ///< A 2-byte signed integer. IMAGE_SYM_TYPE_INT = 4, ///< A natural integer type on the target. IMAGE_SYM_TYPE_LONG = 5, ///< A 4-byte signed integer. IMAGE_SYM_TYPE_FLOAT = 6, ///< A 4-byte floating-point number. IMAGE_SYM_TYPE_DOUBLE = 7, ///< An 8-byte floating-point number. IMAGE_SYM_TYPE_STRUCT = 8, ///< A structure. IMAGE_SYM_TYPE_UNION = 9, ///< An union. IMAGE_SYM_TYPE_ENUM = 10, ///< An enumerated type. IMAGE_SYM_TYPE_MOE = 11, ///< A member of enumeration (a specific value). IMAGE_SYM_TYPE_BYTE = 12, ///< A byte; unsigned 1-byte integer. IMAGE_SYM_TYPE_WORD = 13, ///< A word; unsigned 2-byte integer. IMAGE_SYM_TYPE_UINT = 14, ///< An unsigned integer of natural size. IMAGE_SYM_TYPE_DWORD = 15 ///< An unsigned 4-byte integer. }; enum SymbolComplexType { IMAGE_SYM_DTYPE_NULL = 0, ///< No complex type; simple scalar variable. IMAGE_SYM_DTYPE_POINTER = 1, ///< A pointer to base type. IMAGE_SYM_DTYPE_FUNCTION = 2, ///< A function that returns a base type. IMAGE_SYM_DTYPE_ARRAY = 3, ///< An array of base type. /// Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT)) SCT_COMPLEX_TYPE_SHIFT = 4 }; struct section { char Name[NameSize]; uint32_t VirtualSize; uint32_t VirtualAddress; uint32_t SizeOfRawData; uint32_t PointerToRawData; uint32_t PointerToRelocations; uint32_t PointerToLineNumbers; uint16_t NumberOfRelocations; uint16_t NumberOfLineNumbers; uint32_t Characteristics; }; enum SectionCharacteristics { IMAGE_SCN_TYPE_NO_PAD = 0x00000008, IMAGE_SCN_CNT_CODE = 0x00000020, IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040, IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080, IMAGE_SCN_LNK_OTHER = 0x00000100, IMAGE_SCN_LNK_INFO = 0x00000200, IMAGE_SCN_LNK_REMOVE = 0x00000800, IMAGE_SCN_LNK_COMDAT = 0x00001000, IMAGE_SCN_GPREL = 0x00008000, IMAGE_SCN_MEM_PURGEABLE = 0x00020000, IMAGE_SCN_MEM_16BIT = 0x00020000, IMAGE_SCN_MEM_LOCKED = 0x00040000, IMAGE_SCN_MEM_PRELOAD = 0x00080000, IMAGE_SCN_ALIGN_1BYTES = 0x00100000, IMAGE_SCN_ALIGN_2BYTES = 0x00200000, IMAGE_SCN_ALIGN_4BYTES = 0x00300000, IMAGE_SCN_ALIGN_8BYTES = 0x00400000, IMAGE_SCN_ALIGN_16BYTES = 0x00500000, IMAGE_SCN_ALIGN_32BYTES = 0x00600000, IMAGE_SCN_ALIGN_64BYTES = 0x00700000, IMAGE_SCN_ALIGN_128BYTES = 0x00800000, IMAGE_SCN_ALIGN_256BYTES = 0x00900000, IMAGE_SCN_ALIGN_512BYTES = 0x00A00000, IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000, IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000, IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000, IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000, IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000, IMAGE_SCN_MEM_DISCARDABLE = 0x02000000, IMAGE_SCN_MEM_NOT_CACHED = 0x04000000, IMAGE_SCN_MEM_NOT_PAGED = 0x08000000, IMAGE_SCN_MEM_SHARED = 0x10000000, IMAGE_SCN_MEM_EXECUTE = 0x20000000, IMAGE_SCN_MEM_READ = 0x40000000, IMAGE_SCN_MEM_WRITE = 0x80000000 }; struct relocation { uint32_t VirtualAddress; uint32_t SymbolTableIndex; uint16_t Type; }; enum RelocationTypeX86 { IMAGE_REL_I386_ABSOLUTE = 0x0000, IMAGE_REL_I386_DIR16 = 0x0001, IMAGE_REL_I386_REL16 = 0x0002, IMAGE_REL_I386_DIR32 = 0x0006, IMAGE_REL_I386_DIR32NB = 0x0007, IMAGE_REL_I386_SEG12 = 0x0009, IMAGE_REL_I386_SECTION = 0x000A, IMAGE_REL_I386_SECREL = 0x000B, IMAGE_REL_I386_TOKEN = 0x000C, IMAGE_REL_I386_SECREL7 = 0x000D, IMAGE_REL_I386_REL32 = 0x0014, IMAGE_REL_AMD64_ABSOLUTE = 0x0000, IMAGE_REL_AMD64_ADDR64 = 0x0001, IMAGE_REL_AMD64_ADDR32 = 0x0002, IMAGE_REL_AMD64_ADDR32NB = 0x0003, IMAGE_REL_AMD64_REL32 = 0x0004, IMAGE_REL_AMD64_REL32_1 = 0x0005, IMAGE_REL_AMD64_REL32_2 = 0x0006, IMAGE_REL_AMD64_REL32_3 = 0x0007, IMAGE_REL_AMD64_REL32_4 = 0x0008, IMAGE_REL_AMD64_REL32_5 = 0x0009, IMAGE_REL_AMD64_SECTION = 0x000A, IMAGE_REL_AMD64_SECREL = 0x000B, IMAGE_REL_AMD64_SECREL7 = 0x000C, IMAGE_REL_AMD64_TOKEN = 0x000D, IMAGE_REL_AMD64_SREL32 = 0x000E, IMAGE_REL_AMD64_PAIR = 0x000F, IMAGE_REL_AMD64_SSPAN32 = 0x0010 }; enum COMDATType { IMAGE_COMDAT_SELECT_NODUPLICATES = 1, IMAGE_COMDAT_SELECT_ANY, IMAGE_COMDAT_SELECT_SAME_SIZE, IMAGE_COMDAT_SELECT_EXACT_MATCH, IMAGE_COMDAT_SELECT_ASSOCIATIVE, IMAGE_COMDAT_SELECT_LARGEST }; // Auxiliary Symbol Formats struct AuxiliaryFunctionDefinition { uint32_t TagIndex; uint32_t TotalSize; uint32_t PointerToLinenumber; uint32_t PointerToNextFunction; uint8_t unused[2]; }; struct AuxiliarybfAndefSymbol { uint8_t unused1[4]; uint16_t Linenumber; uint8_t unused2[6]; uint32_t PointerToNextFunction; uint8_t unused3[2]; }; struct AuxiliaryWeakExternal { uint32_t TagIndex; uint32_t Characteristics; uint8_t unused[10]; }; /// These are not documented in the spec, but are located in WinNT.h. enum WeakExternalCharacteristics { IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1, IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2, IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3 }; struct AuxiliaryFile { uint8_t FileName[18]; }; struct AuxiliarySectionDefinition { uint32_t Length; uint16_t NumberOfRelocations; uint16_t NumberOfLinenumbers; uint32_t CheckSum; uint16_t Number; uint8_t Selection; uint8_t unused[3]; }; union Auxiliary { AuxiliaryFunctionDefinition FunctionDefinition; AuxiliarybfAndefSymbol bfAndefSymbol; AuxiliaryWeakExternal WeakExternal; AuxiliaryFile File; AuxiliarySectionDefinition SectionDefinition; }; } // End namespace llvm. } // End namespace COFF. #endif
4,933
432
/* * poll_1.c * * This code used to panic the kernel because of a filter bug. */ #include <fcntl.h> #include <stdio.h> #include <poll.h> int main() { struct pollfd fds[1]; int p = open("/dev/tty", O_RDWR); printf("tty: %d\n", p); fds[0].fd = p; fds[0].events = POLLIN|POLLPRI; fds[0].revents = 0; poll(fds, 1, -1); printf("polled\n"); }
168
301
<gh_stars>100-1000 /* * //****************************************************************** * // * // Copyright 2016 Samsung Electronics All Rights Reserved. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= * // * // Licensed under the Apache License, Version 2.0 (the "License"); * // you may not use this file except in compliance with the License. * // You may obtain a copy of the License at * // * // http://www.apache.org/licenses/LICENSE-2.0 * // * // Unless required by applicable law or agreed to in writing, software * // distributed under the License is distributed on an "AS IS" BASIS, * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * // See the License for the specific language governing permissions and * // limitations under the License. * // * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */ package org.iotivity.cloud.ciserver.resources.proxy.account; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import org.iotivity.cloud.base.connector.ConnectorPool; import org.iotivity.cloud.base.device.CoapDevice; import org.iotivity.cloud.base.device.IRequestChannel; import org.iotivity.cloud.base.protocols.IRequest; import org.iotivity.cloud.base.protocols.IResponse; import org.iotivity.cloud.base.protocols.MessageBuilder; import org.iotivity.cloud.base.protocols.coap.CoapRequest; import org.iotivity.cloud.base.protocols.enums.ContentFormat; import org.iotivity.cloud.base.protocols.enums.RequestMethod; import org.iotivity.cloud.ciserver.Constants; import org.iotivity.cloud.ciserver.DeviceServerSystem; import org.iotivity.cloud.util.Cbor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest(ConnectorPool.class) public class AccountSessionTest { private String mDi = "B371C481-38E6-4D47-8320-7688D8A5B58C"; public static final String SESSION_URI = Constants.ACCOUNT_SESSION_FULL_URI; private CoapDevice mMockDevice = mock(CoapDevice.class); private IResponse mRes = null; private IRequest mReq = null; private ConnectorPool mConnectorPool = null; private DeviceServerSystem mDeviceServerSystem = new DeviceServerSystem(); private final CountDownLatch mLatch = new CountDownLatch(1); @Mock(name = "mASServer") IRequestChannel mRequestChannelASServer; @InjectMocks private AccountSession mAcSessionHandler = new AccountSession(); @Before public void setUp() throws Exception { mRes = null; mReq = null; Mockito.doReturn(mDi).when(mMockDevice).getDeviceId(); Mockito.doReturn("mockDeviceUser").when(mMockDevice).getUserId(); Mockito.doReturn("1689c70ffa245effc563017fee36d250").when(mMockDevice) .getAccessToken(); MockitoAnnotations.initMocks(this); mDeviceServerSystem.addResource(mAcSessionHandler); Mockito.doAnswer(new Answer<Object>() { @Override public CoapRequest answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); CoapRequest request = (CoapRequest) args[0]; mReq = request; mLatch.countDown(); System.out.println( "\t----------payload : " + request.getPayloadString()); System.out.println( "\t----------uripath : " + request.getUriPath()); System.out.println( "\t---------uriquery : " + request.getUriQuery()); return null; } }).when(mRequestChannelASServer).sendRequest(Mockito.any(IRequest.class), Mockito.any(CoapDevice.class)); PowerMockito.mockStatic(ConnectorPool.class); PowerMockito.when(ConnectorPool.getConnection("account")).thenReturn(mRequestChannelASServer); PowerMockito.when(ConnectorPool.containConnection(Mockito.anyString())).thenReturn(true); } @Test public void testAccountSignInOnRequestReceived() throws Exception { System.out.println( "\t--------------OnRequestReceived Sign In Test------------"); IRequest request = makeSignInRequest(); mDeviceServerSystem.onRequestReceived(mMockDevice, request); assertTrue(mLatch.await(1L, SECONDS)); assertEquals(request, request); } @Test public void testAccountResourceOnRequestReceived() throws Exception { System.out.println( "\t--------------OnRequestReceived Sign Out Test------------"); // sign up request from the client IRequest request = makeSignOutRequest(); mDeviceServerSystem.onRequestReceived(mMockDevice, request); // assertion : request msg to the AS is identical to the request msg // from the client assertTrue(mLatch.await(1L, SECONDS)); assertTrue(queryCheck(mReq, Constants.USER_ID)); assertTrue(payloadCheck(mReq, Constants.DEVICE_ID)); assertTrue(payloadCheck(mReq, Constants.ACCESS_TOKEN)); assertTrue(payloadCheck(mReq, Constants.REQ_LOGIN)); } private IRequest makeSignInRequest() { Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>(); IRequest request = null; HashMap<String, Object> payloadData = new HashMap<>(); payloadData.put(Constants.USER_ID, "u0001"); payloadData.put(Constants.DEVICE_ID, mDi); payloadData.put(Constants.ACCESS_TOKEN, "<PASSWORD>"); payloadData.put(Constants.REQ_LOGIN, true); request = MessageBuilder.createRequest(RequestMethod.POST, SESSION_URI, null, ContentFormat.APPLICATION_CBOR, cbor.encodingPayloadToCbor(payloadData)); return request; } private IRequest makeSignOutRequest() { Cbor<HashMap<String, Object>> cbor = new Cbor<HashMap<String, Object>>(); IRequest request = null; HashMap<String, Object> payloadData = new HashMap<>(); payloadData.put(Constants.REQ_LOGIN, false); payloadData.put(Constants.DEVICE_ID, mDi); payloadData.put(Constants.ACCESS_TOKEN, "<PASSWORD>"); request = MessageBuilder.createRequest(RequestMethod.POST, SESSION_URI, null, ContentFormat.APPLICATION_CBOR, cbor.encodingPayloadToCbor(payloadData)); return request; } private boolean payloadCheck(IRequest request, String propertyName) { Cbor<HashMap<String, Object>> mCbor = new Cbor<>(); HashMap<String, Object> payloadData = mCbor .parsePayloadFromCbor(request.getPayload(), HashMap.class); if (payloadData.get(propertyName) != null) return true; else return false; } private boolean queryCheck(IRequest request, String propertyName) { if (request.getUriQueryMap().get(propertyName) != null) return true; else return false; } }
3,154
2,350
#pragma once #include "UEPySCompoundWidget.h" #if WITH_EDITOR #if ENGINE_MINOR_VERSION > 13 #include "Developer/DesktopWidgets/Public/Widgets/Input/SDirectoryPicker.h" extern PyTypeObject ue_PySDirectoryPickerType; typedef struct { ue_PySCompoundWidget s_compound_widget; /* Type-specific fields go here. */ } ue_PySDirectoryPicker; void ue_python_init_sdirectory_picker(PyObject *); #endif #endif
159
5,651
import unicodedata encodings = 'ascii latin1 cp1252 cp437 gb2312 utf-8 utf-16le'.split() widths = {encoding:1 for encoding in encodings[:-3]} widths.update(zip(encodings[-3:], (2, 4, 4))) chars = sorted([ 'A', # \u0041 : LATIN CAPITAL LETTER A '¿', # \u00bf : INVERTED QUESTION MARK 'Ã', # \u00c3 : LATIN CAPITAL LETTER A WITH TILDE 'á', # \u00e1 : LATIN SMALL LETTER A WITH ACUTE 'Ω', # \u03a9 : GREEK CAPITAL LETTER OMEGA 'µ', 'Ц', '€', # \u20ac : EURO SIGN '“', '┌', '气', '氣', # \u6c23 : CJK UNIFIED IDEOGRAPH-6C23 '𝄞', # \u1d11e : MUSICAL SYMBOL G CLEF ]) callout1_code = 0x278a # ➊ DINGBAT NEGATIVE CIRCLED SANS-SERIF DIGIT ONE missing_mark = '*' def list_chars(): for char in chars: print('%r, # \\u%04x : %s' % (char, ord(char), unicodedata.name(char))) def show_encodings(): print(end='\t\t') for encoding in encodings: print(encoding.ljust(widths[encoding] * 2), end='\t') print() for lineno, char in enumerate(chars): codepoint = 'U+{:04X}'.format(ord(char)) print(char, codepoint, sep='\t', end='\t') for encoding in encodings: try: bytes = char.encode(encoding) dump = ' '.join('%02X' % byte for byte in bytes) except UnicodeEncodeError: dump = missing_mark dump = dump.ljust(widths[encoding] * 2) print(dump, end='\t') # print(chr(callout1_code + lineno)) print(unicodedata.name(char)) # print() #list_chars() show_encodings()
804
640
<reponame>jpoikela/z88dk<gh_stars>100-1000 #include "ctype_test.h" void t_isascii_0x00() { Assert(isascii(0) ,"isascii should be 1 for 0x00"); } void t_isascii_0x01() { Assert(isascii(1) ,"isascii should be 1 for 0x01"); } void t_isascii_0x02() { Assert(isascii(2) ,"isascii should be 1 for 0x02"); } void t_isascii_0x03() { Assert(isascii(3) ,"isascii should be 1 for 0x03"); } void t_isascii_0x04() { Assert(isascii(4) ,"isascii should be 1 for 0x04"); } void t_isascii_0x05() { Assert(isascii(5) ,"isascii should be 1 for 0x05"); } void t_isascii_0x06() { Assert(isascii(6) ,"isascii should be 1 for 0x06"); } void t_isascii_0x07() { Assert(isascii(7) ,"isascii should be 1 for 0x07"); } void t_isascii_0x08() { Assert(isascii(8) ,"isascii should be 1 for 0x08"); } void t_isascii_0x09() { Assert(isascii(9) ,"isascii should be 1 for 0x09"); } void t_isascii_0x0a() { Assert(isascii(10) ,"isascii should be 1 for 0x0a"); } void t_isascii_0x0b() { Assert(isascii(11) ,"isascii should be 1 for 0x0b"); } void t_isascii_0x0c() { Assert(isascii(12) ,"isascii should be 1 for 0x0c"); } void t_isascii_0x0d() { Assert(isascii(13) ,"isascii should be 1 for 0x0d"); } void t_isascii_0x0e() { Assert(isascii(14) ,"isascii should be 1 for 0x0e"); } void t_isascii_0x0f() { Assert(isascii(15) ,"isascii should be 1 for 0x0f"); } void t_isascii_0x10() { Assert(isascii(16) ,"isascii should be 1 for 0x10"); } void t_isascii_0x11() { Assert(isascii(17) ,"isascii should be 1 for 0x11"); } void t_isascii_0x12() { Assert(isascii(18) ,"isascii should be 1 for 0x12"); } void t_isascii_0x13() { Assert(isascii(19) ,"isascii should be 1 for 0x13"); } void t_isascii_0x14() { Assert(isascii(20) ,"isascii should be 1 for 0x14"); } void t_isascii_0x15() { Assert(isascii(21) ,"isascii should be 1 for 0x15"); } void t_isascii_0x16() { Assert(isascii(22) ,"isascii should be 1 for 0x16"); } void t_isascii_0x17() { Assert(isascii(23) ,"isascii should be 1 for 0x17"); } void t_isascii_0x18() { Assert(isascii(24) ,"isascii should be 1 for 0x18"); } void t_isascii_0x19() { Assert(isascii(25) ,"isascii should be 1 for 0x19"); } void t_isascii_0x1a() { Assert(isascii(26) ,"isascii should be 1 for 0x1a"); } void t_isascii_0x1b() { Assert(isascii(27) ,"isascii should be 1 for 0x1b"); } void t_isascii_0x1c() { Assert(isascii(28) ,"isascii should be 1 for 0x1c"); } void t_isascii_0x1d() { Assert(isascii(29) ,"isascii should be 1 for 0x1d"); } void t_isascii_0x1e() { Assert(isascii(30) ,"isascii should be 1 for 0x1e"); } void t_isascii_0x1f() { Assert(isascii(31) ,"isascii should be 1 for 0x1f"); } void t_isascii_0x20() { Assert(isascii(32) ,"isascii should be 1 for "); } void t_isascii_0x21() { Assert(isascii(33) ,"isascii should be 1 for !"); } void t_isascii_0x22() { Assert(isascii(34) ,"isascii should be 1 for 0x22"); } void t_isascii_0x23() { Assert(isascii(35) ,"isascii should be 1 for #"); } void t_isascii_0x24() { Assert(isascii(36) ,"isascii should be 1 for $"); } void t_isascii_0x25() { Assert(isascii(37) ,"isascii should be 1 for %"); } void t_isascii_0x26() { Assert(isascii(38) ,"isascii should be 1 for &"); } void t_isascii_0x27() { Assert(isascii(39) ,"isascii should be 1 for '"); } void t_isascii_0x28() { Assert(isascii(40) ,"isascii should be 1 for ("); } void t_isascii_0x29() { Assert(isascii(41) ,"isascii should be 1 for )"); } void t_isascii_0x2a() { Assert(isascii(42) ,"isascii should be 1 for *"); } void t_isascii_0x2b() { Assert(isascii(43) ,"isascii should be 1 for +"); } void t_isascii_0x2c() { Assert(isascii(44) ,"isascii should be 1 for ,"); } void t_isascii_0x2d() { Assert(isascii(45) ,"isascii should be 1 for -"); } void t_isascii_0x2e() { Assert(isascii(46) ,"isascii should be 1 for ."); } void t_isascii_0x2f() { Assert(isascii(47) ,"isascii should be 1 for /"); } void t_isascii_0x30() { Assert(isascii(48) ,"isascii should be 1 for 0"); } void t_isascii_0x31() { Assert(isascii(49) ,"isascii should be 1 for 1"); } void t_isascii_0x32() { Assert(isascii(50) ,"isascii should be 1 for 2"); } void t_isascii_0x33() { Assert(isascii(51) ,"isascii should be 1 for 3"); } void t_isascii_0x34() { Assert(isascii(52) ,"isascii should be 1 for 4"); } void t_isascii_0x35() { Assert(isascii(53) ,"isascii should be 1 for 5"); } void t_isascii_0x36() { Assert(isascii(54) ,"isascii should be 1 for 6"); } void t_isascii_0x37() { Assert(isascii(55) ,"isascii should be 1 for 7"); } void t_isascii_0x38() { Assert(isascii(56) ,"isascii should be 1 for 8"); } void t_isascii_0x39() { Assert(isascii(57) ,"isascii should be 1 for 9"); } void t_isascii_0x3a() { Assert(isascii(58) ,"isascii should be 1 for :"); } void t_isascii_0x3b() { Assert(isascii(59) ,"isascii should be 1 for ;"); } void t_isascii_0x3c() { Assert(isascii(60) ,"isascii should be 1 for <"); } void t_isascii_0x3d() { Assert(isascii(61) ,"isascii should be 1 for ="); } void t_isascii_0x3e() { Assert(isascii(62) ,"isascii should be 1 for >"); } void t_isascii_0x3f() { Assert(isascii(63) ,"isascii should be 1 for ?"); } void t_isascii_0x40() { Assert(isascii(64) ,"isascii should be 1 for @"); } void t_isascii_0x41() { Assert(isascii(65) ,"isascii should be 1 for A"); } void t_isascii_0x42() { Assert(isascii(66) ,"isascii should be 1 for B"); } void t_isascii_0x43() { Assert(isascii(67) ,"isascii should be 1 for C"); } void t_isascii_0x44() { Assert(isascii(68) ,"isascii should be 1 for D"); } void t_isascii_0x45() { Assert(isascii(69) ,"isascii should be 1 for E"); } void t_isascii_0x46() { Assert(isascii(70) ,"isascii should be 1 for F"); } void t_isascii_0x47() { Assert(isascii(71) ,"isascii should be 1 for G"); } void t_isascii_0x48() { Assert(isascii(72) ,"isascii should be 1 for H"); } void t_isascii_0x49() { Assert(isascii(73) ,"isascii should be 1 for I"); } void t_isascii_0x4a() { Assert(isascii(74) ,"isascii should be 1 for J"); } void t_isascii_0x4b() { Assert(isascii(75) ,"isascii should be 1 for K"); } void t_isascii_0x4c() { Assert(isascii(76) ,"isascii should be 1 for L"); } void t_isascii_0x4d() { Assert(isascii(77) ,"isascii should be 1 for M"); } void t_isascii_0x4e() { Assert(isascii(78) ,"isascii should be 1 for N"); } void t_isascii_0x4f() { Assert(isascii(79) ,"isascii should be 1 for O"); } void t_isascii_0x50() { Assert(isascii(80) ,"isascii should be 1 for P"); } void t_isascii_0x51() { Assert(isascii(81) ,"isascii should be 1 for Q"); } void t_isascii_0x52() { Assert(isascii(82) ,"isascii should be 1 for R"); } void t_isascii_0x53() { Assert(isascii(83) ,"isascii should be 1 for S"); } void t_isascii_0x54() { Assert(isascii(84) ,"isascii should be 1 for T"); } void t_isascii_0x55() { Assert(isascii(85) ,"isascii should be 1 for U"); } void t_isascii_0x56() { Assert(isascii(86) ,"isascii should be 1 for V"); } void t_isascii_0x57() { Assert(isascii(87) ,"isascii should be 1 for W"); } void t_isascii_0x58() { Assert(isascii(88) ,"isascii should be 1 for X"); } void t_isascii_0x59() { Assert(isascii(89) ,"isascii should be 1 for Y"); } void t_isascii_0x5a() { Assert(isascii(90) ,"isascii should be 1 for Z"); } void t_isascii_0x5b() { Assert(isascii(91) ,"isascii should be 1 for ["); } void t_isascii_0x5c() { Assert(isascii(92) ,"isascii should be 1 for 0x5c"); } void t_isascii_0x5d() { Assert(isascii(93) ,"isascii should be 1 for ]"); } void t_isascii_0x5e() { Assert(isascii(94) ,"isascii should be 1 for ^"); } void t_isascii_0x5f() { Assert(isascii(95) ,"isascii should be 1 for _"); } void t_isascii_0x60() { Assert(isascii(96) ,"isascii should be 1 for `"); } void t_isascii_0x61() { Assert(isascii(97) ,"isascii should be 1 for a"); } void t_isascii_0x62() { Assert(isascii(98) ,"isascii should be 1 for b"); } void t_isascii_0x63() { Assert(isascii(99) ,"isascii should be 1 for c"); } void t_isascii_0x64() { Assert(isascii(100) ,"isascii should be 1 for d"); } void t_isascii_0x65() { Assert(isascii(101) ,"isascii should be 1 for e"); } void t_isascii_0x66() { Assert(isascii(102) ,"isascii should be 1 for f"); } void t_isascii_0x67() { Assert(isascii(103) ,"isascii should be 1 for g"); } void t_isascii_0x68() { Assert(isascii(104) ,"isascii should be 1 for h"); } void t_isascii_0x69() { Assert(isascii(105) ,"isascii should be 1 for i"); } void t_isascii_0x6a() { Assert(isascii(106) ,"isascii should be 1 for j"); } void t_isascii_0x6b() { Assert(isascii(107) ,"isascii should be 1 for k"); } void t_isascii_0x6c() { Assert(isascii(108) ,"isascii should be 1 for l"); } void t_isascii_0x6d() { Assert(isascii(109) ,"isascii should be 1 for m"); } void t_isascii_0x6e() { Assert(isascii(110) ,"isascii should be 1 for n"); } void t_isascii_0x6f() { Assert(isascii(111) ,"isascii should be 1 for o"); } void t_isascii_0x70() { Assert(isascii(112) ,"isascii should be 1 for p"); } void t_isascii_0x71() { Assert(isascii(113) ,"isascii should be 1 for q"); } void t_isascii_0x72() { Assert(isascii(114) ,"isascii should be 1 for r"); } void t_isascii_0x73() { Assert(isascii(115) ,"isascii should be 1 for s"); } void t_isascii_0x74() { Assert(isascii(116) ,"isascii should be 1 for t"); } void t_isascii_0x75() { Assert(isascii(117) ,"isascii should be 1 for u"); } void t_isascii_0x76() { Assert(isascii(118) ,"isascii should be 1 for v"); } void t_isascii_0x77() { Assert(isascii(119) ,"isascii should be 1 for w"); } void t_isascii_0x78() { Assert(isascii(120) ,"isascii should be 1 for x"); } void t_isascii_0x79() { Assert(isascii(121) ,"isascii should be 1 for y"); } void t_isascii_0x7a() { Assert(isascii(122) ,"isascii should be 1 for z"); } void t_isascii_0x7b() { Assert(isascii(123) ,"isascii should be 1 for {"); } void t_isascii_0x7c() { Assert(isascii(124) ,"isascii should be 1 for |"); } void t_isascii_0x7d() { Assert(isascii(125) ,"isascii should be 1 for }"); } void t_isascii_0x7e() { Assert(isascii(126) ,"isascii should be 1 for ~"); } void t_isascii_0x7f() { Assert(isascii(127) ,"isascii should be 1 for 0x7f"); } void t_isascii_0x80() { Assert(isascii(128) == 0 ,"isascii should be 0 for 0x80"); } void t_isascii_0x81() { Assert(isascii(129) == 0 ,"isascii should be 0 for 0x81"); } void t_isascii_0x82() { Assert(isascii(130) == 0 ,"isascii should be 0 for 0x82"); } void t_isascii_0x83() { Assert(isascii(131) == 0 ,"isascii should be 0 for 0x83"); } void t_isascii_0x84() { Assert(isascii(132) == 0 ,"isascii should be 0 for 0x84"); } void t_isascii_0x85() { Assert(isascii(133) == 0 ,"isascii should be 0 for 0x85"); } void t_isascii_0x86() { Assert(isascii(134) == 0 ,"isascii should be 0 for 0x86"); } void t_isascii_0x87() { Assert(isascii(135) == 0 ,"isascii should be 0 for 0x87"); } void t_isascii_0x88() { Assert(isascii(136) == 0 ,"isascii should be 0 for 0x88"); } void t_isascii_0x89() { Assert(isascii(137) == 0 ,"isascii should be 0 for 0x89"); } void t_isascii_0x8a() { Assert(isascii(138) == 0 ,"isascii should be 0 for 0x8a"); } void t_isascii_0x8b() { Assert(isascii(139) == 0 ,"isascii should be 0 for 0x8b"); } void t_isascii_0x8c() { Assert(isascii(140) == 0 ,"isascii should be 0 for 0x8c"); } void t_isascii_0x8d() { Assert(isascii(141) == 0 ,"isascii should be 0 for 0x8d"); } void t_isascii_0x8e() { Assert(isascii(142) == 0 ,"isascii should be 0 for 0x8e"); } void t_isascii_0x8f() { Assert(isascii(143) == 0 ,"isascii should be 0 for 0x8f"); } void t_isascii_0x90() { Assert(isascii(144) == 0 ,"isascii should be 0 for 0x90"); } void t_isascii_0x91() { Assert(isascii(145) == 0 ,"isascii should be 0 for 0x91"); } void t_isascii_0x92() { Assert(isascii(146) == 0 ,"isascii should be 0 for 0x92"); } void t_isascii_0x93() { Assert(isascii(147) == 0 ,"isascii should be 0 for 0x93"); } void t_isascii_0x94() { Assert(isascii(148) == 0 ,"isascii should be 0 for 0x94"); } void t_isascii_0x95() { Assert(isascii(149) == 0 ,"isascii should be 0 for 0x95"); } void t_isascii_0x96() { Assert(isascii(150) == 0 ,"isascii should be 0 for 0x96"); } void t_isascii_0x97() { Assert(isascii(151) == 0 ,"isascii should be 0 for 0x97"); } void t_isascii_0x98() { Assert(isascii(152) == 0 ,"isascii should be 0 for 0x98"); } void t_isascii_0x99() { Assert(isascii(153) == 0 ,"isascii should be 0 for 0x99"); } void t_isascii_0x9a() { Assert(isascii(154) == 0 ,"isascii should be 0 for 0x9a"); } void t_isascii_0x9b() { Assert(isascii(155) == 0 ,"isascii should be 0 for 0x9b"); } void t_isascii_0x9c() { Assert(isascii(156) == 0 ,"isascii should be 0 for 0x9c"); } void t_isascii_0x9d() { Assert(isascii(157) == 0 ,"isascii should be 0 for 0x9d"); } void t_isascii_0x9e() { Assert(isascii(158) == 0 ,"isascii should be 0 for 0x9e"); } void t_isascii_0x9f() { Assert(isascii(159) == 0 ,"isascii should be 0 for 0x9f"); } void t_isascii_0xa0() { Assert(isascii(160) == 0 ,"isascii should be 0 for 0xa0"); } void t_isascii_0xa1() { Assert(isascii(161) == 0 ,"isascii should be 0 for 0xa1"); } void t_isascii_0xa2() { Assert(isascii(162) == 0 ,"isascii should be 0 for 0xa2"); } void t_isascii_0xa3() { Assert(isascii(163) == 0 ,"isascii should be 0 for 0xa3"); } void t_isascii_0xa4() { Assert(isascii(164) == 0 ,"isascii should be 0 for 0xa4"); } void t_isascii_0xa5() { Assert(isascii(165) == 0 ,"isascii should be 0 for 0xa5"); } void t_isascii_0xa6() { Assert(isascii(166) == 0 ,"isascii should be 0 for 0xa6"); } void t_isascii_0xa7() { Assert(isascii(167) == 0 ,"isascii should be 0 for 0xa7"); } void t_isascii_0xa8() { Assert(isascii(168) == 0 ,"isascii should be 0 for 0xa8"); } void t_isascii_0xa9() { Assert(isascii(169) == 0 ,"isascii should be 0 for 0xa9"); } void t_isascii_0xaa() { Assert(isascii(170) == 0 ,"isascii should be 0 for 0xaa"); } void t_isascii_0xab() { Assert(isascii(171) == 0 ,"isascii should be 0 for 0xab"); } void t_isascii_0xac() { Assert(isascii(172) == 0 ,"isascii should be 0 for 0xac"); } void t_isascii_0xad() { Assert(isascii(173) == 0 ,"isascii should be 0 for 0xad"); } void t_isascii_0xae() { Assert(isascii(174) == 0 ,"isascii should be 0 for 0xae"); } void t_isascii_0xaf() { Assert(isascii(175) == 0 ,"isascii should be 0 for 0xaf"); } void t_isascii_0xb0() { Assert(isascii(176) == 0 ,"isascii should be 0 for 0xb0"); } void t_isascii_0xb1() { Assert(isascii(177) == 0 ,"isascii should be 0 for 0xb1"); } void t_isascii_0xb2() { Assert(isascii(178) == 0 ,"isascii should be 0 for 0xb2"); } void t_isascii_0xb3() { Assert(isascii(179) == 0 ,"isascii should be 0 for 0xb3"); } void t_isascii_0xb4() { Assert(isascii(180) == 0 ,"isascii should be 0 for 0xb4"); } void t_isascii_0xb5() { Assert(isascii(181) == 0 ,"isascii should be 0 for 0xb5"); } void t_isascii_0xb6() { Assert(isascii(182) == 0 ,"isascii should be 0 for 0xb6"); } void t_isascii_0xb7() { Assert(isascii(183) == 0 ,"isascii should be 0 for 0xb7"); } void t_isascii_0xb8() { Assert(isascii(184) == 0 ,"isascii should be 0 for 0xb8"); } void t_isascii_0xb9() { Assert(isascii(185) == 0 ,"isascii should be 0 for 0xb9"); } void t_isascii_0xba() { Assert(isascii(186) == 0 ,"isascii should be 0 for 0xba"); } void t_isascii_0xbb() { Assert(isascii(187) == 0 ,"isascii should be 0 for 0xbb"); } void t_isascii_0xbc() { Assert(isascii(188) == 0 ,"isascii should be 0 for 0xbc"); } void t_isascii_0xbd() { Assert(isascii(189) == 0 ,"isascii should be 0 for 0xbd"); } void t_isascii_0xbe() { Assert(isascii(190) == 0 ,"isascii should be 0 for 0xbe"); } void t_isascii_0xbf() { Assert(isascii(191) == 0 ,"isascii should be 0 for 0xbf"); } void t_isascii_0xc0() { Assert(isascii(192) == 0 ,"isascii should be 0 for 0xc0"); } void t_isascii_0xc1() { Assert(isascii(193) == 0 ,"isascii should be 0 for 0xc1"); } void t_isascii_0xc2() { Assert(isascii(194) == 0 ,"isascii should be 0 for 0xc2"); } void t_isascii_0xc3() { Assert(isascii(195) == 0 ,"isascii should be 0 for 0xc3"); } void t_isascii_0xc4() { Assert(isascii(196) == 0 ,"isascii should be 0 for 0xc4"); } void t_isascii_0xc5() { Assert(isascii(197) == 0 ,"isascii should be 0 for 0xc5"); } void t_isascii_0xc6() { Assert(isascii(198) == 0 ,"isascii should be 0 for 0xc6"); } void t_isascii_0xc7() { Assert(isascii(199) == 0 ,"isascii should be 0 for 0xc7"); } void t_isascii_0xc8() { Assert(isascii(200) == 0 ,"isascii should be 0 for 0xc8"); } void t_isascii_0xc9() { Assert(isascii(201) == 0 ,"isascii should be 0 for 0xc9"); } void t_isascii_0xca() { Assert(isascii(202) == 0 ,"isascii should be 0 for 0xca"); } void t_isascii_0xcb() { Assert(isascii(203) == 0 ,"isascii should be 0 for 0xcb"); } void t_isascii_0xcc() { Assert(isascii(204) == 0 ,"isascii should be 0 for 0xcc"); } void t_isascii_0xcd() { Assert(isascii(205) == 0 ,"isascii should be 0 for 0xcd"); } void t_isascii_0xce() { Assert(isascii(206) == 0 ,"isascii should be 0 for 0xce"); } void t_isascii_0xcf() { Assert(isascii(207) == 0 ,"isascii should be 0 for 0xcf"); } void t_isascii_0xd0() { Assert(isascii(208) == 0 ,"isascii should be 0 for 0xd0"); } void t_isascii_0xd1() { Assert(isascii(209) == 0 ,"isascii should be 0 for 0xd1"); } void t_isascii_0xd2() { Assert(isascii(210) == 0 ,"isascii should be 0 for 0xd2"); } void t_isascii_0xd3() { Assert(isascii(211) == 0 ,"isascii should be 0 for 0xd3"); } void t_isascii_0xd4() { Assert(isascii(212) == 0 ,"isascii should be 0 for 0xd4"); } void t_isascii_0xd5() { Assert(isascii(213) == 0 ,"isascii should be 0 for 0xd5"); } void t_isascii_0xd6() { Assert(isascii(214) == 0 ,"isascii should be 0 for 0xd6"); } void t_isascii_0xd7() { Assert(isascii(215) == 0 ,"isascii should be 0 for 0xd7"); } void t_isascii_0xd8() { Assert(isascii(216) == 0 ,"isascii should be 0 for 0xd8"); } void t_isascii_0xd9() { Assert(isascii(217) == 0 ,"isascii should be 0 for 0xd9"); } void t_isascii_0xda() { Assert(isascii(218) == 0 ,"isascii should be 0 for 0xda"); } void t_isascii_0xdb() { Assert(isascii(219) == 0 ,"isascii should be 0 for 0xdb"); } void t_isascii_0xdc() { Assert(isascii(220) == 0 ,"isascii should be 0 for 0xdc"); } void t_isascii_0xdd() { Assert(isascii(221) == 0 ,"isascii should be 0 for 0xdd"); } void t_isascii_0xde() { Assert(isascii(222) == 0 ,"isascii should be 0 for 0xde"); } void t_isascii_0xdf() { Assert(isascii(223) == 0 ,"isascii should be 0 for 0xdf"); } void t_isascii_0xe0() { Assert(isascii(224) == 0 ,"isascii should be 0 for 0xe0"); } void t_isascii_0xe1() { Assert(isascii(225) == 0 ,"isascii should be 0 for 0xe1"); } void t_isascii_0xe2() { Assert(isascii(226) == 0 ,"isascii should be 0 for 0xe2"); } void t_isascii_0xe3() { Assert(isascii(227) == 0 ,"isascii should be 0 for 0xe3"); } void t_isascii_0xe4() { Assert(isascii(228) == 0 ,"isascii should be 0 for 0xe4"); } void t_isascii_0xe5() { Assert(isascii(229) == 0 ,"isascii should be 0 for 0xe5"); } void t_isascii_0xe6() { Assert(isascii(230) == 0 ,"isascii should be 0 for 0xe6"); } void t_isascii_0xe7() { Assert(isascii(231) == 0 ,"isascii should be 0 for 0xe7"); } void t_isascii_0xe8() { Assert(isascii(232) == 0 ,"isascii should be 0 for 0xe8"); } void t_isascii_0xe9() { Assert(isascii(233) == 0 ,"isascii should be 0 for 0xe9"); } void t_isascii_0xea() { Assert(isascii(234) == 0 ,"isascii should be 0 for 0xea"); } void t_isascii_0xeb() { Assert(isascii(235) == 0 ,"isascii should be 0 for 0xeb"); } void t_isascii_0xec() { Assert(isascii(236) == 0 ,"isascii should be 0 for 0xec"); } void t_isascii_0xed() { Assert(isascii(237) == 0 ,"isascii should be 0 for 0xed"); } void t_isascii_0xee() { Assert(isascii(238) == 0 ,"isascii should be 0 for 0xee"); } void t_isascii_0xef() { Assert(isascii(239) == 0 ,"isascii should be 0 for 0xef"); } void t_isascii_0xf0() { Assert(isascii(240) == 0 ,"isascii should be 0 for 0xf0"); } void t_isascii_0xf1() { Assert(isascii(241) == 0 ,"isascii should be 0 for 0xf1"); } void t_isascii_0xf2() { Assert(isascii(242) == 0 ,"isascii should be 0 for 0xf2"); } void t_isascii_0xf3() { Assert(isascii(243) == 0 ,"isascii should be 0 for 0xf3"); } void t_isascii_0xf4() { Assert(isascii(244) == 0 ,"isascii should be 0 for 0xf4"); } void t_isascii_0xf5() { Assert(isascii(245) == 0 ,"isascii should be 0 for 0xf5"); } void t_isascii_0xf6() { Assert(isascii(246) == 0 ,"isascii should be 0 for 0xf6"); } void t_isascii_0xf7() { Assert(isascii(247) == 0 ,"isascii should be 0 for 0xf7"); } void t_isascii_0xf8() { Assert(isascii(248) == 0 ,"isascii should be 0 for 0xf8"); } void t_isascii_0xf9() { Assert(isascii(249) == 0 ,"isascii should be 0 for 0xf9"); } void t_isascii_0xfa() { Assert(isascii(250) == 0 ,"isascii should be 0 for 0xfa"); } void t_isascii_0xfb() { Assert(isascii(251) == 0 ,"isascii should be 0 for 0xfb"); } void t_isascii_0xfc() { Assert(isascii(252) == 0 ,"isascii should be 0 for 0xfc"); } void t_isascii_0xfd() { Assert(isascii(253) == 0 ,"isascii should be 0 for 0xfd"); } void t_isascii_0xfe() { Assert(isascii(254) == 0 ,"isascii should be 0 for 0xfe"); } void t_isascii_0xff() { Assert(isascii(255) == 0 ,"isascii should be 0 for 0xff"); } int test_isascii() { suite_setup("isascii"); suite_add_test(t_isascii_0x00); suite_add_test(t_isascii_0x01); suite_add_test(t_isascii_0x02); suite_add_test(t_isascii_0x03); suite_add_test(t_isascii_0x04); suite_add_test(t_isascii_0x05); suite_add_test(t_isascii_0x06); suite_add_test(t_isascii_0x07); suite_add_test(t_isascii_0x08); suite_add_test(t_isascii_0x09); suite_add_test(t_isascii_0x0a); suite_add_test(t_isascii_0x0b); suite_add_test(t_isascii_0x0c); suite_add_test(t_isascii_0x0d); suite_add_test(t_isascii_0x0e); suite_add_test(t_isascii_0x0f); suite_add_test(t_isascii_0x10); suite_add_test(t_isascii_0x11); suite_add_test(t_isascii_0x12); suite_add_test(t_isascii_0x13); suite_add_test(t_isascii_0x14); suite_add_test(t_isascii_0x15); suite_add_test(t_isascii_0x16); suite_add_test(t_isascii_0x17); suite_add_test(t_isascii_0x18); suite_add_test(t_isascii_0x19); suite_add_test(t_isascii_0x1a); suite_add_test(t_isascii_0x1b); suite_add_test(t_isascii_0x1c); suite_add_test(t_isascii_0x1d); suite_add_test(t_isascii_0x1e); suite_add_test(t_isascii_0x1f); suite_add_test(t_isascii_0x20); suite_add_test(t_isascii_0x21); suite_add_test(t_isascii_0x22); suite_add_test(t_isascii_0x23); suite_add_test(t_isascii_0x24); suite_add_test(t_isascii_0x25); suite_add_test(t_isascii_0x26); suite_add_test(t_isascii_0x27); suite_add_test(t_isascii_0x28); suite_add_test(t_isascii_0x29); suite_add_test(t_isascii_0x2a); suite_add_test(t_isascii_0x2b); suite_add_test(t_isascii_0x2c); suite_add_test(t_isascii_0x2d); suite_add_test(t_isascii_0x2e); suite_add_test(t_isascii_0x2f); suite_add_test(t_isascii_0x30); suite_add_test(t_isascii_0x31); suite_add_test(t_isascii_0x32); suite_add_test(t_isascii_0x33); suite_add_test(t_isascii_0x34); suite_add_test(t_isascii_0x35); suite_add_test(t_isascii_0x36); suite_add_test(t_isascii_0x37); suite_add_test(t_isascii_0x38); suite_add_test(t_isascii_0x39); suite_add_test(t_isascii_0x3a); suite_add_test(t_isascii_0x3b); suite_add_test(t_isascii_0x3c); suite_add_test(t_isascii_0x3d); suite_add_test(t_isascii_0x3e); suite_add_test(t_isascii_0x3f); suite_add_test(t_isascii_0x40); suite_add_test(t_isascii_0x41); suite_add_test(t_isascii_0x42); suite_add_test(t_isascii_0x43); suite_add_test(t_isascii_0x44); suite_add_test(t_isascii_0x45); suite_add_test(t_isascii_0x46); suite_add_test(t_isascii_0x47); suite_add_test(t_isascii_0x48); suite_add_test(t_isascii_0x49); suite_add_test(t_isascii_0x4a); suite_add_test(t_isascii_0x4b); suite_add_test(t_isascii_0x4c); suite_add_test(t_isascii_0x4d); suite_add_test(t_isascii_0x4e); suite_add_test(t_isascii_0x4f); suite_add_test(t_isascii_0x50); suite_add_test(t_isascii_0x51); suite_add_test(t_isascii_0x52); suite_add_test(t_isascii_0x53); suite_add_test(t_isascii_0x54); suite_add_test(t_isascii_0x55); suite_add_test(t_isascii_0x56); suite_add_test(t_isascii_0x57); suite_add_test(t_isascii_0x58); suite_add_test(t_isascii_0x59); suite_add_test(t_isascii_0x5a); suite_add_test(t_isascii_0x5b); suite_add_test(t_isascii_0x5c); suite_add_test(t_isascii_0x5d); suite_add_test(t_isascii_0x5e); suite_add_test(t_isascii_0x5f); suite_add_test(t_isascii_0x60); suite_add_test(t_isascii_0x61); suite_add_test(t_isascii_0x62); suite_add_test(t_isascii_0x63); suite_add_test(t_isascii_0x64); suite_add_test(t_isascii_0x65); suite_add_test(t_isascii_0x66); suite_add_test(t_isascii_0x67); suite_add_test(t_isascii_0x68); suite_add_test(t_isascii_0x69); suite_add_test(t_isascii_0x6a); suite_add_test(t_isascii_0x6b); suite_add_test(t_isascii_0x6c); suite_add_test(t_isascii_0x6d); suite_add_test(t_isascii_0x6e); suite_add_test(t_isascii_0x6f); suite_add_test(t_isascii_0x70); suite_add_test(t_isascii_0x71); suite_add_test(t_isascii_0x72); suite_add_test(t_isascii_0x73); suite_add_test(t_isascii_0x74); suite_add_test(t_isascii_0x75); suite_add_test(t_isascii_0x76); suite_add_test(t_isascii_0x77); suite_add_test(t_isascii_0x78); suite_add_test(t_isascii_0x79); suite_add_test(t_isascii_0x7a); suite_add_test(t_isascii_0x7b); suite_add_test(t_isascii_0x7c); suite_add_test(t_isascii_0x7d); suite_add_test(t_isascii_0x7e); suite_add_test(t_isascii_0x7f); suite_add_test(t_isascii_0x80); suite_add_test(t_isascii_0x81); suite_add_test(t_isascii_0x82); suite_add_test(t_isascii_0x83); suite_add_test(t_isascii_0x84); suite_add_test(t_isascii_0x85); suite_add_test(t_isascii_0x86); suite_add_test(t_isascii_0x87); suite_add_test(t_isascii_0x88); suite_add_test(t_isascii_0x89); suite_add_test(t_isascii_0x8a); suite_add_test(t_isascii_0x8b); suite_add_test(t_isascii_0x8c); suite_add_test(t_isascii_0x8d); suite_add_test(t_isascii_0x8e); suite_add_test(t_isascii_0x8f); suite_add_test(t_isascii_0x90); suite_add_test(t_isascii_0x91); suite_add_test(t_isascii_0x92); suite_add_test(t_isascii_0x93); suite_add_test(t_isascii_0x94); suite_add_test(t_isascii_0x95); suite_add_test(t_isascii_0x96); suite_add_test(t_isascii_0x97); suite_add_test(t_isascii_0x98); suite_add_test(t_isascii_0x99); suite_add_test(t_isascii_0x9a); suite_add_test(t_isascii_0x9b); suite_add_test(t_isascii_0x9c); suite_add_test(t_isascii_0x9d); suite_add_test(t_isascii_0x9e); suite_add_test(t_isascii_0x9f); suite_add_test(t_isascii_0xa0); suite_add_test(t_isascii_0xa1); suite_add_test(t_isascii_0xa2); suite_add_test(t_isascii_0xa3); suite_add_test(t_isascii_0xa4); suite_add_test(t_isascii_0xa5); suite_add_test(t_isascii_0xa6); suite_add_test(t_isascii_0xa7); suite_add_test(t_isascii_0xa8); suite_add_test(t_isascii_0xa9); suite_add_test(t_isascii_0xaa); suite_add_test(t_isascii_0xab); suite_add_test(t_isascii_0xac); suite_add_test(t_isascii_0xad); suite_add_test(t_isascii_0xae); suite_add_test(t_isascii_0xaf); suite_add_test(t_isascii_0xb0); suite_add_test(t_isascii_0xb1); suite_add_test(t_isascii_0xb2); suite_add_test(t_isascii_0xb3); suite_add_test(t_isascii_0xb4); suite_add_test(t_isascii_0xb5); suite_add_test(t_isascii_0xb6); suite_add_test(t_isascii_0xb7); suite_add_test(t_isascii_0xb8); suite_add_test(t_isascii_0xb9); suite_add_test(t_isascii_0xba); suite_add_test(t_isascii_0xbb); suite_add_test(t_isascii_0xbc); suite_add_test(t_isascii_0xbd); suite_add_test(t_isascii_0xbe); suite_add_test(t_isascii_0xbf); suite_add_test(t_isascii_0xc0); suite_add_test(t_isascii_0xc1); suite_add_test(t_isascii_0xc2); suite_add_test(t_isascii_0xc3); suite_add_test(t_isascii_0xc4); suite_add_test(t_isascii_0xc5); suite_add_test(t_isascii_0xc6); suite_add_test(t_isascii_0xc7); suite_add_test(t_isascii_0xc8); suite_add_test(t_isascii_0xc9); suite_add_test(t_isascii_0xca); suite_add_test(t_isascii_0xcb); suite_add_test(t_isascii_0xcc); suite_add_test(t_isascii_0xcd); suite_add_test(t_isascii_0xce); suite_add_test(t_isascii_0xcf); suite_add_test(t_isascii_0xd0); suite_add_test(t_isascii_0xd1); suite_add_test(t_isascii_0xd2); suite_add_test(t_isascii_0xd3); suite_add_test(t_isascii_0xd4); suite_add_test(t_isascii_0xd5); suite_add_test(t_isascii_0xd6); suite_add_test(t_isascii_0xd7); suite_add_test(t_isascii_0xd8); suite_add_test(t_isascii_0xd9); suite_add_test(t_isascii_0xda); suite_add_test(t_isascii_0xdb); suite_add_test(t_isascii_0xdc); suite_add_test(t_isascii_0xdd); suite_add_test(t_isascii_0xde); suite_add_test(t_isascii_0xdf); suite_add_test(t_isascii_0xe0); suite_add_test(t_isascii_0xe1); suite_add_test(t_isascii_0xe2); suite_add_test(t_isascii_0xe3); suite_add_test(t_isascii_0xe4); suite_add_test(t_isascii_0xe5); suite_add_test(t_isascii_0xe6); suite_add_test(t_isascii_0xe7); suite_add_test(t_isascii_0xe8); suite_add_test(t_isascii_0xe9); suite_add_test(t_isascii_0xea); suite_add_test(t_isascii_0xeb); suite_add_test(t_isascii_0xec); suite_add_test(t_isascii_0xed); suite_add_test(t_isascii_0xee); suite_add_test(t_isascii_0xef); suite_add_test(t_isascii_0xf0); suite_add_test(t_isascii_0xf1); suite_add_test(t_isascii_0xf2); suite_add_test(t_isascii_0xf3); suite_add_test(t_isascii_0xf4); suite_add_test(t_isascii_0xf5); suite_add_test(t_isascii_0xf6); suite_add_test(t_isascii_0xf7); suite_add_test(t_isascii_0xf8); suite_add_test(t_isascii_0xf9); suite_add_test(t_isascii_0xfa); suite_add_test(t_isascii_0xfb); suite_add_test(t_isascii_0xfc); suite_add_test(t_isascii_0xfd); suite_add_test(t_isascii_0xfe); suite_add_test(t_isascii_0xff); return suite_run(); }
17,311
568
<gh_stars>100-1000 package com.jim.framework.web.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; /** * Created by jiang on 2017/2/18. */ //@Configuration public class RabbitMQConfig { protected Logger logger = LoggerFactory.getLogger(getClass().getName()); @Value("${mq.rabbit.host}") private String mqRabbitHost; @Value("${mq.rabbit.port}") private Integer mqRabbitPort; @Value("${mq.rabbit.username}") private String mqRabbitUserName; @Value("${mq.rabbit.password}") private String mqRabbitPassword; @Value("${mq.rabbit.virtualHost}") private String mqRabbitVirtualHost; public final static String QUEUE_NAME = "jim_queue"; public final static String EXCHANGE_NAME = "jim_exchange"; public final static String ROUTING_KEY="jim"; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(this.mqRabbitHost,this.mqRabbitPort); connectionFactory.setUsername(this.mqRabbitUserName); connectionFactory.setPassword(this.mqRabbitPassword); connectionFactory.setVirtualHost(this.mqRabbitVirtualHost); connectionFactory.setPublisherConfirms(true); return connectionFactory; } @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); return template; } @Bean public DirectExchange defaultExchange() { return new DirectExchange(EXCHANGE_NAME); } @Bean public Queue queue() { return new Queue(QUEUE_NAME, true); } @Bean public Binding binding() { return BindingBuilder.bind(queue()).to(defaultExchange()).with(ROUTING_KEY); } @Bean public SimpleMessageListenerContainer messageContainer() { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory()); container.setQueues(queue()); container.setExposeListenerChannel(true); container.setMaxConcurrentConsumers(1); container.setConcurrentConsumers(1); container.setAcknowledgeMode(AcknowledgeMode.MANUAL); container.setMessageListener(new ChannelAwareMessageListener() { public void onMessage(Message message, com.rabbitmq.client.Channel channel) throws Exception { byte[] body = message.getBody(); logger.info("消费端接收到消息 : " + new String(body)); channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } }); return container; } }
1,264
839
<reponame>kimjand/cxf /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.systest.jaxrs.security.oidc; import java.util.List; import org.apache.cxf.rs.security.oauth2.common.UserSubject; import org.apache.cxf.rs.security.oauth2.utils.OAuthUtils; import org.apache.cxf.rs.security.oidc.common.IdToken; import org.apache.cxf.rs.security.oidc.idp.IdTokenProvider; public class IdTokenProviderImpl implements IdTokenProvider { @Override public IdToken getIdToken(String clientId, UserSubject authenticatedUser, List<String> scopes) { IdToken token = new IdToken(); token.setIssuedAt(OAuthUtils.getIssuedAt()); token.setExpiryTime(token.getIssuedAt() + 60L); token.setAudience(clientId); token.setSubject(authenticatedUser.getLogin()); token.setIssuer("OIDC IdP"); return token; } }
516
1,040
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by ddenum.rc // #define IDI_MAIN_ICON 101 #define IDD_DRIVERINFO 102 #define IDC_PREV 1001 #define IDC_NEXT 1002 #define IDC_DEVICEID 1003 #define IDC_VERSION 1004 #define IDC_DESCRIPTION 1005 #define IDC_FILENAME 1006 #define IDC_COUNT 1007 #define IDC_GUID 1010 #define IDC_DWVENDORID 1012 #define IDC_DWDEVICEID 1014 #define IDC_DWSUBSYS 1015 #define IDC_DWREVISION 1016 #define IDC_RADIO_DEVICE 1018 #define IDC_RADIO_HOST 1019 #define IDC_STATIC_WHQLLEVEL 1020 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 103 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1021 #define _APS_NEXT_SYMED_VALUE 103 #endif #endif
711
942
#include "../src/tmultipartformdata.h"
16
384
<reponame>hejamu/gromacs /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team. * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements gmx::analysismodules::Freevolume. * * \author <NAME> <<EMAIL>> * \ingroup module_trajectoryanalysis */ #include "gmxpre.h" #include "freevolume.h" #include <string> #include "gromacs/analysisdata/analysisdata.h" #include "gromacs/analysisdata/modules/average.h" #include "gromacs/analysisdata/modules/plot.h" #include "gromacs/math/functions.h" #include "gromacs/math/units.h" #include "gromacs/math/vec.h" #include "gromacs/options/basicoptions.h" #include "gromacs/options/filenameoption.h" #include "gromacs/options/ioptionscontainer.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/random/threefry.h" #include "gromacs/random/uniformrealdistribution.h" #include "gromacs/selection/nbsearch.h" #include "gromacs/selection/selection.h" #include "gromacs/selection/selectionoption.h" #include "gromacs/topology/atomprop.h" #include "gromacs/topology/mtop_util.h" #include "gromacs/topology/topology.h" #include "gromacs/trajectory/trajectoryframe.h" #include "gromacs/trajectoryanalysis/analysissettings.h" #include "gromacs/trajectoryanalysis/topologyinformation.h" #include "gromacs/utility/arrayref.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/pleasecite.h" namespace gmx { namespace analysismodules { namespace { /*! \brief * Class used to compute free volume in a simulations box. * * Inherits TrajectoryAnalysisModule and all functions from there. * Does not implement any new functionality. * * \ingroup module_trajectoryanalysis */ class FreeVolume : public TrajectoryAnalysisModule { public: FreeVolume(); ~FreeVolume() override {} void initOptions(IOptionsContainer* options, TrajectoryAnalysisSettings* settings) override; void initAnalysis(const TrajectoryAnalysisSettings& settings, const TopologyInformation& top) override; void analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAnalysisModuleData* pdata) override; void finishAnalysis(int nframes) override; void writeOutput() override; private: std::string fnFreevol_; Selection sel_; AnalysisData data_; AnalysisDataAverageModulePointer adata_; int nmol_; double mtot_; double cutoff_; double probeRadius_; gmx::DefaultRandomEngine rng_; int seed_, ninsert_; AnalysisNeighborhood nb_; //! The van der Waals radius per atom std::vector<double> vdw_radius_; // Copy and assign disallowed by base. }; // Constructor. Here it is important to initialize the pointer to // subclasses that are elements of the main class. Here we have only // one. The type of this depends on what kind of tool you need. // Here we only have simple value/time kind of data. FreeVolume::FreeVolume() : adata_(new AnalysisDataAverageModule()) { // We only compute two numbers per frame data_.setColumnCount(0, 2); // Tell the analysis framework that this component exists registerAnalysisDataset(&data_, "freevolume"); nmol_ = 0; mtot_ = 0; cutoff_ = 0; probeRadius_ = 0; seed_ = 0; ninsert_ = 1000; } void FreeVolume::initOptions(IOptionsContainer* options, TrajectoryAnalysisSettings* settings) { static const char* const desc[] = { "[THISMODULE] calculates the free volume in a box as", "a function of time. The free volume is", "plotted as a fraction of the total volume.", "The program tries to insert a probe with a given radius,", "into the simulations box and if the distance between the", "probe and any atom is less than the sums of the", "van der Waals radii of both atoms, the position is", "considered to be occupied, i.e. non-free. By using a", "probe radius of 0, the true free volume is computed.", "By using a larger radius, e.g. 0.14 nm, roughly corresponding", "to a water molecule, the free volume for a hypothetical", "particle with that size will be produced.", "Note however, that since atoms are treated as hard-spheres", "these number are very approximate, and typically only", "relative changes are meaningful, for instance by doing a", "series of simulations at different temperature.[PAR]", "The group specified by the selection is considered to", "delineate non-free volume.", "The number of insertions per unit of volume is important", "to get a converged result. About 1000/nm^3 yields an overall", "standard deviation that is determined by the fluctuations in", "the trajectory rather than by the fluctuations due to the", "random numbers.[PAR]", "The results are critically dependent on the van der Waals radii;", "we recommend to use the values due to Bondi (1964).[PAR]", "The Fractional Free Volume (FFV) that some authors like to use", "is given by 1 - 1.3*(1-Free Volume). This value is printed on", "the terminal." }; settings->setHelpText(desc); // Add option for optional output file options->addOption(FileNameOption("o") .filetype(OptionFileType::Plot) .outputFile() .store(&fnFreevol_) .defaultBasename("freevolume") .description("Computed free volume")); // Add option for selecting a subset of atoms options->addOption( SelectionOption("select").store(&sel_).defaultSelectionText("all").onlyAtoms().description( "Atoms that are considered as part of the excluded volume")); // Add option for the probe radius and initialize it options->addOption( DoubleOption("radius").store(&probeRadius_).description("Radius of the probe to be inserted (nm, 0 yields the true free volume)")); // Add option for the random number seed and initialize it to // generate a value automatically options->addOption(IntegerOption("seed").store(&seed_).description( "Seed for random number generator (0 means generate).")); // Add option to determine number of insertion trials per frame options->addOption(IntegerOption("ninsert").store(&ninsert_).description( "Number of probe insertions per cubic nm to try for each frame in the trajectory.")); // Control input settings settings->setFlags(TrajectoryAnalysisSettings::efRequireTop | TrajectoryAnalysisSettings::efNoUserPBC); settings->setPBC(true); } void FreeVolume::initAnalysis(const TrajectoryAnalysisSettings& settings, const TopologyInformation& top) { // Add the module that will contain the averaging and the time series // for our calculation data_.addModule(adata_); // Add a module for plotting the data automatically at the end of // the calculation. With this in place you only have to add data // points to the data et. AnalysisDataPlotModulePointer plotm_(new AnalysisDataPlotModule()); plotm_->setSettings(settings.plotSettings()); plotm_->setFileName(fnFreevol_); plotm_->setTitle("Free Volume"); plotm_->setXAxisIsTime(); plotm_->setYLabel("Free Volume (%)"); plotm_->appendLegend("Free Volume"); plotm_->appendLegend("Volume"); data_.addModule(plotm_); // Initiate variable cutoff_ = 0; int nnovdw = 0; AtomProperties aps; auto atoms = top.copyAtoms(); // Compute total mass mtot_ = 0; for (int i = 0; (i < atoms->nr); i++) { mtot_ += atoms->atom[i].m; } // Extracts number of molecules nmol_ = gmx_mtop_num_molecules(*top.mtop()); // Loop over atoms in the selection using an iterator const int maxnovdw = 10; ArrayRef<const int> atomind = sel_.atomIndices(); for (ArrayRef<const int>::iterator ai = atomind.begin(); (ai < atomind.end()); ++ai) { // Dereference the iterator to obtain an atom number int i = *ai; real value = 0; // Lookup the Van der Waals radius of this atom int resnr = atoms->atom[i].resind; if (aps.setAtomProperty(epropVDW, *(atoms->resinfo[resnr].name), *(atoms->atomname[i]), &value)) { vdw_radius_.push_back(value); if (value > cutoff_) { cutoff_ = value; } } else { nnovdw++; if (nnovdw < maxnovdw) { fprintf(stderr, "Could not determine VDW radius for %s-%s. Set to zero.\n", *(atoms->resinfo[resnr].name), *(atoms->atomname[i])); } vdw_radius_.push_back(0.0); } } // Increase cutoff by proberadius to make sure we do not miss // anything cutoff_ += probeRadius_; if (nnovdw >= maxnovdw) { fprintf(stderr, "Could not determine VDW radius for %d particles. These were set to zero.\n", nnovdw); } if (seed_ == 0) { seed_ = static_cast<int>(gmx::makeRandomSeed()); } // Print parameters to output. Maybe should make dependent on // verbosity flag? printf("cutoff = %g nm\n", cutoff_); printf("probe_radius = %g nm\n", probeRadius_); printf("seed = %d\n", seed_); printf("ninsert = %d probes per nm^3\n", ninsert_); // Initiate the random number generator rng_.seed(seed_); // Initiate the neighborsearching code nb_.setCutoff(cutoff_); } void FreeVolume::analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAnalysisModuleData* pdata) { AnalysisDataHandle dh = pdata->dataHandle(data_); const Selection& sel = pdata->parallelSelection(sel_); gmx::UniformRealDistribution<real> dist; GMX_RELEASE_ASSERT(nullptr != pbc, "You have no periodic boundary conditions"); // Analysis framework magic dh.startFrame(frnr, fr.time); // Compute volume and number of insertions to perform real V = det(fr.box); int Ninsert = static_cast<int>(ninsert_ * V); // Use neighborsearching tools! AnalysisNeighborhoodSearch nbsearch = nb_.initSearch(pbc, sel); // Then loop over insertions int NinsTot = 0; for (int i = 0; (i < Ninsert); i++) { rvec rand, ins, dx; for (int m = 0; (m < DIM); m++) { // Generate random number between 0 and 1 rand[m] = dist(rng_); } // Generate random 3D position within the box mvmul(fr.box, rand, ins); // Find the first reference position within the cutoff. bool bOverlap = false; AnalysisNeighborhoodPair pair; AnalysisNeighborhoodPairSearch pairSearch = nbsearch.startPairSearch(ins); while (!bOverlap && pairSearch.findNextPair(&pair)) { int jp = pair.refIndex(); // Compute distance vector to first atom in the neighborlist pbc_dx(pbc, ins, sel.position(jp).x(), dx); // See whether the distance is smaller than allowed bOverlap = (norm(dx) < probeRadius_ + vdw_radius_[sel.position(jp).refId()]); } if (!bOverlap) { // We found some free volume! NinsTot++; } } // Compute total free volume for this frame double frac = 0; if (Ninsert > 0) { frac = (100.0 * NinsTot) / Ninsert; } // Add the free volume fraction to the data set in column 0 dh.setPoint(0, frac); // Add the total volume to the data set in column 1 dh.setPoint(1, V); // Magic dh.finishFrame(); } void FreeVolume::finishAnalysis(int /* nframes */) { please_cite(stdout, "Bondi1964a"); please_cite(stdout, "Lourenco2013a"); } void FreeVolume::writeOutput() { // Final results come from statistics module in analysis framework double FVaver = adata_->average(0, 0); double FVerror = adata_->standardDeviation(0, 0); printf("Free volume %.2f +/- %.2f %%\n", FVaver, FVerror); double Vaver = adata_->average(0, 1); double Verror = adata_->standardDeviation(0, 1); printf("Total volume %.2f +/- %.2f nm^3\n", Vaver, Verror); printf("Number of molecules %d total mass %.2f Dalton\n", nmol_, mtot_); double RhoAver = mtot_ / (Vaver * 1e-24 * gmx::c_avogadro); double RhoError = gmx::square(RhoAver / Vaver) * Verror; printf("Average molar mass: %.2f Dalton\n", mtot_ / nmol_); double VmAver = Vaver / nmol_; double VmError = Verror / nmol_; printf("Density rho: %.2f +/- %.2f nm^3\n", RhoAver, RhoError); printf("Molecular volume Vm assuming homogeneity: %.4f +/- %.4f nm^3\n", VmAver, VmError); double VvdWaver = (1 - FVaver / 100) * VmAver; double VvdWerror = 0; printf("Molecular van der Waals volume assuming homogeneity: %.4f +/- %.4f nm^3\n", VvdWaver, VvdWerror); double FFVaver = 1 - 1.3 * ((100 - FVaver) / 100); double FFVerror = (FVerror / FVaver) * FFVaver; printf("Fractional free volume %.3f +/- %.3f\n", FFVaver, FFVerror); } } // namespace const char FreeVolumeInfo::name[] = "freevolume"; const char FreeVolumeInfo::shortDescription[] = "Calculate free volume"; TrajectoryAnalysisModulePointer FreeVolumeInfo::create() { return TrajectoryAnalysisModulePointer(new FreeVolume); } } // namespace analysismodules } // namespace gmx
6,045
409
<gh_stars>100-1000 package org.webrtc.kite.example.steps; import io.cosmosoftware.kite.interfaces.Runner; import io.cosmosoftware.kite.steps.TestStep; import org.webrtc.kite.example.pages.GoogleSearchPage; public class GoogleSearchStep extends TestStep { private final String TARGET = "CoSMo Software Consulting"; private final GoogleSearchPage searchPage; public GoogleSearchStep(Runner runner) { super(runner); this.searchPage = new GoogleSearchPage(runner); } @Override protected void step() { searchPage.open(); searchPage.searchFor(TARGET); } @Override public String stepDescription() { return "Open " + GoogleSearchPage.getURL() + " and look for " + TARGET; } }
248
440
<reponame>kurapov-peter/intel-graphics-compiler /*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ /* * !!! DO NOT EDIT THIS FILE !!! * * This file was automagically crafted by GED's model parser. */ #ifndef GED_INS_FIELD_INTERNAL_H #define GED_INS_FIELD_INTERNAL_H #include "common/ged_types_internal.h" /*! * Table mapping a GED_INS_FIELD to its GED_FIELD_TYPE. */ extern GED_FIELD_TYPE fieldTypesByField[127]; /*! * Table mapping GED_INS_FIELD to its name (string representation). */ extern const char* fieldNameByField[127]; /*! * Table mapping a GED_PSEUDO_FIELD to its GED_FIELD_TYPE. */ extern GED_FIELD_TYPE pseudoFieldTypesByField[36]; /*! * Table mapping GED_PSEUDO_FIELD to its name (string representation). */ extern const char* fieldNameByPseudoField[36]; #endif // GED_INS_FIELD_INTERNAL_H
336
650
<filename>spring-data-rest-core/src/test/java/org/springframework/data/rest/core/mapping/RepositoryResourceMappingsIntegrationTests.java /* * Copyright 2013-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.rest.core.mapping; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.keyvalue.core.mapping.context.KeyValueMappingContext; import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.context.PersistentEntities; import org.springframework.data.repository.support.Repositories; import org.springframework.data.rest.core.Path; import org.springframework.data.rest.core.config.EnumTranslationConfiguration; import org.springframework.data.rest.core.config.MetadataConfiguration; import org.springframework.data.rest.core.config.ProjectionDefinitionConfiguration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.core.domain.Author; import org.springframework.data.rest.core.domain.CreditCard; import org.springframework.data.rest.core.domain.JpaRepositoryConfig; import org.springframework.data.rest.core.domain.Person; import org.springframework.data.rest.core.domain.Profile; import org.springframework.hateoas.LinkRelation; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Integration tests for {@link RepositoryResourceMappings}. * * @author <NAME> * @author <NAME> */ @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = JpaRepositoryConfig.class) class RepositoryResourceMappingsIntegrationTests { @Autowired ListableBeanFactory factory; @Autowired KeyValueMappingContext<?, ?> mappingContext; ResourceMappings mappings; @BeforeEach void setUp() { mappingContext.getPersistentEntity(Profile.class); RepositoryRestConfiguration configuration = new RepositoryRestConfiguration(new ProjectionDefinitionConfiguration(), new MetadataConfiguration(), mock(EnumTranslationConfiguration.class)); Repositories repositories = new Repositories(factory); this.mappings = new RepositoryResourceMappings(repositories, new PersistentEntities(Arrays.asList(mappingContext)), configuration); } @Test void detectsAllMappings() { assertThat(mappings).hasSize(5); } @Test void exportsResourceAndSearchesForPersons() { ResourceMetadata personMappings = mappings.getMetadataFor(Person.class); assertThat(personMappings.isExported()).isTrue(); assertThat(personMappings.getSearchResourceMappings().isExported()).isTrue(); } @Test void doesNotExportAnyMappingsForHiddenRepository() { ResourceMetadata creditCardMapping = mappings.getMetadataFor(CreditCard.class); assertThat(creditCardMapping.isExported()).isFalse(); assertThat(creditCardMapping.getSearchResourceMappings().isExported()).isFalse(); } @Test // DATAREST-112 void usesPropertyNameAsRelForPropertyResourceMapping() { Repositories repositories = new Repositories(factory); PersistentEntity<?, ?> entity = repositories.getPersistentEntity(Person.class); PersistentProperty<?> property = entity.getRequiredPersistentProperty("siblings"); ResourceMetadata metadata = mappings.getMetadataFor(Person.class); ResourceMapping mapping = metadata.getMappingFor(property); assertThat(mapping.getRel()).isEqualTo(LinkRelation.of("siblings")); assertThat(mapping.getPath()).isEqualTo(new Path("siblings")); assertThat(mapping.isExported()).isTrue(); } @Test // DATAREST-111 void exposesResourceByPath() { assertThat(mappings.exportsTopLevelResourceFor("people")).isTrue(); assertThat(mappings.exportsTopLevelResourceFor("orders")).isTrue(); ResourceMetadata creditCardMapping = mappings.getMetadataFor(CreditCard.class); assertThat(creditCardMapping).isNotNull(); assertThat(creditCardMapping.getPath()).isEqualTo(new Path("creditCards")); assertThat(creditCardMapping.isExported()).isFalse(); assertThat(mappings.exportsTopLevelResourceFor("creditCards")).isFalse(); } @Test // DATAREST-107 void skipsSearchMethodsNotExported() { ResourceMetadata creditCardMetadata = mappings.getMetadataFor(CreditCard.class); SearchResourceMappings searchResourceMappings = creditCardMetadata.getSearchResourceMappings(); assertThat(searchResourceMappings).isEmpty(); ResourceMetadata personMetadata = mappings.getMetadataFor(Person.class); List<String> methodNames = new ArrayList<String>(); for (MethodResourceMapping method : personMetadata.getSearchResourceMappings()) { methodNames.add(method.getMethod().getName()); } assertThat(methodNames).hasSize(2); assertThat(methodNames).contains("findByFirstName", "findByCreatedGreaterThan"); } @Test // DATAREST-325 void exposesMethodResourceMappingInPackageProtectedButExportedRepo() { ResourceMetadata metadata = mappings.getMetadataFor(Author.class); assertThat(metadata.isExported()).isTrue(); SearchResourceMappings searchMappings = metadata.getSearchResourceMappings(); assertThat(searchMappings.isExported()).isTrue(); assertThat(searchMappings.getMappedMethod("findByFirstnameContaining")).isNotNull(); for (MethodResourceMapping methodMapping : searchMappings) { System.out.println(methodMapping.getMethod().getName()); assertThat(methodMapping.isExported()).isTrue(); } } @Test void testname() { ResourceMetadata metadata = mappings.getMetadataFor(Person.class); PropertyAwareResourceMapping propertyMapping = metadata.getProperty("father-mapped"); assertThat(propertyMapping.getRel()).isEqualTo(LinkRelation.of("father")); assertThat(propertyMapping.getPath()).isEqualTo(new Path("father-mapped")); } }
2,028
839
/** * 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 demo.hw.client; import java.beans.PropertyDescriptor; import java.io.File; import java.net.URL; import java.util.List; import javax.xml.namespace.QName; import org.apache.cxf.endpoint.Client; import org.apache.cxf.endpoint.ClientImpl; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory; import org.apache.cxf.service.model.BindingInfo; import org.apache.cxf.service.model.BindingMessageInfo; import org.apache.cxf.service.model.BindingOperationInfo; import org.apache.cxf.service.model.MessagePartInfo; import org.apache.cxf.service.model.ServiceInfo; /** * */ public final class ComplexClient { private static final QName SERVICE_NAME = new QName("http://Company.com/Application", "Company_ESB_Application_Biztalk_AgentDetails_4405_AgentDetails_Prt"); private ComplexClient() { } /** * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("please specify wsdl"); System.exit(1); } URL wsdlURL; File wsdlFile = new File(args[0]); if (wsdlFile.exists()) { wsdlURL = wsdlFile.toURI().toURL(); } else { wsdlURL = new URL(args[0]); } System.out.println(wsdlURL); JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); Client client = factory.createClient(wsdlURL.toExternalForm(), SERVICE_NAME); ClientImpl clientImpl = (ClientImpl) client; Endpoint endpoint = clientImpl.getEndpoint(); ServiceInfo serviceInfo = endpoint.getService().getServiceInfos().get(0); QName bindingName = new QName("http://Company.com/Application", "Company_ESB_Application_Biztalk_AgentDetails_4405_AgentDetails_PrtSoap"); BindingInfo binding = serviceInfo.getBinding(bindingName); //{ QName opName = new QName("http://Company.com/Application", "GetAgentDetails"); BindingOperationInfo boi = binding.getOperation(opName); BindingMessageInfo inputMessageInfo = boi.getInput(); List<MessagePartInfo> parts = inputMessageInfo.getMessageParts(); // only one part. MessagePartInfo partInfo = parts.get(0); Class<?> partClass = partInfo.getTypeClass(); System.out.println(partClass.getCanonicalName()); // GetAgentDetails Object inputObject = partClass.newInstance(); // Unfortunately, the slot inside of the part object is also called 'part'. // this is the descriptor for get/set part inside the GetAgentDetails class. PropertyDescriptor partPropertyDescriptor = new PropertyDescriptor("part", partClass); // This is the type of the class which really contains all the parameter information. Class<?> partPropType = partPropertyDescriptor.getPropertyType(); // AgentWSRequest System.out.println(partPropType.getCanonicalName()); Object inputPartObject = partPropType.newInstance(); partPropertyDescriptor.getWriteMethod().invoke(inputObject, inputPartObject); PropertyDescriptor numberPropertyDescriptor = new PropertyDescriptor("agentNumber", partPropType); numberPropertyDescriptor.getWriteMethod().invoke(inputPartObject, Integer.valueOf(314159)); Object[] result = client.invoke(opName, inputObject); Class<?> resultClass = result[0].getClass(); System.out.println(resultClass.getCanonicalName()); // GetAgentDetailsResponse PropertyDescriptor resultDescriptor = new PropertyDescriptor("agentWSResponse", resultClass); Object wsResponse = resultDescriptor.getReadMethod().invoke(result[0]); Class<?> wsResponseClass = wsResponse.getClass(); System.out.println(wsResponseClass.getCanonicalName()); PropertyDescriptor agentNameDescriptor = new PropertyDescriptor("agentName", wsResponseClass); String agentName = (String)agentNameDescriptor.getReadMethod().invoke(wsResponse); System.out.println("Agent name: " + agentName); } }
1,703
1,752
<filename>napalm/base/test/models.py try: from typing import TypedDict except ImportError: from typing_extensions import TypedDict configuration = TypedDict( "configuration", {"running": str, "candidate": str, "startup": str} ) alive = TypedDict("alive", {"is_alive": bool}) facts = TypedDict( "facts", { "os_version": str, "uptime": int, "interface_list": list, "vendor": str, "serial_number": str, "model": str, "hostname": str, "fqdn": str, }, ) interface = TypedDict( "interface", { "is_up": bool, "is_enabled": bool, "description": str, "last_flapped": float, "mtu": int, "speed": float, "mac_address": str, }, ) lldp_neighbors = TypedDict("lldp_neighbors", {"hostname": str, "port": str}) interface_counters = TypedDict( "interface_counters", { "tx_errors": int, "rx_errors": int, "tx_discards": int, "rx_discards": int, "tx_octets": int, "rx_octets": int, "tx_unicast_packets": int, "rx_unicast_packets": int, "tx_multicast_packets": int, "rx_multicast_packets": int, "tx_broadcast_packets": int, "rx_broadcast_packets": int, }, ) temperature = TypedDict( "temperature", {"is_alert": bool, "is_critical": bool, "temperature": float} ) power = TypedDict("power", {"status": bool, "output": float, "capacity": float}) memory = TypedDict("memory", {"used_ram": int, "available_ram": int}) fan = TypedDict("fan", {"status": bool}) cpu = TypedDict("cpu", {"%usage": float}) peer = TypedDict( "peer", { "is_enabled": bool, "uptime": int, "remote_as": int, "description": str, "remote_id": str, "local_as": int, "is_up": bool, "address_family": dict, }, ) af = TypedDict( "af", {"sent_prefixes": int, "accepted_prefixes": int, "received_prefixes": int} ) lldp_neighbors_detail = TypedDict( "lldp_neighbors_detail", { "parent_interface": str, "remote_port": str, "remote_chassis_id": str, "remote_port_description": str, "remote_system_name": str, "remote_system_description": str, "remote_system_capab": list, "remote_system_enable_capab": list, }, ) bgp_config_group = TypedDict( "bgp_config_group", { "type": str, "description": str, "apply_groups": list, "multihop_ttl": int, "multipath": bool, "local_address": str, "local_as": int, "remote_as": int, "import_policy": str, "export_policy": str, "remove_private_as": bool, "prefix_limit": dict, "neighbors": dict, }, ) bgp_config_neighbor = TypedDict( "bgp_config_neighbor", { "description": str, "import_policy": str, "export_policy": str, "local_address": str, "authentication_key": str, "nhs": bool, "route_reflector_client": bool, "local_as": int, "remote_as": int, "prefix_limit": dict, }, ) peer_details = TypedDict( "peer_details", { "up": bool, "local_as": int, "remote_as": int, "router_id": str, "local_address": str, "routing_table": str, "local_address_configured": bool, "local_port": int, "remote_address": str, "remote_port": int, "multihop": bool, "multipath": bool, "remove_private_as": bool, "import_policy": str, "export_policy": str, "input_messages": int, "output_messages": int, "input_updates": int, "output_updates": int, "messages_queued_out": int, "connection_state": str, "previous_connection_state": str, "last_event": str, "suppress_4byte_as": bool, "local_as_prepend": bool, "holdtime": int, "configured_holdtime": int, "keepalive": int, "configured_keepalive": int, "active_prefix_count": int, "received_prefix_count": int, "accepted_prefix_count": int, "suppressed_prefix_count": int, "advertised_prefix_count": int, "flap_count": int, }, ) arp_table = TypedDict( "arp_table", {"interface": str, "mac": str, "ip": str, "age": float} ) ipv6_neighbor = TypedDict( "ipv6_neighbor", {"interface": str, "mac": str, "ip": str, "age": float, "state": str}, ) ntp_peer = TypedDict( "ntp_peer", { # will populate it in the future wit potential keys }, ) ntp_server = TypedDict( "ntp_server", { # will populate it in the future wit potential keys }, ) ntp_stats = TypedDict( "ntp_stats", { "remote": str, "referenceid": str, "synchronized": bool, "stratum": int, "type": str, "when": str, "hostpoll": int, "reachability": int, "delay": float, "offset": float, "jitter": float, }, ) interfaces_ip = TypedDict("interfaces_ip", {"prefix_length": int}) mac_address_table = TypedDict( "mac_address_table", { "mac": str, "interface": str, "vlan": int, "static": bool, "active": bool, "moves": int, "last_move": float, }, ) route = TypedDict( "route", { "protocol": str, "current_active": bool, "last_active": bool, "age": int, "next_hop": str, "outgoing_interface": str, "selected_next_hop": bool, "preference": int, "inactive_reason": str, "routing_table": str, "protocol_attributes": dict, }, ) snmp = TypedDict( "snmp", {"chassis_id": str, "community": dict, "contact": str, "location": str} ) snmp_community = TypedDict("snmp_community", {"acl": str, "mode": str}) probe_test = TypedDict( "probe_test", { "probe_type": str, "target": str, "source": str, "probe_count": int, "test_interval": int, }, ) probe_test_results = TypedDict( "probe_test_results", { "target": str, "source": str, "probe_type": str, "probe_count": int, "rtt": float, "round_trip_jitter": float, "last_test_loss": int, "current_test_min_delay": float, "current_test_max_delay": float, "current_test_avg_delay": float, "last_test_min_delay": float, "last_test_max_delay": float, "last_test_avg_delay": float, "global_test_min_delay": float, "global_test_max_delay": float, "global_test_avg_delay": float, }, ) ping = TypedDict( "ping", { "probes_sent": int, "packet_loss": int, "rtt_min": float, "rtt_max": float, "rtt_avg": float, "rtt_stddev": float, "results": list, }, ) ping_result = TypedDict("ping_result", {"ip_address": str, "rtt": float}) traceroute = TypedDict( "traceroute", {"rtt": float, "ip_address": str, "host_name": str} ) users = TypedDict("users", {"level": int, "password": str, "sshkeys": list}) optics_state = TypedDict( "optics_state", {"instant": float, "avg": float, "min": float, "max": float} ) config = TypedDict("config", {"running": str, "startup": str, "candidate": str}) network_instance = TypedDict( "network_instance", {"name": str, "type": str, "state": dict, "interfaces": dict} ) network_instance_state = TypedDict( "network_instance_state", {"route_distinguisher": str} ) network_instance_interfaces = TypedDict( "network_instance_interfaces", {"interface": dict} ) firewall_policies = TypedDict( "firewall_policies", { "position": int, "packet_hits": int, "byte_hits": int, "id": str, "enabled": bool, "schedule": str, "log": str, "l3_src": str, "l3_dst": str, "service": str, "src_zone": str, "dst_zone": str, "action": str, }, ) vlan = TypedDict("vlan", {"name": str, "interfaces": list})
4,080
3,262
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/Apache-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.tencent.angel.model; import java.util.List; /** * PS matrices load context, it contains all need load matrices partitions stored in the PS */ public class PSMatricesLoadContext { /** * Global load request id */ private final int requestId; /** * Sub-load request id */ private final int subRequestId; /** * Need load matrices */ private final List<PSMatrixLoadContext> matrixLoadContexts; /** * Create a PSMatricesLoadContext * * @param requestId global load request id * @param subRequestId sub-load request id * @param matrixLoadContexts matrix load contexts */ public PSMatricesLoadContext(int requestId, int subRequestId, List<PSMatrixLoadContext> matrixLoadContexts) { this.requestId = requestId; this.subRequestId = subRequestId; this.matrixLoadContexts = matrixLoadContexts; } /** * Get global load request id * * @return global load request id */ public int getRequestId() { return requestId; } /** * Get Sub-load request id * * @return sub-load request id */ public int getSubRequestId() { return subRequestId; } /** * Get matrix load contexts * * @return matrix load contexts */ public List<PSMatrixLoadContext> getMatrixLoadContexts() { return matrixLoadContexts; } }
637
462
<reponame>matvaibhav/pensieve { "appName": { "message": "Gmail", "description": "App name." }, "appDesc": { "message": "Rask, søkbar e-post med mindre nettsøppel.", "description":"App description." } }
109
743
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "AdaptiveCards.Rendering.Uwp.h" namespace AdaptiveCards::Rendering::Uwp { class AdaptiveCardGetResourceStreamArgs : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::RuntimeClassType::WinRt>, ABI::AdaptiveCards::Rendering::Uwp::IAdaptiveCardGetResourceStreamArgs> { AdaptiveRuntime(AdaptiveCardGetResourceStreamArgs); public: HRESULT RuntimeClassInitialize(_In_ ABI::Windows::Foundation::IUriRuntimeClass* url); IFACEMETHODIMP get_Url(_COM_Outptr_ ABI::Windows::Foundation::IUriRuntimeClass** url); private: Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IUriRuntimeClass> m_url; }; }
332
448
// // Created by moqi on 2019-07-05. // #define LOG_TAG "xxx" #include <af_config.h> void testPacket(); void testFrame(); void testDemuxer(); #include <utils/frame_work_log.h> #include <cassert> #include "base/media/AVAFPacket.h" #include "demuxer/avFormatDemuxer.h" #include "../codec/avcodecDecoder.h" extern "C" { #include <libavcodec/avcodec.h> }; using namespace Cicada; void av_buffer_free(void *opaque, uint8_t *data) { AF_LOGD("xxx\n"); av_buffer_default_free(opaque, data); } int main() { // testPacket(); // // testFrame(); #if AF_HAVE_PTHREAD //#error "have thread" #endif testDemuxer(); return 0; } static int callback_read(void *arg, uint8_t *buffer, int size) { } void testDemuxer() { int ret = 0; avFormatDemuxer demuxer("/Users/moqi/work/xx/framework/cmake-build-debug/aliyunmedia.ts"); // demuxer.SetDataCallBack(callback_read, nullptr, nullptr, nullptr, nullptr); ret = demuxer.Open(); if (ret < 0) { AF_LOGE("demuxer open error\n"); return; } Stream_meta meta{}; std::map<int, std::unique_ptr<avcodecDecoder>> decoders{}; for (int i = 0; i < demuxer.GetNbStreams(); ++i) { demuxer.OpenStream(i); demuxer.GetStreamMeta(&meta, i); decoders[i] = std::unique_ptr<avcodecDecoder>(new avcodecDecoder()); decoders[i]->open(&meta, nullptr, 0); releaseMeta(&meta); } int count = 0; // demuxer.Seek(260000000, 0, -1); demuxer.Start(); do { std::unique_ptr<IAFPacket> pkt; ret = demuxer.ReadPacket(pkt, 0); if (ret > 0) { pkt->getInfo().dump(); assert(pkt != nullptr); // _hex_dump(pkt->getData(), 16); AF_LOGD("pkt size is %lld\n", pkt->getSize()); do { unique_ptr<IAFFrame> frame{}; decoders[pkt->getInfo().streamIndex]->getFrame(frame, 0); if (frame != nullptr) { frame->dump(); } int ret1 = decoders[pkt->getInfo().streamIndex]->send_packet(pkt, 0); if (ret1 & STATUS_RETRY_IN) { usleep(10000); } else { break; } } while (true); } if (ret == -EAGAIN) { usleep(10000); continue; } // if (count++ > 10) // break; } while (ret > 0 || ret == -EAGAIN); // EOS std::unique_ptr<IAFPacket> pkt{nullptr}; for (auto &item : decoders) { item.second->send_packet(pkt, 10000); do { unique_ptr<IAFFrame> frame{}; ret = item.second->getFrame(frame, 0); if (frame != nullptr) { frame->dump(); } } while (ret != STATUS_EOS); } demuxer.Stop(); } #if 1 void testFrame() { AVFrame *frame = av_frame_alloc(); frame->format = AV_PIX_FMT_YUV420P; frame->width = 1920; frame->height = 1080; int ret = av_frame_get_buffer(frame, 32); if (ret < 0) { AF_LOGE("Could not allocate the video frame data\n"); } frame->pts = 100; AVAFFrame avafFrame{frame}; av_frame_free(&frame); auto clone_frame = avafFrame.clone(); auto &info = clone_frame->getInfo(); info.pts = 200; clone_frame->dump(); avafFrame.dump(); } void testPacket() { AVPacket opkt; av_init_packet(&opkt); opkt.pts = 100; opkt.duration = 10; opkt.flags = 1; opkt.data = static_cast<uint8_t *>(av_malloc(10)); opkt.size = 10; memset(opkt.data, 0x11, 10); opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_free, nullptr, 0); AVAFPacket avafPacket{opkt}; // av_packet_unref(&opkt); std::unique_ptr<IAFPacket> clone_pkt = avafPacket.clone(); AF_DUMP_INT(clone_pkt->getInfo().duration); AF_DUMP_INT(clone_pkt->getInfo().pts); AF_DUMP_INT(clone_pkt->getSize()); AF_LOGD("buffer is %p\n", clone_pkt->getData()); } #endif
2,014
565
/* * Copyright (c) 2014 Spotify AB * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef __JniHelpersCommon_h__ #define __JniHelpersCommon_h__ #include "JniTypes.h" #include <jni.h> // Disable some annoying compiler warnings #if WIN32 #pragma warning(disable: 4996) // "Security" warnings for vsnprintf #endif #if WIN32 #define EXPORT __declspec(dllexport) #else #define EXPORT #endif // What version of Java should be used when initializing JniHelpers. By default this // is defined to be Java 1.6. #ifndef JAVA_VERSION #define JAVA_VERSION JNI_VERSION_1_6 #endif // Whether string literals are supported by the platform. This is a C++11 feature // which the Visual C++ does not yet support. Currently this feature is only used // by the test suite. #if ! WIN32 #define HAS_RAW_STRING_LITERALS 1 #endif // Whether the JVM should be forcibly terminated if an exception is thrown. This does // not apply to exceptions thrown from within JniHelpers or within Java code attached // to JNI code. This is mostly relevant when looking up classes/methods/fields which // do not exist, and thus represent a misconfiguration on the programmer's end. In such // cases it is sometimes prudent to forcibly quit rather than try to continue running. #ifndef TERMINATE_ON_EXCEPTION #define TERMINATE_ON_EXCEPTION 0 #endif // Windows uses _DEBUG by default, but we prefer plain 'ol DEBUG instead #if WIN32 #define DEBUG _DEBUG #endif // Determines whether exceptions will be raised by JniHelpers #ifndef ENABLE_EXCEPTIONS #define ENABLE_EXCEPTIONS 1 #endif // Determines whether logging messages will be printed by JniHelpers #ifndef ENABLE_LOGGING #define ENABLE_LOGGING 0 #endif // Determines whether debug/info logging messages will be printed by JniHelpers #ifndef ENABLE_LOGGING_DEBUG #define ENABLE_LOGGING_DEBUG DEBUG #endif #if ENABLE_LOGGING #if ANDROID #include <android/log.h> #define LOGGING_TAG "JniHelpers" #if ENABLE_LOGGING_DEBUG #define LOG_DEBUG(...) __android_log_print(ANDROID_LOG_INFO, LOGGING_TAG, __VA_ARGS__) #define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, LOGGING_TAG, __VA_ARGS__) #else #define LOG_DEBUG(...) #define LOG_INFO(...) #endif #define LOG_WARN(...) __android_log_print(ANDROID_LOG_WARN, LOGGING_TAG, __VA_ARGS__) #define LOG_ERROR(...) __android_log_print(ANDROID_LOG_ERROR, LOGGING_TAG, __VA_ARGS__) #else #if ENABLE_LOGGING_DEBUG #define LOG_DEBUG(...) fprintf(stderr, "DEBUG: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n") #define LOG_INFO(...) fprintf(stderr, "INFO: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n") #else #define LOG_DEBUG(...) #define LOG_INFO(...) #endif #define LOG_WARN(...) fprintf(stderr, "WARN: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n") #define LOG_ERROR(...) fprintf(stderr, "ERROR: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n") #endif #else #define LOG_DEBUG(...) #define LOG_INFO(...) #define LOG_WARN(...) #define LOG_ERROR(...) #endif #endif // __JniHelpersCommon_h__
1,229
2,360
<filename>var/spack/repos/builtin/packages/py-pmw/package.py # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPmw(PythonPackage): """Pmw is a toolkit for building high-level compound widgets, or megawidgets, constructed using other widgets as component parts.""" pypi = "Pmw/Pmw-2.0.0.tar.gz" version('2.0.1', sha256='0b9d28f52755a7a081b44591c3dd912054f896e56c9a627db4dd228306ad1120') version('2.0.0', sha256='2babb2855feaabeea1003c6908b61c9d39cff606d418685f0559952714c680bb')
277
388
# Lint as: python3 # Copyright 2019 Google 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. # ============================================================================== """Create multiplier quantizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging from qkeras.qtools.quantized_operators import multiplier_impl from qkeras.qtools.quantized_operators import quantizer_impl class MultiplierFactory: """determine which multiplier implementation to use.""" def __init__(self): # the table below is found in this slides: # https://docs.google.com/presentation/d/1pcmoB6ZpX0IqjhSwgzO-oQwpMRYwIcDe/edit#slide=id.p40 # also attached the output datatype in the table self.multiplier_impl_table = [ [ ( multiplier_impl.FixedPointMultiplier, quantizer_impl.QuantizedBits() ), (multiplier_impl.Shifter, quantizer_impl.QuantizedBits()), (multiplier_impl.Mux, quantizer_impl.QuantizedBits()), (multiplier_impl.Mux, quantizer_impl.QuantizedBits()), (multiplier_impl.AndGate, quantizer_impl.QuantizedBits()), ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint( bits=None) ) ], [ (multiplier_impl.Shifter, quantizer_impl.QuantizedBits()), (multiplier_impl.Adder, quantizer_impl.PowerOfTwo()), (multiplier_impl.Mux, quantizer_impl.PowerOfTwo()), (multiplier_impl.Mux, quantizer_impl.PowerOfTwo()), (multiplier_impl.AndGate, quantizer_impl.PowerOfTwo()), (multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ) ], [ (multiplier_impl.Mux, quantizer_impl.QuantizedBits()), (multiplier_impl.Mux, quantizer_impl.PowerOfTwo()), (multiplier_impl.Mux, quantizer_impl.Ternary()), (multiplier_impl.Mux, quantizer_impl.Ternary()), (multiplier_impl.AndGate, quantizer_impl.Ternary()), (multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None)) ], [ (multiplier_impl.Mux, quantizer_impl.QuantizedBits()), (multiplier_impl.Mux, quantizer_impl.PowerOfTwo()), (multiplier_impl.Mux, quantizer_impl.Ternary()), (multiplier_impl.XorGate, quantizer_impl.Binary( use_01=False)), (multiplier_impl.AndGate, quantizer_impl.Ternary()), (multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None)) ], [ (multiplier_impl.AndGate, quantizer_impl.QuantizedBits()), (multiplier_impl.AndGate, quantizer_impl.PowerOfTwo()), (multiplier_impl.AndGate, quantizer_impl.Ternary()), (multiplier_impl.AndGate, quantizer_impl.Ternary()), (multiplier_impl.AndGate, quantizer_impl.Binary( use_01=True)), (multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None)) ], [ ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ), ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ), ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ), ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ), ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ), ( multiplier_impl.FloatingPointMultiplier, quantizer_impl.FloatingPoint(bits=None) ) ] ] def make_multiplier( self, weight_quantizer: quantizer_impl.IQuantizer, input_quantizer: quantizer_impl.IQuantizer ) -> multiplier_impl.IMultiplier: """Create a multiplier instance. The type and bit width of the multiplier is deteremined from the quantizer type of both the kernel (weight) and input tensor. The table below illustrates the rule of inferring multiplier type from the quantizer type of both the kernel (weight) and input tensor x qb(n) +/-,exp t(-1,0,+1) b(-1,+1) b(0,1) float32 qb(n) * << >>,- ?,- ?,- ? +/-,exp << >>,- + ?,- ^ ?,- w t(-1,0,+1) ?,- ?,- ?,^ ?,^ ^ b(-1,+1) ?,- ^ ?,^ ^ ^ b(0,1) ? ?,- ^ ^ ^ & float32 Args: weight_quantizer: weight quantizer type input_quantizer: input quantizer type Returns: An IMultiplier instance. """ assert weight_quantizer is not None assert input_quantizer is not None (multiplier_impl_class, output_quantizer) = self.multiplier_impl_table[ weight_quantizer.mode][input_quantizer.mode] logging.debug( "multiplier implemented as class %s", multiplier_impl_class.implemented_as()) assert issubclass(multiplier_impl_class, multiplier_impl.IMultiplier) return multiplier_impl_class( weight_quantizer, input_quantizer, output_quantizer )
2,948
1,428
<reponame>PushpneetSingh/Hello-world #include <iostream> #include <algorithm> using namespace std; typedef unsigned long long int ulli; int main() { ulli a, b, x, y, gcdiv; cin>>a>>b>>x>>y; gcdiv = __gcd(x, y); x /= gcdiv; y /= gcdiv; cout<<min(a / x, b / y); return 0; }
142
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"Valence","circ":"3ème circonscription","dpt":"Charente","inscrits":160,"abs":83,"votants":77,"blancs":1,"nuls":4,"exp":72,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":46},{"nuance":"REM","nom":"Mme <NAME>","voix":26}]}
112
3,475
// Copyright 2018 Google 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. #ifndef CC_ASYNC_THREAD_SAFE_QUEUE_H_ #define CC_ASYNC_THREAD_SAFE_QUEUE_H_ #include <queue> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" namespace minigo { template <typename T> class ThreadSafeQueue { public: void Push(const T& x) { absl::MutexLock lock(&m_); queue_.push(x); } void Push(T&& x) { absl::MutexLock lock(&m_); queue_.push(std::forward<T>(x)); } bool TryPop(T* x) { absl::MutexLock lock(&m_); if (queue_.empty()) { return false; } *x = std::move(queue_.front()); queue_.pop(); return true; } T Pop() { absl::MutexLock lock(&m_); m_.Await(absl::Condition(this, &ThreadSafeQueue::has_elements)); T x = std::move(queue_.front()); queue_.pop(); return x; } bool PopWithTimeout(T* x, absl::Duration timeout) { absl::MutexLock lock(&m_); m_.AwaitWithTimeout(absl::Condition(this, &ThreadSafeQueue::has_elements), timeout); if (queue_.empty()) { return false; } *x = std::move(queue_.front()); queue_.pop(); return true; } bool empty() const { absl::MutexLock lock(&m_); return queue_.empty(); } private: bool has_elements() const EXCLUSIVE_LOCKS_REQUIRED(&m_) { return !queue_.empty(); } mutable absl::Mutex m_; std::queue<T> queue_ GUARDED_BY(&m_); }; } // namespace minigo #endif // CC_ASYNC_THREAD_SAFE_QUEUE_H_
807
367
<gh_stars>100-1000 package com.shang.xposed; import android.util.Log; import com.forfan.bigbang.BuildConfig; import de.robv.android.xposed.XposedBridge; public class Logger { private static boolean sEnable = BuildConfig.DEBUG; private static final String TAG = "XposedBigBang"; public static void e(String tag, String msg) { if (sEnable) { Log.e(TAG + ":" + tag, msg); } } public static void d(String tag, String msg) { if (sEnable) { Log.d(TAG + ":" + tag, msg); XposedBridge.log(TAG + ":" + msg); } } public static void logClass(String tag, Class c) { if(sEnable) { d(tag, "class: " + c.getName()); if (c.getSuperclass() != null) { Log.e(TAG + ":" + tag, c.getCanonicalName()); } } } }
405
429
/* vim: tabstop=4 shiftwidth=4 noexpandtab */ #pragma once #include <kernel/types.h> void return_from_signal_handler(void); void fix_signal_stacks(void); #include <sys/signal_defs.h>
76
1,305
<filename>src/javax/swing/plaf/synth/ColorType.java /* * Copyright (c) 2002, 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.plaf.synth; /** * A typesafe enumeration of colors that can be fetched from a style. * <p> * Each <code>SynthStyle</code> has a set of <code>ColorType</code>s that * are accessed by way of the * {@link SynthStyle#getColor(SynthContext, ColorType)} method. * <code>SynthStyle</code>'s <code>installDefaults</code> will install * the <code>FOREGROUND</code> color * as the foreground of * the Component, and the <code>BACKGROUND</code> color to the background of * the component (assuming that you have not explicitly specified a * foreground and background color). Some components * support more color based properties, for * example <code>JList</code> has the property * <code>selectionForeground</code> which will be mapped to * <code>FOREGROUND</code> with a component state of * <code>SynthConstants.SELECTED</code>. * <p> * The following example shows a custom <code>SynthStyle</code> that returns * a red Color for the <code>DISABLED</code> state, otherwise a black color. * <pre> * class MyStyle extends SynthStyle { * private Color disabledColor = new ColorUIResource(Color.RED); * private Color color = new ColorUIResource(Color.BLACK); * protected Color getColorForState(SynthContext context, ColorType type){ * if (context.getComponentState() == SynthConstants.DISABLED) { * return disabledColor; * } * return color; * } * } * </pre> * * @since 1.5 * @author <NAME> */ public class ColorType { /** * ColorType for the foreground of a region. */ public static final ColorType FOREGROUND = new ColorType("Foreground"); /** * ColorType for the background of a region. */ public static final ColorType BACKGROUND = new ColorType("Background"); /** * ColorType for the foreground of a region. */ public static final ColorType TEXT_FOREGROUND = new ColorType( "TextForeground"); /** * ColorType for the background of a region. */ public static final ColorType TEXT_BACKGROUND =new ColorType( "TextBackground"); /** * ColorType for the focus. */ public static final ColorType FOCUS = new ColorType("Focus"); /** * Maximum number of <code>ColorType</code>s. */ public static final int MAX_COUNT; private static int nextID; private String description; private int index; static { MAX_COUNT = Math.max(FOREGROUND.getID(), Math.max( BACKGROUND.getID(), FOCUS.getID())) + 1; } /** * Creates a new ColorType with the specified description. * * @param description String description of the ColorType. */ protected ColorType(String description) { if (description == null) { throw new NullPointerException( "ColorType must have a valid description"); } this.description = description; synchronized(ColorType.class) { this.index = nextID++; } } /** * Returns a unique id, as an integer, for this ColorType. * * @return a unique id, as an integer, for this ColorType. */ public final int getID() { return index; } /** * Returns the textual description of this <code>ColorType</code>. * This is the same value that the <code>ColorType</code> was created * with. * * @return the description of the string */ public String toString() { return description; } }
1,457
2,151
<reponame>swimfish09/quiche<filename>quic/platform/api/quic_macros.h // Copyright (c) 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef QUICHE_QUIC_PLATFORM_API_QUIC_MACROS_H_ #define QUICHE_QUIC_PLATFORM_API_QUIC_MACROS_H_ #include "net/quic/platform/impl/quic_macros_impl.h" #define QUIC_MUST_USE_RESULT QUIC_MUST_USE_RESULT_IMPL #define QUIC_UNUSED QUIC_UNUSED_IMPL #endif // QUICHE_QUIC_PLATFORM_API_QUIC_MACROS_H_
224
1,444
<filename>Mage.Sets/src/mage/cards/p/PsychicPossession.java package mage.cards.p; import java.util.Objects; import java.util.UUID; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.SkipDrawStepEffect; import mage.abilities.keyword.EnchantAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Outcome; import mage.constants.Zone; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; import mage.players.Player; import mage.target.TargetPlayer; import mage.target.common.TargetOpponent; /** * * @author spjspj */ public final class PsychicPossession extends CardImpl { public PsychicPossession(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{2}{U}{U}"); this.subtype.add(SubType.AURA); // Enchant opponent TargetPlayer auraTarget = new TargetOpponent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.DrawCard)); this.addAbility(new EnchantAbility(auraTarget.getTargetName())); // Skip your draw step. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new SkipDrawStepEffect())); // Whenever enchanted opponent draws a card, you may draw a card. this.addAbility(new PsychicPossessionTriggeredAbility()); } private PsychicPossession(final PsychicPossession card) { super(card); } @Override public PsychicPossession copy() { return new PsychicPossession(this); } } class PsychicPossessionTriggeredAbility extends TriggeredAbilityImpl { public PsychicPossessionTriggeredAbility() { super(Zone.BATTLEFIELD, new DrawCardSourceControllerEffect(1), true); } public PsychicPossessionTriggeredAbility(final PsychicPossessionTriggeredAbility ability) { super(ability); } @Override public PsychicPossessionTriggeredAbility copy() { return new PsychicPossessionTriggeredAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DREW_CARD; } @Override public boolean checkTrigger(GameEvent event, Game game) { Permanent enchantment = game.getPermanent(this.sourceId); if (enchantment != null && enchantment.getAttachedTo() != null) { Player opponent = game.getPlayer(enchantment.getAttachedTo()); Player player = game.getPlayer(event.getPlayerId()); if (opponent != null && player != null && Objects.equals(player, opponent)) { return true; } } return false; } @Override public String getRule() { return "Whenever enchanted opponent draws a card, you may draw a card"; } }
1,110
1,073
//===-- llvm/CodeGen/GlobalISel/CallLowering.h - Call lowering --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// This file describes how to lower LLVM calls to machine code calls. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_GLOBALISEL_CALLLOWERING_H #define LLVM_CODEGEN_GLOBALISEL_CALLLOWERING_H #include "llvm/ADT/SmallVector.h" #include "llvm/IR/Function.h" namespace llvm { // Forward declarations. class MachineIRBuilder; class TargetLowering; class Value; class CallLowering { const TargetLowering *TLI; protected: /// Getter for generic TargetLowering class. const TargetLowering *getTLI() const { return TLI; } /// Getter for target specific TargetLowering class. template <class XXXTargetLowering> const XXXTargetLowering *getTLI() const { return static_cast<const XXXTargetLowering *>(TLI); } public: CallLowering(const TargetLowering *TLI) : TLI(TLI) {} virtual ~CallLowering() {} /// This hook must be implemented to lower outgoing return values, described /// by \p Val, into the specified virtual register \p VReg. /// This hook is used by GlobalISel. /// /// \return True if the lowering succeeds, false otherwise. virtual bool lowerReturn(MachineIRBuilder &MIRBuilder, const Value *Val, unsigned VReg) const { return false; } /// This hook must be implemented to lower the incoming (formal) /// arguments, described by \p Args, for GlobalISel. Each argument /// must end up in the related virtual register described by VRegs. /// In other words, the first argument should end up in VRegs[0], /// the second in VRegs[1], and so on. /// \p MIRBuilder is set to the proper insertion for the argument /// lowering. /// /// \return True if the lowering succeeded, false otherwise. virtual bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, const Function::ArgumentListType &Args, const SmallVectorImpl<unsigned> &VRegs) const { return false; } }; } // End namespace llvm. #endif
755
646
/* Copyright (c) 2017 TOSHIBA Digital Solutions Corporation This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*! @file @brief GeomFromText Functor */ #ifndef GIS_GEOMFROMTEXT_H_ #define GIS_GEOMFROMTEXT_H_ #include "function_map.h" #include "gis_geometry.h" #include "gis_linestring.h" #include "gis_multipolygon.h" #include "gis_pointgeom.h" #include "gis_polygon.h" #include "gis_polyhedralsurface.h" #include "gis_quadraticsurface.h" #include "qp_def.h" #include "lexer.h" #include "tql_token.h" #include "wkt.h" #include "wkt_token.h" /*! * @brief GeomFromText Functor * */ class FunctorGeomFromText : public TqlFunc { public: using TqlFunc::operator(); Expr *operator()( ExprList &args, TransactionContext &txn, ObjectManager &objectManager) { if (args.size() != 1) { GS_THROW_USER_ERROR(GS_ERROR_TQ_CONSTRAINT_INVALID_ARGUMENT_COUNT, "Invalid argument count"); } FunctionMap *wktFunctionMap = FunctionMap::getInstanceForWkt(); if (args[0]->isNullValue()) { return Expr::newNullValue(txn); } if (!args[0]->isString()) { GS_THROW_USER_ERROR(GS_ERROR_TQ_CONSTRAINT_INVALID_ARGUMENT_TYPE, "Argument 1 is not a string."); } lemon_wktParser::wktParser *p = QP_NEW_BY_TXN(txn) lemon_wktParser::wktParser(); if (p == NULL) { GS_THROW_USER_ERROR( GS_ERROR_CM_NO_MEMORY, "Cannot allocate WKT parser"); } lemon_wktParser::wktParserArg arg; int ret; const char *c_str = args[0]->getValueAsString(txn); Token t; Expr *e = NULL; arg.ev = &e; arg.txn = &txn; arg.objectManager = &objectManager; arg.fmap = wktFunctionMap; arg.err = 0; #ifdef WKT_TRACE p->wktParserSetTrace(&std::cerr, "wkt_trace:"); #endif do { ret = getToken(txn, c_str, t); if (ret == 0 || ret == -1) { break; } if (t.id == TK_ILLEGAL) { break; } if (ret != -2) { p->Execute(t.id, t, &arg); } if (arg.err != 0) { QP_SAFE_DELETE(p); std::string str2 = "Argument 1 is not a WKT string: "; str2 += c_str; GS_THROW_USER_ERROR( GS_ERROR_TQ_CONSTRAINT_INVALID_ARGUMENT_TYPE, str2.c_str()); } c_str += t.n; } while (1); p->Execute(0, t, &arg); QP_SAFE_DELETE(p); if (*arg.ev == NULL) { std::string str2 = "Argument 1 is not a WKT string: "; str2 += c_str; GS_THROW_USER_ERROR( GS_ERROR_TQ_CONSTRAINT_INVALID_ARGUMENT_TYPE, str2.c_str()); } return *arg.ev; } private: /*! * Get token from the main TQL lexer. * (We do not use special lexer for maintainability.) * * @param str WKT string to parse * @param t Token reference * * @return 1 if succeeded or 0 when failed */ int getToken(TransactionContext &txn, const char *str, Token &t) { int ret = Lexer::gsGetToken(str, t); #define CASE_MAP_TOKEN(x) \ case TK_##x: \ t.id = TK_WKT_##x; \ break switch (t.id) { CASE_MAP_TOKEN(GISFUNC); CASE_MAP_TOKEN(LP); CASE_MAP_TOKEN(RP); CASE_MAP_TOKEN(SEMICOLON); CASE_MAP_TOKEN(INTEGER); CASE_MAP_TOKEN(COMMA); CASE_MAP_TOKEN(MINUS); CASE_MAP_TOKEN(FLOAT); CASE_MAP_TOKEN(PLUS); case TK_ID: { char buf[256], *p; if (t.n < 256) { p = buf; } else { p = reinterpret_cast<char *>(QP_ALLOCATOR.allocate(t.n + 1)); } memcpy(p, t.z, t.n); buf[t.n] = '\0'; if (util::stricmp(p, "EMPTY") == 0) { t.id = TK_WKT_EMPTY; } else { t.id = TK_WKT_GISFUNC; } } break; case TK_SPACE: ret = -2; break; case TK_NAN: case TK_INF: case TK_ILLEGAL: ret = -1; break; default: t.id = TK_WKT_GISFUNC; break; } #undef CASE_MAP_TOKEN return ret; } }; #endif
1,975
319
<gh_stars>100-1000 /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * */ package org.openimaj.tools.faces.extraction; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.openimaj.image.ImageUtilities; import org.openimaj.image.MBFImage; import org.openimaj.image.processing.face.detection.DetectedFace; import org.openimaj.image.processing.face.detection.HaarCascadeDetector; import org.openimaj.math.geometry.shape.Rectangle; import org.openimaj.util.pair.IndependentPair; import org.openimaj.video.processing.shotdetector.ShotBoundary; import org.openimaj.video.processing.shotdetector.HistogramVideoShotDetector; import org.openimaj.video.processing.timefinder.ObjectTimeFinder; import org.openimaj.video.processing.timefinder.ObjectTimeFinder.TimeFinderListener; import org.openimaj.video.processing.tracking.BasicMBFImageObjectTracker; import org.openimaj.video.timecode.VideoTimecode; import org.openimaj.video.xuggle.XuggleVideo; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * A tool that provides a means of extracting faces from videos and images. * * @author <NAME> (<EMAIL>) * * @created 7 Nov 2011 */ public class FaceExtractorTool { /** The options for this tool instance */ private FaceExtractorToolOptions options = null; /** The video from which to extract faces */ private XuggleVideo video = null; /** The output directory where we'll write the extracted faces */ private File outputDir = null; /** Used in the object tracking to store the frame in which the best face was found */ private MBFImage bestFaceFrame = null; /** Used in the object tracking to store the best face timecode for each face */ private VideoTimecode bestFaceTimecode = null; /** Used in the object tracking to store the best face bounding box */ private Rectangle bestFaceBoundingBox = null; /** * Default constructor * @param o the options */ public FaceExtractorTool( FaceExtractorToolOptions o ) { this.options = o; this.outputDir = new File( o.outputFile ); // If we have a video file, read in the video if( options.videoFile != null ) { // Create the video reader for reading the video this.video = new XuggleVideo( new File( options.videoFile ) ); } // Create the output directory if it doesn't exist. if( !this.outputDir.exists() ) this.outputDir.mkdirs(); // Process the video this.processVideo(); } /** * Process the video to extract faces. */ private void processVideo() { if( this.options.verbose ) { System.out.println( this.options.videoFile ); System.out.println( " - Size: "+video.getWidth()+"x"+video.getHeight() ); System.out.println( " - Frame Rate: "+video.getFPS() ); System.out.println( "Detecting shots in video..." ); } // This is the video shot detector we'll use to find the shots in // the incoming video. These shots will provide hard limits for the // face tracking. HistogramVideoShotDetector vsd = new HistogramVideoShotDetector( this.video ); vsd.setThreshold( this.options.threshold ); vsd.setFindKeyframes( true ); vsd.setStoreAllDifferentials( false ); vsd.process(); // Retrieve the shots from the shot detector List<ShotBoundary<MBFImage>> shots = vsd.getShotBoundaries(); if( this.options.verbose ) System.out.println( "Found "+shots.size()+" shots."); // We'll use the HaarCascadeFaceDetector for detecting faces. HaarCascadeDetector fd = HaarCascadeDetector.BuiltInCascade.frontalface_alt2.load(); fd.setMinSize( this.options.faceSize ); // Now we'll go through the video looking for faces every x seconds. this.video.reset(); // For each shot boundary... ShotBoundary<MBFImage> prev = shots.get(0); for( int i = 1; i < shots.size(); i++ ) { ShotBoundary<MBFImage> thiz = shots.get(i); // Get the timecodes of the shot. Remember the timecode gives the // start of the shot, so the shot is between the previous timecode // and one frame before this timecode. long pframe = prev.getTimecode().getFrameNumber(); long tframe = thiz.getTimecode().getFrameNumber()-1; if( this.options.verbose ) System.out.println( "Shot: "+prev+" ("+pframe+") -> "+thiz+" ("+tframe+")" ); // This will be the frame we'll store for a given face MBFImage faceFrame = null; // Now loop around looking for faces in the shot List<DetectedFace> faces = null; boolean doneSearching = false; while( !doneSearching ) { // If we're supposed to use just the centre frame, then we'll work // out where that centre frame is and grab the frame. if( this.options.useCentre ) { long mframe = pframe + ((tframe - pframe) / 2); video.setCurrentFrameIndex(mframe); faceFrame = video.getCurrentFrame(); doneSearching = true; } // If we're searching for a face every x-seconds then we'll skip frames // forward by x-seconds. else { // Push the video forward by x frames pframe += options.seconds * video.getFPS(); // Check if we're still within the shot if( pframe >= tframe ) { doneSearching = true; pframe = tframe; } // Push the video forward video.setCurrentFrameIndex( pframe ); faceFrame = video.getCurrentFrame(); } if( this.options.verbose ) System.out.println( " - Using frame "+ video.getCurrentTimecode()+" ("+video.getTimeStamp()+")" ); // Detect faces in the frame faces = fd.detectFaces( faceFrame.flatten() ); if( this.options.verbose ) System.out.println( " + Found "+faces.size()+" faces in frame."); if( faces.size() > 0 ) doneSearching = true; // For each of the detected faces (if there are any) track // back and forth in the video to find the times at which the // face is best. As a consequence, we will also end up with the // timecodes at which the face appears in the video (at any size) for( DetectedFace f : faces ) { if( options.verbose ) System.out.println( " - Tracking face..." ); bestFaceTimecode = null; bestFaceFrame = null; bestFaceBoundingBox = null; // We'll use this ObjectTimeFinder to track the faces once they're // extracted from the video. ObjectTimeFinder otf = new ObjectTimeFinder(); IndependentPair<VideoTimecode, VideoTimecode> timecodes = otf.trackObject( new BasicMBFImageObjectTracker(), video, video.getCurrentTimecode(), f.getBounds(), new TimeFinderListener<Rectangle,MBFImage>() { double maxArea = 0; @Override public void objectTracked( List<Rectangle> objects, VideoTimecode time, MBFImage image ) { if( objects.size() > 0 && objects.get(0).calculateArea() > maxArea ) { maxArea = objects.get(0).calculateArea(); bestFaceTimecode = time; bestFaceFrame = image.clone(); bestFaceBoundingBox = objects.get(0); } } } ); if( options.verbose ) System.out.println( " - Face tracked between "+timecodes ); if( bestFaceBoundingBox != null ) try { saveFace( bestFaceFrame, bestFaceTimecode.getFrameNumber(), timecodes, bestFaceBoundingBox ); } catch( IOException e ) { e.printStackTrace(); } } } prev = thiz; } } /** * Writes a face image to an appropriate file in the output directory * named as per the input file but suffixed with the frame number. * * @param frame The video frame * @param mframe The frame number * @param timecodes The timecodes of the face * @param bounds The bounding box of the face * @throws IOException If the write cannot be completed */ private void saveFace( MBFImage frame, long mframe, IndependentPair<VideoTimecode, VideoTimecode> timecodes, Rectangle bounds ) throws IOException { File base = new File( this.options.outputFile ); if( options.writeFaceImage ) { File img = new File( base, new File( this.options.videoFile ).getName() + "#" + mframe + ".face.png"); ImageUtilities.write( frame.extractROI( bounds ), img); } if( options.writeFrameImage ) { File img = new File( base, new File( this.options.videoFile ).getName() + "#" + mframe + ".frame.png"); ImageUtilities.write(frame, img); } if( options.writeXML ) { File xml = new File( base, new File( this.options.videoFile ).getName() + "#" + mframe + ".xml"); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElement( "face" ); document.appendChild( rootElement ); Element em = document.createElement( "boundingBox" ); em.appendChild( document.createTextNode( bounds.toString() ) ); rootElement.appendChild(em); em = document.createElement( "appearanceTimecode" ); em.appendChild( document.createTextNode( timecodes.firstObject().toString() ) ); rootElement.appendChild(em); em = document.createElement( "disappearanceTimecode" ); em.appendChild( document.createTextNode( timecodes.secondObject().toString() ) ); rootElement.appendChild(em); em = document.createElement( "appearanceFrame" ); em.appendChild( document.createTextNode( ""+timecodes.firstObject().getFrameNumber() ) ); rootElement.appendChild(em); em = document.createElement( "disappearanceFrame" ); em.appendChild( document.createTextNode( ""+timecodes.secondObject().getFrameNumber() ) ); rootElement.appendChild(em); em = document.createElement( "appearanceTime" ); em.appendChild( document.createTextNode( ""+timecodes.firstObject().getTimecodeInMilliseconds() ) ); rootElement.appendChild(em); em = document.createElement( "disappearanceTime" ); em.appendChild( document.createTextNode( ""+timecodes.secondObject().getTimecodeInMilliseconds() ) ); rootElement.appendChild(em); try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource( document ); StreamResult result = new StreamResult( new FileWriter( xml ) ); transformer.transform( source, result ); } catch( Exception e ) { e.printStackTrace(); } } catch( DOMException e ) { e.printStackTrace(); } catch( ParserConfigurationException e ) { e.printStackTrace(); } } } /** * Parses the command line arguments. * * @param args The arguments to parse * @return The tool options class */ private static FaceExtractorToolOptions parseArgs( String[] args ) { FaceExtractorToolOptions fdto = new FaceExtractorToolOptions(); CmdLineParser parser = new CmdLineParser( fdto ); try { parser.parseArgument( args ); } catch( CmdLineException e ) { System.err.println( e.getMessage()); System.err.println( "java FaceExtractorTool [options...]"); parser.printUsage( System.err ); System.exit(1); } return fdto; } /** * Default main * @param args */ public static void main( String[] args ) { FaceExtractorToolOptions options = parseArgs( args ); new FaceExtractorTool( options ); } }
5,323
379
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.oim.core.business.constant; /** * * @author xh */ public class RemoteConstant { public static final String action_type_shut = "0";//挂断 public static final String action_type_agree = "1";//接受 }
105
502
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alipay.sofa.tracer.boot.springcloud.processor; import com.alipay.sofa.tracer.plugins.springcloud.instruments.feign.SofaTracerFeignContext; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.cloud.openfeign.FeignContext; /** * @author: guolei.sgl (<EMAIL>) 2019/3/13 6:08 PM * @since: **/ public class SofaTracerFeignContextBeanPostProcessor implements BeanPostProcessor { private BeanFactory beanFactory; public SofaTracerFeignContextBeanPostProcessor(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof FeignContext && !(bean instanceof SofaTracerFeignContext)) { return new SofaTracerFeignContext((FeignContext) bean, beanFactory); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
747
639
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Basic lexer and parser needed pip install ply """ from __future__ import generators import re import os.path import time import copy import sys import ply.yacc as yacc import ply.lex as lex # Python 3 compatibility if sys.version_info.major < 3: STRING_TYPES = (str, unicode) else: STRING_TYPES = str xrange = range # tokens for lexing reserved = { # keywords 'if': 'IF', 'else': 'ELSE', 'for': 'FOR', 'void': 'VOID', # data types 'bool': 'TYPE', 'char': 'TYPE', 'double': 'TYPE', 'float': 'TYPE', 'int': 'TYPE', # qualifiers 'const': 'QUALIFIER', '__volatile__': 'QUALIFIER', '__restrict__': 'QUALIFIER', # CUDA '__shared__': 'SHARED', '__syncthreads': 'SYNC', '__global__': 'GLOBAL' } tokens = ['ID', 'INTEGER', 'FLOAT', 'STRING', 'CHAR', 'WS', 'COMMENT1', 'COMMENT2', 'POUND', 'DPOUND'] + list( set(reserved.values())) literals = "+-*/%|&~^<>=!?()[]{}.,;:\\\'\"" # Whitespace def t_WS(t): r'\s+' t.lexer.lineno += t.value.count("\n") return t t_POUND = r'\#' t_DPOUND = r'\#\#' # Identifier def t_ID(t): r'[A-Za-z_][\w_]*' t.type = reserved.get(t.value, 'ID') return t def t_INTEGER(t): r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)' # t.value = int(t.value) return t # String literal def t_STRING(t): r'\"([^\\\n]|(\\(.|\n)))*?\"' t.lexer.lineno += t.value.count("\n") return t # Character constant 'c' or L'c' def t_CHAR(t): r'(L)?\'([^\\\n]|(\\(.|\n)))*?\'' t.lexer.lineno += t.value.count("\n") return t # Comment def t_COMMENT1(t): r'(/\*(.|\n)*?\*/)' ncr = t.value.count("\n") t.lexer.lineno += ncr # replace with one space or a number of '\n' t.type = 'WS' t.value = '\n' * ncr if ncr else ' ' return t # Line comment def t_COMMENT2(t): r'(//.*?(\n|$))' # replace with '/n' t.type = 'WS' t.value = '\n' return t # error handling def t_error(t): t.type = t.value[0] t.value = t.value[0] t.lexer.skip(1) print("error token encountered", t) return t # rules for parsing shared memory and sync thread shared_memory = {"symbol": [], "dtype": [], "size": []} arguments = {"symbol": [], "dtype": []} signature = [] def p_start(p): '''start : signature | shared ''' def p_signature(p): 'signature : GLOBAL VOID ID \'(\' parameters \')\'' signature.append(p[3]) def p_parameters(p): '''parameters : parameter | parameters \',\' parameter ''' def p_parameter(p): '''parameter : type ID | type QUALIFIER ID | QUALIFIER type ID ''' if (str(p.slice[1]) == "type"): arguments["dtype"].append(p[1]) else: arguments["dtype"].append(p[2]) arguments["symbol"].append(p[len(p) - 1]) def p_type(p): '''type : TYPE | TYPE \'*\' ''' # not all cases are covered like: const type * const p[0] = ''.join(p[1:]) def p_shared(p): 'shared : SHARED TYPE ID \'[\' INTEGER \']\' \';\' ' shared_memory["symbol"].append(p[3]) shared_memory["dtype"].append(p[2]) shared_memory["size"].append(int(p[5])) def p_error(p): if p: # Just discard the token and tell the parser it's okay. parser.errok() else: print("Syntax error at EOF") lexer = lex.lex() parser = yacc.yacc() def clear_global(): shared_memory["symbol"].clear() shared_memory["dtype"].clear() shared_memory["size"].clear() arguments["symbol"].clear() arguments["dtype"].clear() signature.clear() re_func = re.compile( r'(.*__global__\s+void\s+[A-Za-z_]\w*\s*\([^{]*\))\s*({.+\Z)', re.DOTALL) re_sharedmem = re.compile( r'__shared__\s+[A-Za-z_]\w*\s+[A-Za-z_]\w*\s*\[\s*\d+\s*\]\s*;') re_syncthread = re.compile(r'__syncthreads\s*\(\s*\)\s*;') print_sync = r''' if (blockIdx.x == 0 && blockIdx.y == 0&& blockIdx.z == 0&& threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) { printf("Amount of syncthreads logged: %d\n", SYNC_COUNT); } ''' def parse(code, parameters): clear_global() func_sig, func_body = re_func.match(code).groups() new_code = sync_code = func_body parser.parse(func_sig) for (i, dtype) in enumerate(parameters["dtype"]): assert dtype == arguments["dtype"][i] if parameters["symbol"][i] != arguments["symbol"][i]: new_code = "{} {} = {};\n".format( dtype, arguments["symbol"][i], parameters["symbol"][i]) + new_code for m in re_sharedmem.finditer(code): new_code = new_code.replace(m.group(0), "") parser.parse(m.group(0)) for m in re_syncthread.finditer(code): sync_code = sync_code.replace(m.group(0), "__LOGSYNC()\n") sync_code = "#define __LOGSYNC() {__syncthreads(); SYNC_COUNT++;}\n" + \ func_sig + "{\n" + "int SYNC_COUNT = 0;\n" + \ sync_code + print_sync + "}" return func_body, shared_memory, new_code, sync_code, signature[-1]
2,450
350
<gh_stars>100-1000 ''' This code is written by bidongqinxian ''' class Solution: def GetUglyNumber_Solution(self, index): # write code here if index == 0: return False array = [1,2,3,5] while len(array)-1 < index: array = self.GetUglyNumber(array) array = sorted(array) return array[index-1] def GetUglyNumber(self, array): list2 = [] for i in range(1,len(array)): for j in range(1,len(array)): new_num = array[i] * array[j] list2.append(new_num) array = array + list2 array = list(set(array)) return array
347
30,023
"""Describe logbook events.""" from homeassistant.components.logbook.const import ( LOGBOOK_ENTRY_ENTITY_ID, LOGBOOK_ENTRY_MESSAGE, LOGBOOK_ENTRY_NAME, ) from homeassistant.core import callback from .const import DOMAIN, EVENT_ALEXA_SMART_HOME @callback def async_describe_events(hass, async_describe_event): """Describe logbook events.""" @callback def async_describe_logbook_event(event): """Describe a logbook event.""" data = event.data if entity_id := data["request"].get("entity_id"): state = hass.states.get(entity_id) name = state.name if state else entity_id message = f"sent command {data['request']['namespace']}/{data['request']['name']} for {name}" else: message = ( f"sent command {data['request']['namespace']}/{data['request']['name']}" ) return { LOGBOOK_ENTRY_NAME: "Amazon Alexa", LOGBOOK_ENTRY_MESSAGE: message, LOGBOOK_ENTRY_ENTITY_ID: entity_id, } async_describe_event(DOMAIN, EVENT_ALEXA_SMART_HOME, async_describe_logbook_event)
517
460
<filename>trunk/win/Source/Includes/QtIncludes/src/network/access/qnetworkaccesshttpbackend_p.h /**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (<EMAIL>) ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QNETWORKACCESSHTTPBACKEND_P_H #define QNETWORKACCESSHTTPBACKEND_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of the Network Access API. This header file may change from // version to version without notice, or even be removed. // // We mean it. // #include "qhttpnetworkconnection_p.h" #include "qnetworkaccessbackend_p.h" #include "qnetworkrequest.h" #include "qnetworkreply.h" #include "qabstractsocket.h" #include "QtCore/qpointer.h" #include "QtCore/qdatetime.h" #ifndef QT_NO_HTTP QT_BEGIN_NAMESPACE class QNetworkAccessCachedHttpConnection; class QNetworkAccessHttpBackendIODevice; class QNetworkAccessHttpBackend: public QNetworkAccessBackend { Q_OBJECT public: QNetworkAccessHttpBackend(); virtual ~QNetworkAccessHttpBackend(); virtual void open(); virtual void closeDownstreamChannel(); virtual void downstreamReadyWrite(); virtual void setDownstreamLimited(bool b); virtual void copyFinished(QIODevice *); #ifndef QT_NO_OPENSSL virtual void ignoreSslErrors(); virtual void ignoreSslErrors(const QList<QSslError> &errors); virtual void fetchSslConfiguration(QSslConfiguration &configuration) const; virtual void setSslConfiguration(const QSslConfiguration &configuration); #endif QNetworkCacheMetaData fetchCacheMetaData(const QNetworkCacheMetaData &metaData) const; // we return true since HTTP needs to send PUT/POST data again after having authenticated bool needsResetableUploadData() { return true; } bool canResume() const; void setResumeOffset(quint64 offset); virtual bool processRequestSynchronously(); private slots: void replyReadyRead(); void replyFinished(); void replyHeaderChanged(); void httpAuthenticationRequired(const QHttpNetworkRequest &request, QAuthenticator *auth); void httpCacheCredentials(const QHttpNetworkRequest &request, QAuthenticator *auth); void httpError(QNetworkReply::NetworkError error, const QString &errorString); bool sendCacheContents(const QNetworkCacheMetaData &metaData); void finished(); // override private: QHttpNetworkReply *httpReply; QPointer<QHttpNetworkConnection> http; QByteArray cacheKey; QNetworkAccessBackendUploadIODevice *uploadDevice; #ifndef QT_NO_OPENSSL QSslConfiguration *pendingSslConfiguration; bool pendingIgnoreAllSslErrors; QList<QSslError> pendingIgnoreSslErrorsList; #endif quint64 resumeOffset; void disconnectFromHttp(); void validateCache(QHttpNetworkRequest &httpRequest, bool &loadedFromCache); void invalidateCache(); void postRequest(); void readFromHttp(); void checkForRedirect(const int statusCode); }; class QNetworkAccessHttpBackendFactory : public QNetworkAccessBackendFactory { public: virtual QNetworkAccessBackend *create(QNetworkAccessManager::Operation op, const QNetworkRequest &request) const; }; QT_END_NAMESPACE #endif // QT_NO_HTTP #endif
1,622
3,508
<filename>src/main/java/com/fishercoder/solutions/_1991.java package com.fishercoder.solutions; public class _1991 { public static class Solution1 { public int findMiddleIndex(int[] nums) { int middleIndex = -1; long sum = 0; for (int i = 0; i < nums.length; i++) { sum += nums[i]; } long leftSum = 0; for (int i = 0; i < nums.length; i++) { sum -= nums[i]; if (i > 0) { leftSum += nums[i - 1]; } if (sum == leftSum) { return i; } } return middleIndex; } } }
422
1,178
/* * svc_auth.h, Service side of rpc authentication. * * Copyright (c) 2010, Oracle America, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the "Oracle America, 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _RPC_SVC_AUTH_H #define _RPC_SVC_AUTH_H 1 #include <features.h> #include <rpc/svc.h> __BEGIN_DECLS /* * Server side authenticator */ extern enum auth_stat _authenticate (struct svc_req *__rqst, struct rpc_msg *__msg) __THROW; __END_DECLS #endif /* rpc/svc_auth.h */
652
1,540
<reponame>punamsapkale/testng package test.expectedexceptions.issue2235; import org.testng.annotations.Test; public class ExampleTestCase { @Test(timeOut = 1000, expectedExceptions = IllegalArgumentException.class) public void testMethod() { throw new IllegalArgumentException("foo"); } }
94
506
// https://open.kattis.com/problems/trainpassengers #include <iostream> using namespace std; int main() { int k, n, s = 0; cin >> k >> n; bool ok = true; while (n-- && ok) { int a, b, c; cin >> a >> b >> c; if (a > s) ok = false; s -= a; if (s + b > k) ok = false; s += b; if (c && s < k) ok = false; if (!n && (c || s)) ok = false; } cout << (ok ? "possible\n" : "impossible\n"); }
194
1,778
<gh_stars>1000+ /* * Copyright (c) 2014-2018 Cesanta Software Limited * All rights reserved * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FreeRTOS.h" #include "queue.h" #include "task.h" #include "common/cs_dbg.h" #include "arm_exc.h" #include "mgos_core_dump.h" #include "mgos_freertos.h" #include "mgos_gpio.h" #include "mgos_system.h" #include "stm32_sdk_hal.h" #include "stm32_system.h" HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { /* Override the HAL function but do nothing, FreeRTOS will take care of it. */ (void) TickPriority; return 0; } static void stm32_set_nocache(void) { #if STM32_NOCACHE_SIZE > 0 extern uint8_t __nocache_start__, __nocache_end__; /* Linker symbols */ int num_regions = (MPU->TYPE & MPU_TYPE_DREGION_Msk) >> MPU_TYPE_DREGION_Pos; int prot_size = (&__nocache_end__ - &__nocache_start__); if (prot_size == 0) return; if (num_regions == 0) { LOG(LL_ERROR, ("Memory protection is requested but not available")); return; } if (prot_size > STM32_NOCACHE_SIZE) { LOG(LL_ERROR, ("Max size of protected region is %d", STM32_NOCACHE_SIZE)); return; } /* Protected regions must be size-aligned. */ if ((((uintptr_t) &__nocache_start__) & (STM32_NOCACHE_SIZE - 1)) != 0) { LOG(LL_ERROR, ("Protected region must be %d-aligned", STM32_NOCACHE_SIZE)); return; } MPU_Region_InitTypeDef MPU_InitStruct; HAL_MPU_Disable(); MPU_InitStruct.Enable = MPU_REGION_ENABLE; MPU_InitStruct.BaseAddress = (uintptr_t) &__nocache_start__; // TODO: other sizes? #if STM32_NOCACHE_SIZE != 0x400 #error STM32_NOCACHE_SIZE must be 1K #endif MPU_InitStruct.Size = MPU_REGION_SIZE_1KB; MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS; MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE; MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE; MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE; MPU_InitStruct.Number = MPU_REGION_NUMBER0; MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0; MPU_InitStruct.SubRegionDisable = 0x00; MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE; HAL_MPU_ConfigRegion(&MPU_InitStruct); HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT); LOG(LL_DEBUG, ("Marked [%p, %p) as no-cache", &__nocache_start__, &__nocache_end__)); #endif // STM32_NOCACHE_SIZE > 0 } enum mgos_init_result mgos_freertos_pre_init() { stm32_set_nocache(); return MGOS_INIT_OK; } uint32_t SystemCoreClockMHZ = 0; uint32_t mgos_bitbang_n100_cal = 0; extern void mgos_nsleep100_cal(void); void SystemCoreClockUpdate(void) { uint32_t presc = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos)]; SystemCoreClock = HAL_RCC_GetSysClockFreq() >> presc; SystemCoreClockMHZ = SystemCoreClock / 1000000; mgos_nsleep100_cal(); } #ifndef MGOS_BOOT_BUILD static void stm32_dump_sram(void) { mgos_cd_write_section("SRAM", (void *) STM32_SRAM_BASE_ADDR, STM32_SRAM_SIZE); } #if STM32_SRAM2_SIZE > 0 static void stm32_dump_sram2(void) { mgos_cd_write_section("SRAM2", (void *) STM32_SRAM2_BASE_ADDR, STM32_SRAM2_SIZE); } #endif extern void __libc_init_array(void); int main(void) { stm32_setup_int_vectors(); if ((WWDG->CR & WWDG_CR_WDGA) != 0) { // WWDG was started by boot loader and is already ticking, // we have to reconfigure the int handler *now*. mgos_wdt_enable(); mgos_wdt_set_timeout(10 /* seconds */); } stm32_system_init(); __libc_init_array(); stm32_clock_config(); SystemCoreClockUpdate(); if ((WWDG->CR & WWDG_CR_WDGA) != 0) { // APB clock has most likely changed, recalculate the WDT timings. mgos_wdt_set_timeout(10 /* seconds */); } mgos_cd_register_section_writer(arm_exc_dump_regs); mgos_cd_register_section_writer(stm32_dump_sram); #if STM32_SRAM2_SIZE > 0 mgos_cd_register_section_writer(stm32_dump_sram2); #endif HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4); HAL_NVIC_SetPriority(MemoryManagement_IRQn, 0, 0); HAL_NVIC_SetPriority(BusFault_IRQn, 0, 0); HAL_NVIC_SetPriority(UsageFault_IRQn, 0, 0); HAL_NVIC_SetPriority(DebugMonitor_IRQn, 0, 0); stm32_set_int_handler(SVCall_IRQn, vPortSVCHandler); stm32_set_int_handler(PendSV_IRQn, xPortPendSVHandler); stm32_set_int_handler(SysTick_IRQn, xPortSysTickHandler); mgos_freertos_run_mgos_task(true /* start_scheduler */); /* not reached */ abort(); } #endif // MGOS_BOOT_BUILD void assert_failed(uint8_t *file, uint32_t line) { fprintf(stderr, "assert_failed @ %s:%d\r\n", file, (int) line); abort(); }
2,097
6,717
/* * Copyright (c) 2011, The Iconfactory. All rights reserved. * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of The Iconfactory 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 ICONFACTORY BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #import "UIKitExport.h" #import <Foundation/Foundation.h> #import <CoreGraphics/CGGeometry.h> typedef NS_ENUM(NSInteger, UIForceTouchCapability) { UIForceTouchCapabilityUnknown = 0, UIForceTouchCapabilityUnavailable = 1, UIForceTouchCapabilityAvailable = 2, }; typedef NS_ENUM(NSInteger, UITouchType) { UITouchTypeDirect, UITouchTypeIndirect, UITouchTypeStylus, }; typedef NS_OPTIONS(NSInteger, UITouchProperties) { UITouchPropertyForce = (1UL << 0), UITouchPropertyAzimuth = (1UL << 1), UITouchPropertyAltitude = (1UL << 2), UITouchPropertyLocation = (1UL << 3), }; typedef NS_ENUM(NSInteger, UITouchPhase) { UITouchPhaseBegan, UITouchPhaseMoved, UITouchPhaseStationary, UITouchPhaseEnded, UITouchPhaseCancelled, }; @class UIView, UIWindow, SKNode; UIKIT_EXPORT_CLASS @interface UITouch : NSObject - (CGFloat)azimuthAngleInView:(UIView*)view STUB_METHOD; - (CGPoint)locationInNode:(SKNode*)node STUB_METHOD; - (CGPoint)locationInView:(UIView*)inView; - (CGPoint)preciseLocationInView:(UIView*)view STUB_METHOD; - (CGPoint)preciseLocationInView:(UIView*)view STUB_METHOD; - (CGPoint)precisePreviousLocationInView:(UIView*)view STUB_METHOD; - (CGPoint)precisePreviousLocationInView:(UIView*)view STUB_METHOD; - (CGPoint)previousLocationInNode:(SKNode*)node STUB_METHOD; - (CGPoint)previousLocationInView:(UIView*)inView; - (CGVector)azimuthUnitVectorInView:(UIView*)view STUB_METHOD; @property (nonatomic, readonly) NSTimeInterval timestamp; @property (nonatomic, readonly) NSUInteger tapCount; @property (nonatomic, readonly) UITouchPhase phase; @property (nonatomic, readonly, copy) NSArray* gestureRecognizers STUB_PROPERTY; @property (nonatomic, readonly, retain) UIView* view; @property (nonatomic, readonly, retain) UIWindow* window; @property (readonly, nonatomic) CGFloat altitudeAngle STUB_PROPERTY; @property (readonly, nonatomic) CGFloat force STUB_PROPERTY; @property (readonly, nonatomic) CGFloat majorRadius STUB_PROPERTY; @property (readonly, nonatomic) CGFloat majorRadiusTolerance STUB_PROPERTY; @property (readonly, nonatomic) CGFloat maximumPossibleForce STUB_PROPERTY; @property (readonly, nonatomic) NSNumber* estimationUpdateIndex STUB_PROPERTY; @property (readonly, nonatomic) UITouchProperties estimatedProperties STUB_PROPERTY; @property (readonly, nonatomic) UITouchProperties estimatedPropertiesExpectingUpdates STUB_PROPERTY; @property (readonly, nonatomic) UITouchType type STUB_PROPERTY; @end
1,355
701
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-present <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef _OgreVoxelizedMeshCache_H_ #define _OgreVoxelizedMeshCache_H_ #include "OgreVctVoxelizerSourceBase.h" #include "OgreIdString.h" #include "OgreResourceTransition.h" #include <ogrestd/map.h> #include "OgreHeaderPrefix.h" namespace Ogre { /** @class VoxelizedMeshCache Uses a VctVoxelizer to convert a single mesh made up of triangles into a voxel 3D texture representation. This cache can be shared by multiple users (e.g. VctImageVoxelizer) */ class _OgreHlmsPbsExport VoxelizedMeshCache : IdObject { public: struct VoxelizedMesh { uint64 hash[2]; String meshName; TextureGpu *albedoVox; TextureGpu *normalVox; TextureGpu *emissiveVox; }; protected: typedef map<IdString, VoxelizedMesh>::type MeshCacheMap; uint32 mMeshWidth; uint32 mMeshHeight; uint32 mMeshDepth; uint32 mMeshMaxWidth; uint32 mMeshMaxHeight; uint32 mMeshMaxDepth; Ogre::Vector3 mMeshDimensionPerPixel; MeshCacheMap mMeshes; /// Many meshes have no emissive at all, thus just use a 1x1x1 emissive /// texture for all those meshes instead of wasting ton of RAM. TextureGpu *mBlankEmissive; public: /// The number of texture units GL can handle may exceed the hard limit in /// ShaderParams::ManualParam::dataBytes so we need to use EX and store /// the data here FastArray<int32> mGlslTexUnits; public: VoxelizedMeshCache( IdType id, TextureGpuManager *textureManager ); ~VoxelizedMeshCache(); /** @brief addMeshToCache Checks if the mesh is already cached. If it's not, it gets voxelized. @param mesh Mesh to voxelize @param sceneManager We need it to temporarily create an Item @param refItem Reference Item in case we need to copy its materials. Can be nullptr @returns Entry to VoxelizedMesh in cache */ const VoxelizedMesh &addMeshToCache( const MeshPtr &mesh, SceneManager *sceneManager, RenderSystem *renderSystem, HlmsManager *hlmsManager, const Item *refItem ); /** @brief setCacheResolution When building the mesh cache, meshes must be voxelized at some arbitrary resolution This function lets you specify how many voxels per volume in units. e.g. if you call @code imageVoxelizer->setCacheResolution( 32u, 32u, 32u, maxWidth, maxHeight, maxDepth Ogre::Vector3( 1.0f, 1.0f, 1.0f ) ); @endcode And the mesh AABB is 2x2x2 in units, then we will voxelize at 64x64x64 voxels (unless this resolution exceeds maxWidth/maxHeight/maxDepth) @remarks This setting can be changed individually for each mesh. Call it as often as you need. e.g. a literal cube mesh only needs 1x1x1 of resolution. @param width The width in pixels per dimension.x in units i.e. the width / dimension.x @param height The height in pixels per dimension.y in units i.e. the height / dimension.y @param depth The height in pixels per dimension.z in units i.e. the depth / dimension.z @param maxWidth Width can never exceed this value @param maxHeight Height can never exceed this value @param maxDepth Depth can never exceed this value @param dimension Units to cover (see previous parameters) */ void setCacheResolution( uint32 width, uint32 height, uint32 depth, uint32 maxWidth, uint32 maxHeight, uint32 maxDepth, const Ogre::Vector3 &dimension ); TextureGpu *getBlankEmissive() { return mBlankEmissive; } }; } // namespace Ogre #include "OgreHeaderSuffix.h" #endif
2,213
1,731
from setuptools import setup setup( name="demo-extras", version="0.0.1", description="test demo", py_modules=["demo"], install_requires=[], extras_require={"extra1": ["requests[security]"], "extra2": ["requests[socks]"]}, )
99
324
/* * 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.jclouds.ec2.features; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.util.Set; import java.util.SortedSet; import org.jclouds.aws.AWSResponseException; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.ec2.EC2Api; import org.jclouds.ec2.domain.KeyPair; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Sets; /** * Tests behavior of {@code KeyPairApi} */ @Test(groups = "live", singleThreaded = true, testName = "KeyPairApiLiveTest") public class KeyPairApiLiveTest extends BaseComputeServiceContextLiveTest { public KeyPairApiLiveTest() { provider = "ec2"; } private EC2Api ec2Api; private KeyPairApi client; @Override @BeforeClass(groups = { "integration", "live" }) public void setupContext() { super.setupContext(); ec2Api = view.unwrapApi(EC2Api.class); client = ec2Api.getKeyPairApi().get(); } @Test void testDescribeKeyPairs() { for (String region : ec2Api.getConfiguredRegions()) { SortedSet<KeyPair> allResults = Sets.newTreeSet(client.describeKeyPairsInRegion(region)); assertNotNull(allResults); if (!allResults.isEmpty()) { KeyPair pair = allResults.last(); SortedSet<KeyPair> result = Sets.newTreeSet(client.describeKeyPairsInRegion(region, pair.getKeyName())); assertNotNull(result); KeyPair compare = result.last(); assertEquals(compare, pair); } } } @Test void testDescribeKeyPairsWithFilter() { for (String region : ec2Api.getConfiguredRegions()) { SortedSet<KeyPair> allResults = Sets.newTreeSet(client.describeKeyPairsInRegion(region)); assertNotNull(allResults); if (!allResults.isEmpty()) { KeyPair pair = allResults.last(); SortedSet<KeyPair> result = Sets.newTreeSet(client.describeKeyPairsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("key-name", pair.getKeyName()).build())); assertNotNull(result); KeyPair compare = result.last(); assertEquals(compare, pair); } } } @Test(expectedExceptions = AWSResponseException.class) void testDescribeKeyPairsWithInvalidFilter() { for (String region : ec2Api.getConfiguredRegions()) { SortedSet<KeyPair> allResults = Sets.newTreeSet(client.describeKeyPairsInRegion(region)); assertNotNull(allResults); if (!allResults.isEmpty()) { KeyPair pair = allResults.last(); client.describeKeyPairsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter", pair.getKeyName()).build()); } } } public static final String PREFIX = System.getProperty("user.name") + "-ec2"; @Test void testCreateKeyPair() { String keyName = PREFIX + "1"; try { client.deleteKeyPairInRegion(null, keyName); } catch (Exception e) { } client.deleteKeyPairInRegion(null, keyName); KeyPair result = client.createKeyPairInRegion(null, keyName); assertNotNull(result); assertNotNull(result.getKeyMaterial()); assertNotNull(result.getSha1OfPrivateKey()); assertEquals(result.getKeyName(), keyName); Set<KeyPair> twoResults = Sets.newLinkedHashSet(client.describeKeyPairsInRegion(null, keyName)); assertNotNull(twoResults); assertEquals(twoResults.size(), 1); KeyPair listPair = twoResults.iterator().next(); assertEquals(listPair.getKeyName(), result.getKeyName()); assertEquals(listPair.getSha1OfPrivateKey(), result.getSha1OfPrivateKey()); } @AfterClass(groups = { "integration", "live" }) @Override protected void tearDownContext() { String keyName = PREFIX + "1"; try { client.deleteKeyPairInRegion(null, keyName); } catch (Exception e) { } super.tearDownContext(); } }
1,966
1,040
<gh_stars>1000+ //----------------------------------------------------------------------------- // File: GameProc.h // // Desc: Game processing routines // // Copyright (C) 1995-1999 Microsoft Corporation. All Rights Reserved. //----------------------------------------------------------------------------- #define IDIRECTPLAY2_OR_GREATER #include <ddraw.h> #include <dplay.h> #include <dsound.h> // align on single byte boundaries // this is a stop-gap measure until the structures can be re-arranged. #pragma pack(1) #define MAX_SHIP_X (MAX_SCREEN_X - 32) #define MAX_SHIP_Y (MAX_SCREEN_Y - 32) #define MAX_SHIP_FRAME 40 #define MAX_BULLET_X (MAX_SCREEN_X - 3) #define MAX_BULLET_Y (MAX_SCREEN_Y - 3) #define MAX_BULLET_FRAME 400 #define NUM_SHIP_TYPES 4 #define DEF_SHOW_DELAY (2000) #define MAX_BUFFER_SIZE 256 #define UPDATE_INTERVAL 40 // interval between position updates in milliseconds (25 FPS) #define SYNC_INTERVAL 1000 // synchronize once every second #define HIDE_TIMEOUT 5000 // time for which a ship is disabled after a hit // Keyboard commands #define KEY_STOP 0x00000001l #define KEY_DOWN 0x00000002l #define KEY_LEFT 0x00000004l #define KEY_RIGHT 0x00000008l #define KEY_UP 0x00000010l #define KEY_FIRE 0x00000020l #define KEY_ENGINEOFF 0x00000040l // Offsets for the bullet bitmap #define BULLET_X 304 #define BULLET_Y 0 struct FRAG { double dPosX; double dPosY; LPDIRECTDRAWSURFACE pdds; RECT src; double dVelX; double dVelY; BOOL valid; }; struct SHIP { double dPosX, dPosY; // ship x and y position double dBulletPosX, dBulletPosY; // bullet x and y position DWORD dwBulletFrame; // bullet frame char cFrame; // current ship frame BYTE byType; // ship type BOOL bEnable; // is this ship active? BOOL bBulletEnable; // Is there an active bullet? double dVelX, dVelY; // ship x and y velocity (pixels/millisecond) double dBulletVelX, dBulletVelY; // bullet x and y velocity (pixels/millisecond) DWORD dwScore; // current score DWORD dwLastTick; // most recent time stamp BOOL bIgnore; // flag used to synchronize ship explosions int iCountDown; // enable time-out DWORD dwFrameCount; // number of frames since beginning of time // DSound members DWORD dwKeys; // the keyboard state BOOL bEngineRunning; // These BOOLs keep track of the ship's BOOL bMoving; // last condition so we can play sounds BOOL bBounced; // when they change BOOL bBlockHit; BOOL bDeath; BOOL bFiring; }; struct BLOCKS { BYTE bits[30][5]; }; //----------------------------------------------------------------------------- // communication packet structures //----------------------------------------------------------------------------- #define MSG_HOST 0x11 // message containing field layout, sent by host #define MSG_BLOCKHIT 0x22 // block hit message #define MSG_SHIPHIT 0x33 // ship hit message #define MSG_ADDBLOCK 0x44 // add block message #define MSG_CONTROL 0x55 // game keys message #define MSG_SYNC 0x66 // synchronization message containing the rendezvous location struct GENERICMSG { BYTE byType; }; struct OLDHOSTMSG { BYTE byType; BLOCKS Blocks; }; struct HOSTMSG { BYTE byType; BLOCKS Blocks; int usedShipTypes[NUM_SHIP_TYPES]; }; struct BLOCKHITMSG { BYTE byType; BYTE byRow; BYTE byCol; BYTE byMask; }; struct SHIPHITMSG { BYTE byType; DPID Id; }; struct ADDBLOCKMSG { BYTE byType; BYTE byX; BYTE byY; }; struct CONTROLMSG { BYTE byType; BYTE byState; }; struct SYNCMSG { BYTE byType; BYTE byShipType; // this is needed only when sends are unreliable char cFrame; double dPosX; double dPosY; }; //----------------------------------------------------------------------------- // Prototypes //----------------------------------------------------------------------------- VOID LaunchGame(); VOID ExitGame(); HRESULT InitOurShip(); HRESULT InitLocalSoundData(); BOOL WINAPI SetPlayerLocalSoundDataCB( DPID dpId, DWORD dwPlayerType, LPCDPNAME pName, DWORD dwFlags, VOID* pContext ); VOID ReleaseLocalData(); VOID ReleasePlayerLocalSoundData( SHIP* pShip ); BOOL WINAPI ReleasePlayerLocalDataCB( DPID dpId, DWORD dwPlayerType, LPCDPNAME pName, DWORD dwFlags, VOID* pContext ); VOID UpdateState( SHIP* pShip, DWORD dwControls ); VOID SendSync( SHIP* pShip ); VOID UpdateDisplayStatus( SHIP* pShip ); VOID UpdatePosition( DPID dpId, SHIP* ship ); BOOL IsHit( int x, int y ); VOID InitField(); BOOL setBlock( int x, int y ); VOID AddFrag( SHIP* pShip, int offX, int offY ); VOID UpdateFragment( int i ); VOID DestroyShip( SHIP* pShip ); VOID DestroyGame(); BOOL UpdateFrame(); VOID ProcessSoundFlags( SHIP* pShip ); BOOL WINAPI RenderPlayerCB( DPID dpId, DWORD dwPlayerType, LPCDPNAME pName, DWORD dwFlags, VOID* pContext ); BOOL DrawScreen(); BOOL DrawScore(); VOID DrawShip( SHIP* pShip ); VOID DrawBlock( int x, int y ); VOID DrawBullet( SHIP* pShip ); VOID DrawFragments(); VOID DisplayFrameRate(); VOID GetConnection(); HRESULT ReceiveMessages(); VOID DoSystemMessage( DPMSG_GENERIC* pMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo ); VOID DoApplicationMessage( GENERICMSG* pMsg, DWORD dwMsgSize, DPID idFrom, DPID idTo ); VOID SendGameMessage( GENERICMSG* pMsg, DPID idTo ); VOID CleanupComm(); HRESULT InitializeGameSounds(); VOID CleanupGameSounds(); // restore default alignment #pragma pack()
3,116
775
<reponame>badoo/Chateau<gh_stars>100-1000 package com.badoo.chateau.example.ui.conversations.list; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.badoo.barf.mvp.PresenterFactory; import com.badoo.chateau.core.usecases.conversations.DeleteConversations; import com.badoo.chateau.core.usecases.conversations.LoadConversations; import com.badoo.chateau.core.usecases.conversations.SubscribeToConversationUpdates; import com.badoo.chateau.example.R; import com.badoo.chateau.example.data.model.ExampleConversation; import com.badoo.chateau.example.ui.BaseActivity; import com.badoo.chateau.example.ui.ExampleConfiguration; import com.badoo.chateau.example.ui.Injector; import com.badoo.chateau.example.ui.chat.ChatActivity; import com.badoo.chateau.example.ui.conversations.create.selectusers.SelectUserActivity; import com.badoo.chateau.example.ui.conversations.list.CreateConversationPresenter.CreateConversationFlowListener; import com.badoo.chateau.example.ui.conversations.list.CreateConversationPresenter.CreateConversationView; import com.badoo.chateau.extras.ViewFinder; import com.badoo.chateau.ui.conversations.list.BaseConversationListPresenter; import com.badoo.chateau.ui.conversations.list.ConversationListPresenter; import com.badoo.chateau.ui.conversations.list.ConversationListPresenter.ConversationListFlowListener; import com.badoo.chateau.ui.conversations.list.ConversationListPresenter.ConversationListView; public class ConversationListActivity extends BaseActivity implements ConversationListFlowListener<ExampleConversation>, CreateConversationFlowListener { public static class DefaultConfiguration extends ExampleConfiguration<ConversationListActivity> { @Override public void inject(ConversationListActivity target) { createConversationListView(target); createCreateConversationView(target); } protected ExampleConversationListView createConversationListView(@NonNull ConversationListActivity activity) { final PresenterFactory<ConversationListView<ExampleConversation>, ConversationListPresenter<ExampleConversation>> presenterFactory = new PresenterFactory<>(v -> createConversationListPresenter(v, activity)); final ExampleConversationListView view = new ExampleConversationListView(ViewFinder.from(activity), activity.getToolbar(), presenterFactory); activity.registerPresenter(presenterFactory.get()); return view; } protected ConversationListPresenter<ExampleConversation> createConversationListPresenter(@NonNull ConversationListView<ExampleConversation> view, @NonNull ConversationListFlowListener<ExampleConversation> flowListener) { final LoadConversations<ExampleConversation> loadConversations = new LoadConversations<>(getConversationRepo()); final SubscribeToConversationUpdates subscribeToConversationUpdates = new SubscribeToConversationUpdates(getConversationRepo()); final DeleteConversations deleteConversations = new DeleteConversations(getConversationRepo()); return new BaseConversationListPresenter<>(view, flowListener, loadConversations, subscribeToConversationUpdates, deleteConversations); } protected CreateConversationView createCreateConversationView(@NonNull ConversationListActivity activity) { return new CreateConversationViewImpl(ViewFinder.from(activity), new PresenterFactory<>(v -> createCreateConversationPresenter(v, activity))); } protected CreateConversationPresenter createCreateConversationPresenter(@NonNull CreateConversationView view, @NonNull CreateConversationFlowListener flowListener) { return new CreateConversationPresenterImpl(flowListener); } } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_conversations); setTitle(R.string.title_activity_conversations); Injector.inject(this); } @Override public void requestOpenConversation(@NonNull ExampleConversation conversation) { final Intent intent = ChatActivity.create(this, conversation.getId(), conversation.getName()); startActivity(intent); } @Override public void requestCreateNewConversation() { final Intent intent = new Intent(this, SelectUserActivity.class); startActivity(intent); } }
1,507
8,649
package org.hswebframework.web.context; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; @SuppressWarnings("all") class MapContext implements Context { private Map<String, Object> map = new ConcurrentHashMap<>(); @Override public <T> Optional<T> get(ContextKey<T> key) { return Optional.ofNullable(map.get(key.getKey())) .map(v -> ((T) v)); } @Override public <T> T getOrDefault(ContextKey<T> key, Supplier<? extends T> defaultValue) { return (T) map.computeIfAbsent(key.getKey(), __ -> defaultValue.get()); } @Override public <T> void put(ContextKey<T> key, T value) { map.put(key.getKey(), value); } @Override public <T> T remove(ContextKey<T> key) { return (T)map.remove(key); } @Override public Map<String, Object> getAll() { return new HashMap<>(map); } @Override public void clean() { map.clear(); } }
436
1,742
/** @file expairseq.cpp * * Implementation of sequences of expression pairs. */ /* * GiNaC Copyright (C) 1999-2008 Johannes Gutenberg University Mainz, Germany * (C) 2015-2018 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "expairseq.h" #include "lst.h" #include "add.h" #include "mul.h" #include "power.h" #include "relational.h" #include "wildcard.h" #include "archive.h" #include "operators.h" #include "utils.h" #include "infinity.h" #include "compiler.h" #include "cmatcher.h" #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <stdexcept> #if EXPAIRSEQ_USE_HASHTAB #include <cmath> #endif // EXPAIRSEQ_USE_HASHTAB namespace GiNaC { GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(expairseq, basic, print_func<print_context>(&expairseq::do_print). print_func<print_tree>(&expairseq::do_print_tree)) ////////// // helper classes ////////// class epp_is_less { public: bool operator()(const epp &lh, const epp &rh) const { return (*lh).is_less(*rh); } }; ////////// // default constructor ////////// // public expairseq::expairseq() : inherited(&expairseq::tinfo_static) #if EXPAIRSEQ_USE_HASHTAB , hashtabsize(0) #endif // EXPAIRSEQ_USE_HASHTAB {} // protected #if 0 /** For use by copy ctor and assignment operator. */ void expairseq::copy(const expairseq &other) { seq = other.seq; overall_coeff = other.overall_coeff; #if EXPAIRSEQ_USE_HASHTAB // copy hashtab hashtabsize = other.hashtabsize; if (hashtabsize!=0) { hashmask = other.hashmask; hashtab.resize(hashtabsize); epvector::const_iterator osb = other.seq.begin(); for (unsigned i=0; i<hashtabsize; ++i) { hashtab[i].clear(); for (epplist::const_iterator cit=other.hashtab[i].begin(); cit!=other.hashtab[i].end(); ++cit) { hashtab[i].push_back(seq.begin()+((*cit)-osb)); } } } else { hashtab.clear(); } #endif // EXPAIRSEQ_USE_HASHTAB } #endif ////////// // other constructors ////////// expairseq::expairseq(const ex &lh, const ex &rh) : inherited(&expairseq::tinfo_static) { construct_from_2_ex(lh,rh); GINAC_ASSERT(is_canonical()); } expairseq::expairseq(const exvector &v) : inherited(&expairseq::tinfo_static) { construct_from_exvector(v); GINAC_ASSERT(is_canonical()); } expairseq::expairseq(const epvector &v, const numeric& oc, bool do_index_renaming) : inherited(&expairseq::tinfo_static), overall_coeff(oc) { construct_from_epvector(v, do_index_renaming); GINAC_ASSERT(is_canonical()); } expairseq::expairseq(std::unique_ptr<epvector> vp, const numeric& oc, bool do_index_renaming) : inherited(&expairseq::tinfo_static), overall_coeff(oc) { GINAC_ASSERT(vp.get()!=0); construct_from_epvector(*vp, do_index_renaming); GINAC_ASSERT(is_canonical()); } ////////// // archiving ////////// expairseq::expairseq(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst) #if EXPAIRSEQ_USE_HASHTAB , hashtabsize(0) #endif { auto first = n.find_first("rest"); auto last = n.find_last("coeff"); ++last; seq.reserve((last-first)/2); for (auto loc = first; loc < last;) { ex lrest; ex lcoeff; n.find_ex_by_loc(loc++, lrest, sym_lst); n.find_ex_by_loc(loc++, lcoeff, sym_lst); seq.emplace_back(lrest, lcoeff); } ex oc; n.find_ex("overall_coeff", oc, sym_lst); overall_coeff = ex_to<numeric>(oc); canonicalize(); GINAC_ASSERT(is_canonical()); } void expairseq::archive(archive_node &n) const { inherited::archive(n); for (const auto & elem : seq) { n.add_ex("rest", elem.rest); n.add_ex("coeff", elem.coeff); } n.add_ex("overall_coeff", ex(overall_coeff)); } ////////// // functions overriding virtual functions from base classes ////////// // public void expairseq::do_print(const print_context & c, unsigned level) const { c.s << "[["; printseq(c, ',', precedence(), level); c.s << "]]"; } void expairseq::do_print_tree(const print_tree & c, unsigned level) const { c.s << std::string(level, ' ') << class_name() << " @" << this << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec << ", nops=" << nops() << std::endl; size_t num = seq.size(); for (size_t i=0; i<num; ++i) { seq[i].rest.print(c, level + c.delta_indent); seq[i].coeff.print(c, level + c.delta_indent); if (i != num - 1) c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl; } if (!overall_coeff_equals_default()) { c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl << std::string(level + c.delta_indent, ' ') << "overall_coeff" << std::endl; overall_coeff.print(c, level + c.delta_indent); } c.s << std::string(level + c.delta_indent,' ') << "=====" << std::endl; #if EXPAIRSEQ_USE_HASHTAB c.s << std::string(level + c.delta_indent,' ') << "hashtab size " << hashtabsize << std::endl; if (hashtabsize == 0) return; #define MAXCOUNT 5 unsigned count[MAXCOUNT+1]; for (int i=0; i<MAXCOUNT+1; ++i) count[i] = 0; unsigned this_bin_fill; unsigned cum_fill_sq = 0; unsigned cum_fill = 0; for (unsigned i=0; i<hashtabsize; ++i) { this_bin_fill = 0; if (hashtab[i].size() > 0) { c.s << std::string(level + c.delta_indent, ' ') << "bin " << i << " with entries "; for (epplist::const_iterator it=hashtab[i].begin(); it!=hashtab[i].end(); ++it) { c.s << *it-seq.begin() << " "; ++this_bin_fill; } c.s << std::endl; cum_fill += this_bin_fill; cum_fill_sq += this_bin_fill*this_bin_fill; } if (this_bin_fill<MAXCOUNT) ++count[this_bin_fill]; else ++count[MAXCOUNT]; } unsigned fact = 1; double cum_prob = 0; double lambda = (1.0*seq.size()) / hashtabsize; for (int k=0; k<MAXCOUNT; ++k) { if (k>0) fact *= k; double prob = std::pow(lambda,k)/fact * std::exp(-lambda); cum_prob += prob; c.s << std::string(level + c.delta_indent, ' ') << "bins with " << k << " entries: " << int(1000.0*count[k]/hashtabsize)/10.0 << "% (expected: " << int(prob*1000)/10.0 << ")" << std::endl; } c.s << std::string(level + c.delta_indent, ' ') << "bins with more entries: " << int(1000.0*count[MAXCOUNT]/hashtabsize)/10.0 << "% (expected: " << int((1-cum_prob)*1000)/10.0 << ")" << std::endl; c.s << std::string(level + c.delta_indent, ' ') << "variance: " << 1.0/hashtabsize*cum_fill_sq-(1.0/hashtabsize*cum_fill)*(1.0/hashtabsize*cum_fill) << std::endl; c.s << std::string(level + c.delta_indent, ' ') << "average fill: " << (1.0*cum_fill)/hashtabsize << " (should be equal to " << (1.0*seq.size())/hashtabsize << ")" << std::endl; #endif // EXPAIRSEQ_USE_HASHTAB } bool expairseq::info(unsigned inf) const { switch(inf) { case info_flags::expanded: return (flags & status_flags::expanded) != 0u; } return inherited::info(inf); } size_t expairseq::nops() const { if (overall_coeff_equals_default()) return seq.size(); return seq.size()+1; } const ex expairseq::op(size_t i) const { if (i < seq.size()) return recombine_pair_to_ex(seq[i]); GINAC_ASSERT(!overall_coeff_equals_default()); return overall_coeff; } ex expairseq::stable_op(size_t i) const { if (i < seq.size()) { return recombine_pair_to_ex(get_sorted_seq()[i]); } GINAC_ASSERT(!overall_coeff_equals_default()); return overall_coeff; } ex expairseq::map(map_function &f) const { std::unique_ptr<epvector> v(new epvector); v->reserve(seq.size()+1); for (const auto & elem : seq) v->push_back(split_ex_to_pair(f(recombine_pair_to_ex(elem)))); if (overall_coeff_equals_default()) return thisexpairseq(std::move(v), default_overall_coeff(), true); ex newcoeff = f(overall_coeff); if(is_exactly_a<numeric>(newcoeff)) return thisexpairseq(std::move(v), ex_to<numeric>(newcoeff), true); v->push_back(split_ex_to_pair(newcoeff)); return thisexpairseq(std::move(v), default_overall_coeff(), true); } /** Perform coefficient-wise automatic term rewriting rules in this class. */ ex expairseq::eval(int level) const { if ((level==1) and is_evaluated()) return *this; std::unique_ptr<epvector> vp = evalchildren(level); if (vp == nullptr) return this->hold(); return (new expairseq(std::move(vp), overall_coeff))->setflag(status_flags::dynallocated | status_flags::evaluated); } epvector* conjugateepvector(const epvector& epv) { epvector *newepv = nullptr; for (const auto & elem : epv) { if (newepv != nullptr) { newepv->push_back(elem.conjugate()); continue; } expair x = elem.conjugate(); if (x.is_equal(elem)) { continue; } newepv = new epvector; newepv->reserve(epv.size()); for (const auto & elem2 : epv) if (&elem2 != &elem) newepv->push_back(elem2); else break; newepv->push_back(x); } return newepv; } ex expairseq::conjugate() const { std::unique_ptr<epvector> newepv(conjugateepvector(seq)); // this is known to be numeric const numeric& x = ex_to<numeric>(overall_coeff.conjugate()); if (!newepv and overall_coeff.is_equal(x)) { return *this; } ex result = thisexpairseq(newepv ? *newepv : seq, x); return result; } // returns total degree of this sequence numeric expairseq::calc_total_degree() const { numeric deg = 0; for (const auto & elem : seq) deg = deg.add(ex_to<numeric>(elem.coeff)); return deg; } // protected int expairseq::compare_same_type(const basic &other) const { GINAC_ASSERT(is_a<expairseq>(other)); const expairseq &o = static_cast<const expairseq &>(other); int cmpval; // compare number of elements if (seq.size() != o.seq.size()) return (seq.size()<o.seq.size()) ? -1 : 1; // compare overall_coeff cmpval = overall_coeff.compare_same_type(o.overall_coeff); if (cmpval!=0) return cmpval; #if EXPAIRSEQ_USE_HASHTAB GINAC_ASSERT(hashtabsize==o.hashtabsize); if (hashtabsize==0) { #endif // EXPAIRSEQ_USE_HASHTAB auto cit1 = seq.begin(); auto cit2 = o.seq.begin(); auto last1 = seq.end(); auto last2 = o.seq.end(); for (; (cit1!=last1)&&(cit2!=last2); ++cit1, ++cit2) { cmpval = (*cit1).compare(*cit2); if (cmpval!=0) return cmpval; } GINAC_ASSERT(cit1==last1); GINAC_ASSERT(cit2==last2); return 0; #if EXPAIRSEQ_USE_HASHTAB } // compare number of elements in each hashtab entry for (unsigned i=0; i<hashtabsize; ++i) { unsigned cursize=hashtab[i].size(); if (cursize != o.hashtab[i].size()) return (cursize < o.hashtab[i].size()) ? -1 : 1; } // compare individual (sorted) hashtab entries for (unsigned i=0; i<hashtabsize; ++i) { unsigned sz = hashtab[i].size(); if (sz>0) { const epplist &eppl1 = hashtab[i]; const epplist &eppl2 = o.hashtab[i]; epplist::const_iterator it1 = eppl1.begin(); epplist::const_iterator it2 = eppl2.begin(); while (it1!=eppl1.end()) { cmpval = (*(*it1)).compare(*(*it2)); if (cmpval!=0) return cmpval; ++it1; ++it2; } } } return 0; // equal #endif // EXPAIRSEQ_USE_HASHTAB } bool expairseq::is_equal_same_type(const basic &other) const { const expairseq &o = static_cast<const expairseq &>(other); // compare number of elements if (seq.size()!=o.seq.size()) return false; // compare overall_coeff if (!overall_coeff.is_equal(o.overall_coeff)) return false; #if EXPAIRSEQ_USE_HASHTAB // compare number of elements in each hashtab entry if (hashtabsize!=o.hashtabsize) { print(print_tree(std::cout)); other.print(print_tree(std::cout)); } GINAC_ASSERT(hashtabsize==o.hashtabsize); if (hashtabsize==0) { #endif // EXPAIRSEQ_USE_HASHTAB auto cit1 = seq.begin(); auto cit2 = o.seq.begin(); auto last1 = seq.end(); while (cit1!=last1) { if (!(*cit1).is_equal(*cit2)) return false; ++cit1; ++cit2; } return true; #if EXPAIRSEQ_USE_HASHTAB } for (unsigned i=0; i<hashtabsize; ++i) { if (hashtab[i].size() != o.hashtab[i].size()) return false; } // compare individual sorted hashtab entries for (unsigned i=0; i<hashtabsize; ++i) { unsigned sz = hashtab[i].size(); if (sz>0) { const epplist &eppl1 = hashtab[i]; const epplist &eppl2 = o.hashtab[i]; epplist::const_iterator it1 = eppl1.begin(); epplist::const_iterator it2 = eppl2.begin(); while (it1!=eppl1.end()) { if (!(*(*it1)).is_equal(*(*it2))) return false; ++it1; ++it2; } } } return true; #endif // EXPAIRSEQ_USE_HASHTAB } unsigned expairseq::return_type() const { return return_types::noncommutative_composite; } long expairseq::calchash() const { long v = golden_ratio_hash((intptr_t)tinfo()); for (const auto & elem : seq) { v ^= elem.rest.gethash(); #if !EXPAIRSEQ_USE_HASHTAB // rotation spoils commutativity! v = rotate_left(v); v ^= elem.coeff.gethash(); #endif // !EXPAIRSEQ_USE_HASHTAB } v ^= overall_coeff.gethash(); // store calculated hash value only if object is already evaluated if (is_evaluated()) { setflag(status_flags::hash_calculated); hashvalue = v; } return v; } ex expairseq::expand(unsigned options) const { std::unique_ptr<epvector> vp = expandchildren(options); if (vp != nullptr) return thisexpairseq(std::move(vp), overall_coeff); // The terms have not changed, so it is safe to declare this expanded return (options == 0) ? setflag(status_flags::expanded) : *this; } ex expairseq::subs(const exmap & m, unsigned options) const { std::unique_ptr<epvector> vp = subschildren(m, options); if (vp != nullptr) { const ex& ocs = overall_coeff.subs(m, options); if (is_exactly_a<numeric>(ocs)) return ex_to<basic>(thisexpairseq(std::move(vp), ex_to<numeric>(ocs), (options & subs_options::no_index_renaming) == 0)); else return ex_to<basic>(add(ocs, thisexpairseq(std::move(vp), *_num0_p, (options & subs_options::no_index_renaming) == 0))); } if (((options & subs_options::algebraic) != 0u) && is_exactly_a<mul>(*this)) return static_cast<const mul *>(this)->algebraic_subs_mul(m, options); else return subs_one_level(m, options); } ////////// // new virtual functions which can be overridden by derived classes ////////// // protected /** Create an object of this type. * This method works similar to a constructor. It is useful because expairseq * has (at least) two possible different semantics but we want to inherit * methods thus avoiding code duplication. Sometimes a method in expairseq * has to create a new one of the same semantics, which cannot be done by a * ctor because the name (add, mul,...) is unknown on the expaiseq level. In * order for this trick to work a derived class must of course override this * definition. */ ex expairseq::thisexpairseq(const epvector &v, const numeric &oc, bool do_index_renaming) const { return expairseq(v, oc, do_index_renaming); } ex expairseq::thisexpairseq(std::unique_ptr<epvector> vp, const numeric &oc, bool do_index_renaming) const { return expairseq(std::move(vp), oc, do_index_renaming); } void expairseq::printpair(const print_context & c, const expair & p, unsigned /*unused*/) const { c.s << "[["; p.rest.print(c, precedence()); c.s << ","; p.coeff.print(c, precedence()); c.s << "]]"; } void expairseq::printseq(const print_context & c, char delim, unsigned this_precedence, unsigned upper_precedence) const { if (this_precedence <= upper_precedence) c.s << "("; auto it = seq.begin(); auto it_last = seq.end() - 1; for (; it != it_last; ++it) { printpair(c, *it, this_precedence); c.s << delim; } printpair(c, *it, this_precedence); if (!overall_coeff_equals_default()) { c.s << delim; overall_coeff.print(c, this_precedence); } if (this_precedence <= upper_precedence) c.s << ")"; } /** Form an expair from an ex, using the corresponding semantics. * @see expairseq::recombine_pair_to_ex() */ expair expairseq::split_ex_to_pair(const ex &e) const { return expair(e,_ex1); } expair expairseq::combine_ex_with_coeff_to_pair(const ex &e, const numeric &c) const { return expair(e,c); } expair expairseq::combine_pair_with_coeff_to_pair(const expair &p, const numeric &c) const { GINAC_ASSERT(is_exactly_a<numeric>(p.coeff)); return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(c)); } /** Form an ex out of an expair, using the corresponding semantics. * @see expairseq::split_ex_to_pair() */ ex expairseq::recombine_pair_to_ex(const expair &p) const { return lst(p.rest,p.coeff); } bool expairseq::expair_needs_further_processing(epp /*unused*/) { #if EXPAIRSEQ_USE_HASHTAB //# error "FIXME: expair_needs_further_processing not yet implemented for hashtabs, sorry. A.F." #endif // EXPAIRSEQ_USE_HASHTAB return false; } numeric expairseq::default_overall_coeff() const { return *_num0_p; } bool expairseq::overall_coeff_equals_default() const { return (overall_coeff.is_exact() and overall_coeff.is_equal(default_overall_coeff())); } void expairseq::combine_overall_coeff(const numeric &c) { overall_coeff += c; } void expairseq::combine_overall_coeff(const numeric &c1, const numeric &c2) { overall_coeff += c1.mul(c2); } bool expairseq::can_make_flat(const expair & /*unused*/) const { return true; } ////////// // non-virtual functions in this class ////////// void expairseq::construct_from_2_ex_via_exvector(const ex &lh, const ex &rh) { exvector v; v.reserve(2); v.push_back(lh); v.push_back(rh); construct_from_exvector(v); #if EXPAIRSEQ_USE_HASHTAB GINAC_ASSERT((hashtabsize==0)||(hashtabsize>=minhashtabsize)); GINAC_ASSERT(hashtabsize==calc_hashtabsize(seq.size())); #endif // EXPAIRSEQ_USE_HASHTAB } void expairseq::construct_from_2_ex(const ex &lh, const ex &rh) { if (ex_to<basic>(lh).tinfo()==this->tinfo()) { if (ex_to<basic>(rh).tinfo()==this->tinfo()) { #if EXPAIRSEQ_USE_HASHTAB unsigned totalsize = ex_to<expairseq>(lh).seq.size() + ex_to<expairseq>(rh).seq.size(); construct_from_2_ex_via_exvector(lh,rh); { } else { #endif // EXPAIRSEQ_USE_HASHTAB construct_from_2_expairseq(ex_to<expairseq>(lh), ex_to<expairseq>(rh)); #if EXPAIRSEQ_USE_HASHTAB } #endif // EXPAIRSEQ_USE_HASHTAB return; } #if EXPAIRSEQ_USE_HASHTAB unsigned totalsize = ex_to<expairseq>(lh).seq.size()+1; if (calc_hashtabsize(totalsize)!=0) { construct_from_2_ex_via_exvector(lh, rh); } else { #endif // EXPAIRSEQ_USE_HASHTAB construct_from_expairseq_ex(ex_to<expairseq>(lh), rh); #if EXPAIRSEQ_USE_HASHTAB } #endif // EXPAIRSEQ_USE_HASHTAB return; } else if (ex_to<basic>(rh).tinfo()==this->tinfo()) { #if EXPAIRSEQ_USE_HASHTAB unsigned totalsize=ex_to<expairseq>(rh).seq.size()+1; if (calc_hashtabsize(totalsize)!=0) { construct_from_2_ex_via_exvector(lh,rh); } else { #endif // EXPAIRSEQ_USE_HASHTAB construct_from_expairseq_ex(ex_to<expairseq>(rh),lh); #if EXPAIRSEQ_USE_HASHTAB } #endif // EXPAIRSEQ_USE_HASHTAB return; } #if EXPAIRSEQ_USE_HASHTAB if (calc_hashtabsize(2)!=0) { construct_from_2_ex_via_exvector(lh,rh); return; } hashtabsize = 0; #endif // EXPAIRSEQ_USE_HASHTAB if (is_exactly_a<numeric>(lh)) { const numeric& lhn = ex_to<numeric>(lh); if (is_exactly_a<numeric>(rh)) { combine_overall_coeff(lhn); combine_overall_coeff(ex_to<numeric>(rh)); } else { combine_overall_coeff(lhn); seq.push_back(split_ex_to_pair(rh)); } } else { if (is_exactly_a<numeric>(rh)) { combine_overall_coeff(ex_to<numeric>(rh)); seq.push_back(split_ex_to_pair(lh)); } else { expair p1 = split_ex_to_pair(lh); expair p2 = split_ex_to_pair(rh); int cmpval = p1.rest.compare(p2.rest); if (cmpval==0 and likely(not is_exactly_a<infinity>(p1.rest))) { p1.coeff = ex_to<numeric>(p1.coeff).add_dyn(ex_to<numeric>(p2.coeff)); if (!ex_to<numeric>(p1.coeff).is_zero()) { // no further processing is necessary, since this // one element will usually be recombined in eval() seq.push_back(p1); } } else { seq.reserve(2); if (cmpval<0) { seq.push_back(p1); seq.push_back(p2); } else { seq.push_back(p2); seq.push_back(p1); } } } } } void expairseq::construct_from_2_expairseq(const expairseq &s1, const expairseq &s2) { combine_overall_coeff(s1.overall_coeff); combine_overall_coeff(s2.overall_coeff); auto first1 = s1.seq.begin(); auto last1 = s1.seq.end(); auto first2 = s2.seq.begin(); auto last2 = s2.seq.end(); seq.reserve(s1.seq.size()+s2.seq.size()); bool needs_further_processing=false; while (first1!=last1 && first2!=last2) { int cmpval = (*first1).rest.compare((*first2).rest); if (cmpval==0) { // infinity evaluation is handled in the eval() method // do not let infinities cancel each other here if (unlikely(is_exactly_a<infinity>(first1->rest))) { seq.push_back(*first1); seq.push_back(*first2); } else { // combine terms const numeric &newcoeff = ex_to<numeric>(first1->coeff). add(ex_to<numeric>(first2->coeff)); if (!newcoeff.is_zero()) { seq.emplace_back(first1->rest,newcoeff); if (expair_needs_further_processing(seq.end()-1)) { needs_further_processing = true; } } } ++first1; ++first2; } else if (cmpval<0) { seq.push_back(*first1); ++first1; } else { seq.push_back(*first2); ++first2; } } while (first1!=last1) { seq.push_back(*first1); ++first1; } while (first2!=last2) { seq.push_back(*first2); ++first2; } if (needs_further_processing) { epvector v = seq; seq.clear(); construct_from_epvector(v); } } void expairseq::construct_from_expairseq_ex(const expairseq &s, const ex &e) { combine_overall_coeff(s.overall_coeff); if (is_exactly_a<numeric>(e)) { combine_overall_coeff(ex_to<numeric>(e)); seq = s.seq; return; } auto first = s.seq.begin(); auto last = s.seq.end(); expair p = split_ex_to_pair(e); // infinity evaluation is handled in eval() // do not let infinities cancel each other here if (unlikely(is_exactly_a<infinity>(p.rest))) { seq.push_back(p); seq.insert(seq.end(), first, last); return; } seq.reserve(s.seq.size()+1); bool p_pushed = false; bool needs_further_processing=false; // merge p into s.seq while (first!=last) { int cmpval = (*first).rest.compare(p.rest); if (cmpval==0) { // combine terms const numeric &newcoeff = ex_to<numeric>(first->coeff). add(ex_to<numeric>(p.coeff)); if (!newcoeff.is_zero()) { seq.emplace_back(first->rest,newcoeff); if (expair_needs_further_processing(seq.end()-1)) needs_further_processing = true; } ++first; p_pushed = true; break; } if (cmpval<0) { seq.push_back(*first); ++first; } else { seq.push_back(p); p_pushed = true; break; } } if (p_pushed) { // while loop exited because p was pushed, now push rest of s.seq while (first!=last) { seq.push_back(*first); ++first; } } else { // while loop exited because s.seq was pushed, now push p seq.push_back(p); } if (needs_further_processing) { epvector v = seq; seq.clear(); construct_from_epvector(v); } } void expairseq::construct_from_exvector(const exvector &v, bool do_hold) { // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity) // +(d,b,c,a) -> +(a,b,c,d) (canonicalization) // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric) // (same for (+,*) -> (*,^) make_flat(v, do_hold); #if EXPAIRSEQ_USE_HASHTAB combine_same_terms(); #else if (!do_hold) { canonicalize(); combine_same_terms_sorted_seq(); } #endif // EXPAIRSEQ_USE_HASHTAB } void expairseq::construct_from_epvector(const epvector &v, bool do_index_renaming) { // simplifications: +(a,+(b,c),d) -> +(a,b,c,d) (associativity) // +(d,b,c,a) -> +(a,b,c,d) (canonicalization) // +(...,x,*(x,c1),*(x,c2)) -> +(...,*(x,1+c1+c2)) (c1, c2 numeric) // same for (+,*) -> (*,^) make_flat(v, do_index_renaming); #if EXPAIRSEQ_USE_HASHTAB combine_same_terms(); #else canonicalize(); combine_same_terms_sorted_seq(); #endif // EXPAIRSEQ_USE_HASHTAB } /** Combine this expairseq with argument exvector. * It cares for associativity as well as for special handling of numerics. */ void expairseq::make_flat(const exvector &v, bool do_hold) { // count number of operands which are of same expairseq derived type // and their cumulative number of operands int nexpairseqs = 0; int noperands = 0; bool do_idx_rename = false; if (!do_hold) { for (const auto & elem : v) { if (ex_to<basic>(elem).tinfo()==this->tinfo()) { ++nexpairseqs; noperands += ex_to<expairseq>(elem).seq.size(); } } } else this->hold(); // reserve seq and coeffseq which will hold all operands seq.reserve(v.size()+noperands-nexpairseqs); // copy elements and split off numerical part make_flat_inserter mf(v, do_idx_rename); for (const auto & elem : v) { if (ex_to<basic>(elem).tinfo()==this->tinfo() && !do_hold) { ex newfactor = mf.handle_factor(elem, _ex1); const expairseq &subseqref = ex_to<expairseq>(newfactor); combine_overall_coeff(subseqref.overall_coeff); for (const auto & elem2 : subseqref.seq) seq.push_back(elem2); } else { if (is_exactly_a<numeric>(elem)) combine_overall_coeff(ex_to<numeric>(elem)); else { ex newfactor = mf.handle_factor(elem, _ex1); seq.push_back(split_ex_to_pair(newfactor)); } } } } /** Combine this expairseq with argument epvector. * It cares for associativity as well as for special handling of numerics. */ void expairseq::make_flat(const epvector &v, bool do_index_renaming) { // count number of operands which are of same expairseq derived type // and their cumulative number of operands int nexpairseqs = 0; int noperands = 0; for (const auto & elem : v) { if (ex_to<basic>(elem.rest).tinfo()==this->tinfo()) { ++nexpairseqs; noperands += ex_to<expairseq>(elem.rest).seq.size(); } } // reserve seq and coeffseq which will hold all operands seq.reserve(v.size()+noperands-nexpairseqs); make_flat_inserter mf(v, false); // copy elements and split off numerical part for (const auto & elem : v) { if (ex_to<basic>(elem.rest).tinfo()==this->tinfo() && this->can_make_flat(elem)) { ex newrest; if (is_exactly_a<numeric>(elem.coeff) and elem.coeff.is_zero()) { newrest = default_overall_coeff(); } else { newrest = elem.rest; } const expairseq &subseqref = ex_to<expairseq>(newrest); combine_overall_coeff(subseqref.overall_coeff, ex_to<numeric>(elem.coeff)); for (const auto & elem2 : subseqref.seq) seq.emplace_back(elem2.rest, ex_to<numeric>(elem2.coeff).mul_dyn(ex_to<numeric>(elem.coeff))); } else { if (elem.is_canonical_numeric()) combine_overall_coeff(ex_to<numeric>(mf.handle_factor(elem.rest, _ex1))); else { if ((is_exactly_a<numeric>(elem.coeff) and elem.coeff.is_zero()) or (is_exactly_a<numeric>(elem.rest) and (ex_to<numeric>(elem.rest).is_equal(default_overall_coeff())))) { combine_overall_coeff(default_overall_coeff()); } else { seq.push_back(elem); } } } } } /** Brings this expairseq into a sorted (canonical) form. */ void expairseq::canonicalize() { std::sort(seq.begin(), seq.end(), expair_rest_is_less()); } /** Compact a presorted expairseq by combining all matching expairs to one * each. On an add object, this is responsible for 2*x+3*x+y -> 5*x+y, for * instance. */ void expairseq::combine_same_terms_sorted_seq() { if (seq.size()<2) return; bool needs_further_processing = false; auto itin1 = seq.begin(); auto itin2 = itin1+1; auto itout = itin1; auto last = seq.end(); // must_copy will be set to true the first time some combination is // possible from then on the sequence has changed and must be compacted bool must_copy = false; while (itin2!=last) { if (itin1->rest.compare(itin2->rest)==0 and likely(not is_exactly_a<infinity>(itin1->rest))) { itin1->coeff = ex_to<numeric>(itin1->coeff). add_dyn(ex_to<numeric>(itin2->coeff)); if (expair_needs_further_processing(itin1)) needs_further_processing = true; must_copy = true; } else { if (not ex_to<numeric>(itin1->coeff).is_zero()) { if (must_copy) *itout = *itin1; ++itout; } itin1 = itin2; } ++itin2; } if (not ex_to<numeric>(itin1->coeff).is_zero()) { if (must_copy) *itout = *itin1; ++itout; } if (itout!=last) seq.erase(itout,last); if (needs_further_processing) { epvector v = seq; seq.clear(); construct_from_epvector(v); } } #if EXPAIRSEQ_USE_HASHTAB unsigned expairseq::calc_hashtabsize(unsigned sz) const { unsigned size; unsigned nearest_power_of_2 = 1 << log2(sz); // if (nearest_power_of_2 < maxhashtabsize/hashtabfactor) { // size = nearest_power_of_2*hashtabfactor; size = nearest_power_of_2/hashtabfactor; if (size<minhashtabsize) return 0; // hashtabsize must be a power of 2 GINAC_ASSERT((1U << log2(size))==size); return size; } unsigned expairseq::calc_hashindex(const ex &e) const { // calculate hashindex unsigned hashindex; if (is_a<numeric>(e)) { hashindex = hashmask; } else { hashindex = e.gethash() & hashmask; // last hashtab entry is reserved for numerics if (hashindex==hashmask) hashindex = 0; } GINAC_ASSERT((hashindex<hashtabsize)||(hashtabsize==0)); return hashindex; } void expairseq::shrink_hashtab() { unsigned new_hashtabsize; while (hashtabsize!=(new_hashtabsize=calc_hashtabsize(seq.size()))) { GINAC_ASSERT(new_hashtabsize<hashtabsize); if (new_hashtabsize==0) { hashtab.clear(); hashtabsize = 0; canonicalize(); return; } // shrink by a factor of 2 unsigned half_hashtabsize = hashtabsize/2; for (unsigned i=0; i<half_hashtabsize-1; ++i) hashtab[i].merge(hashtab[i+half_hashtabsize],epp_is_less()); // special treatment for numeric hashes hashtab[0].merge(hashtab[half_hashtabsize-1],epp_is_less()); hashtab[half_hashtabsize-1] = hashtab[hashtabsize-1]; hashtab.resize(half_hashtabsize); hashtabsize = half_hashtabsize; hashmask = hashtabsize-1; } } void expairseq::remove_hashtab_entry(epvector::const_iterator element) { if (hashtabsize==0) return; // nothing to do // calculate hashindex of element to be deleted unsigned hashindex = calc_hashindex((*element).rest); // find it in hashtab and remove it epplist &eppl = hashtab[hashindex]; epplist::iterator epplit = eppl.begin(); bool erased = false; while (epplit!=eppl.end()) { if (*epplit == element) { eppl.erase(epplit); erased = true; break; } ++epplit; } if (!erased) { unsigned hashindex = calc_hashindex(element->rest); epplist &eppl = hashtab[hashindex]; epplist::iterator epplit = eppl.begin(); bool erased = false; while (epplit!=eppl.end()) { if (*epplit == element) { eppl.erase(epplit); erased = true; break; } ++epplit; } GINAC_ASSERT(erased); } GINAC_ASSERT(erased); } void expairseq::move_hashtab_entry(epvector::const_iterator oldpos, epvector::iterator newpos) { GINAC_ASSERT(hashtabsize!=0); // calculate hashindex of element which was moved unsigned hashindex=calc_hashindex((*newpos).rest); // find it in hashtab and modify it epplist &eppl = hashtab[hashindex]; epplist::iterator epplit = eppl.begin(); while (epplit!=eppl.end()) { if (*epplit == oldpos) { *epplit = newpos; break; } ++epplit; } GINAC_ASSERT(epplit!=eppl.end()); } void expairseq::sorted_insert(epplist &eppl, epvector::const_iterator elem) { epplist::const_iterator current = eppl.begin(); while ((current!=eppl.end()) && ((*current)->is_less(*elem))) { ++current; } eppl.insert(current,elem); } void expairseq::build_hashtab_and_combine(epvector::iterator &first_numeric, epvector::iterator &last_non_zero, std::vector<bool> &touched, unsigned &number_of_zeroes) { epp current = seq.begin(); while (current!=first_numeric) { if (is_exactly_a<numeric>(current->rest)) { --first_numeric; iter_swap(current,first_numeric); } else { // calculate hashindex unsigned currenthashindex = calc_hashindex(current->rest); // test if there is already a matching expair in the hashtab-list epplist &eppl=hashtab[currenthashindex]; epplist::iterator epplit = eppl.begin(); while (epplit!=eppl.end()) { if (current->rest.is_equal((*epplit)->rest)) break; ++epplit; } if (epplit==eppl.end()) { // no matching expair found, append this to end of list sorted_insert(eppl,current); ++current; } else { // epplit points to a matching expair, combine it with current (*epplit)->coeff = ex_to<numeric>((*epplit)->coeff). add_dyn(ex_to<numeric>(current->coeff)); // move obsolete current expair to end by swapping with last_non_zero element // if this was a numeric, it is swapped with the expair before first_numeric iter_swap(current,last_non_zero); --first_numeric; if (first_numeric!=last_non_zero) iter_swap(first_numeric,current); --last_non_zero; ++number_of_zeroes; // test if combined term has coeff 0 and can be removed is done later touched[(*epplit)-seq.begin()] = true; } } } } void expairseq::drop_coeff_0_terms(epvector::iterator &first_numeric, epvector::iterator &last_non_zero, std::vector<bool> &touched, unsigned &number_of_zeroes) { // move terms with coeff 0 to end and remove them from hashtab // check only those elements which have been touched epp current = seq.begin(); size_t i = 0; while (current!=first_numeric) { if (!touched[i]) { ++current; ++i; } else if (!ex_to<numeric>((*current).coeff).is_zero()) { ++current; ++i; } else { remove_hashtab_entry(current); // move element to the end, unless it is already at the end if (current!=last_non_zero) { iter_swap(current,last_non_zero); --first_numeric; bool numeric_swapped = first_numeric!=last_non_zero; if (numeric_swapped) iter_swap(first_numeric,current); epvector::iterator changed_entry; if (numeric_swapped) changed_entry = first_numeric; else changed_entry = last_non_zero; --last_non_zero; ++number_of_zeroes; if (first_numeric!=current) { // change entry in hashtab which referred to first_numeric or last_non_zero to current move_hashtab_entry(changed_entry,current); touched[current-seq.begin()] = touched[changed_entry-seq.begin()]; } } else { --first_numeric; --last_non_zero; ++number_of_zeroes; } } } GINAC_ASSERT(i==current-seq.begin()); } /** True if one of the coeffs vanishes, otherwise false. * This would be an invariant violation, so this should only be used for * debugging purposes. */ bool expairseq::has_coeff_0() const { epvector::const_iterator i = seq.begin(), end = seq.end(); while (i != end) { if (i->coeff.is_zero()) return true; ++i; } return false; } void expairseq::add_numerics_to_hashtab(epvector::iterator first_numeric, epvector::const_iterator last_non_zero) { if (first_numeric == seq.end()) return; // no numerics epvector::const_iterator current = first_numeric, last = last_non_zero + 1; while (current != last) { sorted_insert(hashtab[hashmask], current); ++current; } } void expairseq::combine_same_terms() { // combine same terms, drop term with coeff 0, move numerics to end // calculate size of hashtab hashtabsize = calc_hashtabsize(seq.size()); // hashtabsize is a power of 2 hashmask = hashtabsize-1; // allocate hashtab hashtab.clear(); hashtab.resize(hashtabsize); if (hashtabsize==0) { canonicalize(); combine_same_terms_sorted_seq(); GINAC_ASSERT(!has_coeff_0()); return; } // iterate through seq, move numerics to end, // fill hashtab and combine same terms epvector::iterator first_numeric = seq.end(); epvector::iterator last_non_zero = seq.end()-1; size_t num = seq.size(); std::vector<bool> touched(num); unsigned number_of_zeroes = 0; GINAC_ASSERT(!has_coeff_0()); build_hashtab_and_combine(first_numeric,last_non_zero,touched,number_of_zeroes); // there should not be any terms with coeff 0 from the beginning, // so it should be safe to skip this step if (number_of_zeroes!=0) { drop_coeff_0_terms(first_numeric,last_non_zero,touched,number_of_zeroes); } add_numerics_to_hashtab(first_numeric,last_non_zero); // pop zero elements for (unsigned i=0; i<number_of_zeroes; ++i) { seq.pop_back(); } // shrink hashtabsize to calculated value GINAC_ASSERT(!has_coeff_0()); shrink_hashtab(); GINAC_ASSERT(!has_coeff_0()); } #endif // EXPAIRSEQ_USE_HASHTAB /** Check if this expairseq is in sorted (canonical) form. Useful mainly for * debugging or in assertions since being sorted is an invariance. */ bool expairseq::is_canonical() const { if (seq.size() <= 1) return true; #if EXPAIRSEQ_USE_HASHTAB if (hashtabsize > 0) return 1; // not canoncalized #endif // EXPAIRSEQ_USE_HASHTAB auto it = seq.begin(), itend = seq.end(); auto it_last = it; for (++it; it!=itend; it_last=it, ++it) { if (!(it_last->is_less(*it) || it_last->is_equal(*it))) { if (!is_exactly_a<numeric>(it_last->rest) || !is_exactly_a<numeric>(it->rest)) { // double test makes it easier to set a breakpoint... if (!is_exactly_a<numeric>(it_last->rest) || !is_exactly_a<numeric>(it->rest)) { printpair(std::clog, *it_last, 0); std::clog << ">"; printpair(std::clog, *it, 0); std::clog << "\n"; std::clog << "pair1:" << std::endl; it_last->rest.print(print_tree(std::clog)); it_last->coeff.print(print_tree(std::clog)); std::clog << "pair2:" << std::endl; it->rest.print(print_tree(std::clog)); it->coeff.print(print_tree(std::clog)); return false; } } } } return true; } /** Member-wise expand the expairs in this sequence. * * @see expairseq::expand() * @return pointer to epvector containing expanded pairs or zero pointer, * if no members were changed. */ std::unique_ptr<epvector> expairseq::expandchildren(unsigned options) const { auto cit = seq.begin(); auto last = seq.end(); while (cit!=last) { const ex expanded_ex = cit->rest.expand(options); if (!are_ex_trivially_equal(cit->rest,expanded_ex)) { // something changed, copy seq, eval and return it std::unique_ptr<epvector> s(new epvector); s->reserve(seq.size()); // copy parts of seq which are known not to have changed s->insert(s->begin(), seq.begin(), cit); // copy first changed element s->push_back(expair(expanded_ex, cit->coeff)); ++cit; // copy rest while (cit != last) { s->push_back(expair(cit->rest.expand(options), cit->coeff)); ++cit; } return s; } ++cit; } return std::unique_ptr<epvector>(nullptr); // signalling nothing has changed } /** Member-wise evaluate the expairs in this sequence. * * @see expairseq::eval() * @return pointer to epvector containing evaluated pairs or zero pointer, * if no members were changed. */ std::unique_ptr<epvector> expairseq::evalchildren(int level) const { if (level == -max_recursion_level) throw(std::runtime_error("max recursion level reached")); auto last = seq.end(); auto cit = seq.begin(); while (cit!=last) { const ex evaled_rest = level==1 ? cit->rest : cit->rest.eval(level-1); const expair evaled_pair = combine_ex_with_coeff_to_pair(evaled_rest, ex_to<numeric>(cit->coeff)); if (unlikely(!evaled_pair.is_equal(*cit))) { // something changed: copy seq, eval, and return it std::unique_ptr<epvector> s(new epvector); s->reserve(seq.size()); // copy parts of seq which are known not to have changed s->insert(s->begin(), seq.begin(), cit); // copy first changed element s->push_back(evaled_pair); ++cit; // copy rest while (cit != last) { const ex evaled_rest1 = level==1 ? cit->rest : cit->rest.eval(level-1); s->push_back(combine_ex_with_coeff_to_pair(evaled_rest1, ex_to<numeric>(cit->coeff))); ++cit; } return s; } ++cit; } return std::unique_ptr<epvector>(nullptr); // signalling nothing has changed } /** Member-wise substitute in this sequence. * * @see expairseq::subs() * @return pointer to epvector containing pairs after application of subs, * or NULL pointer if no members were changed. */ std::unique_ptr<epvector> expairseq::subschildren(const exmap & m, unsigned options) const { // When any of the objects to be substituted is a product or power // we have to recombine the pairs because the numeric coefficients may // be part of the search pattern. if ((options & (subs_options::pattern_is_product | subs_options::pattern_is_not_product)) == 0u) { // Search the list of substitutions and cache our findings for (const auto & elem : m) { if (is_exactly_a<mul>(elem.first) || is_exactly_a<power>(elem.first)) { options |= subs_options::pattern_is_product; break; } } if ((options & subs_options::pattern_is_product) == 0u) options |= subs_options::pattern_is_not_product; } if ((options & subs_options::pattern_is_product) != 0u) { // Substitute in the recombined pairs auto cit = seq.begin(), last = seq.end(); while (cit != last) { const ex &orig_ex = recombine_pair_to_ex(*cit); const ex &subsed_ex = orig_ex.subs(m, options); if (!are_ex_trivially_equal(orig_ex, subsed_ex)) { // Something changed: copy seq, subs, and return it std::unique_ptr<epvector> s(new epvector); s->reserve(seq.size()); // Copy parts of seq which are known not to have changed s->insert(s->begin(), seq.begin(), cit); // Copy first changed element s->push_back(split_ex_to_pair(subsed_ex)); ++cit; // Copy rest while (cit != last) { s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit).subs(m, options))); ++cit; } return s; } ++cit; } } else { auto cit = seq.begin(), last = seq.end(); while (cit != last) { const ex &subsed_exr = cit->rest.subs(m, options); const ex &subsed_exc = ex_to<numeric>(cit->coeff).subs(m, options); if (not are_ex_trivially_equal(cit->rest, subsed_exr) or not are_ex_trivially_equal(cit->coeff, subsed_exc)) { // Something changed, copy seq, subs and return it std::unique_ptr<epvector> s(new epvector); s->reserve(seq.size()); // Copy parts of seq which are known not to have changed s->insert(s->begin(), seq.begin(), cit); // Copy first changed element if (is_exactly_a<numeric>(subsed_exc)) s->push_back(combine_ex_with_coeff_to_pair(subsed_exr, ex_to<numeric>(subsed_exc))); else s->push_back(split_ex_to_pair(mul(subsed_exr, subsed_exc))); ++cit; // Copy rest while (cit != last) { const ex &sr = cit->rest.subs(m, options); const ex &sc = ex_to<numeric>(cit->coeff).subs(m, options); if (is_exactly_a<numeric>(sc)) s->push_back(combine_ex_with_coeff_to_pair(sr, ex_to<numeric>(sc))); else s->push_back(split_ex_to_pair(mul(sr, sc))); ++cit; } return s; } ++cit; } } // Nothing has changed return std::unique_ptr<epvector>(nullptr); } const epvector & expairseq::get_sorted_seq() const { if (seq_sorted.empty()) return seq; return seq_sorted; } bool expairseq::match(const ex & pattern, exmap& map) const { CMatcher::level=0; CMatcher cm(*this, pattern, map); opt_exmap m = cm.get(); if (not m) return false; map = m.value(); return true; } ////////// // static member variables ////////// #if EXPAIRSEQ_USE_HASHTAB unsigned expairseq::maxhashtabsize = 0x4000000U; unsigned expairseq::minhashtabsize = 0x1000U; unsigned expairseq::hashtabfactor = 1; #endif // EXPAIRSEQ_USE_HASHTAB } // namespace GiNaC
21,290
5,216
<reponame>Eason312/bleEason // // ViewController.h // BabyBluetoothOSDemo // // Created by liuyanwei on 15/9/6. // Copyright (c) 2015年 liuyanwei. All rights reserved. // #import <Cocoa/Cocoa.h> @interface ViewController : NSViewController @end
99
3,102
#pragma once extern int some_val; template <typename T> struct TS { int tsmeth() { ++some_val; return undef_tsval; } };
57
984
<filename>generation/WinSDK/RecompiledIdlHeaders/um/wincontypes.h /*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: wincontypes.h Abstract: This module contains the common data types exported by the NT console subsystem. Created: 08-Sep-2017 Revision History: 26-Oct-1990 - Originally created in wincon.h --*/ #ifndef _WINCONTYPES_ #define _WINCONTYPES_ #pragma once #include <minwindef.h> #ifdef __cplusplus extern "C" { #endif #pragma region Application Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES) typedef struct _COORD { SHORT X; SHORT Y; } COORD, *PCOORD; typedef struct _SMALL_RECT { SHORT Left; SHORT Top; SHORT Right; SHORT Bottom; } SMALL_RECT, *PSMALL_RECT; typedef struct _KEY_EVENT_RECORD { BOOL bKeyDown; WORD wRepeatCount; WORD wVirtualKeyCode; WORD wVirtualScanCode; union { WCHAR UnicodeChar; CHAR AsciiChar; } uChar; DWORD dwControlKeyState; } KEY_EVENT_RECORD, *PKEY_EVENT_RECORD; // // ControlKeyState flags // #define RIGHT_ALT_PRESSED 0x0001 // the right alt key is pressed. #define LEFT_ALT_PRESSED 0x0002 // the left alt key is pressed. #define RIGHT_CTRL_PRESSED 0x0004 // the right ctrl key is pressed. #define LEFT_CTRL_PRESSED 0x0008 // the left ctrl key is pressed. #define SHIFT_PRESSED 0x0010 // the shift key is pressed. #define NUMLOCK_ON 0x0020 // the numlock light is on. #define SCROLLLOCK_ON 0x0040 // the scrolllock light is on. #define CAPSLOCK_ON 0x0080 // the capslock light is on. #define ENHANCED_KEY 0x0100 // the key is enhanced. #define NLS_DBCSCHAR 0x00010000 // DBCS for JPN: SBCS/DBCS mode. #define NLS_ALPHANUMERIC 0x00000000 // DBCS for JPN: Alphanumeric mode. #define NLS_KATAKANA 0x00020000 // DBCS for JPN: Katakana mode. #define NLS_HIRAGANA 0x00040000 // DBCS for JPN: Hiragana mode. #define NLS_ROMAN 0x00400000 // DBCS for JPN: Roman/Noroman mode. #define NLS_IME_CONVERSION 0x00800000 // DBCS for JPN: IME conversion. #define ALTNUMPAD_BIT 0x04000000 // AltNumpad OEM char (copied from ntuser\inc\kbd.h) ;internal_NT #define NLS_IME_DISABLE 0x20000000 // DBCS for JPN: IME enable/disable. typedef struct _MOUSE_EVENT_RECORD { COORD dwMousePosition; DWORD dwButtonState; DWORD dwControlKeyState; DWORD dwEventFlags; } MOUSE_EVENT_RECORD, *PMOUSE_EVENT_RECORD; // // ButtonState flags // #define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001 #define RIGHTMOST_BUTTON_PRESSED 0x0002 #define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004 #define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008 #define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010 // // EventFlags // #define MOUSE_MOVED 0x0001 #define DOUBLE_CLICK 0x0002 #define MOUSE_WHEELED 0x0004 #if(_WIN32_WINNT >= 0x0600) #define MOUSE_HWHEELED 0x0008 #endif /* _WIN32_WINNT >= 0x0600 */ typedef struct _WINDOW_BUFFER_SIZE_RECORD { COORD dwSize; } WINDOW_BUFFER_SIZE_RECORD, *PWINDOW_BUFFER_SIZE_RECORD; typedef struct _MENU_EVENT_RECORD { UINT dwCommandId; } MENU_EVENT_RECORD, *PMENU_EVENT_RECORD; typedef struct _FOCUS_EVENT_RECORD { BOOL bSetFocus; } FOCUS_EVENT_RECORD, *PFOCUS_EVENT_RECORD; typedef struct _INPUT_RECORD { WORD EventType; union { KEY_EVENT_RECORD KeyEvent; MOUSE_EVENT_RECORD MouseEvent; WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent; MENU_EVENT_RECORD MenuEvent; FOCUS_EVENT_RECORD FocusEvent; } Event; } INPUT_RECORD, *PINPUT_RECORD; // // EventType flags: // #define KEY_EVENT 0x0001 // Event contains key event record #define MOUSE_EVENT 0x0002 // Event contains mouse event record #define WINDOW_BUFFER_SIZE_EVENT 0x0004 // Event contains window change event record #define MENU_EVENT 0x0008 // Event contains menu event record #define FOCUS_EVENT 0x0010 // event contains focus change typedef struct _CHAR_INFO { union { WCHAR UnicodeChar; CHAR AsciiChar; } Char; WORD Attributes; } CHAR_INFO, *PCHAR_INFO; typedef struct _CONSOLE_FONT_INFO { DWORD nFont; COORD dwFontSize; } CONSOLE_FONT_INFO, *PCONSOLE_FONT_INFO; typedef VOID* HPCON; #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM | WINAPI_PARTITION_GAMES) */ #pragma endregion #ifdef __cplusplus } #endif #endif // _WINCONTYPES_
1,957
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <AzCore/Serialization/ObjectStream.h> #include <AzCore/Asset/AssetCommon.h> #include <AzCore/std/string/string.h> #include <AzCore/IO/FileIO.h> #include <AzCore/JSON/document.h> #include <AzCore/JSON/writer.h> #include <AzCore/Serialization/Json/JsonSerializationResult.h> namespace AZ { namespace IO { class GenericStream; } struct JsonSerializerSettings; struct JsonDeserializerSettings; // Utility functions which use json serializer/deserializer to save/load object to file/stream namespace JsonSerializationUtils { struct WriteJsonSettings { int m_maxDecimalPlaces = -1; // -1 means use default }; /////////////////////////////////////////////////////////////////////////////////// // Save functions //! Save a json document to text. Otherwise returns a failure with error message. AZ::Outcome<void, AZStd::string> WriteJsonString(const rapidjson::Document& document, AZStd::string& jsonText, WriteJsonSettings settings = WriteJsonSettings{}); //! Save a json document to a file. Otherwise returns a failure with error message. AZ::Outcome<void, AZStd::string> WriteJsonFile(const rapidjson::Document& document, AZStd::string_view filePath, WriteJsonSettings settings = WriteJsonSettings{}); //! Save a json document to a stream. Otherwise returns a failure with error message. AZ::Outcome<void, AZStd::string> WriteJsonStream(const rapidjson::Document& document, IO::GenericStream& stream, WriteJsonSettings settings = WriteJsonSettings{}); AZ::Outcome<void, AZStd::string> SaveObjectToStreamByType(const void* objectPtr, const Uuid& objectType, IO::GenericStream& stream, const void* defaultObjectPtr = nullptr, const JsonSerializerSettings* settings = nullptr); AZ::Outcome<void, AZStd::string> SaveObjectToFileByType(const void* objectPtr, const Uuid& objectType, const AZStd::string& filePath, const void* defaultObjectPtr = nullptr, const JsonSerializerSettings* settings = nullptr); template <typename ObjectType> AZ::Outcome<void, AZStd::string> SaveObjectToStream(const ObjectType* classPtr, IO::GenericStream& stream, const ObjectType* defaultClassPtr = nullptr, const JsonSerializerSettings* settings = nullptr) { return SaveObjectToStreamByType(classPtr, AzTypeInfo<ObjectType>::Uuid(), stream, defaultClassPtr, settings); } template <typename ObjectType> AZ::Outcome<void, AZStd::string> SaveObjectToFile(const ObjectType* classPtr, const AZStd::string& filePath, const ObjectType* defaultClassPtr = nullptr, const JsonSerializerSettings* settings = nullptr) { return SaveObjectToFileByType(classPtr, AzTypeInfo<ObjectType>::Uuid(), filePath, defaultClassPtr, settings); } /////////////////////////////////////////////////////////////////////////////////// // Load functions //! Parse json text. Returns a failure with error message if the content is not valid JSON. AZ::Outcome<rapidjson::Document, AZStd::string> ReadJsonString(AZStd::string_view jsonText); //! Parse a json file. Returns a failure with error message if the content is not valid JSON. AZ::Outcome<rapidjson::Document, AZStd::string> ReadJsonFile(AZStd::string_view filePath); //! Parse a json stream. Returns a failure with error message if the content is not valid JSON. AZ::Outcome<rapidjson::Document, AZStd::string> ReadJsonStream(IO::GenericStream& stream); //! Load object with known class type AZ::Outcome<void, AZStd::string> LoadObjectFromStreamByType(void* objectToLoad, const Uuid& objectType, IO::GenericStream& stream, const JsonDeserializerSettings* settings = nullptr); template <typename ObjectType> AZ::Outcome<void, AZStd::string> LoadObjectFromStream(ObjectType& objectToLoad, IO::GenericStream& stream, const JsonDeserializerSettings* settings = nullptr) { return LoadObjectFromStreamByType(&objectToLoad, AzTypeInfo<ObjectType>::Uuid(), stream, settings); } template <typename ObjectType> AZ::Outcome<void, AZStd::string> LoadObjectFromFile(ObjectType& objectToLoad, const AZStd::string& filePath, const JsonDeserializerSettings* settings = nullptr) { AZ::IO::FileIOStream inputFileStream; if (!inputFileStream.Open(filePath.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeText)) { return AZ::Failure(AZStd::string::format("Error opening file '%s' for reading", filePath.c_str())); } return LoadObjectFromStream(objectToLoad, inputFileStream, settings); } //! Load any object AZ::Outcome<AZStd::any, AZStd::string> LoadAnyObjectFromStream(IO::GenericStream& stream, const JsonDeserializerSettings* settings = nullptr); AZ::Outcome<AZStd::any, AZStd::string> LoadAnyObjectFromFile(const AZStd::string& filePath,const JsonDeserializerSettings* settings = nullptr); } // namespace JsonSerializationUtils } // namespace Az
2,005
746
package org.protege.editor.core.ui.util; import javax.swing.*; import java.awt.*; /** * <NAME> * Stanford Center for Biomedical Informatics Research * 4 Aug 16 */ public class InlineFieldSearchIcon implements Icon { private static final int WIDTH = 12; private static final int HEIGHT = 12; private final Color iconColor; private double scaleFactor = 1.0; public static final BasicStroke RIM_STROKE = new BasicStroke(2f); public static final BasicStroke HANDLE_STROKE = new BasicStroke(3f); public InlineFieldSearchIcon(Color color) { this.iconColor = color; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(iconColor); g.translate(x, y); Graphics2D g2 = (Graphics2D) g; Stroke s = g2.getStroke(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.scale(scaleFactor, scaleFactor); g2.setStroke(HANDLE_STROKE); g.drawLine(6, 6, 11, 11); g.setColor(c.getBackground()); g2.setStroke(RIM_STROKE); g.fillOval(1, 1, 8, 8); g.setColor(iconColor); g.drawOval(1, 1, 8, 8); g.setColor(iconColor); g2.setStroke(s); g.translate(-x, -y); g2.scale(1, 1); } @Override public int getIconWidth() { return (int) (WIDTH * scaleFactor + 0.5); } @Override public int getIconHeight() { return (int) (HEIGHT * scaleFactor + 0.5); } /** * Sets the scale factor that can be used to scale the icon up or down. The default value is 1.0. * @param scaleFactor The scale factor. */ public void setScaleFactor(double scaleFactor) { this.scaleFactor = scaleFactor; } }
782
573
#!/usr/bin/env python3 from taiseilib.common import ( run_main, ) from pathlib import Path, PureWindowsPath, PurePosixPath import sys def main(args): import argparse parser = argparse.ArgumentParser(description='Because Windows is the worst.', prog=args[0]) parser.add_argument('path', help='the path to operate on' ) parser.add_argument('--from-windows', action='store_true', help='interpret source as a Windows path (default: POSIX path)' ) parser.add_argument('--to-windows', action='store_true', help='output a Windows path (default: POSIX path)' ) parser.add_argument('--escape-backslashes', action='store_true', help='escape any backslashes in the output' ) args = parser.parse_args(args[1:]) if args.from_windows: path = PureWindowsPath(args.path) else: path = PurePosixPath(args.path) if args.to_windows: out = str(PureWindowsPath(path)) else: out = path.as_posix() if args.escape_backslashes: out = out.replace('\\', '\\\\') sys.stdout.write(out) if __name__ == '__main__': run_main(main)
482
2,671
if False: # NL True = False # NEWLINE
20
402
from .element import Element from .navbar import Navbar from .fontawesomeicon import FontAwesomeIcon class View(Element): """Main object representing a webpage""" def __init__(self, title=None, cl=None, style=None, bscss="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", bsjs="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", jquery="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"): self._children = list() if title is None: self.title = "Sofi" else: self.title = title self.cl = cl self.style = style self.bootstrapcss = bscss self.bootstrapjs = bsjs self.jquery = jquery def __repr__(self): return "<View>" def __str__(self): head = [ "<title>", self.title, "</title>", "<link href=\"", self.bootstrapcss, "\" rel=\"stylesheet\">" ] body = [] for child in self._children: if self.check_for_element_available(child, FontAwesomeIcon): head.append('<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"></link>') if type(child) == Navbar: if child.fixed == "top": head.append('<style>/* Added to make room for the navbar at top */\nbody { padding-top: 70px; }\n</style>') body.append(str(child)) output = [] output.append('<head>') output.extend(head) output.append('</head><body') if self.cl: output.append(" class=\"") output.append(self.cl) output.append("\"") if self.style: output.append(" style=\"") output.append(self.style) output.append("\"") output.append(">") output.extend(body) output.append("</body>") return "".join(output) def check_for_element_available(self, child, element): if type(child) == element: return True else: for obj in child._children: if not isinstance(obj, str): result = self.check_for_element_available(obj, element) if result: return True return False
1,170
572
<gh_stars>100-1000 /****************************************************************************/ /*! @file @brief DirectShowのHRESULTをメッセージに変える例外クラス ----------------------------------------------------------------------------- Copyright (C) 2004 T.Imoto <http://www.kaede-software.com> ----------------------------------------------------------------------------- @author T.Imoto @date 2004/08/16 @note 2004/08/16 T.Imoto *****************************************************************************/ #ifndef __DSHOW_EXCEPTION_H__ #define __DSHOW_EXCEPTION_H__ #include <dshow.h> //---------------------------------------------------------------------------- //! @brief DirectShowのHRESULTをメッセージに変える例外クラス //! //! 文字列の初期化をこまめに行うので、使用時はエラー時のみに限り、 //! エラー処理のif文の中でインスタンス化するようにした方がよい。 //---------------------------------------------------------------------------- class DShowException { TCHAR m_ErrorMes[MAX_ERROR_TEXT_LEN]; HRESULT m_Hr; public: DShowException( ) throw( ); DShowException(const DShowException& right) throw( ); DShowException( HRESULT hr ) throw( ); DShowException& operator=(const DShowException& right) throw( ); virtual ~DShowException() throw( ); virtual const TCHAR *what( ) const throw( ); void SetHResult( HRESULT hr ) throw( ); }; void ThrowDShowException(const tjs_char *comment, HRESULT hr); #endif // __DSHOW_EXCEPTION_H__
475
407
// MIT License // // Copyright (c) 2019 <NAME>, Chair for Embedded Security. All Rights reserved. // Copyright (c) 2021 Max Planck Institute for Security and Privacy. All Rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <QObject> #include <QString> #include <QVariant> namespace hal { class SettingsWidget; /** * @ingroup settings * @brief The interface for the logical part of a setting. * * The SettingsItem class provides an interface and commonly shared function * for all kinds of specific settings. It is the logical part of a setting in * comparison to the SettingsWidget, which represents the corresponding visual * part. It -more precise the specific settings- connects to the SettingsManager. */ class SettingsItem : public QObject { Q_OBJECT public: /** * The constructor. * * @param parent - The settings parent. */ SettingsItem(QObject* parent = nullptr) : QObject(parent) {} /** * The destructor. */ virtual ~ SettingsItem() {} /** * Get the current value. * * @return The current value. */ virtual QVariant value() const = 0; /** * Get the default value. * * @return The default value. */ virtual QVariant defaultValue() const = 0; /** * Sets the value of the setting. * * @param v - The value to set. */ virtual void setValue(const QVariant& v) = 0; /** * Sets the default value of the setting. * * @param dv - The default value. */ virtual void setDefaultValue(const QVariant& dv) = 0; /** * Get a corresponding SettingsWidget which holds a reference to the * settings item. * * @param parent - The widget's soon to be parent. * @return A SettingsWidget able to modify the setting. */ virtual SettingsWidget* editWidget(QWidget* parent = nullptr) = 0; /** * Compares the default value to the current value. * * @return True if they are the same. False otherwise. */ virtual bool isDefaultValue() const { return value() == defaultValue(); } /** * Get the value of the item. See value(). * * @return The current value. */ virtual QVariant persistToSettings() const { return value(); } /** * Sets the value of the settings to the given value. * * @param val - The value to set. */ virtual void restoreFromSettings(const QVariant& val) { setValue(val); } /** * Checks if the setting is a global setting. * * @return True if it is, False otherwise. */ virtual bool isGlobal() const { return mIsGlobal; } /** * Get the settings label. * * @return The label. */ virtual QString label() const { return mLabel; } /** * Get the setting's description. * * @return The setting's description. */ virtual QString description() const { return mDescription; } /** * Get the setting's tag (key). * * @return The tag (key). */ virtual QString tag() const { return mTag; } /** * Get the category this setting belongs to. * * @return The category. */ virtual QString category() const { return mCategory; } Q_SIGNALS: /** * Q_SIGNAL that should be commited when the value changes. */ void valueChanged(); protected: bool mIsGlobal; QString mLabel; QString mDescription; QString mTag; QString mCategory; }; }
2,202
1,005
#ifndef TACO_STORAGE_TYPED_VECTOR_H #define TACO_STORAGE_TYPED_VECTOR_H #include <cstring> #include <vector> #include <taco/type.h> #include <taco/storage/array.h> #include <taco/storage/typed_value.h> #include <taco/storage/typed_index.h> namespace taco { /// Like std::vector but for a dynamic DataType type. Backed by a char vector /// Templated over TypedComponentVal or TypedIndexVal template <typename Typed> class TypedVector { public: /// Create a new empty TypedVector of undefined type TypedVector() : type(Datatype::Undefined) { } /// Create a new empty TypedVector of specified type TypedVector(Datatype type) : type(type) { } /// Create a new empty TypedVector initialized to specified size TypedVector(Datatype type, size_t size) : type(type) { resize(size); } /// Accesses the value at a given index typename Typed::Ref operator[] (const size_t index) const { return get(index); } /// Accesses the value at a given index typename Typed::Ref get(size_t index) const { return typename Typed::Ref(getType(), (void *) &charVector[index * type.getNumBytes()]); } /// Gets the type of the TypedVector Datatype getType() const { return type; } /// Gets the size of the TypedVector size_t size() const { return charVector.size() / type.getNumBytes(); } /// Resizes the TypedVector to a given size (in number of items) void resize(size_t size) { charVector.resize(size * type.getNumBytes()); } /// Returns a pointer to the underlying char vector char* data() const { return (char *) charVector.data(); } /// Clears the data from the TypedVector void clear() { charVector.clear(); } /// Sets the value at a given index to either TypedComponentVal or TypedIndexVal void set(size_t index, Typed value) { taco_iassert(value.getType() == type); get(index) = value; } /// Sets the value at a given index to either TypedComponentRef or TypedIndexRef void set(size_t index, typename Typed::Ref value) { taco_iassert(value.getType() == type); get(index) = value; } /// Sets the value at a given index to a constant cast to the type of the TypedVector template<typename T> void set(size_t index, T constant) { set(index, Typed(type, constant)); } /// Sets the value at a given index to the value stored at a pointer of the type of the TypedVector template<typename T> void set(size_t index, T* value) { get(index) = typename Typed::Ref(type, (void *) value); } /// Push value at pointer of type of the TypedVector void push_back(void *value) { resize(size() + 1); set(size() - 1, value); } /// Push constant casted to type of the TypedVector template<typename T> void push_back(T constant) { resize(size() + 1); set(size() - 1, constant); } /// Push typed value (either TypedComponentVal or TypedIndexVal) void push_back(Typed value) { taco_iassert(value.getType() == type); resize(size() + 1); set(size() - 1, value); } /// Push typed reference (either TypedComponentRef or TypedIndexRef) void push_back(typename Typed::Ref value) { taco_iassert(value.getType() == type); resize(size() + 1); set(size() - 1, value); } /// Push back all values in TypedVector void push_back_vector(TypedVector vector) { taco_iassert(type == vector.getType()); resize(size() + vector.size()); memcpy(&get(size()-vector.size()).get(), vector.data(), type.getNumBytes()*vector.size()); } /// Push back all values in std::vector template<typename T> void push_back_vector(std::vector<T> v) { resize(size() + v.size()); for (size_t i = 0; i < v.size(); i++) { set(size() - v.size() + i, v.at(i)); } } /// Compare two TypedVectors bool operator==(const TypedVector &other) const { if (size() != other.size()) return false; if (type != other.getType()) return false; return (memcmp(data(), other.data(), size()*type.getNumBytes()) == 0); } /// Compare two TypedVectors bool operator!=(const TypedVector &other) const { return !(*this == other); } /// Comparison operator needed to use in Set bool operator>(const TypedVector &other) const { return !(*this < other) && !(*this == other); } /// Comparison operator needed to use in Set. Uses lexicographical comparison. bool operator<(const TypedVector &other) const { size_t minSize = size() < other.size() ? size() : other.size(); for (size_t i = 0; i < minSize; i++) { if (get(i) < other.get(i)) return true; if (get(i) > other.get(i)) return false; } return size() < other.size(); } /// Iterator for vector /// Implementation based off of https://gist.github.com/jeetsukumaran/307264 class iterator { public: /// Typedef for self typedef iterator self_type; /// Typedef for type of value (either TypedComponentVal or TypedIndexVal) typedef Typed value_type; /// Type of reference of value_type (either TypedComponentRef or TypedIndexRef) typedef typename Typed::Ref reference; /// Type of pointer of value_type (either TypedComponentPtr or TypedIndexPtr) typedef typename Typed::Ptr pointer; /// Help compiler choose right iterator typedef std::forward_iterator_tag iterator_category; /// Create an iterator from pointer and datatype iterator(pointer ptr, Datatype type) : ptr_(ptr), type(type) { } /// Post-increment iterator self_type operator++(int junk) { self_type i = *this; ptr_++; return i; } /// Pre-increment iterator self_type operator++() { ptr_++; return *this; } /// Get current reference of iterator reference operator*() { return *ptr_; } /// Get current pointer of iterator pointer operator->() { return ptr_; } /// Equality comparison of two iterators bool operator==(const self_type& rhs) { return ptr_ == rhs.ptr_; } /// Inequality comparison of two iterators bool operator!=(const self_type& rhs) { return ptr_ != rhs.ptr_; } private: /// Current pointer of iterator pointer ptr_; /// Data type of iterator Datatype type; }; /// Constant iterator for vector /// Implementation based off of https://gist.github.com/jeetsukumaran/307264 class const_iterator { public: /// Typedef for self typedef const_iterator self_type; /// Typedef for type of value (either TypedComponentVal or TypedIndexVal) typedef Typed value_type; /// Type of reference of value_type (either TypedComponentRef or TypedIndexRef) typedef typename Typed::Ref reference; /// Type of pointer of value_type (either TypedComponentPtr or TypedIndexPtr) typedef typename Typed::Ptr pointer; /// Help compiler choose right iterator typedef std::forward_iterator_tag iterator_category; /// Create an iterator from pointer and datatype const_iterator(pointer ptr, Datatype type) : ptr_(ptr), type(type) { } /// Post-increment iterator self_type operator++(int junk) { self_type i = *this; ptr_++; return i; } /// Pre-increment iterator self_type operator++() { ptr_++; return *this; } /// Get current reference of iterator reference operator*() { return *ptr_; } /// Get current pointer of iterator pointer operator->() { return ptr_; } /// Equality comparison of two iterators bool operator==(const self_type& rhs) { return ptr_ == rhs.ptr_; } /// Inequality comparison of two iterators bool operator!=(const self_type& rhs) { return ptr_ != rhs.ptr_; } private: /// Current pointer of iterator pointer ptr_; /// Data type of iterator Datatype type; }; /// Return iterator at start of TypedVector iterator begin() { return iterator(&get(0), type); } /// Return iterator at end of TypedVector iterator end() { return iterator(&get(size()), type); } /// Return constant iterator at start of TypedVector const_iterator begin() const { return const_iterator(&get(0), type); } /// Return constant iterator at end of TypedVector const_iterator end() const { return const_iterator(&get(size()), type); } private: /// Char vector that backs the TypedVector std::vector<char> charVector; /// Type of items in TypedVector Datatype type; }; /// Type alias for a TypedVector templated to TypedComponentVals using TypedComponentVector = TypedVector<TypedComponentVal>; /// Type alias for a TypedVector templated to TypedIndexVals using TypedIndexVector = TypedVector<TypedIndexVal>; } #endif
2,864
43,319
<gh_stars>1000+ { "name": "commonjs-esm", "private": true, "module": "dist/index.js", "dependencies": { "lodash": "*" } }
64
348
{"nom":"Tourtrol","circ":"2ème circonscription","dpt":"Ariège","inscrits":204,"abs":81,"votants":123,"blancs":8,"nuls":5,"exp":110,"res":[{"nuance":"REM","nom":"<NAME>","voix":60},{"nuance":"FI","nom":"<NAME>","voix":50}]}
89
366
<gh_stars>100-1000 #!/usr/bin/env python import distutils.core import sys version = "1.0" distutils.core.setup( name="pyxl", version=version, packages = ["pyxl", "pyxl.codec", "pyxl.scripts", "pyxl.examples"], author="<NAME>", author_email="<EMAIL>", url="http://github.com/awable/pyxl", download_url="http://github.com/downloads/awable/pyxl/pyxl-%s.tar.gz" % version, license="http://www.apache.org/licenses/LICENSE-2.0", description=""" Pyxl is an open source package that extends Python to support inline HTML. It converts HTML fragments into valid Python expressions, and is meant as a replacement for traditional python templating systems like Mako or Cheetah. It automatically escapes data, enforces correct markup and makes it easier to write reusable and well structured UI code. Pyxl was inspired by the XHP project at Facebook. """ )
338
591
/* * ====================== BioSoupColor.h ========================== * -- tpr -- * CREATE -- 2020.03.10 * MODIFY -- * ---------------------------------------------------------- */ #ifndef TPR_BIO_SOUP_COLOR_H #define TPR_BIO_SOUP_COLOR_H #include "pch.h" #include <utility> //-------------------- Engine --------------------// #include "FloatVec.h" namespace gameObjs::bioSoup {//------------- namespace gameObjs::bioSoup ---------------- class Color { public: constexpr Color()=default; constexpr Color( const FloatVec3 &light_, const FloatVec3 &mid_, const FloatVec3 &dark_ ): light(light_), mid(mid_), dark(dark_) {} // param: pct_ (0, 1.0) // return: // true - do close // false - already close enough, do nothing inline bool close_to( const Color &target_, float pct_ )noexcept{ FloatVec3 lOff = target_.light - this->light; FloatVec3 mOff = target_.mid - this->mid; FloatVec3 dOff = target_.dark - this->dark; constexpr FloatVec3 zero { 0.0f, 0.0f, 0.0f }; //-- if( is_closeEnough( lOff, zero, 0.01f ) && is_closeEnough( mOff, zero, 0.01f ) && is_closeEnough( dOff, zero, 0.01f ) ){ return false; // close enough } // do close this->light += lOff * pct_; this->mid += mOff * pct_; this->dark += dOff * pct_; return true; } //===// FloatVec3 light; FloatVec3 mid; FloatVec3 dark; }; class ColorNode { public: const Color *colorPtr {}; float closePct {}; // 从任何颜色,接近本 node color 的接近率 (0.0f, 1.0f) }; // 一组循环流动的 颜色信息, // 当 diosoup 进入一种 chain 实例,就会停留在里面,循环播放这些颜色 class ColorNodeChain{ public: static void init_for_state()noexcept; // 切换不同的 chain inline static void bind_a_chain( const std::string &chainName_ )noexcept{ tprAssert( ColorNodeChain::chains.find(chainName_) != ColorNodeChain::chains.end() ); ColorNodeChain::currentChainPtr = ColorNodeChain::chains.at(chainName_).get(); //-- ColorNodeChain::nodeIdx = 0; } // 自动计算 本帧的 颜色 static const Color &calc_next_baseColor()noexcept{ const ColorNode &node = ColorNodeChain::currentChainPtr->get_node( ColorNodeChain::nodeIdx ); bool ret = ColorNodeChain::currentColor.close_to( *node.colorPtr , node.closePct ); if( !ret ){ ColorNodeChain::nodeIdx++; if( ColorNodeChain::nodeIdx >= ColorNodeChain::currentChainPtr->nodes.size() ){ ColorNodeChain::nodeIdx = 0; } } //=== return ColorNodeChain::currentColor; } private: // 在构造语句中,直接创建 nodes explicit ColorNodeChain( std::vector<ColorNode> &&nodes_ ): nodes( std::move(nodes_) ) {} const ColorNode &get_node( size_t idx_ )const noexcept{ tprAssert( this->nodes.size() > idx_ ); return this->nodes.at(idx_); } const std::vector<ColorNode> nodes; // 在 init 就被创建的 固定不变的数据 //------------ all chains --------------// static std::unordered_map<std::string, std::unique_ptr<ColorNodeChain>> chains; //------------- user data -------------// static const ColorNodeChain *currentChainPtr; static size_t nodeIdx; // 指向 currentChain 中的 targetNode static Color currentColor; // 调和色,返回给用户 }; }//------------- namespace gameObjs::bioSoup: end ---------------- #endif
1,848
488
<reponame>maurizioabba/rose<gh_stars>100-1000 #ifndef __removeInit #define __removeInit #include "AstNodePtrs.h" // [MS]: required because we use the STL find algorithm // DQ (12/7/2003): use platform independent macro defined in config.h // #include STL_ALGO_HEADER_FILE // Permited to include AST testing // #include "AstTraversal.h" // [MS] class RemoveInitializedNamePtrInheritedAttribute { public: RemoveInitializedNamePtrInheritedAttribute() : firstInitializedNameVisited(false), parentNode(NULL) {} bool firstInitializedNameVisited; SgNode* parentNode; }; // [MS] class RemoveInitializedNamePtr : public SgTopDownProcessing<RemoveInitializedNamePtrInheritedAttribute> { public: // DQ (1/18/2004): list of types that have been traversed static std::list<SgNode*> listOfTraversedNodes; RemoveInitializedNamePtrInheritedAttribute evaluateInheritedAttribute ( SgNode* node, RemoveInitializedNamePtrInheritedAttribute ia); }; // DQ (8/20/2005): Changed name of subTemporaryAstFixes() to removeInitializedNamePtr() // to match the design of the other AST fixup operations in this directory. void removeInitializedNamePtr(SgNode* node); // [MS]: delete AST nodes which represent operators and do not have any successor. // case1: SgDotExp: can have 2 successors, both can be null class DeleteEmptyOperatorNodes : public AstNodePtrs { protected: // DQ (1/18/2004): list of types that have been traversed static std::list<SgNode*> listOfTraversedTypes; protected: virtual void visitWithAstNodePointersList(SgNode* node, AstNodePointersList l); }; #endif
667
493
import numpy as np import torch from torch import nn from core import * from collections import namedtuple from itertools import count torch.backends.cudnn.benchmark = True device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") cpu = torch.device("cpu") @cat.register(torch.Tensor) def _(*xs): return torch.cat(xs) @to_numpy.register(torch.Tensor) def _(x): return x.detach().cpu().numpy() @pad.register(torch.Tensor) def _(x, border): return nn.ReflectionPad2d(border)(x) @transpose.register(torch.Tensor) def _(x, source, target): return x.permute([source.index(d) for d in target]) def to(*args, **kwargs): return lambda x: x.to(*args, **kwargs) @flip_lr.register(torch.Tensor) def _(x): return torch.flip(x, [-1]) ##################### ## dataset ##################### from functools import lru_cache as cache @cache(None) def cifar10(root='./data'): try: import torchvision download = lambda train: torchvision.datasets.CIFAR10(root=root, train=train, download=True) return {k: {'data': v.data, 'targets': v.targets} for k,v in [('train', download(train=True)), ('valid', download(train=False))]} except ImportError: from tensorflow.keras import datasets (train_images, train_labels), (valid_images, valid_labels) = datasets.cifar10.load_data() return { 'train': {'data': train_images, 'targets': train_labels.squeeze()}, 'valid': {'data': valid_images, 'targets': valid_labels.squeeze()} } cifar10_mean, cifar10_std = [ (125.31, 122.95, 113.87), # equals np.mean(cifar10()['train']['data'], axis=(0,1,2)) (62.99, 62.09, 66.70), # equals np.std(cifar10()['train']['data'], axis=(0,1,2)) ] cifar10_classes= 'airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck'.split(', ') ##################### ## data loading ##################### class DataLoader(): def __init__(self, dataset, batch_size, shuffle, set_random_choices=False, num_workers=0, drop_last=False): self.dataset = dataset self.batch_size = batch_size self.set_random_choices = set_random_choices self.dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, shuffle=shuffle, drop_last=drop_last ) def __iter__(self): if self.set_random_choices: self.dataset.set_random_choices() return ({'input': x.to(device).half(), 'target': y.to(device).long()} for (x,y) in self.dataloader) def __len__(self): return len(self.dataloader) #GPU dataloading chunks = lambda data, splits: (data[start:end] for (start, end) in zip(splits, splits[1:])) even_splits = lambda N, num_chunks: np.cumsum([0] + [(N//num_chunks)+1]*(N % num_chunks) + [N//num_chunks]*(num_chunks - (N % num_chunks))) def shuffled(xs, inplace=False): xs = xs if inplace else copy.copy(xs) np.random.shuffle(xs) return xs def transformed(data, targets, transform, max_options=None, unshuffle=False): i = torch.randperm(len(data), device=device) data = data[i] options = shuffled(transform.options(data.shape), inplace=True)[:max_options] data = torch.cat([transform(x, **choice) for choice, x in zip(options, chunks(data, even_splits(len(data), len(options))))]) return (data[torch.argsort(i)], targets) if unshuffle else (data, targets[i]) class GPUBatches(): def __init__(self, batch_size, transforms=(), dataset=None, shuffle=True, drop_last=False, max_options=None): self.dataset, self.transforms, self.shuffle, self.max_options = dataset, transforms, shuffle, max_options N = len(dataset['data']) self.splits = list(range(0, N+1, batch_size)) if not drop_last and self.splits[-1] != N: self.splits.append(N) def __iter__(self): data, targets = self.dataset['data'], self.dataset['targets'] for transform in self.transforms: data, targets = transformed(data, targets, transform, max_options=self.max_options, unshuffle=not self.shuffle) if self.shuffle: i = torch.randperm(len(data), device=device) data, targets = data[i], targets[i] return ({'input': x.clone(), 'target': y} for (x, y) in zip(chunks(data, self.splits), chunks(targets, self.splits))) def __len__(self): return len(self.splits) - 1 ##################### ## Layers ##################### #Network class Network(nn.Module): def __init__(self, net): super().__init__() self.graph = build_graph(net) for path, (val, _) in self.graph.items(): setattr(self, path.replace('/', '_'), val) def nodes(self): return (node for node, _ in self.graph.values()) def forward(self, inputs): outputs = dict(inputs) for k, (node, ins) in self.graph.items(): #only compute nodes that are not supplied as inputs. if k not in outputs: outputs[k] = node(*[outputs[x] for x in ins]) return outputs def half(self): for node in self.nodes(): if isinstance(node, nn.Module) and not isinstance(node, nn.BatchNorm2d): node.half() return self class Identity(namedtuple('Identity', [])): def __call__(self, x): return x class Add(namedtuple('Add', [])): def __call__(self, x, y): return x + y class AddWeighted(namedtuple('AddWeighted', ['wx', 'wy'])): def __call__(self, x, y): return self.wx*x + self.wy*y class Mul(nn.Module): def __init__(self, weight): super().__init__() self.weight = weight def __call__(self, x): return x*self.weight class Flatten(nn.Module): def forward(self, x): return x.view(x.size(0), x.size(1)) class Concat(nn.Module): def forward(self, *xs): return torch.cat(xs, 1) class BatchNorm(nn.BatchNorm2d): def __init__(self, num_features, eps=1e-05, momentum=0.1, weight_freeze=False, bias_freeze=False, weight_init=1.0, bias_init=0.0): super().__init__(num_features, eps=eps, momentum=momentum) if weight_init is not None: self.weight.data.fill_(weight_init) if bias_init is not None: self.bias.data.fill_(bias_init) self.weight.requires_grad = not weight_freeze self.bias.requires_grad = not bias_freeze class GhostBatchNorm(BatchNorm): def __init__(self, num_features, num_splits, **kw): super().__init__(num_features, **kw) self.num_splits = num_splits self.register_buffer('running_mean', torch.zeros(num_features*self.num_splits)) self.register_buffer('running_var', torch.ones(num_features*self.num_splits)) def train(self, mode=True): if (self.training is True) and (mode is False): #lazily collate stats when we are going to use them self.running_mean = torch.mean(self.running_mean.view(self.num_splits, self.num_features), dim=0).repeat(self.num_splits) self.running_var = torch.mean(self.running_var.view(self.num_splits, self.num_features), dim=0).repeat(self.num_splits) return super().train(mode) def forward(self, input): N, C, H, W = input.shape if self.training or not self.track_running_stats: return nn.functional.batch_norm( input.view(-1, C*self.num_splits, H, W), self.running_mean, self.running_var, self.weight.repeat(self.num_splits), self.bias.repeat(self.num_splits), True, self.momentum, self.eps).view(N, C, H, W) else: return nn.functional.batch_norm( input, self.running_mean[:self.num_features], self.running_var[:self.num_features], self.weight, self.bias, False, self.momentum, self.eps) # Losses class CrossEntropyLoss(namedtuple('CrossEntropyLoss', [])): def __call__(self, log_probs, target): return torch.nn.functional.nll_loss(log_probs, target, reduction='none') class KLLoss(namedtuple('KLLoss', [])): def __call__(self, log_probs): return -log_probs.mean(dim=1) class Correct(namedtuple('Correct', [])): def __call__(self, classifier, target): return classifier.max(dim = 1)[1] == target class LogSoftmax(namedtuple('LogSoftmax', ['dim'])): def __call__(self, x): return torch.nn.functional.log_softmax(x, self.dim, _stacklevel=5) x_ent_loss = Network({ 'loss': (nn.CrossEntropyLoss(reduction='none'), ['logits', 'target']), 'acc': (Correct(), ['logits', 'target']) }) label_smoothing_loss = lambda alpha: Network({ 'logprobs': (LogSoftmax(dim=1), ['logits']), 'KL': (KLLoss(), ['logprobs']), 'xent': (CrossEntropyLoss(), ['logprobs', 'target']), 'loss': (AddWeighted(wx=1-alpha, wy=alpha), ['xent', 'KL']), 'acc': (Correct(), ['logits', 'target']), }) trainable_params = lambda model: {k:p for k,p in model.named_parameters() if p.requires_grad} ##################### ## Optimisers ##################### from functools import partial def nesterov_update(w, dw, v, lr, weight_decay, momentum): dw.add_(weight_decay, w).mul_(-lr) v.mul_(momentum).add_(dw) w.add_(dw.add_(momentum, v)) norm = lambda x: torch.norm(x.reshape(x.size(0),-1).float(), dim=1)[:,None,None,None] def LARS_update(w, dw, v, lr, weight_decay, momentum): nesterov_update(w, dw, v, lr*(norm(w)/(norm(dw)+1e-2)).to(w.dtype), weight_decay, momentum) def zeros_like(weights): return [torch.zeros_like(w) for w in weights] def optimiser(weights, param_schedule, update, state_init): weights = list(weights) return {'update': update, 'param_schedule': param_schedule, 'step_number': 0, 'weights': weights, 'opt_state': state_init(weights)} def opt_step(update, param_schedule, step_number, weights, opt_state): step_number += 1 param_values = {k: f(step_number) for k, f in param_schedule.items()} for w, v in zip(weights, opt_state): if w.requires_grad: update(w.data, w.grad.data, v, **param_values) return {'update': update, 'param_schedule': param_schedule, 'step_number': step_number, 'weights': weights, 'opt_state': opt_state} LARS = partial(optimiser, update=LARS_update, state_init=zeros_like) SGD = partial(optimiser, update=nesterov_update, state_init=zeros_like) ##################### ## training ##################### from itertools import chain def reduce(batches, state, steps): #state: is a dictionary #steps: are functions that take (batch, state) #and return a dictionary of updates to the state (or None) for batch in chain(batches, [None]): #we send an extra batch=None at the end for steps that #need to do some tidying-up (e.g. log_activations) for step in steps: updates = step(batch, state) if updates: for k,v in updates.items(): state[k] = v return state #define keys in the state dict as constants MODEL = 'model' LOSS = 'loss' VALID_MODEL = 'valid_model' OUTPUT = 'output' OPTS = 'optimisers' ACT_LOG = 'activation_log' WEIGHT_LOG = 'weight_log' #step definitions def forward(training_mode): def step(batch, state): if not batch: return model = state[MODEL] if training_mode or (VALID_MODEL not in state) else state[VALID_MODEL] if model.training != training_mode: #without the guard it's slow! model.train(training_mode) return {OUTPUT: state[LOSS](model(batch))} return step def forward_tta(tta_transforms): def step(batch, state): if not batch: return model = state[MODEL] if (VALID_MODEL not in state) else state[VALID_MODEL] if model.training: model.train(False) logits = torch.mean(torch.stack([model({'input': transform(batch['input'].clone())})['logits'].detach() for transform in tta_transforms], dim=0), dim=0) return {OUTPUT: state[LOSS](dict(batch, logits=logits))} return step def backward(dtype=None): def step(batch, state): state[MODEL].zero_grad() if not batch: return loss = state[OUTPUT][LOSS] if dtype is not None: loss = loss.to(dtype) loss.sum().backward() return step def opt_steps(batch, state): if not batch: return return {OPTS: [opt_step(**opt) for opt in state[OPTS]]} def log_activations(node_names=('loss', 'acc')): def step(batch, state): if '_tmp_logs_' not in state: state['_tmp_logs_'] = [] if batch: state['_tmp_logs_'].extend((k, state[OUTPUT][k].detach()) for k in node_names) else: res = {k: to_numpy(torch.cat(xs)).astype(np.float) for k, xs in group_by_key(state['_tmp_logs_']).items()} del state['_tmp_logs_'] return {ACT_LOG: res} return step epoch_stats = lambda state: {k: np.mean(v) for k, v in state[ACT_LOG].items()} def update_ema(momentum, update_freq=1): n = iter(count()) rho = momentum**update_freq def step(batch, state): if not batch: return if (next(n) % update_freq) != 0: return for v, ema_v in zip(state[MODEL].state_dict().values(), state[VALID_MODEL].state_dict().values()): if not v.dtype.is_floating_point: continue #skip things like num_batches_tracked. ema_v *= rho ema_v += (1-rho)*v return step default_train_steps = (forward(training_mode=True), log_activations(('loss', 'acc')), backward(), opt_steps) default_valid_steps = (forward(training_mode=False), log_activations(('loss', 'acc'))) def train_epoch(state, timer, train_batches, valid_batches, train_steps=default_train_steps, valid_steps=default_valid_steps, on_epoch_end=(lambda state: state)): train_summary, train_time = epoch_stats(on_epoch_end(reduce(train_batches, state, train_steps))), timer() valid_summary, valid_time = epoch_stats(reduce(valid_batches, state, valid_steps)), timer(include_in_total=False) #DAWNBench rules return { 'train': union({'time': train_time}, train_summary), 'valid': union({'time': valid_time}, valid_summary), 'total time': timer.total_time } #on_epoch_end def log_weights(state, weights): state[WEIGHT_LOG] = state.get(WEIGHT_LOG, []) state[WEIGHT_LOG].append({k: to_numpy(v.data) for k,v in weights.items()}) return state def fine_tune_bn_stats(state, batches, model_key=VALID_MODEL): reduce(batches, {MODEL: state[model_key]}, [forward(True)]) return state #misc def warmup_cudnn(model, loss, batch): #run forward and backward pass of the model #to allow benchmarking of cudnn kernels reduce([batch], {MODEL: model, LOSS: loss}, [forward(True), backward()]) torch.cuda.synchronize() ##################### ## input whitening ##################### def cov(X): X = X/np.sqrt(X.size(0) - 1) return X.t() @ X def patches(data, patch_size=(3, 3), dtype=torch.float32): h, w = patch_size c = data.size(1) return data.unfold(2,h,1).unfold(3,w,1).transpose(1,3).reshape(-1, c, h, w).to(dtype) def eigens(patches): n,c,h,w = patches.shape Σ = cov(patches.reshape(n, c*h*w)) Λ, V = torch.symeig(Σ, eigenvectors=True) return Λ.flip(0), V.t().reshape(c*h*w, c, h, w).flip(0) def whitening_filter(Λ, V, eps=1e-2): filt = nn.Conv2d(3, 27, kernel_size=(3,3), padding=(1,1), bias=False) filt.weight.data = (V/torch.sqrt(Λ+eps)[:,None,None,None]) filt.weight.requires_grad = False return filt
6,698
335
/* * SampleGenerator.h * ----------------- * Purpose: Generate samples from math formulas using muParser * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #pragma once #include "openmpt/all/BuildSettings.hpp" #ifdef MPT_DISABLED_CODE #include "Mptrack.h" #include "Mainfrm.h" #include "Sndfile.h" #include "../muParser/include/muParser.h" // sample length #define SMPGEN_MINLENGTH 1 #define SMPGEN_MAXLENGTH MAX_SAMPLE_LENGTH // sample frequency #define SMPGEN_MINFREQ 1 #define SMPGEN_MAXFREQ 96000 // MAX_SAMPLE_RATE // 16-bit sample quality - when changing this, also change CSampleGenerator::sampling_type and 16-bit flags in SampleGenerator.cpp! #define SMPGEN_MIXBYTES 2 enum smpgen_clip_methods { smpgen_clip, smpgen_overflow, smpgen_normalize, }; class CSampleGenerator { protected: // sample parameters static int sample_frequency; static int sample_length; static mu::string_type expression; static smpgen_clip_methods sample_clipping; // rendering helper variables (they're here for the callback functions) static mu::value_type *sample_buffer; static size_t samples_written; typedef int16 sampling_type; // has to match SMPGEN_MIXBYTES! static constexpr sampling_type sample_maxvalue = (1 << ((SMPGEN_MIXBYTES << 3) - 1)) - 1; // muParser object for parsing the expression mu::Parser muParser; // Rendering callback functions // functions static mu::value_type ClipCallback(mu::value_type val, mu::value_type min, mu::value_type max) { return Clamp(val, min, max); }; static mu::value_type PWMCallback(mu::value_type pos, mu::value_type duty, mu::value_type width) { if(width == 0) return 0; else return (fmod(pos, width) < ((duty / 100) * width)) ? 1 : -1; }; static mu::value_type RndCallback(mu::value_type v) { return v * std::rand() / (mu::value_type)(RAND_MAX + 1.0); }; static mu::value_type SampleDataCallback(mu::value_type v); static mu::value_type TriangleCallback(mu::value_type pos, mu::value_type width) { if((int)width == 0) return 0; else return std::abs(((int)pos % (int)(width)) - width / 2) / (width / 4) - 1; }; // binary operators static mu::value_type ModuloCallback(mu::value_type x, mu::value_type y) { if(y == 0) return 0; else return fmod(x , y); }; void ShowError(mu::Parser::exception_type *e); public: bool ShowDialog(); bool TestExpression(); bool CanRenderSample() const; bool RenderSample(CSoundFile *pSndFile, SAMPLEINDEX nSample); CSampleGenerator(); }; ////////////////////////////////////////////////////////////////////////// // Sample Generator Formula Preset implementation struct samplegen_expression { std::string description; // e.g. "Pulse" mu::string_type expression; // e.g. "pwm(x,y,z)" - empty if this is a sub menu }; #define MAX_SAMPLEGEN_PRESETS 100 class CSmpGenPresets { protected: vector<samplegen_expression> presets; public: bool AddPreset(samplegen_expression new_preset) { if(GetNumPresets() >= MAX_SAMPLEGEN_PRESETS) return false; presets.push_back(new_preset); return true;}; bool RemovePreset(size_t which) { if(which < GetNumPresets()) { presets.erase(presets.begin() + which); return true; } else return false; }; samplegen_expression *GetPreset(size_t which) { if(which < GetNumPresets()) return &presets[which]; else return nullptr; }; size_t GetNumPresets() { return presets.size(); }; void Clear() { presets.clear(); }; CSmpGenPresets() { Clear(); } ~CSmpGenPresets() { Clear(); } }; ////////////////////////////////////////////////////////////////////////// // Sample Generator Dialog implementation class CSmpGenDialog: public CDialog { protected: // sample parameters int sample_frequency; int sample_length; double sample_seconds; mu::string_type expression; smpgen_clip_methods sample_clipping; // pressed "OK"? bool apply; // preset slots CSmpGenPresets presets; HFONT hButtonFont; // "Marlett" font for "dropdown" button void RecalcParameters(bool secondsChanged, bool forceRefresh = false); // function presets void CreateDefaultPresets(); public: const int GetFrequency() { return sample_frequency; }; const int GetLength() { return sample_length; }; const smpgen_clip_methods GetClipping() { return sample_clipping; } const mu::string_type GetExpression() { return expression; }; bool CanApply() { return apply; }; CSmpGenDialog(int freq, int len, smpgen_clip_methods clipping, mu::string_type expr):CDialog(IDD_SAMPLE_GENERATOR, CMainFrame::GetMainFrame()) { sample_frequency = freq; sample_length = len; sample_clipping = clipping; expression = expr; apply = false; } protected: virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void OnCancel(); afx_msg void OnSampleLengthChanged(); afx_msg void OnSampleSecondsChanged(); afx_msg void OnSampleFreqChanged(); afx_msg void OnExpressionChanged(); afx_msg void OnShowExpressions(); afx_msg void OnShowPresets(); afx_msg void OnInsertExpression(UINT nId); afx_msg void OnSelectPreset(UINT nId); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////// // Sample Generator Preset Dialog implementation class CSmpGenPresetDlg: public CDialog { protected: CSmpGenPresets *presets; size_t currentItem; // first item is actually 1! void RefreshList(); public: CSmpGenPresetDlg(CSmpGenPresets *pPresets):CDialog(IDD_SAMPLE_GENERATOR_PRESETS, CMainFrame::GetMainFrame()) { presets = pPresets; currentItem = 0; } protected: virtual BOOL OnInitDialog(); virtual void OnOK(); afx_msg void OnListSelChange(); afx_msg void OnTextChanged(); afx_msg void OnExpressionChanged(); afx_msg void OnAddPreset(); afx_msg void OnRemovePreset(); DECLARE_MESSAGE_MAP() }; #endif // MPT_DISABLED_CODE
1,935
325
<gh_stars>100-1000 #include "il2c_private.h" ///////////////////////////////////////////////////////////// // System.Threading.ParameterizedThreadStart void System_Threading_ParameterizedThreadStart_Invoke(System_Threading_ParameterizedThreadStart* this__, System_Object* obj) { il2c_assert(this__ != NULL); il2c_assert(this__->vptr0__ == &System_Delegate_VTABLE__); il2c_assert(this__->count__ >= 1); uintptr_t index = 0; do { IL2C_METHOD_TABLE* pMethodtbl = &this__->methodtbl__[index]; if (pMethodtbl->target != NULL) ((void (*)(void*, System_Object*))(pMethodtbl->methodPtr))(pMethodtbl->target, obj); else ((void (*)(System_Object*))(pMethodtbl->methodPtr))(obj); index++; } while (il2c_unlikely__(index < this__->count__)); } ///////////////////////////////////////////////// // VTable and runtime type info declarations IL2C_RUNTIME_TYPE_BEGIN( System_Threading_ParameterizedThreadStart, "System.Threading.ParameterizedThreadStart", IL2C_TYPE_VARIABLE | IL2C_TYPE_WITH_MARK_HANDLER, 0, System_MulticastDelegate, System_Delegate_MarkHandler__, 0) IL2C_RUNTIME_TYPE_END();
472
2,338
<reponame>mkinsner/llvm // RUN: %clangxx_msan -O0 -g %s -o %t && not %run %t 2>&1 | FileCheck %s // Verify that CHECK handler prints a stack on CHECK fail. #include <stdlib.h> int main(void) { // Allocate chunk from the secondary allocator to trigger CHECK(IsALigned()) // in its free() path. void *p = malloc(8 << 20); free(reinterpret_cast<char*>(p) + 1); // CHECK: MemorySanitizer: bad pointer // CHECK: MemorySanitizer: CHECK failed // CHECK: #0 return 0; }
184
334
#!/usr/bin/env python # # // SPDX-License-Identifier: BSD-3-CLAUSE # # (C) Copyright 2018, Xilinx, Inc. # import cv2 from turbojpeg import TurboJPEG import timeit import os import multiprocessing as mp import argparse # specifying library path explicitly # jpeg = TurboJPEG(r'D:\turbojpeg.dll') # jpeg = TurboJPEG('/usr/lib64/libturbojpeg.so') # jpeg = TurboJPEG('/usr/local/lib/libturbojpeg.dylib') def absoluteFilePaths(directory): dirlist = [] for dirpath,_,filenames in os.walk(directory): for f in filenames: dirlist.append( os.path.abspath(os.path.join(dirpath, f))) return dirlist # decoding input.jpg to BGR array def img_decode (f): in_file = open(f, 'rb') try: bgr_array = jpeg.decode(in_file.read()) bgr_array = cv2.resize(bgr_array, (224,224)) in_file.close() except Exception, e: bgr_array = None parser = argparse.ArgumentParser() parser.add_argument("--numproc", type=int, default=8) parser.add_argument("--numiter", type=int, default=1) parser.add_argument("--dir", type = str ) parser.add_argument("--lib", type = str, default="./lib") args = parser.parse_args() # using default library installation jpeg = TurboJPEG(args.lib + "/libturbojpeg.so") file_dir = absoluteFilePaths(args.dir) flist = [] for i in range(args.numiter): flist += file_dir p = mp.Pool(processes=args.numproc) elapsed = timeit.default_timer() for i in flist: p.apply_async(img_decode, args=(i,)) p.close() p.join() print ("%g img/s\n" % (len(flist) / (timeit.default_timer() - elapsed)) )
619
563
package com.gentics.mesh.core.data.root.impl; import static com.gentics.mesh.core.data.perm.InternalPermission.READ_PERM; import static com.gentics.mesh.core.data.relationship.GraphRelationships.HAS_ROLE; import static com.gentics.mesh.core.rest.error.Errors.error; import static com.gentics.mesh.madl.index.EdgeIndexDefinition.edgeIndex; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import com.gentics.madl.index.IndexHandler; import com.gentics.madl.type.TypeHandler; import com.gentics.mesh.context.BulkActionContext; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.data.Group; import com.gentics.mesh.core.data.Role; import com.gentics.mesh.core.data.generic.MeshVertexImpl; import com.gentics.mesh.core.data.impl.GroupImpl; import com.gentics.mesh.core.data.impl.RoleImpl; import com.gentics.mesh.core.data.page.Page; import com.gentics.mesh.core.data.page.impl.DynamicTransformablePageImpl; import com.gentics.mesh.core.data.root.RoleRoot; import com.gentics.mesh.core.data.user.HibUser; import com.gentics.mesh.core.rest.role.RoleResponse; import com.gentics.mesh.event.EventQueueBatch; import com.gentics.mesh.parameter.PagingParameters; import com.syncleus.ferma.traversals.VertexTraversal; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @see RoleRoot */ public class RoleRootImpl extends AbstractRootVertex<Role> implements RoleRoot { private static final Logger log = LoggerFactory.getLogger(RoleRootImpl.class); /** * Initialize the vertex type and index. * * @param type * @param index */ public static void init(TypeHandler type, IndexHandler index) { type.createVertexType(RoleRootImpl.class, MeshVertexImpl.class); index.createIndex(edgeIndex(HAS_ROLE).withInOut().withOut()); } @Override public Class<? extends Role> getPersistanceClass() { return RoleImpl.class; } @Override public String getRootLabel() { return HAS_ROLE; } @Override public void addRole(Role role) { if (log.isDebugEnabled()) { log.debug("Adding role {" + role.getUuid() + ":" + role.getName() + "#" + role.id() + "} to roleRoot {" + id() + "}"); } addItem(role); } @Override public void removeRole(Role role) { // TODO delete the role? unlink from all groups? how is ferma / blueprint handling this. Neo4j would explode when trying to remove a node that still has // connecting edges. removeItem(role); } @Override public long globalCount() { return db().count(RoleImpl.class); } @Override public void delete(BulkActionContext bac) { throw error(INTERNAL_SERVER_ERROR, "The global role root can't be deleted."); } @Override public Page<? extends Group> getGroups(Role role, HibUser user, PagingParameters pagingInfo) { VertexTraversal<?, ?, ?> traversal = role.out(HAS_ROLE); return new DynamicTransformablePageImpl<Group>(user, traversal, pagingInfo, READ_PERM, GroupImpl.class); } /** * Create a new role vertex. */ public Role create() { return getGraph().addFramedVertex(RoleImpl.class); } @Override public Role create(InternalActionContext ac, EventQueueBatch batch, String uuid) { throw new RuntimeException("Wrong invocation. Use Dao instead."); } @Override public RoleResponse transformToRestSync(Role element, InternalActionContext ac, int level, String... languageTags) { throw new RuntimeException("Wrong invocation. Use Dao instead."); } }
1,170
909
import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; public class ClosestEntriesTest { private int expected; private List<List<Integer>> sortedArrays; @Test public void findMin1() throws Exception { expected = 1; sortedArrays = Arrays.asList( Arrays.asList(5,10,15), Arrays.asList(3,6,9,12,15), Arrays.asList(8,16,24) ); test(expected, sortedArrays); } @Test public void findMin2() throws Exception { expected = 7; sortedArrays = Arrays.asList( Arrays.asList(1,2,3), Arrays.asList(3,5,7,9), Arrays.asList(9,10,11) ); test(expected, sortedArrays); } private void test(int expected, List<List<Integer>> sortedArrays) { assertEquals(expected, ClosestEntries.findMin(sortedArrays)); } }
463
16,461
#import <UIKit/UIKit.h> #import "ABI42_0_0RNCSafeAreaViewMode.h" #import "ABI42_0_0RNCSafeAreaViewEdges.h" NS_ASSUME_NONNULL_BEGIN @interface ABI42_0_0RNCSafeAreaViewLocalData : NSObject - (instancetype)initWithInsets:(UIEdgeInsets)insets mode:(ABI42_0_0RNCSafeAreaViewMode)mode edges:(ABI42_0_0RNCSafeAreaViewEdges)edges; @property (atomic, readonly) UIEdgeInsets insets; @property (atomic, readonly) ABI42_0_0RNCSafeAreaViewMode mode; @property (atomic, readonly) ABI42_0_0RNCSafeAreaViewEdges edges; @end NS_ASSUME_NONNULL_END
228
3,384
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #pragma mark Blocks typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown #pragma mark Named Structures struct CGPoint { double x; double y; }; struct CGRect { struct CGPoint _field1; struct CGSize _field2; }; struct CGSize { double _field1; double _field2; }; struct UIEdgeInsets { double top; double left; double bottom; double right; }; struct UIOffset { double _field1; double _field2; }; struct _NSRange { unsigned long long _field1; unsigned long long _field2; }; #pragma mark - // // File: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/ToneKit.framework/ToneKit // UUID: D7091C57-01BE-3E51-AE07-8DAD91EC7D68 // // Arch: x86_64 // Current version: 1.0.0 // Compatibility version: 1.0.0 // Source version: 252.0.0.0.0 // Minimum iOS version: 8.0.0 // SDK version: 8.0.0 // // Objective-C Garbage Collection: Unsupported // @protocol MPMediaPickerControllerDelegate <NSObject> @optional - (void)mediaPickerDidCancel:(MPMediaPickerController *)arg1; - (void)mediaPicker:(MPMediaPickerController *)arg1 didPickMediaItems:(MPMediaItemCollection *)arg2; @end @protocol NSObject @property(readonly, copy) NSString *description; @property(readonly) Class superclass; @property(readonly) unsigned long long hash; - (struct _NSZone *)zone; - (unsigned long long)retainCount; - (id)autorelease; - (oneway void)release; - (id)retain; - (_Bool)respondsToSelector:(SEL)arg1; - (_Bool)conformsToProtocol:(Protocol *)arg1; - (_Bool)isMemberOfClass:(Class)arg1; - (_Bool)isKindOfClass:(Class)arg1; - (_Bool)isProxy; - (id)performSelector:(SEL)arg1 withObject:(id)arg2 withObject:(id)arg3; - (id)performSelector:(SEL)arg1 withObject:(id)arg2; - (id)performSelector:(SEL)arg1; - (id)self; - (Class)class; - (_Bool)isEqual:(id)arg1; @optional @property(readonly, copy) NSString *debugDescription; @end @protocol TKPickerContainerItem <NSObject> @property(readonly, nonatomic) long long numberOfChildren; - (TKPickerItem *)childItemAtIndex:(long long)arg1; @end @protocol TKTonePickerControllerDelegate <NSObject> @optional - (void)tonePickerController:(TKTonePickerController *)arg1 selectedToneWithIdentifier:(NSString *)arg2; - (void)tonePickerController:(TKTonePickerController *)arg1 didUpdateDetailText:(NSString *)arg2 ofTonePickerItem:(TKTonePickerItem *)arg3; - (void)tonePickerController:(TKTonePickerController *)arg1 didUpdateCheckedStatus:(_Bool)arg2 ofTonePickerItem:(TKTonePickerItem *)arg3; - (void)tonePickerControllerDidReloadTones:(TKTonePickerController *)arg1; @end @protocol TKTonePickerControllerDelegateInternal <NSObject> @optional - (void)tonePickerControllerRequestsPresentingVibrationPicker:(TKTonePickerController *)arg1; - (void)tonePickerControllerRequestsPresentingToneStore:(TKTonePickerController *)arg1; - (void)tonePickerController:(TKTonePickerController *)arg1 requestsPresentingToneClassicsPickerForItem:(TKTonePickerItem *)arg2; - (void)tonePickerControllerDidStopPlaying:(TKTonePickerController *)arg1 withFadeOutDuration:(double)arg2; - (void)tonePickerControllerRequestsPresentingMediaItemPicker:(TKTonePickerController *)arg1; - (void)tonePickerController:(TKTonePickerController *)arg1 didSelectMediaItemAtIndex:(unsigned long long)arg2 selectionDidChange:(_Bool)arg3; - (unsigned long long)tonePickerController:(TKTonePickerController *)arg1 indexOfMediaItemWithIdentifier:(NSNumber *)arg2; - (NSString *)tonePickerController:(TKTonePickerController *)arg1 titleOfMediaItemAtIndex:(unsigned long long)arg2; - (NSNumber *)tonePickerController:(TKTonePickerController *)arg1 identifierOfMediaItemAtIndex:(unsigned long long)arg2; - (unsigned long long)numberOfMediaItemsInTonePickerController:(TKTonePickerController *)arg1; - (void)tonePickerControllerRequestsMediaItemsRefresh:(TKTonePickerController *)arg1; - (_Bool)tonePickerControllerShouldShowMedia:(TKTonePickerController *)arg1; - (void)tonePickerController:(TKTonePickerController *)arg1 selectedMediaItemWithIdentifier:(NSNumber *)arg2; @end @protocol TKTonePickerTableViewControllerHelper <NSObject> - (void)tonePickerTableViewControllerWillBeDeallocated:(UITableViewController<TKTonePickerTableViewLayoutMarginsObserver> *)arg1; - (void)tonePickerTableViewWillDisappear:(_Bool)arg1; - (void)tableView:(UITableView *)arg1 didSelectRowAtIndexPath:(NSIndexPath *)arg2 forPickerRowItem:(TKPickerRowItem *)arg3; - (void)updateCell:(UITableViewCell *)arg1 withDetailText:(NSString *)arg2; - (void)updateCell:(UITableViewCell *)arg1 withCheckedStatus:(_Bool)arg2; - (TKTonePickerItem *)selectedTonePickerItem; - (void)tableView:(UITableView *)arg1 updateCell:(UITableViewCell *)arg2 withSeparatorForPickerRowItem:(TKPickerRowItem *)arg3; - (void)tableView:(UITableView *)arg1 willDisplayCell:(UITableViewCell *)arg2 forPickerRowItem:(TKPickerRowItem *)arg3; - (UITableViewCell *)tableView:(UITableView *)arg1 cellForPickerRowItem:(TKPickerRowItem *)arg2; - (void)loadViewForTonePickerTableViewController:(UITableViewController<TKTonePickerTableViewLayoutMarginsObserver> *)arg1; @end @protocol TKTonePickerTableViewLayoutMarginsObserver <NSObject> @optional - (void)layoutMarginsDidChangeInTonePickerTableView:(TKTonePickerTableView *)arg1; @end @protocol TKVibrationPickerTableViewCellDelegate <NSObject> @optional - (void)vibrationPickerTableViewCell:(TKVibrationPickerTableViewCell *)arg1 endedEditingWithText:(NSString *)arg2; @end @protocol TKVibrationPickerViewControllerDelegate <NSObject> @optional - (void)vibrationPickerViewController:(TKVibrationPickerViewController *)arg1 selectedVibrationWithIdentifier:(NSString *)arg2; @end @protocol TKVibrationPickerViewControllerDismissalDelegate <NSObject> - (void)vibrationPickerViewControllerWasDismissed:(TKVibrationPickerViewController *)arg1; @end @protocol TKVibrationRecorderStyleProvider <NSObject> @property(readonly, nonatomic) double vibrationRecorderRippleFingerMovingSpeed; @property(readonly, nonatomic) double vibrationRecorderRippleFingerStillSpeed; @property(readonly, nonatomic) double vibrationRecorderRippleFinalRadius; @property(readonly, nonatomic) double vibrationRecorderRippleInitialRadius; @property(readonly, nonatomic) double vibrationRecorderRippleRingLineWidth; @property(readonly, nonatomic) UIColor *vibrationRecorderRippleViewBackgroundColor; @property(readonly, nonatomic) double vibrationRecorderProgressViewAccessibilityAdditionalHeight; @property(readonly, nonatomic) UIImage *vibrationRecorderProgressViewResizableDotImage; @property(readonly, nonatomic) double vibrationRecorderProgressViewDotHorizontalInset; @property(readonly, nonatomic) UIColor *vibrationRecorderProgressViewTrackColor; @property(readonly, nonatomic) double vibrationRecorderProgressViewHeight; @property(readonly, nonatomic) double vibrationRecorderProgressViewHorizontalOffsetFromEdge; @property(readonly, nonatomic) double vibrationRecorderProgressToolbarAdditionalHeight; @property(readonly, nonatomic) double vibrationRecorderProgressToolbarVerticalOffset; @property(readonly, nonatomic) double vibrationRecorderControlsToolbarItemsHorizontalOffsetFromEdge; @property(readonly, nonatomic) double vibrationRecorderControlsToolbarAdditionalHeight; @property(readonly, nonatomic) double vibrationRecorderControlsToolbarVerticalOffset; @property(readonly, nonatomic) double vibrationRecorderInstructionsLabelFadeAnimationDuration; @property(readonly, nonatomic) struct UIEdgeInsets vibrationRecorderInstructionsLabelEdgeInsets; @property(readonly, nonatomic) struct UIOffset vibrationRecorderInstructionsLabelPositionOffset; @property(readonly, nonatomic) UIColor *vibrationRecorderInstructionsLabelBackgroundColor; @property(readonly, nonatomic) UIColor *vibrationRecorderInstructionsLabelTextColor; @property(readonly, nonatomic) UIFont *vibrationRecorderInstructionsLabelFont; @property(retain, nonatomic) UIScreen *screen; @property(readonly, nonatomic) UIColor *vibrationRecorderBarsBackgroundColor; @end @protocol TKVibrationRecorderTouchSurfaceDelegate <NSObject> - (void)vibrationRecorderTouchSurfaceDidFinishReplayingVibration:(TKVibrationRecorderTouchSurface *)arg1; - (void)vibrationRecorderTouchSurface:(TKVibrationRecorderTouchSurface *)arg1 didExitRecordingModeWithContextObject:(id)arg2; - (void)vibrationComponentDidEndForVibrationRecorderTouchSurface:(TKVibrationRecorderTouchSurface *)arg1; - (void)vibrationComponentDidStartForVibrationRecorderTouchSurface:(TKVibrationRecorderTouchSurface *)arg1; - (_Bool)vibrationRecorderTouchSurfaceDidEnterRecordingMode:(TKVibrationRecorderTouchSurface *)arg1; @end @protocol TKVibrationRecorderViewControllerDelegate <NSObject> - (void)vibrationRecorderViewControllerWasDismissedWithoutSavingRecordedVibrationPattern:(TKVibrationRecorderViewController *)arg1; - (void)vibrationRecorderViewController:(TKVibrationRecorderViewController *)arg1 didFinishRecordingVibrationPattern:(NSDictionary *)arg2 name:(NSString *)arg3; @end @protocol TKVibrationRecorderViewDelegate <NSObject> - (void)vibrationRecorderViewDidReachVibrationRecordingMaximumDuration:(TKVibrationRecorderView *)arg1; - (void)vibrationRecorderView:(TKVibrationRecorderView *)arg1 didExitRecordingModeWithContextObject:(id)arg2; - (_Bool)vibrationRecorderViewDidEnterRecordingMode:(TKVibrationRecorderView *)arg1; - (void)vibrationRecorderViewDidFinishReplayingVibration:(TKVibrationRecorderView *)arg1; - (void)vibrationRecorderView:(TKVibrationRecorderView *)arg1 buttonTappedWithIdentifier:(int)arg2; - (void)vibrationComponentDidEndForVibrationRecorderView:(TKVibrationRecorderView *)arg1; - (void)vibrationComponentDidStartForVibrationRecorderView:(TKVibrationRecorderView *)arg1; @end @protocol UINavigationControllerDelegate <NSObject> @optional - (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)arg1 animationControllerForOperation:(long long)arg2 fromViewController:(UIViewController *)arg3 toViewController:(UIViewController *)arg4; - (id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)arg1 interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>)arg2; - (long long)navigationControllerPreferredInterfaceOrientationForPresentation:(UINavigationController *)arg1; - (unsigned long long)navigationControllerSupportedInterfaceOrientations:(UINavigationController *)arg1; - (void)navigationController:(UINavigationController *)arg1 didShowViewController:(UIViewController *)arg2 animated:(_Bool)arg3; - (void)navigationController:(UINavigationController *)arg1 willShowViewController:(UIViewController *)arg2 animated:(_Bool)arg3; @end @protocol UITextFieldDelegate <NSObject> @optional - (_Bool)textFieldShouldReturn:(UITextField *)arg1; - (_Bool)textFieldShouldClear:(UITextField *)arg1; - (_Bool)textField:(UITextField *)arg1 shouldChangeCharactersInRange:(struct _NSRange)arg2 replacementString:(NSString *)arg3; - (void)textFieldDidEndEditing:(UITextField *)arg1; - (_Bool)textFieldShouldEndEditing:(UITextField *)arg1; - (void)textFieldDidBeginEditing:(UITextField *)arg1; - (_Bool)textFieldShouldBeginEditing:(UITextField *)arg1; @end @interface NSIndexPath (TKSectionAwareTableView) + (id)tk_indexPathForRow:(long long)arg1 inSection:(long long)arg2; @property(readonly, nonatomic) long long tk_row; @property(readonly, nonatomic) long long tk_section; @end @interface NSLayoutConstraint (TKExtensions) - (void)tk_removeFromContainer; @end @interface NSMutableArray (TKExtensions) - (void)tk_ensureHasItemsOrNullUpToIndex:(unsigned long long)arg1; @end @interface NSMutableArray (TKQueue) - (id)tk_nextDequeuedObject; - (id)tk_lastEnqueuedObject; - (id)tk_dequeueObject; - (void)tk_enqueueObject:(id)arg1; @end @interface TKCapabilitiesManager : NSObject { _Bool _ringtoneStoreAvailable; _Bool _alertToneStoreAvailable; } + (id)sharedCapabilitiesManager; @property(nonatomic, getter=_isAlertToneStoreAvailable, setter=_setAlertToneStoreAvailable:) _Bool _alertToneStoreAvailable; // @synthesize _alertToneStoreAvailable; @property(nonatomic, getter=_isRingtoneStoreAvailable, setter=_setRingtoneStoreAvailable:) _Bool _ringtoneStoreAvailable; // @synthesize _ringtoneStoreAvailable; @property(readonly, nonatomic) _Bool hasUserGeneratedVibrationsCapability; @property(readonly, nonatomic) _Bool hasVibratorCapability; @property(readonly, nonatomic, getter=isAlertToneStoreAvailable) _Bool alertToneStoreAvailable; @property(readonly, nonatomic, getter=isRingtoneStoreAvailable) _Bool ringtoneStoreAvailable; - (void)_checkRingtoneStoreAvailability; - (_Bool)_hasTelephonyCapability; - (void)dealloc; - (id)init; @end @interface TKDisplayLinkManager : NSObject { _Bool _hasUpdatedTargetActions; _Bool _handlingDisplayRefresh; CADisplayLink *_storedDisplayLink; NSMutableSet *_activeTargetActions; NSMutableSet *_updatedTargetActions; unsigned long long _warmUpModeRequirementsCount; } + (void)_releaseCurrentDisplayLinkManager; + (id)currentDisplayLinkManager; @property(nonatomic, setter=_setWarmUpModeRequirementsCount:) unsigned long long _warmUpModeRequirementsCount; // @synthesize _warmUpModeRequirementsCount; @property(nonatomic, getter=_isHandlingDisplayRefresh, setter=_setHandlingDisplayRefresh:) _Bool _handlingDisplayRefresh; // @synthesize _handlingDisplayRefresh; @property(nonatomic, setter=_setHasUpdatedTargetActions:) _Bool _hasUpdatedTargetActions; // @synthesize _hasUpdatedTargetActions; @property(retain, nonatomic, setter=_setUpdatedTargetActions:) NSMutableSet *_updatedTargetActions; // @synthesize _updatedTargetActions; @property(retain, nonatomic, setter=_setActiveTargetActions:) NSMutableSet *_activeTargetActions; // @synthesize _activeTargetActions; @property(retain, nonatomic, setter=_setStoredDisplayLink:) CADisplayLink *_storedDisplayLink; // @synthesize _storedDisplayLink; - (void)_displayDidRefresh:(id)arg1; - (void)endRequiringWarmUpMode; - (void)beginRequiringWarmUpMode; @property(readonly, nonatomic, getter=_isWarmUpModeEnabled) _Bool _warmUpModeEnabled; - (void)_didRemoveLastTargetAction; - (void)_didAddFirstTargetAction; - (id)_prepareUpdatedTargetActionsForModification; - (void)removeTarget:(id)arg1 selector:(SEL)arg2; - (void)addTarget:(id)arg1 selector:(SEL)arg2 frameInterval:(unsigned long long)arg3; - (void)addTarget:(id)arg1 selector:(SEL)arg2; @property(retain, nonatomic, setter=_setDisplayLink:) CADisplayLink *_displayLink; @property(readonly, nonatomic) unsigned long long frameInterval; @property(readonly, nonatomic) double timestamp; @property(readonly, nonatomic) double duration; @property(readonly, nonatomic, getter=isPaused) _Bool paused; - (void)dealloc; - (id)init; @end @interface TKDisplayLinkManagerTargetAction : NSObject { id _target; SEL _actionSelector; NSString *_actionSelectorName; unsigned long long _frameInterval; unsigned long long _displayDidRefreshCount; } @property(nonatomic, setter=_setDisplayDidRefreshCount:) unsigned long long _displayDidRefreshCount; // @synthesize _displayDidRefreshCount; @property(nonatomic, setter=_setFrameInterval:) unsigned long long _frameInterval; // @synthesize _frameInterval; @property(copy, nonatomic, setter=_setActionSelectorName:) NSString *_actionSelectorName; // @synthesize _actionSelectorName; @property(nonatomic, setter=_setActionSelector:) SEL _actionSelector; // @synthesize _actionSelector; @property(retain, nonatomic, setter=_setTarget:) id _target; // @synthesize _target; - (void)displayDidRefresh:(id)arg1; - (unsigned long long)hash; - (_Bool)isEqual:(id)arg1; - (void)dealloc; - (id)initWithTarget:(id)arg1 actionSelector:(SEL)arg2 frameInterval:(unsigned long long)arg3; - (id)initWithTarget:(id)arg1 actionSelector:(SEL)arg2; @end @interface TKLabelContainerView : UIView { UILabel *_label; struct UIEdgeInsets _labelPaddingInsets; } @property(retain, nonatomic, setter=_setLabel:) UILabel *_label; // @synthesize _label; @property(nonatomic) struct UIEdgeInsets labelPaddingInsets; // @synthesize labelPaddingInsets=_labelPaddingInsets; - (void)layoutSubviews; - (struct CGSize)sizeThatFits:(struct CGSize)arg1; @property(nonatomic) struct UIOffset labelShadowOffset; @property(retain, nonatomic) UIColor *labelShadowColor; @property(retain, nonatomic) UIColor *labelTextColor; @property(retain, nonatomic) UIFont *labelFont; @property(copy, nonatomic) NSString *labelText; - (void)dealloc; - (id)initWithFrame:(struct CGRect)arg1; @end @interface TKPickerItem : NSObject { long long _section; } - (void)_setSection:(long long)arg1; @property(nonatomic) long long section; // @synthesize section=_section; - (void)_appendDescriptionOfAttributeNamed:(id)arg1 withStringValue:(id)arg2 toString:(id)arg3; - (void)_appendDescriptionOfAttributeNamed:(id)arg1 withBoolValue:(_Bool)arg2 toString:(id)arg3; - (void)_appendDescriptionOfAttributeNamed:(id)arg1 withIntegerValue:(long long)arg2 toString:(id)arg3; - (void)_appendDescriptionOfAttributesToString:(id)arg1; - (id)description; @end @interface TKPickerRowItem : TKPickerItem { long long _row; } - (void)_setRow:(long long)arg1; @property(nonatomic) long long row; // @synthesize row=_row; - (void)_appendDescriptionOfAttributesToString:(id)arg1; @end @interface TKPickerDividerItem : TKPickerRowItem { } @end @interface TKPickerDividerTableViewCell : UITableViewCell { UIView *_dividerView; long long _contentBackdropOverlayBlendMode; } @property(nonatomic, setter=_setContentBackdropOverlayBlendMode:) long long _contentBackdropOverlayBlendMode; // @synthesize _contentBackdropOverlayBlendMode; @property(retain, nonatomic, setter=_setDividerView:) UIView *_dividerView; // @synthesize _dividerView; - (struct CGRect)_dividerViewFrame; - (void)layoutSubviews; - (void)setSeparatorStyle:(long long)arg1; @property(nonatomic) long long contentBackdropOverlayBlendMode; @property(retain, nonatomic) UIColor *contentBackgroundColor; - (void)dealloc; - (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2; @end @interface TKPickerSectionItem : TKPickerItem { NSString *_text; } - (void)_setText:(id)arg1; @property(copy, nonatomic) NSString *text; // @synthesize text=_text; - (void)_appendDescriptionOfAttributesToString:(id)arg1; - (void)dealloc; @end @interface TKPickerSelectableItem : TKPickerRowItem { _Bool _textCentered; _Bool _showsCheckmark; _Bool _showsDisclosureIndicator; NSString *_text; NSString *_detailText; } - (void)_setShowsDisclosureIndicator:(_Bool)arg1; @property(nonatomic) _Bool showsDisclosureIndicator; // @synthesize showsDisclosureIndicator=_showsDisclosureIndicator; - (void)_setShowsCheckmark:(_Bool)arg1; @property(nonatomic) _Bool showsCheckmark; // @synthesize showsCheckmark=_showsCheckmark; - (void)_setDetailText:(id)arg1; @property(copy, nonatomic) NSString *detailText; // @synthesize detailText=_detailText; - (void)_setTextCentered:(_Bool)arg1; @property(nonatomic, getter=isTextCentered) _Bool textCentered; // @synthesize textCentered=_textCentered; - (void)_setText:(id)arg1; @property(copy, nonatomic) NSString *text; // @synthesize text=_text; - (void)_appendDescriptionOfAttributesToString:(id)arg1; - (void)dealloc; @end @interface TKPickerTableViewCell : UITableViewCell { } - (void)setSectionLocation:(int)arg1 animated:(_Bool)arg2; @end @interface TKStyleProvider : NSObject <TKVibrationRecorderStyleProvider> { UIScreen *_screen; NSBundle *_bundle; NSMutableDictionary *_cachedStyleProperties; } @property(retain, nonatomic, setter=_setCachedStyleProperties:) NSMutableDictionary *_cachedStyleProperties; // @synthesize _cachedStyleProperties; @property(retain, nonatomic, setter=_setBundle:) NSBundle *_bundle; // @synthesize _bundle; @property(retain, nonatomic) UIScreen *screen; // @synthesize screen=_screen; @property(readonly, nonatomic) double vibrationRecorderRippleFingerMovingSpeed; @property(readonly, nonatomic) double vibrationRecorderRippleFingerStillSpeed; @property(readonly, nonatomic) double vibrationRecorderRippleFinalRadius; @property(readonly, nonatomic) double vibrationRecorderRippleInitialRadius; @property(readonly, nonatomic) double vibrationRecorderRippleRingLineWidth; @property(readonly, nonatomic) UIColor *vibrationRecorderRippleViewBackgroundColor; @property(readonly, nonatomic) double vibrationRecorderProgressViewAccessibilityAdditionalHeight; @property(readonly, nonatomic) UIImage *vibrationRecorderProgressViewResizableDotImage; @property(readonly, nonatomic) double vibrationRecorderProgressViewDotHorizontalInset; @property(readonly, nonatomic) UIColor *vibrationRecorderProgressViewTrackColor; @property(readonly, nonatomic) double vibrationRecorderProgressViewHeight; @property(readonly, nonatomic) double vibrationRecorderProgressViewHorizontalOffsetFromEdge; @property(readonly, nonatomic) double vibrationRecorderProgressToolbarAdditionalHeight; @property(readonly, nonatomic) double vibrationRecorderProgressToolbarVerticalOffset; @property(readonly, nonatomic) double vibrationRecorderControlsToolbarItemsHorizontalOffsetFromEdge; @property(readonly, nonatomic) double vibrationRecorderControlsToolbarAdditionalHeight; @property(readonly, nonatomic) double vibrationRecorderControlsToolbarVerticalOffset; @property(readonly, nonatomic) double vibrationRecorderInstructionsLabelFadeAnimationDuration; @property(readonly, nonatomic) struct UIEdgeInsets vibrationRecorderInstructionsLabelEdgeInsets; @property(readonly, nonatomic) struct UIOffset vibrationRecorderInstructionsLabelPositionOffset; @property(readonly, nonatomic) UIColor *vibrationRecorderInstructionsLabelBackgroundColor; @property(readonly, nonatomic) UIColor *vibrationRecorderInstructionsLabelTextColor; @property(readonly, nonatomic) UIFont *vibrationRecorderInstructionsLabelFont; @property(readonly, nonatomic) UIColor *vibrationRecorderBarsBackgroundColor; @property(readonly, nonatomic) double defaultAnimationDuration; - (void)_didReceiveMemoryWarning:(id)arg1; - (id)_cachedResizableImageForPropertyWithSelector:(SEL)arg1 capInsets:(struct UIEdgeInsets)arg2 size:(struct CGSize)arg3 opaque:(_Bool)arg4 withDrawingBlock:(CDUnknownBlockType)arg5; - (id)_cachedImageForPropertyWithSelector:(SEL)arg1 size:(struct CGSize)arg2 opaque:(_Bool)arg3 withDrawingBlock:(CDUnknownBlockType)arg4; - (id)_cachedImageWithName:(id)arg1 forPropertyWithSelector:(SEL)arg2; - (void)_setCachedStyleObject:(id)arg1 forPropertyWithSelector:(SEL)arg2; - (id)_cachedStyleObjectForPropertyWithSelector:(SEL)arg1; - (void)dealloc; - (id)init; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKTonePickerItem : TKPickerSelectableItem <TKPickerContainerItem> { TKTonePickerController *_parentTonePickerController; long long _numberOfChildren; unsigned long long _itemKind; } - (void)_setItemKind:(unsigned long long)arg1; @property(nonatomic) unsigned long long itemKind; // @synthesize itemKind=_itemKind; - (void)_setNumberOfChildren:(long long)arg1; @property(nonatomic) long long numberOfChildren; // @synthesize numberOfChildren=_numberOfChildren; @property(nonatomic, setter=_setParentTonePickerController:) TKTonePickerController *_parentTonePickerController; // @synthesize _parentTonePickerController; - (void)_appendDescriptionOfAttributesToString:(id)arg1; - (id)childItemAtIndex:(long long)arg1; @property(readonly, nonatomic) TKTonePickerSectionItem *parentSectionItem; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKToneClassicsPickerItem : TKTonePickerItem { long long _classicToneIndex; } - (void)_setClassicToneIndex:(long long)arg1; @property(nonatomic) long long classicToneIndex; // @synthesize classicToneIndex=_classicToneIndex; - (void)_appendDescriptionOfAttributesToString:(id)arg1; - (id)childItemAtIndex:(long long)arg1; @property(readonly, nonatomic) TKTonePickerItem *parentItem; @end @interface TKToneClassicsTableViewController : UITableViewController <TKTonePickerTableViewLayoutMarginsObserver> { id <TKTonePickerTableViewControllerHelper> _tonePickerTableViewControllerHelper; TKTonePickerItem *_classicTonesHeaderItem; } @property(retain, nonatomic, setter=_setClassicTonesHeaderItem:) TKTonePickerItem *_classicTonesHeaderItem; // @synthesize _classicTonesHeaderItem; @property(nonatomic) id <TKTonePickerTableViewControllerHelper> tonePickerTableViewControllerHelper; // @synthesize tonePickerTableViewControllerHelper=_tonePickerTableViewControllerHelper; - (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2; - (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forRowAtIndexPath:(id)arg3; - (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2; - (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2; - (long long)numberOfSectionsInTableView:(id)arg1; - (void)layoutMarginsDidChangeInTonePickerTableView:(id)arg1; - (void)viewWillDisappear:(_Bool)arg1; - (void)viewWillAppear:(_Bool)arg1; - (void)loadView; - (void)didUpdateDetailText:(id)arg1 ofToneClassicsPickerItem:(id)arg2; - (void)didUpdateCheckedStatus:(_Bool)arg1 ofToneClassicsPickerItem:(id)arg2; - (void)didReloadTones; - (void)dealloc; - (id)initWithClassicTonesHeaderItem:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKTonePickerController : NSObject { _Bool _behavesAsRingtonePicker; _Bool _defaultToneIdentifierWasExplicitlySet; _Bool _selectedToneWasExplicitlySetToDefaultTone; _Bool _showsToneStore; _Bool _showsDefault; _Bool _showsNone; _Bool _noneAtTop; _Bool _showsNothingSelected; _Bool _shouldCachePickerItems; _Bool _startedInterruption; _Bool _mediaAtTop; _Bool _showsVibrations; int _alertType; id <TKTonePickerControllerDelegate> _delegate; unsigned long long _toneTypes; NSString *_accountIdentifier; NSString *_defaultToneIdentifier; NSString *_noneString; NSMutableArray *_cachedPickerSectionItems; NSMutableArray *_cachedPickerRowItems; NSMutableArray *_cachedClassicRingtonePickerItems; NSMutableArray *_cachedClassicAlertTonePickerItems; NSIndexPath *_selectedToneIndexPath; NSArray *_classicAlertToneIdentifiers; NSArray *_classicRingtoneIdentifiers; unsigned long long _selectedClassicRingtoneIndex; unsigned long long _selectedClassicAlertToneIndex; NSMutableArray *_toneGroupLists; NSMutableArray *_toneGroupNames; TLToneManager *_toneManager; TLSound *_playingPreviewSound; AVController *_storedAVController; NSString *_selectedVibrationIdentifier; } @property(copy, nonatomic, setter=_setSelectedVibrationIdentifier:) NSString *_selectedVibrationIdentifier; // @synthesize _selectedVibrationIdentifier; @property(nonatomic, setter=_setShowsVibrations:) _Bool _showsVibrations; // @synthesize _showsVibrations; @property(nonatomic, getter=isMediaAtTop) _Bool mediaAtTop; // @synthesize mediaAtTop=_mediaAtTop; @property(nonatomic, setter=_setStartedInterruption:) _Bool _startedInterruption; // @synthesize _startedInterruption; @property(retain, nonatomic, setter=_setStoredAVController:) AVController *_storedAVController; // @synthesize _storedAVController; @property(retain, nonatomic, setter=_setPlayingPreviewSound:) TLSound *_playingPreviewSound; // @synthesize _playingPreviewSound; @property(retain, nonatomic, setter=_setToneManager:) TLToneManager *_toneManager; // @synthesize _toneManager; @property(retain, nonatomic, setter=_setToneGroupNames:) NSMutableArray *_toneGroupNames; // @synthesize _toneGroupNames; @property(retain, nonatomic, setter=_setToneGroupLists:) NSMutableArray *_toneGroupLists; // @synthesize _toneGroupLists; @property(nonatomic, setter=_setSelectedClassicAlertToneIndex:) unsigned long long _selectedClassicAlertToneIndex; // @synthesize _selectedClassicAlertToneIndex; @property(nonatomic, setter=_setSelectedClassicRingtoneIndex:) unsigned long long _selectedClassicRingtoneIndex; // @synthesize _selectedClassicRingtoneIndex; @property(retain, nonatomic, setter=_setClassicRingtoneIdentifiers:) NSArray *_classicRingtoneIdentifiers; // @synthesize _classicRingtoneIdentifiers; @property(retain, nonatomic, setter=_setClassicAlertToneIdentifiers:) NSArray *_classicAlertToneIdentifiers; // @synthesize _classicAlertToneIdentifiers; @property(retain, nonatomic, setter=_setSelectedToneIndexPath:) NSIndexPath *_selectedToneIndexPath; // @synthesize _selectedToneIndexPath; @property(retain, nonatomic, setter=_setCachedClassicAlertTonePickerItems:) NSMutableArray *_cachedClassicAlertTonePickerItems; // @synthesize _cachedClassicAlertTonePickerItems; @property(retain, nonatomic, setter=_setCachedClassicRingtonePickerItems:) NSMutableArray *_cachedClassicRingtonePickerItems; // @synthesize _cachedClassicRingtonePickerItems; @property(retain, nonatomic, setter=_setCachedPickerRowItems:) NSMutableArray *_cachedPickerRowItems; // @synthesize _cachedPickerRowItems; @property(retain, nonatomic, setter=_setCachedPickerSectionItems:) NSMutableArray *_cachedPickerSectionItems; // @synthesize _cachedPickerSectionItems; @property(nonatomic, setter=_setShouldCachePickerItems:) _Bool _shouldCachePickerItems; // @synthesize _shouldCachePickerItems; @property(nonatomic, setter=_setShowsNothingSelected:) _Bool _showsNothingSelected; // @synthesize _showsNothingSelected; @property(copy, nonatomic, setter=_setNoneString:) NSString *_noneString; // @synthesize _noneString; @property(nonatomic, getter=isNoneAtTop) _Bool noneAtTop; // @synthesize noneAtTop=_noneAtTop; @property(nonatomic, setter=_setShowsNone:) _Bool _showsNone; // @synthesize _showsNone; @property(nonatomic, setter=_setShowsDefault:) _Bool _showsDefault; // @synthesize _showsDefault; @property(nonatomic, setter=_setShowsToneStore:) _Bool _showsToneStore; // @synthesize _showsToneStore; @property(nonatomic, setter=_setSelectedToneWasExplicitlySetToDefaultTone:) _Bool _selectedToneWasExplicitlySetToDefaultTone; // @synthesize _selectedToneWasExplicitlySetToDefaultTone; @property(nonatomic, setter=_setDefaultToneIdentifierWasExplicitlySet:) _Bool _defaultToneIdentifierWasExplicitlySet; // @synthesize _defaultToneIdentifierWasExplicitlySet; @property(copy, nonatomic, setter=_setDefaultToneIdentifier:) NSString *_defaultToneIdentifier; // @synthesize _defaultToneIdentifier; @property(copy, nonatomic) NSString *accountIdentifier; // @synthesize accountIdentifier=_accountIdentifier; @property(nonatomic, setter=_setAlertType:) int _alertType; // @synthesize _alertType; @property(nonatomic, setter=_setBehavesAsRingtonePicker:) _Bool _behavesAsRingtonePicker; // @synthesize _behavesAsRingtonePicker; @property(nonatomic, setter=_setToneTypes:) unsigned long long _toneTypes; // @synthesize _toneTypes; @property(nonatomic) id <TKTonePickerControllerDelegate> delegate; // @synthesize delegate=_delegate; - (void)_toneManagerContentsChanged:(id)arg1; - (void)_resetSelectedClassicAlertToneIndex; - (void)_resetSelectedClassicRingtoneIndex; - (void)_didUpdateCheckedStatus:(_Bool)arg1 ofToneClassicsPickerItem:(id)arg2; - (void)_didUpdateDetailText:(id)arg1 ofPickerItemForRowAtIndexPath:(id)arg2; - (void)_didUpdateCheckedStatus:(_Bool)arg1 ofPickerItemForRowAtIndexPath:(id)arg2; - (void)_didSelectToneWithIdentifier:(id)arg1; - (void)_didReloadTones; - (id)_annotatedNameForToneIdentifier:(id)arg1; - (void)_updateDetailTextOfVibrationItem; - (void)_unregisterForUserGeneratedVibrationsDidChangeNotification; - (void)_registerForUserGeneratedVibrationsDidChangeNotification; - (id)_nameOfVibrationWithIdentifier:(id)arg1; - (void)_resetSelectedVibrationIdentifier; @property(copy, nonatomic) NSString *selectedVibrationIdentifier; @property(nonatomic) _Bool showsVibrations; - (void)_reloadMediaItems; - (void)_didSelectMediaItemWithIdentifier:(id)arg1; - (unsigned long long)_indexOfMediaItemWithIdentifier:(id)arg1; - (id)_identifierOfMediaItemAtIndex:(unsigned long long)arg1; - (unsigned long long)_mediaItemsCount; - (_Bool)_isMediaAtTop; - (_Bool)_showsMedia; - (void)finishedWithPicker; - (void)stopPlayingWithFadeOut:(_Bool)arg1; - (void)_handleItemPlaybackDidEndWithAVController:(id)arg1; - (void)_unregisterForItemPlaybackDidEndNotificationWithCurrentAVController; - (void)_registerForItemPlaybackDidEndNotificationWithCurrentAVController; - (void)_togglePlayForToneWithIdentifier:(id)arg1; - (void)_playToneWithIdentifier:(id)arg1; - (id)_avController; - (_Bool)_shouldUseAudioServicesForPlayback; - (void)_goToStore; @property(readonly, nonatomic) _Bool canShowStore; - (void)_sortToneIdentifiersArray:(id)arg1; - (void)_addRingtonesInDirectory:(id)arg1 toArray:(id)arg2 fileExtension:(id)arg3; - (id)_loadRingtonesFromPlist; - (id)_loadAlertTonesFromPlist; - (id)_loadTonesFromPlistNamed:(id)arg1; @property(readonly, nonatomic) NSString *_ringtonesPlistName; @property(readonly, nonatomic) NSString *_alertTonesPlistName; - (void)_reloadTonesForExternalChange:(_Bool)arg1; - (void)_reloadTones; - (_Bool)_didSelectToneClassicsPickerItem:(id)arg1; - (_Bool)didSelectTonePickerItem:(id)arg1; - (id)_selectedIdentifier:(_Bool *)arg1; - (id)_identifierOfSelectedClassicRingtone; - (id)_identifierOfSelectedClassicAlertTone; - (void)_setSelectedToneIdentifier:(id)arg1 currentlyReloadingTones:(_Bool)arg2; @property(copy, nonatomic) NSString *selectedToneIdentifier; @property(readonly, nonatomic) TKTonePickerItem *selectedTonePickerItem; @property(readonly, nonatomic) TKTonePickerItem *_topLevelSelectedTonePickerItem; - (id)_identifierAtIndexPath:(id)arg1 isMediaItem:(_Bool *)arg2; - (id)_identifierOfToneAtIndexPath:(id)arg1; - (id)_indexPathForToneWithIdentifier:(id)arg1; - (_Bool)_isDividerAtIndexPath:(id)arg1; - (_Bool)_isVibrationGroupAtIndexPath:(id)arg1; - (_Bool)_isMediaGroupAtIndexPath:(id)arg1; - (_Bool)_isNoneGroupAtIndexPath:(id)arg1; - (_Bool)_isDefaultGroupAtIndexPath:(id)arg1; - (_Bool)_isToneStoreGroupAtIndexPath:(id)arg1; @property(readonly, nonatomic) NSIndexPath *indexPathForSelectedTone; @property(readonly, nonatomic) NSIndexPath *_indexPathForVibrationGroup; @property(readonly, nonatomic) NSIndexPath *_indexPathForNone; @property(readonly, nonatomic) NSIndexPath *_indexPathForMediaGroup; @property(readonly, nonatomic) NSIndexPath *_indexPathForFirstToneGroup; @property(readonly, nonatomic) NSIndexPath *_indexPathForDefaultGroup; @property(readonly, nonatomic) NSIndexPath *_indexPathForToneStoreGroup; - (void)_invalidatePickerItemCaches; - (_Bool)_cacheToneClassicsPickerItem:(id)arg1 forIndex:(long long)arg2 headerKind:(unsigned long long)arg3; - (id)_cachedToneClassicsPickerItemForIndex:(long long)arg1 headerKind:(unsigned long long)arg2; - (_Bool)_cachePickerRowItem:(id)arg1 atIndex:(long long)arg2 inSectionForItem:(id)arg3; - (id)_cachedPickerRowItemAtIndex:(long long)arg1 inSectionForItem:(id)arg2; - (_Bool)_cachePickerRowItem:(id)arg1 forSection:(long long)arg2; - (id)_cachedPickerItemForSection:(long long)arg1; - (id)_toneClassicsPickerItemAtIndex:(long long)arg1 belowTonePickerItem:(id)arg2; - (id)_pickerRowItemAtIndex:(long long)arg1 inSectionForItem:(id)arg2; - (id)pickerItemForSection:(long long)arg1; - (long long)numberOfSections; @property(nonatomic) _Bool showsNothingSelected; @property(copy, nonatomic) NSString *noneString; @property(nonatomic) _Bool showsNone; @property(nonatomic) _Bool showsDefault; @property(nonatomic) _Bool showsToneStore; @property(copy, nonatomic) NSString *defaultToneIdentifier; @property(readonly, nonatomic) int alertType; - (void)dealloc; - (id)initWithAlertType:(int)arg1; - (id)init; @end @interface TKTonePickerSectionItem : TKPickerSectionItem <TKPickerContainerItem> { TKTonePickerController *_parentTonePickerController; long long _numberOfChildren; unsigned long long _sectionHeader; unsigned long long _regularToneSectionIndex; } - (void)_setRegularToneSectionIndex:(unsigned long long)arg1; @property(nonatomic) unsigned long long regularToneSectionIndex; // @synthesize regularToneSectionIndex=_regularToneSectionIndex; - (void)_setSectionHeader:(unsigned long long)arg1; @property(nonatomic) unsigned long long sectionHeader; // @synthesize sectionHeader=_sectionHeader; - (void)_setNumberOfChildren:(long long)arg1; @property(nonatomic) long long numberOfChildren; // @synthesize numberOfChildren=_numberOfChildren; @property(nonatomic, setter=_setParentTonePickerController:) TKTonePickerController *_parentTonePickerController; // @synthesize _parentTonePickerController; - (void)_appendDescriptionOfAttributesToString:(id)arg1; - (id)childItemAtIndex:(long long)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKTonePickerTableView : UITableView { id <TKTonePickerTableViewLayoutMarginsObserver> _layoutMarginsObserver; } @property(nonatomic) id <TKTonePickerTableViewLayoutMarginsObserver> layoutMarginsObserver; // @synthesize layoutMarginsObserver=_layoutMarginsObserver; - (void)layoutMarginsDidChange; @end @interface TKTonePickerTableViewCellLayoutManager : UITableViewCellLayoutManagerValue1 { double _minimumTextIndentation; } @property(nonatomic) double minimumTextIndentation; // @synthesize minimumTextIndentation=_minimumTextIndentation; - (struct CGRect)textRectForCell:(id)arg1; @end @interface TKTonePickerViewController : UITableViewController <TKTonePickerControllerDelegate, TKTonePickerControllerDelegateInternal, TKTonePickerTableViewControllerHelper, TKTonePickerTableViewLayoutMarginsObserver, TKVibrationPickerViewControllerDelegate, TKVibrationPickerViewControllerDismissalDelegate, MPMediaPickerControllerDelegate> { _Bool _showsStoreButtonInNavigationBar; _Bool _needsScrollPositionReset; _Bool _showsMedia; id <TKTonePickerViewControllerDelegate> _delegate; TKTonePickerController *_tonePickerController; UIImage *_checkmarkImage; TKTonePickerTableViewCellLayoutManager *_tableViewCellLayoutManager; TKToneClassicsTableViewController *_toneClassicsTableViewController; UIBarButtonItem *_storeBarButtonItem; TKVibrationPickerViewController *_vibrationPickerViewController; id <TKTonePickerStyleProvider> _styleProvider; UIView *_defaultSectionHeaderView; UIView *_mediaSectionHeaderView; NSMutableArray *_regularToneSectionHeaderViews; NSMutableArray *_mediaItems; MPMediaPickerController *_mediaPickerController; MPMusicPlayerController *_storedMusicPlayer; } @property(retain, nonatomic, setter=_setStoredMusicPlayer:) MPMusicPlayerController *_storedMusicPlayer; // @synthesize _storedMusicPlayer; @property(retain, nonatomic, setter=_setMediaPickerController:) MPMediaPickerController *_mediaPickerController; // @synthesize _mediaPickerController; @property(retain, nonatomic, setter=_setMediaItems:) NSMutableArray *_mediaItems; // @synthesize _mediaItems; @property(nonatomic) _Bool showsMedia; // @synthesize showsMedia=_showsMedia; @property(nonatomic, setter=_setNeedsScrollPositionReset:) _Bool _needsScrollPositionReset; // @synthesize _needsScrollPositionReset; @property(retain, nonatomic, setter=_setRegularToneSectionHeaderViews:) NSMutableArray *_regularToneSectionHeaderViews; // @synthesize _regularToneSectionHeaderViews; @property(retain, nonatomic, setter=_setMediaSectionHeaderView:) UIView *_mediaSectionHeaderView; // @synthesize _mediaSectionHeaderView; @property(retain, nonatomic, setter=_setDefaultSectionHeaderView:) UIView *_defaultSectionHeaderView; // @synthesize _defaultSectionHeaderView; @property(retain, nonatomic, setter=_setStyleProvider:) id <TKTonePickerStyleProvider> _styleProvider; // @synthesize _styleProvider; @property(retain, nonatomic, setter=_setVibrationPickerViewController:) TKVibrationPickerViewController *_vibrationPickerViewController; // @synthesize _vibrationPickerViewController; @property(retain, nonatomic, setter=_setStoreBarButtonItem:) UIBarButtonItem *_storeBarButtonItem; // @synthesize _storeBarButtonItem; @property(nonatomic, setter=_setShowsStoreButtonInNavigationBar:) _Bool _showsStoreButtonInNavigationBar; // @synthesize _showsStoreButtonInNavigationBar; @property(retain, nonatomic, setter=_setToneClassicsTableViewController:) TKToneClassicsTableViewController *_toneClassicsTableViewController; // @synthesize _toneClassicsTableViewController; @property(retain, nonatomic, setter=_setTableViewCellLayoutManager:) TKTonePickerTableViewCellLayoutManager *_tableViewCellLayoutManager; // @synthesize _tableViewCellLayoutManager; @property(retain, nonatomic, setter=_setCheckmarkImage:) UIImage *_checkmarkImage; // @synthesize _checkmarkImage; @property(retain, nonatomic, setter=_setTonePickerController:) TKTonePickerController *_tonePickerController; // @synthesize _tonePickerController; @property(nonatomic) id <TKTonePickerViewControllerDelegate> delegate; // @synthesize delegate=_delegate; - (void)vibrationPickerViewControllerWasDismissed:(id)arg1; - (void)vibrationPickerViewController:(id)arg1 selectedVibrationWithIdentifier:(id)arg2; - (void)tonePickerControllerRequestsPresentingVibrationPicker:(id)arg1; - (void)tonePickerControllerRequestsPresentingToneStore:(id)arg1; - (void)tonePickerController:(id)arg1 requestsPresentingToneClassicsPickerForItem:(id)arg2; - (void)tonePickerControllerDidStopPlaying:(id)arg1 withFadeOutDuration:(double)arg2; - (void)tonePickerControllerRequestsPresentingMediaItemPicker:(id)arg1; - (void)tonePickerController:(id)arg1 didSelectMediaItemAtIndex:(unsigned long long)arg2 selectionDidChange:(_Bool)arg3; - (unsigned long long)tonePickerController:(id)arg1 indexOfMediaItemWithIdentifier:(id)arg2; - (id)tonePickerController:(id)arg1 titleOfMediaItemAtIndex:(unsigned long long)arg2; - (id)tonePickerController:(id)arg1 identifierOfMediaItemAtIndex:(unsigned long long)arg2; - (unsigned long long)numberOfMediaItemsInTonePickerController:(id)arg1; - (void)tonePickerControllerRequestsMediaItemsRefresh:(id)arg1; - (_Bool)tonePickerControllerShouldShowMedia:(id)arg1; - (void)tonePickerController:(id)arg1 selectedMediaItemWithIdentifier:(id)arg2; - (void)tonePickerController:(id)arg1 selectedToneWithIdentifier:(id)arg2; - (void)tonePickerController:(id)arg1 didUpdateDetailText:(id)arg2 ofTonePickerItem:(id)arg3; - (void)tonePickerController:(id)arg1 didUpdateCheckedStatus:(_Bool)arg2 ofTonePickerItem:(id)arg3; - (void)tonePickerControllerDidReloadTones:(id)arg1; - (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forRowAtIndexPath:(id)arg3; - (double)tableView:(id)arg1 heightForHeaderInSection:(long long)arg2; - (id)tableView:(id)arg1 titleForHeaderInSection:(long long)arg2; - (id)tableView:(id)arg1 viewForHeaderInSection:(long long)arg2; - (double)tableView:(id)arg1 heightForRowAtIndexPath:(id)arg2; - (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2; - (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2; - (long long)numberOfSectionsInTableView:(id)arg1; - (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2; - (void)layoutMarginsDidChangeInTonePickerTableView:(id)arg1; - (void)tonePickerTableViewControllerWillBeDeallocated:(id)arg1; - (void)tonePickerTableViewWillDisappear:(_Bool)arg1; - (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2 forPickerRowItem:(id)arg3; - (void)updateCell:(id)arg1 withDetailText:(id)arg2; - (void)updateCell:(id)arg1 withCheckedStatus:(_Bool)arg2; - (void)tableView:(id)arg1 updateCell:(id)arg2 withSeparatorForPickerRowItem:(id)arg3; - (id)selectedTonePickerItem; - (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forPickerRowItem:(id)arg3; - (id)tableView:(id)arg1 cellForPickerRowItem:(id)arg2; - (void)loadViewForTonePickerTableViewController:(id)arg1; - (void)mediaPicker:(id)arg1 didPickMediaItems:(id)arg2; - (void)mediaPickerDidCancel:(id)arg1; - (void)_playMediaItemWithIdentifier:(id)arg1; - (void)_togglePlayMediaItemWithIdentifier:(id)arg1; @property(readonly, nonatomic) MPMusicPlayerController *_musicPlayer; - (void)_didSelectMediaItemWithIdentifier:(id)arg1; - (id)_mediaItemForIdentifier:(id)arg1; - (unsigned long long)_addMediaIdentifierToList:(id)arg1; - (void)removeMediaItems:(id)arg1; - (void)addMediaItems:(id)arg1; @property(copy, nonatomic) NSNumber *selectedMediaIdentifier; - (id)selectedIdentifier:(_Bool *)arg1; @property(nonatomic, getter=isMediaAtTop) _Bool mediaAtTop; - (void)_handleMediaLibraryDidChangeNotification; - (void)_resetScrollingPosition; - (void)_reloadData; - (id)_pickerRowItemForIndexPath:(id)arg1; - (void)_configureTextColorOfLabelInCell:(id)arg1 checked:(_Bool)arg2; - (void)_didSelectToneWithIdentifier:(id)arg1; - (void)_goToStore; - (void)_updateMinimumTextIndentation; - (double)_minimumTextIndentationForTableView:(id)arg1 withCheckmarkImage:(id)arg2; - (void)_getTitle:(id *)arg1 customHeaderView:(id *)arg2 forHeaderInSection:(long long)arg3; - (void)applicationWillSuspend; - (void)viewDidLayoutSubviews; - (void)viewWillDisappear:(_Bool)arg1; - (void)viewDidAppear:(_Bool)arg1; - (void)viewDidLoad; - (void)loadView; - (void)_updateStyleOfTableView:(id)arg1 forStyleProvider:(id)arg2; @property(retain, nonatomic) id <TKTonePickerStyleProvider> styleProvider; @property(copy, nonatomic) NSString *selectedVibrationIdentifier; @property(nonatomic) _Bool showsVibrations; - (void)_configureNavigationBarIfNeeded; @property(nonatomic) _Bool showsStoreButtonInNavigationBar; @property(copy, nonatomic) NSString *selectedToneIdentifier; @property(nonatomic) _Bool showsNothingSelected; @property(copy, nonatomic) NSString *noneString; @property(nonatomic, getter=isNoneAtTop) _Bool noneAtTop; @property(nonatomic) _Bool showsNone; @property(copy, nonatomic) NSString *defaultToneIdentifier; @property(nonatomic) _Bool showsDefault; @property(copy, nonatomic) NSString *accountIdentifier; @property(readonly, nonatomic) int alertType; - (void)dealloc; - (id)initWithAlertType:(int)arg1; - (id)initWithStyle:(long long)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKVibrationInterfaceUtilities : NSObject { } + (id)descriptionForDuration:(double)arg1; + (_Bool)vibrationNameTextField:(id)arg1 shouldChangeCharactersInRange:(struct _NSRange)arg2 replacementString:(id)arg3; + (void)configureVibrationNameTextField:(id)arg1; @end @interface TKVibrationPickerTableViewCell : TKPickerTableViewCell <UITextFieldDelegate> { _Bool _editable; id <TKVibrationPickerTableViewCellDelegate> _delegate; UIColor *_regularTextColor; UITextField *_removableTextField; } @property(retain, nonatomic, setter=_setRemovableTextField:) UITextField *_removableTextField; // @synthesize _removableTextField; @property(retain, nonatomic) UIColor *regularTextColor; // @synthesize regularTextColor=_regularTextColor; @property(nonatomic, getter=isEditable) _Bool editable; // @synthesize editable=_editable; @property(nonatomic) id <TKVibrationPickerTableViewCellDelegate> delegate; // @synthesize delegate=_delegate; - (void)textFieldDidEndEditing:(id)arg1; - (void)textFieldDidBeginEditing:(id)arg1; - (_Bool)textFieldShouldReturn:(id)arg1; - (_Bool)textField:(id)arg1 shouldChangeCharactersInRange:(struct _NSRange)arg2 replacementString:(id)arg3; - (void)_makeRemovableTextFieldEditable:(_Bool)arg1; - (void)willTransitionToState:(unsigned long long)arg1; - (void)didTransitionToState:(unsigned long long)arg1; - (void)layoutSubviews; - (void)_layoutRemovableTextField; - (void)makeTextFieldResignFirstResponderIfNeeded; @property(readonly, nonatomic, getter=_isDisplayingRemovableTextField) _Bool _displayingRemovableTextField; @property(nonatomic, getter=isChecked) _Bool checked; @property(retain, nonatomic) UIColor *highlightedTextColor; @property(retain, nonatomic) UIFont *regularTextFont; @property(retain, nonatomic) NSString *placeholderText; @property(retain, nonatomic) NSString *labelText; - (void)dealloc; - (id)initWithReuseIdentifier:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKVibrationPickerViewController : UITableViewController <TKVibrationPickerTableViewCellDelegate, TKVibrationRecorderViewControllerDelegate, UINavigationControllerDelegate> { int _alertType; _Bool _showsDefault; _Bool _showsUserGenerated; _Bool _showsNone; _Bool _showsNothingSelected; _Bool _showsEditButtonAtRightSideOfCurrentNavigationController; _Bool _allowsDeletingDefaultVibration; NSString *_noneString; NSIndexPath *_selectedVibrationIndexPath; _Bool _canEnterEditingMode; _Bool _vibrating; _Bool _viewHasAppearedAtLeastOnce; _Bool _isCallingParentViewController; _Bool _swipeToDeleteMode; _Bool _skipNextUserGeneratedVibrationsDidChangeNotification; TLVibrationManager *_vibrationManager; TKVibratorController *_vibratorController; id <TKVibrationPickerViewControllerDelegate> _delegate; NSTimer *_vibrationShouldStopTimer; NSArray *_sortedVibrationIdentifiers; NSArray *_sortedUserGeneratedVibrationIdentifiers; _Bool _defaultVibrationIdentifierWasExplicitlySet; _Bool _showsEditButtonInNavigationBar; _Bool _shouldForceShowingAllAvailableSections; NSString *_accountIdentifier; id <TKVibrationPickerViewControllerDelegate> _additionalDelegate; id <TKVibrationPickerViewControllerDismissalDelegate> _dismissalDelegate; NSString *_defaultVibrationIdentifier; NSIndexPath *_indexPathOfCellBeingDeleted; id <TKVibrationPickerStyleProvider> _styleProvider; TKLabelContainerView *_defaultSectionHeaderView; TKLabelContainerView *_systemSectionHeaderView; TKLabelContainerView *_userGeneratedSectionHeaderView; } @property(retain, nonatomic, setter=_setUserGeneratedSectionHeaderView:) TKLabelContainerView *_userGeneratedSectionHeaderView; // @synthesize _userGeneratedSectionHeaderView; @property(retain, nonatomic, setter=_setSystemSectionHeaderView:) TKLabelContainerView *_systemSectionHeaderView; // @synthesize _systemSectionHeaderView; @property(retain, nonatomic, setter=_setDefaultSectionHeaderView:) TKLabelContainerView *_defaultSectionHeaderView; // @synthesize _defaultSectionHeaderView; @property(nonatomic, setter=_setShouldForceShowingAllAvailableSections:) _Bool _shouldForceShowingAllAvailableSections; // @synthesize _shouldForceShowingAllAvailableSections; @property(retain, nonatomic, setter=_setStyleProvider:) id <TKVibrationPickerStyleProvider> _styleProvider; // @synthesize _styleProvider; @property(retain, nonatomic, setter=_setIndexPathOfCellBeingDeleted:) NSIndexPath *_indexPathOfCellBeingDeleted; // @synthesize _indexPathOfCellBeingDeleted; @property(nonatomic) _Bool allowsDeletingDefaultVibration; // @synthesize allowsDeletingDefaultVibration=_allowsDeletingDefaultVibration; @property(nonatomic) _Bool showsEditButtonInNavigationBar; // @synthesize showsEditButtonInNavigationBar=_showsEditButtonInNavigationBar; @property(nonatomic) _Bool showsNothingSelected; // @synthesize showsNothingSelected=_showsNothingSelected; @property(retain, nonatomic) NSString *noneString; // @synthesize noneString=_noneString; @property(nonatomic) _Bool showsNone; // @synthesize showsNone=_showsNone; @property(nonatomic) _Bool showsUserGenerated; // @synthesize showsUserGenerated=_showsUserGenerated; @property(nonatomic, setter=_setDefaultVibrationIdentifierWasExplicitlySet:) _Bool _defaultVibrationIdentifierWasExplicitlySet; // @synthesize _defaultVibrationIdentifierWasExplicitlySet; @property(copy, nonatomic, setter=_setDefaultVibrationIdentifier:) NSString *_defaultVibrationIdentifier; // @synthesize _defaultVibrationIdentifier; @property(nonatomic) _Bool showsDefault; // @synthesize showsDefault=_showsDefault; @property(nonatomic, setter=_setDismissalDelegate:) id <TKVibrationPickerViewControllerDismissalDelegate> _dismissalDelegate; // @synthesize _dismissalDelegate; @property(nonatomic, setter=_setAdditionalDelegate:) id <TKVibrationPickerViewControllerDelegate> _additionalDelegate; // @synthesize _additionalDelegate; @property(nonatomic) id <TKVibrationPickerViewControllerDelegate> delegate; // @synthesize delegate=_delegate; @property(copy, nonatomic) NSString *accountIdentifier; // @synthesize accountIdentifier=_accountIdentifier; @property(readonly, nonatomic) int alertType; // @synthesize alertType=_alertType; - (void)setEditing:(_Bool)arg1 animated:(_Bool)arg2; - (void)_presentVibrationRecorderViewController; - (void)vibrationPickerTableViewCell:(id)arg1 endedEditingWithText:(id)arg2; - (void)_stopVibrating; - (void)_startVibratingWithVibrationIdentifier:(id)arg1; - (unsigned long long)navigationControllerSupportedInterfaceOrientations:(id)arg1; - (void)vibrationRecorderViewControllerWasDismissedWithoutSavingRecordedVibrationPattern:(id)arg1; - (void)vibrationRecorderViewController:(id)arg1 didFinishRecordingVibrationPattern:(id)arg2 name:(id)arg3; - (void)tableView:(id)arg1 didEndEditingRowAtIndexPath:(id)arg2; - (void)tableView:(id)arg1 willBeginEditingRowAtIndexPath:(id)arg2; - (long long)tableView:(id)arg1 editingStyleForRowAtIndexPath:(id)arg2; - (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2; - (id)tableView:(id)arg1 willSelectRowAtIndexPath:(id)arg2; - (double)tableView:(id)arg1 heightForHeaderInSection:(long long)arg2; - (id)tableView:(id)arg1 titleForHeaderInSection:(long long)arg2; - (id)tableView:(id)arg1 viewForHeaderInSection:(long long)arg2; - (void)_getTitle:(id *)arg1 customHeaderView:(id *)arg2 forHeaderInSection:(long long)arg3; - (void)tableView:(id)arg1 commitEditingStyle:(long long)arg2 forRowAtIndexPath:(id)arg3; - (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2; - (long long)numberOfSectionsInTableView:(id)arg1; - (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2; @property(readonly, nonatomic) long long _sectionForNoneGroup; @property(readonly, nonatomic) long long _sectionForUserGeneratedGroup; @property(readonly, nonatomic) long long _sectionForSystemGroup; @property(readonly, nonatomic) long long _sectionForDefaultGroup; - (void)_updateSectionVisibilityFlagAtLocation:(_Bool *)arg1 toValue:(_Bool)arg2 sectionIndexGetter:(CDUnknownBlockType)arg3; - (void)_performBlockForcingShowingAllAvailableSections:(CDUnknownBlockType)arg1; - (void)_handleError:(id)arg1; - (void)_handleUserGeneratedVibrationsDidChangeNotification; - (id)_adjustedNameForVibrationWithDesiredName:(id)arg1 vibrationIdentifier:(id)arg2; - (void)_updateSelectionStyleForCell:(id)arg1 indexPath:(id)arg2; - (void)_updateEditButtonItemWithAnimation:(_Bool)arg1; - (void)_updateEditButtonItem; - (id)_navigationItem; - (void)_processSelectionOfVibrationWithIdentifier:(id)arg1; - (id)_indexPathForVibrationWithIdentifier:(id)arg1; - (id)_identifierOfVibrationAtIndexPath:(id)arg1; @property(readonly, nonatomic) NSArray *_sortedUserGeneratedVibrationIdentifiers; @property(readonly, nonatomic) NSArray *_sortedVibrationIdentifiers; - (id)_sortedArrayWithVibrationIdentifiers:(id)arg1 allowsDuplicateVibrationNames:(_Bool)arg2; - (void)applicationWillSuspend; - (unsigned long long)supportedInterfaceOrientations; - (void)viewDidDisappear:(_Bool)arg1; - (void)viewWillDisappear:(_Bool)arg1; - (void)viewDidAppear:(_Bool)arg1; - (void)viewWillAppear:(_Bool)arg1; - (void)viewDidLoad; @property(readonly, nonatomic) _Bool _showsOnlyEditableSections; @property(retain, nonatomic, setter=_setSelectedVibrationIndexPathAdjustedForCurrentEditingMode:) NSIndexPath *_selectedVibrationIndexPathAdjustedForCurrentEditingMode; - (id)_actualIndexPathFromNonEditingIndexPath:(id)arg1; - (id)_nonEditingIndexPathFromActualIndexPath:(id)arg1; - (void)_updateStyleOfTableView:(id)arg1 forStyleProvider:(id)arg2; @property(retain, nonatomic) id <TKVibrationPickerStyleProvider> styleProvider; - (void)_setSelectedVibrationIdentifier:(id)arg1 processSelectionOfVibrationIdentifier:(_Bool)arg2; @property(retain, nonatomic) NSString *selectedVibrationIdentifier; @property(readonly, nonatomic) _Bool canEnterEditingMode; @property(copy, nonatomic) NSString *defaultVibrationIdentifier; - (void)dealloc; - (id)initWithAlertType:(int)arg1; - (id)initWithStyle:(long long)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKVibrationRecorderContentViewController : UIViewController <TKVibrationRecorderViewDelegate, UITextFieldDelegate> { _Bool _waitingForEndOfCurrentVibrationComponent; int _mode; id <TKVibrationRecorderViewControllerDelegate> _delegate; TKVibrationRecorderViewController *_parentVibrationRecorderViewController; UIBarButtonItem *_cancelButton; UIBarButtonItem *_saveButton; UIAlertController *_vibrationNameAlertController; UIAlertAction *_vibrationNameAlertSaveAction; UITextField *_vibrationNameAlertTextField; TKVibratorController *_vibratorController; NSDictionary *_indefiniteVibrationPattern; TKVibrationRecorderView *_vibrationRecorderView; TLVibrationPattern *_recordedVibrationPattern; double _currentVibrationComponentDidStartTimeStamp; double _currentVibrationProgressDidStartTimestamp; } @property(nonatomic, getter=_isWaitingForEndOfCurrentVibrationComponent, setter=_setWaitingForEndOfCurrentVibrationComponent:) _Bool _waitingForEndOfCurrentVibrationComponent; // @synthesize _waitingForEndOfCurrentVibrationComponent; @property(nonatomic, setter=_setCurrentVibrationProgressDidStartTimestamp:) double _currentVibrationProgressDidStartTimestamp; // @synthesize _currentVibrationProgressDidStartTimestamp; @property(nonatomic, setter=_setCurrentVibrationComponentDidStartTimeStamp:) double _currentVibrationComponentDidStartTimeStamp; // @synthesize _currentVibrationComponentDidStartTimeStamp; @property(retain, nonatomic, setter=_setRecordedVibrationPattern:) TLVibrationPattern *_recordedVibrationPattern; // @synthesize _recordedVibrationPattern; @property(retain, nonatomic, setter=_setVibrationRecorderView:) TKVibrationRecorderView *_vibrationRecorderView; // @synthesize _vibrationRecorderView; @property(nonatomic, setter=_setMode:) int _mode; // @synthesize _mode; @property(retain, nonatomic, setter=_setIndefiniteVibrationPattern:) NSDictionary *_indefiniteVibrationPattern; // @synthesize _indefiniteVibrationPattern; @property(retain, nonatomic, setter=_setVibratorController:) TKVibratorController *_vibratorController; // @synthesize _vibratorController; @property(retain, nonatomic, setter=_setVibrationNameAlertTextField:) UITextField *_vibrationNameAlertTextField; // @synthesize _vibrationNameAlertTextField; @property(retain, nonatomic, setter=_setVibrationNameAlertSaveAction:) UIAlertAction *_vibrationNameAlertSaveAction; // @synthesize _vibrationNameAlertSaveAction; @property(retain, nonatomic, setter=_setVibrationNameAlertController:) UIAlertController *_vibrationNameAlertController; // @synthesize _vibrationNameAlertController; @property(retain, nonatomic, setter=_setSaveButton:) UIBarButtonItem *_saveButton; // @synthesize _saveButton; @property(retain, nonatomic, setter=_setCancelButton:) UIBarButtonItem *_cancelButton; // @synthesize _cancelButton; @property(nonatomic) TKVibrationRecorderViewController *parentVibrationRecorderViewController; // @synthesize parentVibrationRecorderViewController=_parentVibrationRecorderViewController; @property(nonatomic) id <TKVibrationRecorderViewControllerDelegate> delegate; // @synthesize delegate=_delegate; - (void)_accessibilityDidExitReplayMode; - (void)_accessibilityDidEnterReplayMode; - (void)_accessibilityDidExitRecordingMode; - (void)_accessibilityDidEnterRecordingMode; - (void)_accessibilityMakeAnnouncementWithStringForLocalizationIdentifier:(id)arg1; - (void)_finishedWithRecorder; - (void)vibrationRecorderViewDidReachVibrationRecordingMaximumDuration:(id)arg1; - (void)vibrationRecorderView:(id)arg1 didExitRecordingModeWithContextObject:(id)arg2; - (_Bool)vibrationRecorderViewDidEnterRecordingMode:(id)arg1; - (void)vibrationRecorderViewDidFinishReplayingVibration:(id)arg1; - (void)vibrationRecorderView:(id)arg1 buttonTappedWithIdentifier:(int)arg2; - (void)vibrationComponentDidEndForVibrationRecorderView:(id)arg1; - (void)vibrationComponentDidStartForVibrationRecorderView:(id)arg1; - (void)_eraseCurrentVibrationComponentDidStartTimeStamp; - (void)_storeVibrationComponentOfTypePause:(_Bool)arg1; - (void)_stopVibrating; - (void)_startVibratingWithVibrationPattern:(id)arg1; - (_Bool)textFieldShouldReturn:(id)arg1; - (_Bool)textField:(id)arg1 shouldChangeCharactersInRange:(struct _NSRange)arg2 replacementString:(id)arg3; - (void)_cleanUpVibrationNameAlertController; - (void)_vibrationNameTextFieldContentsDidChange:(id)arg1; - (void)_updateStateSaveButtonInAlert; - (void)_saveButtonInAlertTapped:(id)arg1; - (void)_cancelButtonInAlertTapped:(id)arg1; - (void)_saveButtonTapped:(id)arg1; - (void)_cancelButtonTapped:(id)arg1; - (unsigned long long)supportedInterfaceOrientations; - (void)willRotateToInterfaceOrientation:(long long)arg1 duration:(double)arg2; - (void)viewDidDisappear:(_Bool)arg1; - (void)viewWillAppear:(_Bool)arg1; - (void)viewWillDisappear:(_Bool)arg1; - (void)viewDidAppear:(_Bool)arg1; - (void)loadView; - (void)applicationWillSuspend; - (void)dealloc; - (id)initWithVibratorController:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKVibrationRecorderProgressDotImageView : UIImageView { double _timeInterval; double _duration; double _previousPauseTimeInterval; double _previousPauseDuration; double _accessibilityFrameAdditionalHeight; } @property(nonatomic) double accessibilityFrameAdditionalHeight; // @synthesize accessibilityFrameAdditionalHeight=_accessibilityFrameAdditionalHeight; @property(nonatomic) double previousPauseDuration; // @synthesize previousPauseDuration=_previousPauseDuration; @property(nonatomic) double previousPauseTimeInterval; // @synthesize previousPauseTimeInterval=_previousPauseTimeInterval; @property(nonatomic) double duration; // @synthesize duration=_duration; @property(nonatomic) double timeInterval; // @synthesize timeInterval=_timeInterval; - (unsigned long long)accessibilityTraits; - (struct CGRect)accessibilityFrame; - (id)accessibilityValue; - (id)accessibilityLabel; - (_Bool)isAccessibilityElement; @end @interface TKVibrationRecorderProgressView : UIView { int _roundedCornersCompensationDelayMode; double _currentTimeInterval; double _maximumTimeInterval; double _currentVibrationComponentDidBeginTimeInterval; double _previousPauseDidBeginTimeInterval; id <TKVibrationRecorderStyleProvider> _styleProvider; UIView *_progressView; NSLayoutConstraint *_progressViewWidthConstraint; TKVibrationRecorderProgressDotImageView *_dotForCurrentVibrationComponent; NSLayoutConstraint *_dotForCurrentVibrationComponentLeftConstraint; NSLayoutConstraint *_dotForCurrentVibrationComponentRightConstraint; NSMutableArray *_dots; } @property(retain, nonatomic, setter=_setDots:) NSMutableArray *_dots; // @synthesize _dots; @property(retain, nonatomic, setter=_setDotForCurrentVibrationComponentRightConstraint:) NSLayoutConstraint *_dotForCurrentVibrationComponentRightConstraint; // @synthesize _dotForCurrentVibrationComponentRightConstraint; @property(retain, nonatomic, setter=_setDotForCurrentVibrationComponentLeftConstraint:) NSLayoutConstraint *_dotForCurrentVibrationComponentLeftConstraint; // @synthesize _dotForCurrentVibrationComponentLeftConstraint; @property(retain, nonatomic, setter=_setDotForCurrentVibrationComponent:) TKVibrationRecorderProgressDotImageView *_dotForCurrentVibrationComponent; // @synthesize _dotForCurrentVibrationComponent; @property(retain, nonatomic, setter=_setProgressViewWidthConstraint:) NSLayoutConstraint *_progressViewWidthConstraint; // @synthesize _progressViewWidthConstraint; @property(retain, nonatomic, setter=_setProgressView:) UIView *_progressView; // @synthesize _progressView; @property(retain, nonatomic, setter=_setStyleProvider:) id <TKVibrationRecorderStyleProvider> _styleProvider; // @synthesize _styleProvider; @property(nonatomic, setter=_setPreviousPauseDidBeginTimeInterval:) double _previousPauseDidBeginTimeInterval; // @synthesize _previousPauseDidBeginTimeInterval; @property(nonatomic, setter=_setCurrentVibrationComponentDidBeginTimeInterval:) double _currentVibrationComponentDidBeginTimeInterval; // @synthesize _currentVibrationComponentDidBeginTimeInterval; @property(nonatomic, setter=_setMaximumTimeInterval:) double _maximumTimeInterval; // @synthesize _maximumTimeInterval; @property(nonatomic, setter=_setCurrentTimeInterval:) double _currentTimeInterval; // @synthesize _currentTimeInterval; @property(nonatomic) int roundedCornersCompensationDelayMode; // @synthesize roundedCornersCompensationDelayMode=_roundedCornersCompensationDelayMode; - (struct CGRect)accessibilityFrame; - (id)accessibilityValue; - (id)accessibilityLabel; - (_Bool)isAccessibilityElement; - (double)_cappedValueForTimeInterval:(double)arg1; - (void)didMoveToWindow; - (void)didMoveToSuperview; - (struct CGRect)_frameForDotAtTimeInterval:(double)arg1 duration:(double)arg2; - (void)_updateHorizontalConstraintsOfDotForCurrentVibrationComponent:(id)arg1 withFrame:(struct CGRect)arg2; - (struct CGSize)intrinsicContentSize; - (void)clearAllVibrationComponents; - (void)vibrationComponentDidEnd; - (void)vibrationComponentDidStart; @property(readonly, nonatomic) struct UIOffset _dotInsets; @property(readonly, nonatomic) struct CGSize _dotSize; @property(readonly, nonatomic) UIImage *_resizableDotImage; - (void)_updateProgressViewBackgroundColor; @property(nonatomic) double currentTimeInterval; - (void)dealloc; - (id)initWithMaximumTimeInterval:(double)arg1 styleProvider:(id)arg2; - (id)initWithFrame:(struct CGRect)arg1; @end @interface TKVibrationRecorderRippleRingLayer : CAShapeLayer { double _creationTimestamp; double _ringSpeed; struct CGPoint _normalizedRingLocation; } @property(nonatomic, setter=_setRingSpeed:) double _ringSpeed; // @synthesize _ringSpeed; @property(nonatomic, setter=_setNormalizedRingLocation:) struct CGPoint _normalizedRingLocation; // @synthesize _normalizedRingLocation; @property(nonatomic, setter=_setCreationTimestamp:) double _creationTimestamp; // @synthesize _creationTimestamp; - (void)reset; - (void)configureWithTimeIntervalSinceCreation:(double)arg1 normalizedRingLocation:(struct CGPoint)arg2 ringSpeed:(double)arg3; - (double)timeIntervalSinceCreation; @property(readonly, nonatomic) double ringSpeed; @property(readonly, nonatomic) struct CGPoint normalizedRingLocation; - (id)init; @end @interface TKVibrationRecorderRippleTouchContext : NSObject { double _creationTimestamp; struct CGPoint _location; } @property(nonatomic, setter=_setLocation:) struct CGPoint _location; // @synthesize _location; @property(nonatomic, setter=_setCreationTimestamp:) double _creationTimestamp; // @synthesize _creationTimestamp; - (void)reset; - (void)configureWithTimeIntervalSinceCreation:(double)arg1 location:(struct CGPoint)arg2; - (double)timeIntervalSinceCreation; @property(readonly, nonatomic) struct CGPoint location; - (id)init; @end @interface TKVibrationRecorderRippleView : UIView { _Bool _trackingTouch; _Bool _needsCurrentSpeedRefresh; _Bool _animating; double _fingerStillSpeed; double _fingerMovingSpeed; double _firstRippleInitialRadius; double _fadeOutRadius; id <TKVibrationRecorderStyleProvider> _styleProvider; double _currentTouchStartTime; unsigned long long _numberOfRipplesForCurrentTouch; NSMutableArray *_recentTouchesContextQueue; NSMutableArray *_reusableTouchContexts; double _currentSpeedCoefficient; NSMutableArray *_ringLayersQueue; NSMutableArray *_reusableRingLayers; NSMutableDictionary *_ringLayersByIdentifiers; unsigned long long _lastRingLayerIdentifier; CAAnimation *_ringEnlargementAnimation; struct CGPoint _currentTouchLocation; } @property(retain, nonatomic, setter=_setRingEnlargementAnimation:) CAAnimation *_ringEnlargementAnimation; // @synthesize _ringEnlargementAnimation; @property(nonatomic, setter=_setLastRingLayerIdentifier:) unsigned long long _lastRingLayerIdentifier; // @synthesize _lastRingLayerIdentifier; @property(retain, nonatomic, setter=_setRingLayersByIdentifiers:) NSMutableDictionary *_ringLayersByIdentifiers; // @synthesize _ringLayersByIdentifiers; @property(retain, nonatomic, setter=_setReusableRingLayers:) NSMutableArray *_reusableRingLayers; // @synthesize _reusableRingLayers; @property(retain, nonatomic, setter=_setRingLayersQueue:) NSMutableArray *_ringLayersQueue; // @synthesize _ringLayersQueue; @property(nonatomic, getter=_isAnimating, setter=_setAnimating:) _Bool _animating; // @synthesize _animating; @property(nonatomic, setter=_setNeedsCurrentSpeedRefresh:) _Bool _needsCurrentSpeedRefresh; // @synthesize _needsCurrentSpeedRefresh; @property(nonatomic, setter=_setCurrentSpeedCoefficient:) double _currentSpeedCoefficient; // @synthesize _currentSpeedCoefficient; @property(retain, nonatomic, setter=_setReusableTouchContexts:) NSMutableArray *_reusableTouchContexts; // @synthesize _reusableTouchContexts; @property(retain, nonatomic, setter=_setRecentTouchesContextQueue:) NSMutableArray *_recentTouchesContextQueue; // @synthesize _recentTouchesContextQueue; @property(nonatomic, getter=_isTrackingTouch, setter=_setTrackingTouch:) _Bool _trackingTouch; // @synthesize _trackingTouch; @property(nonatomic, setter=_setNumberOfRipplesForCurrentTouch:) unsigned long long _numberOfRipplesForCurrentTouch; // @synthesize _numberOfRipplesForCurrentTouch; @property(nonatomic, setter=_setCurrentTouchStartTime:) double _currentTouchStartTime; // @synthesize _currentTouchStartTime; @property(nonatomic, setter=_setCurrentTouchLocation:) struct CGPoint _currentTouchLocation; // @synthesize _currentTouchLocation; @property(retain, nonatomic, setter=_setStyleProvider:) id <TKVibrationRecorderStyleProvider> _styleProvider; // @synthesize _styleProvider; @property(nonatomic) double fadeOutRadius; // @synthesize fadeOutRadius=_fadeOutRadius; @property(nonatomic) double firstRippleInitialRadius; // @synthesize firstRippleInitialRadius=_firstRippleInitialRadius; @property(nonatomic) double fingerMovingSpeed; // @synthesize fingerMovingSpeed=_fingerMovingSpeed; @property(nonatomic) double fingerStillSpeed; // @synthesize fingerStillSpeed=_fingerStillSpeed; - (void)touchesCancelled:(id)arg1 withEvent:(id)arg2; - (void)touchesEnded:(id)arg1 withEvent:(id)arg2; - (void)touchesMoved:(id)arg1 withEvent:(id)arg2; - (void)touchesBegan:(id)arg1 withEvent:(id)arg2; - (void)_touchEndedAtLocation:(struct CGPoint)arg1; - (void)_touchMovedToLocation:(struct CGPoint)arg1; - (void)_touchBeganAtLocation:(struct CGPoint)arg1; - (void)animationDidStop:(id)arg1 finished:(_Bool)arg2; - (void)layoutSubviews; - (void)_updateRingEnlargementAnimation; - (void)_enqueueReusableRingLayer:(id)arg1; - (id)_reusableRingLayer; - (void)_enqueueRingLayerWithTimeIntervalSinceCreation:(double)arg1 normalizedLocation:(struct CGPoint)arg2 speed:(double)arg3; - (void)_stopAnimation; - (void)_startAnimation; - (void)_enqueueReusableTouchContextObject:(id)arg1; - (id)_reusableTouchContextObject; @property(readonly, nonatomic) double _currentSpeed; - (void)_refresh:(id)arg1; @property(readonly, nonatomic, getter=_isTouchDown) _Bool _touchDown; - (void)dealloc; - (id)initWithStyleProvider:(id)arg1; - (id)init; @end @interface TKVibrationRecorderTouchSurface : TKVibrationRecorderRippleView { _Bool _recordingModeEnabled; _Bool _shouldIgnoreCurrentTouch; _Bool _replayModeEnabled; id <TKVibrationRecorderTouchSurfaceDelegate> _delegate; double _vibrationPatternMaximumDuration; TKVibrationRecorderTouchSurfaceRecordedDataWrapper *_recordedDataWrapper; TLVibrationPattern *_vibrationPatternToReplay; double _replayModeWasEnteredStartTime; } @property(nonatomic, setter=_setReplayModeWasEnteredStartTime:) double _replayModeWasEnteredStartTime; // @synthesize _replayModeWasEnteredStartTime; @property(retain, nonatomic, setter=_setVibrationPatternToReplay:) TLVibrationPattern *_vibrationPatternToReplay; // @synthesize _vibrationPatternToReplay; @property(nonatomic, getter=_isReplayModeEnabled, setter=_setReplayModeEnabled:) _Bool _replayModeEnabled; // @synthesize _replayModeEnabled; @property(nonatomic, setter=_setShouldIgnoreCurrentTouch:) _Bool _shouldIgnoreCurrentTouch; // @synthesize _shouldIgnoreCurrentTouch; @property(retain, nonatomic, setter=_setRecordedDataWrapper:) TKVibrationRecorderTouchSurfaceRecordedDataWrapper *_recordedDataWrapper; // @synthesize _recordedDataWrapper; @property(nonatomic, setter=_setVibrationPatternMaximumDuration:) double _vibrationPatternMaximumDuration; // @synthesize _vibrationPatternMaximumDuration; @property(nonatomic, getter=_isRecordingModeEnabled, setter=_setRecordingModeEnabled:) _Bool _recordingModeEnabled; // @synthesize _recordingModeEnabled; @property(nonatomic) id <TKVibrationRecorderTouchSurfaceDelegate> delegate; // @synthesize delegate=_delegate; - (void)_updateTouchLocationForReplayMode:(id)arg1; - (void)exitReplayMode; - (void)enterReplayModeWithVibrationPattern:(id)arg1; - (void)_recordTouchLocation:(struct CGPoint)arg1 touchPhase:(int)arg2; - (void)currentVibrationComponentShouldEnd; - (void)exitRecordingMode; - (void)enterRecordingMode; - (void)touchesCancelled:(id)arg1 withEvent:(id)arg2; - (void)touchesEnded:(id)arg1 withEvent:(id)arg2; - (void)touchesMoved:(id)arg1 withEvent:(id)arg2; - (void)touchesBegan:(id)arg1 withEvent:(id)arg2; - (void)dealloc; - (id)initWithVibrationPatternMaximumDuration:(double)arg1 styleProvider:(id)arg2; - (id)init; @end @interface TKVibrationRecorderTouchSurfaceRecordedDataWrapper : NSObject { _Bool _warmUpModeEnabled; _Bool _displayLinkHasRefreshedAtLeastOnce; double _vibrationPatternMaximumDuration; double _vibrationPatternDidStartTimestamp; unsigned long long _maximumFramesPerSecondRate; void *_recordedData; unsigned long long _recordedDataElementsCount; unsigned long long _recordedDataCursor; double _warmUpModeDidStartTimestamp; } @property(nonatomic, setter=_setDisplayLinkHasRefreshedAtLeastOnce:) _Bool _displayLinkHasRefreshedAtLeastOnce; // @synthesize _displayLinkHasRefreshedAtLeastOnce; @property(nonatomic, setter=_setWarmUpModeDidStartTimestamp:) double _warmUpModeDidStartTimestamp; // @synthesize _warmUpModeDidStartTimestamp; @property(nonatomic, getter=_isWarmUpModeEnabled, setter=_setWarmUpModeEnabled:) _Bool _warmUpModeEnabled; // @synthesize _warmUpModeEnabled; @property(nonatomic, setter=_setRecordedDataCursor:) unsigned long long _recordedDataCursor; // @synthesize _recordedDataCursor; @property(nonatomic, setter=_setRecordedDataElementsCount:) unsigned long long _recordedDataElementsCount; // @synthesize _recordedDataElementsCount; @property(nonatomic, setter=_setRecordedData:) void *_recordedData; // @synthesize _recordedData; @property(nonatomic, setter=_setMaximumFramesPerSecondRate:) unsigned long long _maximumFramesPerSecondRate; // @synthesize _maximumFramesPerSecondRate; @property(nonatomic, setter=_setVibrationPatternDidStartTimestamp:) double _vibrationPatternDidStartTimestamp; // @synthesize _vibrationPatternDidStartTimestamp; @property(nonatomic, setter=_setVibrationPatternMaximumDuration:) double _vibrationPatternMaximumDuration; // @synthesize _vibrationPatternMaximumDuration; - (void)_updateMaximumFramesPerSecondRate:(id)arg1; - (_Bool)getNormalizedTouchLocation:(struct CGPoint *)arg1 touchPhase:(int *)arg2 forTimeInterval:(double)arg3; - (void)didStopRecording; - (void)recordNormalizedTouchLocation:(struct CGPoint)arg1 touchPhase:(int)arg2; - (void)_recordFinalDataWithNormalizedTouchLocation:(struct CGPoint)arg1 touchPhase:(int)arg2 timeIntervalSinceBeginningOfPattern:(double)arg3; - (void)_prepareRecordedDataBufferForStoringEnoughElementsForRecordingDuration:(double)arg1; - (void)dealloc; - (id)initWithVibrationPatternMaximumDuration:(double)arg1; @end @interface TKVibrationRecorderView : UIView <TKVibrationRecorderTouchSurfaceDelegate> { _Bool _replayModeEnabled; _Bool _waitingForEndOfCurrentVibrationComponent; _Bool _animatingProgress; int _leftButtonIdentifier; int _rightButtonIdentifier; id <TKVibrationRecorderViewDelegate> _delegate; id <TKVibrationRecorderStyleProvider> _styleProvider; UILabel *_instructionsLabel; UIToolbar *_controlsToolbar; TKVibrationRecorderProgressView *_progressView; TKVibrationRecorderTouchSurface *_touchSurface; NSLayoutConstraint *_controlsToolbarTopConstraint; NSLayoutConstraint *_progressToolbarBottomConstraint; NSLayoutConstraint *_touchSurfaceTopConstraint; double _vibrationPatternMaximumDuration; double _currentVibrationProgressDidStartTimestamp; double _currentVibrationComponentDidStartTimestamp; } @property(nonatomic, getter=_isAnimatingProgress, setter=_setAnimatingProgress:) _Bool _animatingProgress; // @synthesize _animatingProgress; @property(nonatomic, getter=_isWaitingForEndOfCurrentVibrationComponent, setter=_setWaitingForEndOfCurrentVibrationComponent:) _Bool _waitingForEndOfCurrentVibrationComponent; // @synthesize _waitingForEndOfCurrentVibrationComponent; @property(nonatomic, setter=_setCurrentVibrationComponentDidStartTimestamp:) double _currentVibrationComponentDidStartTimestamp; // @synthesize _currentVibrationComponentDidStartTimestamp; @property(nonatomic, setter=_setCurrentVibrationProgressDidStartTimestamp:) double _currentVibrationProgressDidStartTimestamp; // @synthesize _currentVibrationProgressDidStartTimestamp; @property(nonatomic, setter=_setVibrationPatternMaximumDuration:) double _vibrationPatternMaximumDuration; // @synthesize _vibrationPatternMaximumDuration; @property(nonatomic, getter=_isReplayModeEnabled, setter=_setReplayModeEnabled:) _Bool _replayModeEnabled; // @synthesize _replayModeEnabled; @property(nonatomic, setter=_setRightButtonIdentifier:) int _rightButtonIdentifier; // @synthesize _rightButtonIdentifier; @property(nonatomic, setter=_setLeftButtonIdentifier:) int _leftButtonIdentifier; // @synthesize _leftButtonIdentifier; @property(retain, nonatomic, setter=_setTouchSurfaceTopConstraint:) NSLayoutConstraint *_touchSurfaceTopConstraint; // @synthesize _touchSurfaceTopConstraint; @property(retain, nonatomic, setter=_setProgressToolbarBottomConstraint:) NSLayoutConstraint *_progressToolbarBottomConstraint; // @synthesize _progressToolbarBottomConstraint; @property(retain, nonatomic, setter=_setControlsToolbarTopConstraint:) NSLayoutConstraint *_controlsToolbarTopConstraint; // @synthesize _controlsToolbarTopConstraint; @property(retain, nonatomic, setter=_setTouchSurface:) TKVibrationRecorderTouchSurface *_touchSurface; // @synthesize _touchSurface; @property(retain, nonatomic, setter=_setProgressView:) TKVibrationRecorderProgressView *_progressView; // @synthesize _progressView; @property(retain, nonatomic, setter=_setControlsToolbar:) UIToolbar *_controlsToolbar; // @synthesize _controlsToolbar; @property(retain, nonatomic, setter=_setInstructionsLabel:) UILabel *_instructionsLabel; // @synthesize _instructionsLabel; @property(retain, nonatomic, setter=_setStyleProvider:) id <TKVibrationRecorderStyleProvider> _styleProvider; // @synthesize _styleProvider; @property(nonatomic) id <TKVibrationRecorderViewDelegate> delegate; // @synthesize delegate=_delegate; - (void)vibrationRecorderTouchSurface:(id)arg1 didExitRecordingModeWithContextObject:(id)arg2; - (_Bool)vibrationRecorderTouchSurfaceDidEnterRecordingMode:(id)arg1; - (void)vibrationRecorderTouchSurfaceDidFinishReplayingVibration:(id)arg1; - (void)vibrationComponentDidEndForVibrationRecorderTouchSurface:(id)arg1; - (void)vibrationComponentDidStartForVibrationRecorderTouchSurface:(id)arg1; - (void)navigationController:(id)arg1 willRotateToInterfaceOrientation:(long long)arg2 duration:(double)arg3; - (void)wasAddedToNavigationController:(id)arg1; - (void)didMoveToWindow; - (void)_updateProgress:(id)arg1; - (void)stopAnimatingProgress; - (void)startAnimatingProgress; - (void)exitReplayMode; - (void)enterReplayModeWithVibrationPattern:(id)arg1; - (void)exitRecordingModeWithPlayButtonEnabled:(_Bool)arg1; - (void)enterRecordingMode; - (void)_exitWaitingModeWithAnimation:(_Bool)arg1; - (void)_enterWaitingModeWithAnimation:(_Bool)arg1 enablePlayButton:(_Bool)arg2; - (void)_handleRightButtonTapped:(id)arg1; - (void)_handleLeftButtonTapped:(id)arg1; - (void)_setLeftButtonIdentifier:(int)arg1 enabled:(_Bool)arg2 rightButtonIdentifier:(int)arg3 enabled:(_Bool)arg4 animated:(_Bool)arg5; - (id)_titleForControlsToolbarButtonWithIdentifier:(int)arg1; - (void)dealloc; - (id)initWithVibrationPatternMaximumDuration:(double)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end @interface TKVibrationRecorderViewController : UINavigationController { TKVibrationRecorderContentViewController *_vibrationRecorderContentViewController; } @property(retain, nonatomic, setter=_setVibrationRecorderContentViewController:) TKVibrationRecorderContentViewController *_vibrationRecorderContentViewController; // @synthesize _vibrationRecorderContentViewController; @property(nonatomic) id <TKVibrationRecorderViewControllerDelegate> vibrationRecorderViewControllerDelegate; - (void)dealloc; - (id)initWithVibratorController:(id)arg1; @end @interface TKVibratorController : NSObject { } - (void)turnOff; - (void)turnOnWithVibrationPattern:(id)arg1; @end @interface UIResponder (TKExtensions) - (id)tk_firstViewControllerInResponderChain; @end @interface UIView (TKConstraintBasedLayout) - (id)_tk_autolayoutTrace; - (id)_tk_recursiveAutolayoutTraceAtLevel:(long long)arg1 anyDescendantHasAmbiguousLayout:(_Bool *)arg2; - (id)tk_firstCommonAncestorWithView:(id)arg1; - (unsigned long long)_tl_depth; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 relatedBy:(long long)arg2 toItem:(id)arg3 attribute:(long long)arg4 multiplier:(double)arg5 constant:(double)arg6; - (void)tk_constrainLayoutAttribute:(long long)arg1 relatedBy:(long long)arg2 toItem:(id)arg3 attribute:(long long)arg4 multiplier:(double)arg5 constant:(double)arg6; - (id)tk_addedConstraintFotLayoutAttribute:(long long)arg1 asGreaterThanOrEqualToValueOfView:(id)arg2 withOffset:(double)arg3; - (void)tk_constrainLayoutAttribute:(long long)arg1 asGreaterThanOrEqualToValueOfView:(id)arg2 withOffset:(double)arg3; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asLessThanOrEqualToValueOfView:(id)arg2 withOffset:(double)arg3; - (void)tk_constrainLayoutAttribute:(long long)arg1 asLessThanOrEqualToValueOfView:(id)arg2 withOffset:(double)arg3; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToLayoutAttribute:(long long)arg2 ofView:(id)arg3 withMultiplier:(double)arg4; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToValueOfView:(id)arg2 withMultiplier:(double)arg3; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToLayoutAttribute:(long long)arg2 ofView:(id)arg3 withOffset:(double)arg4; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToLayoutAttribute:(long long)arg2 ofView:(id)arg3; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToValueOfView:(id)arg2 withOffset:(double)arg3; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToValueOfView:(id)arg2; - (id)tk_addedConstraintForLayoutAttribute:(long long)arg1 asEqualToConstant:(double)arg2; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToLayoutAttribute:(long long)arg2 ofView:(id)arg3 withMultiplier:(double)arg4; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToValueOfView:(id)arg2 withMultiplier:(double)arg3; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToLayoutAttribute:(long long)arg2 ofView:(id)arg3 withOffset:(double)arg4; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToLayoutAttribute:(long long)arg2 ofView:(id)arg3; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToValueOfView:(id)arg2 withOffset:(double)arg3; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToValueOfView:(id)arg2; - (void)tk_constrainLayoutAttribute:(long long)arg1 asEqualToConstant:(double)arg2; @end
28,919
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 UI_GFX_GEOMETRY_GEOMETRY_SKIA_EXPORT_H_ #define UI_GFX_GEOMETRY_GEOMETRY_SKIA_EXPORT_H_ #if defined(COMPONENT_BUILD) #if defined(WIN32) #if defined(GEOMETRY_SKIA_IMPLEMENTATION) #define GEOMETRY_SKIA_EXPORT __declspec(dllexport) #else #define GEOMETRY_SKIA_EXPORT __declspec(dllimport) #endif // defined(GEOMETRY_SKIA_IMPLEMENTATION) #else // defined(WIN32) #if defined(GEOMETRY_SKIA_IMPLEMENTATION) #define GEOMETRY_SKIA_EXPORT __attribute__((visibility("default"))) #else #define GEOMETRY_SKIA_EXPORT #endif #endif #else // defined(COMPONENT_BUILD) #define GEOMETRY_SKIA_EXPORT #endif #endif // UI_GFX_GEOMETRY_GEOMETRY_SKIA_EXPORT_H_
336
831
<gh_stars>100-1000 /* * Copyright (C) 2016 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.lint; import com.android.tools.idea.lint.common.AndroidLintGradleDependencyInspection; import com.android.tools.idea.lint.common.AndroidLintGradleDeprecatedConfigurationInspection; import com.android.tools.idea.lint.common.AndroidLintGradleDynamicVersionInspection; import com.android.tools.idea.lint.common.AndroidLintGradleIdeErrorInspection; import com.android.tools.idea.lint.common.AndroidLintGradlePathInspection; import com.android.tools.idea.lint.common.AndroidLintInspectionBase; import com.android.tools.lint.checks.GradleDetector; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.android.AndroidTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LintIdeGradleDetectorTest extends AndroidTestCase { private static final String BASE_PATH = "gradle/"; public void testDependencies() throws Exception { AndroidLintGradleDependencyInspection inspection = new AndroidLintGradleDependencyInspection(); doTest(inspection, null); } public void testIncompatiblePlugin() throws Exception { AndroidLintGradlePluginVersionInspection inspection = new AndroidLintGradlePluginVersionInspection(); doTest(inspection, null); } public void testOldBetaPlugin() throws Exception { // note: the test file needs updating when major/minor versions of AGP are removed from the offline // Google Maven cache, and in particular there may be no way to get this test to pass (i.e. to show a // warning) if the only stable AGP version in the offline Google Maven cache is a .0 patchlevel version. AndroidLintGradleDependencyInspection inspection = new AndroidLintGradleDependencyInspection(); doTest(inspection, null); } public void testOldBetaPluginNoGMaven() throws Exception { AndroidLintGradleDependencyInspection inspection = new AndroidLintGradleDependencyInspection(); doTest(inspection, null); } public void testPaths() throws Exception { if (SystemInfo.isWindows) { // This test doesn't work on Windows; the data file supplies what looks like an absolute elsewhere, // and flags it; on Windows the File#isAbsolute() call will return false and will not flag the issue. return; } AndroidLintGradlePathInspection inspection = new AndroidLintGradlePathInspection(); doTest(inspection, null); } public void testSetter() throws Exception { AndroidLintGradleGetterInspection inspection = new AndroidLintGradleGetterInspection(); doTest(inspection, null); } public void testCompatibility() throws Exception { AndroidLintGradleCompatibleInspection inspection = new AndroidLintGradleCompatibleInspection(); doTest(inspection, null); } public void testPlus() throws Exception { GradleDetector.PLUS.setEnabledByDefault(true); AndroidLintGradleDynamicVersionInspection inspection = new AndroidLintGradleDynamicVersionInspection(); doTest(inspection, null); } public void testIdSuffix() throws Exception { AndroidLintGradlePathInspection inspection = new AndroidLintGradlePathInspection(); doTest(inspection, null); } public void testPackage() throws Exception { AndroidLintGradleDeprecatedInspection inspection = new AndroidLintGradleDeprecatedInspection(); doTest(inspection, null); } public void testMinSdkAssignment() throws Exception { AndroidLintGradleIdeErrorInspection inspection = new AndroidLintGradleIdeErrorInspection(); doTest(inspection, null); } public void testMinSdkAssignment2() throws Exception { AndroidLintGradleIdeErrorInspection inspection = new AndroidLintGradleIdeErrorInspection(); doTest(inspection, null); } public void testPathSuppress() throws Exception { AndroidLintGradlePathInspection inspection = new AndroidLintGradlePathInspection(); doTest(inspection, "Suppress: Add //noinspection GradlePath"); } public void testPathSuppressJoin() throws Exception { AndroidLintGradlePathInspection inspection = new AndroidLintGradlePathInspection(); doTest(inspection, "Suppress: Add //noinspection GradlePath"); } public void testBadPlayServicesVersion() throws Exception { AndroidLintGradleCompatibleInspection inspection = new AndroidLintGradleCompatibleInspection(); doTest(inspection, "Change to 12.0.1"); } public void testStringInt() throws Exception { AndroidLintStringShouldBeIntInspection inspection = new AndroidLintStringShouldBeIntInspection(); doTest(inspection, null); } public void testDeprecatedPluginId() throws Exception { AndroidLintGradleDeprecatedInspection inspection = new AndroidLintGradleDeprecatedInspection(); doTest(inspection, null); } public void testSuppressLine2() throws Exception { // Tests that issues on line 2, which are suppressed with a comment on line 1, are correctly // handled (until recently, the suppression comment on the first line did not work) AndroidLintGradleDeprecatedInspection inspection = new AndroidLintGradleDeprecatedInspection(); doTest(inspection, null); } public void testIgnoresGStringsInDependencies() throws Exception { AndroidLintGradlePluginVersionInspection inspection = new AndroidLintGradlePluginVersionInspection(); doTest(inspection, null); } public void testDataBindingWithoutKaptUsingApplyPlugin() throws Exception { AndroidLintDataBindingWithoutKaptInspection inspection = new AndroidLintDataBindingWithoutKaptInspection(); doTest(inspection, null); } public void testDataBindingWithKaptUsingApplyPlugin() throws Exception { AndroidLintDataBindingWithoutKaptInspection inspection = new AndroidLintDataBindingWithoutKaptInspection(); doTest(inspection, null); } public void testDataBindingWithoutKaptUsingPluginsBlock() throws Exception { AndroidLintDataBindingWithoutKaptInspection inspection = new AndroidLintDataBindingWithoutKaptInspection(); doTest(inspection, null); } public void testDataBindingWithKaptUsingPluginsBlock() throws Exception { AndroidLintDataBindingWithoutKaptInspection inspection = new AndroidLintDataBindingWithoutKaptInspection(); doTest(inspection, null); } public void testDeprecatedConfigurationUse() throws Exception { AndroidLintGradleDeprecatedConfigurationInspection inspection = new AndroidLintGradleDeprecatedConfigurationInspection(); doTest(inspection, null); } private void doTest(@NotNull final AndroidLintInspectionBase inspection, @Nullable String quickFixName) throws Exception { createManifest(); myFixture.enableInspections(inspection); VirtualFile file = myFixture.copyFileToProject(BASE_PATH + getTestName(false) + ".gradle", "build.gradle"); myFixture.configureFromExistingVirtualFile(file); myFixture.checkHighlighting(true, false, false); if (quickFixName != null) { final IntentionAction quickFix = myFixture.getAvailableIntention(quickFixName); assertNotNull(quickFix); myFixture.launchAction(quickFix); myFixture.checkResultByFile(BASE_PATH + getTestName(false) + "_after.gradle"); } } }
2,309
403
package org.camunda.bpm.example.multiple_versions_parallel; import java.util.Properties; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.ExecutionListener; public class SetVersionVariableListener implements ExecutionListener { @Override public void notify(DelegateExecution execution) throws Exception { Properties version = new Properties(); version.load(this.getClass().getResourceAsStream("/version.properties")); execution.setVariable("processDefinitionVersion", version.getProperty("maven.version.major") + "." + version.getProperty("maven.version.minor")); } }
183
335
<filename>B/Babe_noun.json { "word": "Babe", "definitions": [ "A sexually attractive young woman.", "An affectionate form of address, typically for someone with whom one has a sexual or romantic relationship.", "A baby.", "An innocent or helpless person." ], "parts-of-speech": "Noun" }
127
1,375
<gh_stars>1000+ #import "AppController.h" #import "Article.h" #import "ArticleConverter.h" #import "ArticleListView.h" #import "ArticleViewDelegate.h" #import "DisclosureView.h" #import "FolderView.h" #import "HelperFunctions.h" #import "NSFileManager+Paths.h" #import "OpenReader.h" #import "PluginManager.h" #import "Preferences.h" #import "RefreshManager.h" #import "UnifiedDisplayView.h" #import "ViennaApp.h" #import "WebViewBrowser.h" #import "WKPreferences+Private.h" #import "WKWebView+Private.h" #import "WKWebViewConfiguration+Private.h"
207
2,253
<filename>src/unit_tests/variant_array_view/variant_array_view_test.cpp /************************************************************************************ * * * Copyright (c) 2014 - 2018 <NAME> <<EMAIL>> * * * * This file is part of RTTR (Run Time Type Reflection) * * License: MIT License * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * * SOFTWARE. * * * *************************************************************************************/ #include <catch/catch.hpp> #include <rttr/type> #include <vector> #include <map> #include <string> using namespace rttr; using namespace std; RTTR_BEGIN_DISABLE_DEPRECATED_WARNING ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::ctor", "[variant_array_view]") { SECTION("empty") { variant_array_view a; CHECK(a.is_valid() == false); variant_array_view b(a); CHECK(b.is_valid() == false); variant var; variant_array_view c = var.create_array_view(); CHECK(c.is_valid() == false); CHECK(c.is_dynamic() == false); CHECK(c.get_rank_type(0).is_valid() == false); CHECK(c.get_rank() == 0); CHECK(c.get_type().is_valid() == false); CHECK(c.get_size() == 0); CHECK(c.get_size(0) == 0); CHECK(c.get_size(0, 0) == 0); CHECK(c.get_size_variadic({}) == 0); CHECK(c.set_size(0) == false); CHECK(c.set_size(0, 0) == false); CHECK(c.set_size(0, 0, 0) == false); CHECK(c.set_size_variadic(0, {}) == false); CHECK(c.set_value(0) == false); CHECK(c.set_value(0, 0) == false); CHECK(c.set_value(0, 0, 0) == false); CHECK(c.set_value(0, 0, 0, 0) == false); CHECK(c.set_value_variadic({}, 0) == false); CHECK(c.get_value(0).is_valid() == false); CHECK(c.get_value(0, 0).is_valid() == false); CHECK(c.get_value(0, 0, 0).is_valid() == false); CHECK(c.get_value_variadic({}).is_valid() == false); CHECK(c.insert_value(0, 0) == false); CHECK(c.insert_value(0, 0, 0) == false); CHECK(c.insert_value(0, 0, 0, 0) == false); CHECK(c.insert_value_variadic({}, 0) == false); CHECK(c.remove_value(0) == false); CHECK(c.remove_value(0, 0) == false); CHECK(c.remove_value(0, 0, 0) == false); CHECK(c.remove_value_variadic({}) == false); } SECTION("invalid") { variant var = 2; variant_array_view a = var.create_array_view(); CHECK(a.is_valid() == false); } SECTION("full") { variant var = std::array<int, 10>(); variant_array_view a = var.create_array_view(); CHECK(a.is_valid() == true); variant_array_view b(a); CHECK(b.is_valid() == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::assignment", "[variant_array_view]") { SECTION("empty") { variant_array_view a; variant_array_view b; b = a; CHECK(b.is_valid() == false); variant var; variant_array_view c; c = var.create_array_view(); CHECK(c.is_valid() == false); } SECTION("full") { variant var = std::array<int, 10>(); variant_array_view a; a = var.create_array_view(); CHECK(a.is_valid() == true); variant_array_view b; b = a; CHECK(b.is_valid() == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::get_type", "[variant_array_view]") { SECTION("empty") { variant_array_view a; CHECK(a.get_type().is_valid() == false); } SECTION("array") { variant var = std::array<int, 10>(); variant_array_view a = var.create_array_view(); CHECK((a.get_type() == type::get<std::array<int, 10>>())); } SECTION("raw array") { int array[2] = {1, 2}; variant var = array; variant_array_view a = var.create_array_view(); CHECK((a.get_type() == type::get<int[2]>())); } SECTION("pointer") { std::array<int, 10> array; variant var = &array; CHECK((var.get_type() == type::get<std::array<int, 10>*>())); variant_array_view a = var.create_array_view(); CHECK((a.get_type() == type::get<std::array<int, 10>>())); } SECTION("wrapper") { std::array<int, 10> array; variant var = std::ref(array); CHECK((var.get_type() == type::get<std::reference_wrapper<std::array<int, 10>>>())); variant_array_view a = var.create_array_view(); CHECK((a.get_type() == type::get<std::array<int, 10>>())); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::swap", "[variant_array_view]") { SECTION("empty") { variant_array_view a; variant_array_view b; a.swap(b); CHECK(b.is_valid() == false); CHECK(a.is_valid() == false); } SECTION("full") { variant var = std::array<int, 10>(); variant_array_view a = var.create_array_view(); variant_array_view b; a.swap(b); CHECK(a.is_valid() == false); CHECK(b.is_valid() == true); a = b; CHECK(a.is_valid() == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::is_dynamic", "[variant_array_view]") { SECTION("static") { variant var = std::array<int, 10>(); variant_array_view a = var.create_array_view(); CHECK(a.is_dynamic() == false); } SECTION("dynamic") { variant var = std::vector<int>(); variant_array_view a = var.create_array_view(); CHECK(a.is_dynamic() == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::get_rank", "[variant_array_view]") { SECTION("1D") { int obj[2] = {0, 0}; variant var = obj; variant_array_view array = var.create_array_view(); CHECK(array.get_rank() == 1); } SECTION("2D") { int obj[2][2] = {{0, 0}, {0, 0}}; variant var = obj; variant_array_view array = var.create_array_view(); CHECK(array.get_rank() == 2); } SECTION("3D") { int obj[2][2][2] = {{{0, 0}, {0, 0}}, {{0, 0}, {0, 0}}}; variant var = obj; variant_array_view array = var.create_array_view(); CHECK(array.get_rank() == 3); } SECTION("dynamic 2D") { std::vector<std::vector<int>> vec_2d; variant var = vec_2d; variant_array_view array = var.create_array_view(); CHECK(array.get_rank() == 2); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::get_rank_type", "[variant_array_view]") { SECTION("2D") { int obj[2][10] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; variant var = obj; variant_array_view array = var.create_array_view(); CHECK(array.get_rank_type(0) == type::get<int[2][10]>()); CHECK(array.get_rank_type(1) == type::get<int[10]>()); CHECK(array.get_rank_type(2) == type::get<int>()); CHECK(array.get_rank_type(3).is_valid() == false); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::get_size", "[variant_array_view]") { SECTION("1D") { variant var = std::vector<int>(50, 0); variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 50); CHECK(array.get_size(0) == 0); } SECTION("2D") { int obj[2][10] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; variant var = obj; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 2); CHECK(array.get_size(0) == 10); CHECK(array.get_size(1) == 10); CHECK(array.get_size(3) == 0); } SECTION("2D") { std::vector<std::vector<int>> vec; vec.push_back(std::vector<int>(10, 0)); vec.push_back(std::vector<int>(20, 0)); vec.push_back(std::vector<int>(30, 0)); vec.push_back(std::vector<int>(40, 0)); vec.push_back(std::vector<int>(50, 0)); variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 5); CHECK(array.get_size(0) == 10); CHECK(array.get_size(1) == 20); CHECK(array.get_size(2) == 30); CHECK(array.get_size(3) == 40); CHECK(array.get_size(4) == 50); CHECK(array.get_size(5) == 0); } SECTION("3D") { int vec[4][3][2] = { {{0, 1}, {2, 3}, {4, 5}}, {{6, 7}, {8, 9}, {10, 11}}, {{12, 13}, {14, 15}, {16, 17}}, {{18, 19}, {20, 21}, {22, 23}} }; variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 4); CHECK(array.get_size(0) == 3); CHECK(array.get_size(1) == 3); CHECK(array.get_size(2) == 3); CHECK(array.get_size(3) == 3); CHECK(array.get_size(4) == 0); CHECK(array.get_size(0, 0) == 2); CHECK(array.get_size(0, 1) == 2); CHECK(array.get_size(0, 2) == 2); CHECK(array.get_size(0, 3) == 0); } SECTION("get_size_variadic") { int vec[6][5][4][3] = {}; variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 6); CHECK(array.get_size(0) == 5); CHECK(array.get_size(0, 0) == 4); CHECK(array.get_size_variadic({}) == 6); CHECK(array.get_size_variadic({0}) == 5); CHECK((array.get_size_variadic({0, 0}) == 4)); CHECK((array.get_size_variadic({0, 0, 0}) == 3)); CHECK((array.get_size_variadic({0, 0, 0, 0}) == 0)); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::set_size", "[variant_array_view]") { SECTION("empty") { variant var; variant_array_view array = var.create_array_view(); CHECK(array.set_size(10) == false); } SECTION("static array") { int obj[10] = {0}; variant var = obj; variant_array_view array = var.create_array_view(); CHECK(array.set_size(5) == false); } SECTION("dynamic array") { variant var = std::vector<int>(50, 0); variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 50); CHECK(array.set_size(10) == true); CHECK(array.get_size() == 10); } SECTION("2D - dynamic") { std::vector<std::vector<int>> vec; variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 0); CHECK(array.set_size(10) == true); CHECK(array.get_size() == 10); CHECK(array.get_size(0) == 0); CHECK(array.set_size(10, 0) == true); CHECK(array.get_size(0) == 10); CHECK(array.get_size(9) == 0); CHECK(array.set_size(10, 9) == true); CHECK(array.get_size(9) == 10); CHECK(array.get_size(10) == 0); CHECK(array.set_size(10, 10)== false); CHECK(array.get_size(10) == 0); } SECTION("3D - dynamic") { std::vector<std::vector<std::vector<int>>> vec; variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 0); CHECK(array.set_size(10) == true); CHECK(array.get_size() == 10); CHECK(array.get_size(0) == 0); CHECK(array.set_size(8, 0) == true); CHECK(array.get_size(0) == 8); CHECK(array.get_size(0, 0) == 0); CHECK(array.set_size(6, 0, 0)== true); CHECK(array.get_size(0, 0) == 6); CHECK(array.get_size(0, 1) == 0); CHECK(array.set_size(4, 0, 1)== true); CHECK(array.get_size(0, 1) == 4); } SECTION("set_size_variadic") { std::vector<std::vector<std::vector<int>>> vec; variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size_variadic({}) == 0); CHECK(array.set_size_variadic(10, {}) == true); CHECK(array.get_size_variadic({}) == 10); CHECK(array.get_size_variadic({0}) == 0); CHECK(array.set_size_variadic(8, {0}) == true); CHECK(array.get_size_variadic({0}) == 8); CHECK(array.get_size_variadic({0, 0}) == 0); CHECK(array.set_size_variadic(6, {0, 0})== true); CHECK(array.get_size_variadic({0, 0}) == 6); CHECK(array.get_size_variadic({0, 1}) == 0); CHECK(array.set_size_variadic(4, {0, 1})== true); CHECK(array.get_size_variadic({0, 1}) == 4); // negative test CHECK(array.get_size_variadic({0, 1, 2}) == 0); CHECK(array.set_size_variadic(4, {0, 1, 2}) == false); } SECTION("Mix dynamic/static") { std::vector<std::array<int, 5>> vec; variant var = vec; variant_array_view array = var.create_array_view(); CHECK(array.get_size() == 0); CHECK(array.set_size(10) == true); CHECK(array.get_size() == 10); CHECK(array.get_size(0) == 5); CHECK(array.set_size(8, 0) == false); CHECK(array.get_size(0) == 5); } SECTION("test const array") { const std::vector<int> vec(50, 0); variant var = &vec; variant_array_view vec_array = var.create_array_view(); // pointer to const array cannot be changed REQUIRE(vec_array.set_size(0) == false); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::get_value", "[variant_array_view]") { SECTION("empty") { variant var; variant_array_view array = var.create_array_view(); CHECK(array.get_value(0).is_valid() == false); CHECK(array.get_value(0, 0).is_valid() == false); CHECK(array.get_value(0, 0, 0).is_valid() == false); CHECK(array.get_value_variadic({0, 0, 0}).is_valid() == false); } SECTION("raw array") { int obj[2][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {10, 11, 12, 13, 14, 15, 16, 17, 18, 19}}; variant var = &obj; variant_array_view array = var.create_array_view(); variant var_1 = array.get_value(0); CHECK(var_1.is_valid() == true); CHECK(var_1.get_type() == type::get<int[10]>()); CHECK(array.get_value(0, 0).get_type() == type::get<int>()); CHECK(array.get_value(0, 0).to_int() == 0); CHECK(array.get_value(0, 5).to_int() == 5); CHECK(array.get_value(1, 0).to_int() == 10); CHECK(array.get_value(1, 5).to_int() == 15); obj[0][0] = 23; obj[0][5] = 23; obj[1][0] = 23; obj[1][5] = 23; CHECK(array.get_value(0, 0).to_int() == 23); CHECK(array.get_value(0, 5).to_int() == 23); CHECK(array.get_value(1, 0).to_int() == 23); CHECK(array.get_value(1, 5).to_int() == 23); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::set_value", "[variant_array_view]") { SECTION("empty") { variant var; variant_array_view array = var.create_array_view(); CHECK(array.set_value("test") == false); CHECK(array.set_value(0, "test") == false); CHECK(array.set_value(0, 0, "test") == false); CHECK(array.set_value_variadic({0, 0, 0}, "test") == false); } SECTION("1D") { int obj[42] = { 0 }; variant var = &obj; variant_array_view array = var.create_array_view(); for (std::size_t i = 0; i < array.get_size(); ++i) array.set_value(i, 23); CHECK(obj[0] == 23); CHECK(obj[41] == 23); // negative test CHECK(array.set_value(0, 0, 12) == false); } SECTION("2D") { int obj[2][10] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; variant var = &obj; variant_array_view array = var.create_array_view(); int sub_array_int[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (std::size_t i = 0; i < array.get_size(); ++i) array.set_value(i, sub_array_int); CHECK(obj[0][5] == 5); CHECK(obj[1][9] == 9); for (std::size_t i = 0; i < array.get_size(); ++i) for (std::size_t j = 0; j < array.get_size(i); ++j) array.set_value(i, j, -1); CHECK(obj[0][5] == -1); CHECK(obj[1][9] == -1); // negative test CHECK(array.set_value(0, 0, 0, 12) == false); } SECTION("3D") { int obj[3][3][3] = {}; variant var = &obj; variant_array_view array = var.create_array_view(); for (std::size_t i = 0; i < array.get_size(); ++i) for (std::size_t j = 0; j < array.get_size(i); ++j) for (std::size_t k = 0; k < array.get_size(i, j); ++k) array.set_value(i, j, k, -1); CHECK(obj[0][0][0] == -1); CHECK(obj[2][2][2] == -1); // negative test CHECK(array.set_value_variadic({0, 0, 0, 0}, 12) == false); } SECTION("variadic") { int obj[3][3][3][3] = {}; variant var = &obj; variant_array_view array = var.create_array_view(); for (std::size_t i = 0; i < array.get_size_variadic({}); ++i) for (std::size_t j = 0; j < array.get_size_variadic({i}); ++j) for (std::size_t k = 0; k < array.get_size_variadic({i, j}); ++k) for (std::size_t l = 0; l < array.get_size_variadic({i, j, k}); ++l) array.set_value_variadic({i, j, k, l}, -1); CHECK(obj[0][0][0][0] == -1); CHECK(obj[2][2][2][2] == -1); // negative test CHECK(array.set_value_variadic({0, 0, 0, 0, 0}, 12) == false); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::insert_value", "[variant_array_view]") { SECTION("static array") { int obj[50] = { 0 }; variant var = &obj; variant_array_view array = var.create_array_view(); CHECK(array.insert_value(15, 23) == false); CHECK(obj[15] == 0); } SECTION("1D") { std::vector<int> obj(10, 0); variant var = &obj; variant_array_view array = var.create_array_view(); const auto size = array.get_size(); CHECK(array.insert_value(5, 23) == true); CHECK(obj[5] == 23); CHECK(array.get_size() == size + 1); // negative test CHECK(array.insert_value(0, 0, 23) == false); CHECK(array.get_size() == size + 1); } SECTION("2D") { std::vector<std::vector<int>> obj(10, std::vector<int>(10, 0)); variant var = &obj; variant_array_view array = var.create_array_view(); { const auto size = array.get_size(); CHECK(array.insert_value(5, std::vector<int>()) == true); CHECK(obj[5] == std::vector<int>()); CHECK(array.get_size() == size + 1); } { const auto size = array.get_size(5); CHECK(array.insert_value(5, 0, 23) == true); CHECK(obj[5][0] == 23); CHECK(array.get_size(5) == size + 1); } // negative test CHECK(array.insert_value(5, 23) == false); } SECTION("3D") { std::vector<std::vector<std::vector<int>>> obj(10, std::vector<std::vector<int>>(10, std::vector<int>(10, 0))); variant var = &obj; variant_array_view array = var.create_array_view(); const auto size = array.get_size(5, 5); CHECK(array.insert_value(5, 5, 5, 23) == true); CHECK(obj[5][5][5] == 23); CHECK(array.get_size(5, 5) == size + 1); // negative test CHECK(array.insert_value(5, 23) == false); CHECK(array.insert_value(5, 5, 23) == false); } SECTION("variadic") { std::vector<std::vector<std::vector<int>>> obj(10, std::vector<std::vector<int>>(10, std::vector<int>(10, 0))); variant var = &obj; variant_array_view array = var.create_array_view(); const auto size = array.get_size(5, 5); CHECK(array.insert_value_variadic({5, 5, 5}, 23) == true); CHECK(obj[5][5][5] == 23); CHECK(array.get_size_variadic({5, 5}) == size + 1); // negative test CHECK(array.insert_value_variadic({5}, 23) == false); CHECK(array.insert_value_variadic({5, 5}, 23) == false); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::remove_value", "[variant_array_view]") { SECTION("static array") { int obj[50] = { 0 }; variant var = &obj; variant_array_view array = var.create_array_view(); CHECK(array.remove_value(15, 23) == false); CHECK(obj[15] == 0); } SECTION("1D") { std::vector<int> obj(10, 0); variant var = &obj; variant_array_view array = var.create_array_view(); const auto size = array.get_size(); obj[5] = 23; CHECK(array.remove_value(5) == true); CHECK(obj[5] == 0); CHECK(array.get_size() == size - 1); // negative test CHECK(array.remove_value(0, 0) == false); CHECK(array.remove_value(100) == false); CHECK(array.get_size() == size - 1); } SECTION("2D") { std::vector<std::vector<int>> obj(10, std::vector<int>(10, 0)); variant var = &obj; variant_array_view array = var.create_array_view(); { const auto size = array.get_size(); CHECK(array.remove_value(5) == true); CHECK(array.get_size() == size - 1); } { const auto size = array.get_size(5); obj[5][5] = 23; CHECK(array.remove_value(5, 0) == true); CHECK(obj[5][5] == 0); CHECK(array.get_size(5) == size - 1); } // negative test CHECK(array.remove_value(5, 5, 5) == false); } SECTION("3D") { std::vector<std::vector<std::vector<int>>> obj(10, std::vector<std::vector<int>>(10, std::vector<int>(10, 0))); variant var = &obj; variant_array_view array = var.create_array_view(); const auto size = array.get_size(5, 5); obj[5][5][5] = 23; CHECK(array.remove_value(5, 5, 5) == true); CHECK(obj[5][5][5] == 0); CHECK(array.get_size(5, 5) == size - 1); // negative test CHECK(array.remove_value(5, 5, 222) == false); } SECTION("variadic") { std::vector<std::vector<std::vector<int>>> obj(10, std::vector<std::vector<int>>(10, std::vector<int>(10, 0))); variant var = &obj; variant_array_view array = var.create_array_view(); const auto size = array.get_size(5, 5); obj[5][5][5] = 23; CHECK(array.remove_value_variadic({5, 5, 5}) == true); CHECK(obj[5][5][5] == 0); CHECK(array.get_size_variadic({5, 5}) == size - 1); // negative test CHECK(array.remove_value_variadic({5, 5, 5, 5}) == false); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::get_value_as_ref", "[variant_array_view]") { SECTION("positiv test") { std::vector<int> vec(50, 0); int i = 0; for (auto& value : vec) { value = ++i; } variant var = &vec; auto array_view = var.create_array_view(); variant var_value = array_view.get_value_as_ref(0); CHECK(var_value.get_type() == type::get<std::reference_wrapper<int>>()); auto& value_ref = var_value.get_wrapped_value<int>(); CHECK(value_ref == 1); variant extr_var = var_value.extract_wrapped_value(); REQUIRE(extr_var.get_type() == type::get<int>()); CHECK(extr_var.get_value<int>() == 1); } SECTION("negative test") { std::vector <bool> vec(50, true); variant var = &vec; auto array_view = var.create_array_view(); variant var_value = array_view.get_value_as_ref(0); CHECK(var_value.is_valid() == false); var_value = array_view.get_value(0); CHECK(var_value.is_valid() == true); CHECK(var_value.get_type() == type::get<bool>()); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant_array_view::misc", "[variant_array_view]") { SECTION("check support of vector<bool>()") { auto orig_vec = std::vector<bool>({true, false, false}); variant var = &orig_vec; CHECK(*var.get_value<std::vector<bool>*>() == orig_vec); variant_array_view var_arr = var.create_array_view(); var_arr.set_value(0, false); CHECK(orig_vec[0] == false); var_arr.set_size(100); CHECK(orig_vec.size() == 100); var_arr.set_size(50); CHECK(orig_vec.size() == 50); var_arr.insert_value(25, true); CHECK(orig_vec[25] == true); // check copied array var = std::vector<bool>({true, false, false}); var_arr = var.create_array_view(); REQUIRE(var_arr.get_size() == 3); var_arr.set_value(0, false); CHECK(var_arr.get_value(0).get_value<bool>() == false); CHECK(var_arr.get_value(1).get_value<bool>() == false); CHECK(var_arr.get_value(2).get_value<bool>() == false); var_arr.set_value(1, true); var_arr.set_value(2, true); CHECK(var_arr.get_value(1).get_value<bool>() == true); CHECK(var_arr.get_value(2).get_value<bool>() == true); } SECTION("check array with wrapper type") { std::vector<int> vec(50, 0); std::reference_wrapper<decltype(vec)> ref_vec = std::ref(vec); variant var = ref_vec; variant_array_view array = var.create_array_view(); REQUIRE(array.is_valid() == true); REQUIRE(array.get_type() == type::get<decltype(vec)>()); array.set_size(70); CHECK(array.get_size() == 70); CHECK(vec.size() == 70); array.set_value(50, 23); variant ret = array.get_value(50); REQUIRE(ret.is_type<int>() == true); REQUIRE(ret.get_value<int>() == 23); } } RTTR_END_DISABLE_DEPRECATED_WARNING /////////////////////////////////////////////////////////////////////////////////////////
14,264
482
<reponame>liangchengzhi/nutzboot package org.nutz.boot.starter.velocity; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.nutz.lang.Lang; import org.nutz.mvc.view.AbstractPathView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * */ public class VelocityView extends AbstractPathView { private VelocityEngine engine; private String templateClasspath; private String charsetEncoding; public VelocityView(String dest, VelocityEngine engine, String templateClasspath, String charsetEncoding) { super(dest); this.engine = engine; this.templateClasspath = templateClasspath; this.charsetEncoding = charsetEncoding; } @Override public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable { resp.setCharacterEncoding(charsetEncoding); if (resp.getContentType() == null) { resp.setContentType("text/html; charset=" + charsetEncoding); } try { String templateUrl = templateClasspath + evalPath(req, obj); Template template = engine.getTemplate(templateUrl, charsetEncoding); VelocityWebContext webContext = new VelocityWebContext(req, resp); VelocityContext context = new VelocityContext(webContext); PrintWriter writer = resp.getWriter(); template.merge(context, writer); //writer.flush(); } catch (IOException e) { throw Lang.wrapThrow(e); } } }
641
14,668
<filename>ios/chrome/browser/ui/settings/safety_check/safety_check_service_delegate.h // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_UI_SETTINGS_SAFETY_CHECK_SAFETY_CHECK_SERVICE_DELEGATE_H_ #define IOS_CHROME_BROWSER_UI_SETTINGS_SAFETY_CHECK_SAFETY_CHECK_SERVICE_DELEGATE_H_ #import <UIKit/UIKit.h> @class TableViewItem; // Protocol to handle user actions from the safety check view. @protocol SafetyCheckServiceDelegate <NSObject> // Called when item is tapped. - (void)didSelectItem:(TableViewItem*)item; // Determines if selection animation should be shown for |item|. - (BOOL)isItemClickable:(TableViewItem*)item; // Checks if |item| should have an error popover. - (BOOL)isItemWithErrorInfo:(TableViewItem*)item; // Notifies the mediator that an info button was tapped for |itemType|. - (void)infoButtonWasTapped:(UIButton*)buttonView usingItemType:(NSInteger)itemType; @end #endif // IOS_CHROME_BROWSER_UI_SETTINGS_SAFETY_CHECK_SAFETY_CHECK_SERVICE_DELEGATE_H_
407
1,133
<gh_stars>1000+ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "frToTEC.h" /** * Convert from a map of Faraday rotation to Total Electron Count (TEC) * This function assumes a constant value for the magnetic field in the * look direction of the radar (bdotk). * * @param frFilename the file containing the Faraday rotation map [radians] * @param outFilename the output file name * @param width the width of the input and output files in number of samples * @param bdotk a constant value for the B field in the direction k [gauss] * @param fc the carrier frequency of the radar [Hz] */ int convertToTec(char *frFilename, char *outFilename, int width, float bdotk, float fc) { int i,j,length; float *fr,*tec; FILE *frFile,*outFile; frFile = fopen(frFilename,"rb"); outFile = fopen(outFilename,"wb"); fseek(frFile,0L,SEEK_END); length = ftell(frFile); rewind(frFile); if ( (length%width) != 0 ) { printf("File has a non-integer number of lines\n"); exit(EXIT_FAILURE); } length = (int)(length/(sizeof(float)*width)); fr = (float *)malloc(width*sizeof(float)); tec = (float *)malloc(width*sizeof(float)); for(i=0;i<length;i++) { fread(fr,sizeof(float),width,frFile); for(j=0;j<width;j++) { tec[j] = frToTec(fr[j],fc,bdotk); } fwrite(tec,sizeof(float),width,outFile); } free(fr); free(tec); fclose(frFile); fclose(outFile); return 1; } /** * Convert from a map of Faraday rotation to Total Electron Count (TEC) * This function assumes that a file containing the values of the magnetic * B-vector in units of gauss in the look direction of the radar (bdotk) at * each point is provided. * * @param frFilename the file containing the Faraday rotation map [radians] * @param outFilename the output file name * @param bdotkFilename the file containing the values of bdotk [gauss] * @param width the width of the input and output files in number of samples * @param fc the carrier frequency of the radar [Hz] */ int convertToTecWBdotK(char *frFilename, char *outFilename, char *bdotkFilename,int width, float fc) { int i,j,length; float *tec,*fr,*bdotk; FILE *frFile,*bdotkFile,*outfile; frFile = fopen(frFilename,"rb"); bdotkFile = fopen(bdotkFilename,"rb"); outfile = fopen(outFilename,"wb"); fseek(frFile,0L,SEEK_END); length = ftell(frFile); rewind(frFile); if ( (length%width) != 0 ) { printf("File has a non-integer number of lines\n"); exit(EXIT_FAILURE); } length = (int)(length/(sizeof(float)*width)); fr = (float *)malloc(width*sizeof(float)); bdotk = (float *)malloc(width*sizeof(float)); tec = (float *)malloc(width*sizeof(float)); for(i=0;i<length;i++) { fread(fr,sizeof(float),width,frFile); fread(bdotk,sizeof(float),width,bdotkFile); for(j=0;j<width;j++) { tec[j] = frToTec(fr[j],fc,bdotk[j]); } fwrite(tec,sizeof(float),width,outfile); } free(fr); free(bdotk); free(tec); fclose(frFile); fclose(bdotkFile); fclose(outfile); return 1; } /** * Convert from Faraday rotation in radians, to Total Electron Count (TEC) in electrons/m^2*1e16 * * @param fr the Faraday rotation [radians] * @param fc the carrier frequency of the radar [Hz] * @param bdotk the value of the B field in the direction k [gauss] * @return The Total Electron Count (TEC) [electrons/m^2/1e16] */ float frToTec(float fr,float fc, float bdotk) { float tec; // Constant |e|^3/(8pi^2 c \epsilon_0 m^2_e) // e is the elementary charge, \epsilon is the permitivity of free space, m_e is the electron mass, and c is the speed of light // [=] coulombs^3/((m/s)^2 (F/m) kg^2) // [=] coulomb m/kg (? maybe) float k1 = 2.365e4; tec = (fr*powf(fc,(float)2.0)/(k1*bdotk*1e-4))/1e16; return tec; }
1,510